пионер
Пт 19 августа 2016 г., 7:48 утра
Я никогда раньше не использовал функцию Shiftout, пока. Я работаю с шаговым драйвером http: // таблица данных.осьминога.com/a3992slp- ... 790836.PDF Этот драйвер потребовался два из 19 бит с 3 -й проводной последовательным портом (защелка, часы, данные) и MSBFirst для управления шаговым двигателем. Я искал сеть и нашел только 8 или 16 бит Shiftout (). Как мне сдвинуть остальные 3 бита, чтобы сделать его в общей сложности 19 бит? Большая помощь, если вы можете показать мне код. Спасибо. пожалуйста, порекомендуйте.
Пито
Пт 19 августа 2016 г. 8:14
Вы можете использовать петлю и бить булавки, например, (не протестировано):
const int pwmOutPin = PA1;
HardwareTimer pwmtimer(2);
void setup() {
pinMode(pwmOutPin, PWM);
pwmtimer.pause();
pwmtimer.setPrescaleFactor(220); //Prescaler
pwmtimer.setOverflow(65455); //Period width
pwmtimer.setCompare(TIMER_CH2, 32768); //Pulse width
pwmtimer.refresh();
pwmtimer.resume();
pinMode(pwmOutPin, PWM);
}
void loop() {
}
Racemaniac
Пт 19 августа 2016 г. 8:28 утра
Пионер написал:Я никогда раньше не использовал функцию Shiftout, пока. Я работаю с шаговым драйвером http: // таблица данных.осьминога.com/a3992slp- ... 790836.PDF Этот драйвер потребовался два из 19 бит с 3 -й проводной последовательным портом (защелка, часы, данные) и MSBFirst для управления шаговым двигателем. Я искал сеть и нашел только 8 или 16 бит Shiftout (). Как мне сдвинуть остальные 3 бита, чтобы сделать его в общей сложности 19 бит? Большая помощь, если вы можете показать мне код. Спасибо. пожалуйста, порекомендуйте.
Пито
Пт 19 августа 2016 г. 8:57 утра
Я сделал это в качестве функции "SendData (data)", опечатки исправлены..
Racemaniac
Пт 19 августа 2016 г., 9:05
Пито написал:Я сделал это в качестве функции "SendData (data)", опечатки исправлены..
Ахулл
Пт 19 августа 2016 г. 10:14
Реданьяк написал:Пито написал:Я сделал это в качестве функции "SendData (data)", опечатки исправлены..
Пито
Пт 19 августа 2016 г., 14:40
В любом случае, я был бы осторожен со слишком большой оптимизацией, так как используется чип драйвера, он медленно со своим интерфейсом 3Wire
const int pwmOutPin = PA1; // pin10
HardwareTimer pwmtimer(2);
uint16 maxduty, duty;
uint32 period, mypulse;
void setup() {
pwmtimer.pause();
period = 250000; // PWM period in useconds, freq 4Hz
maxduty = pwmtimer.setPeriod(period);
pwmtimer.refresh();
pwmtimer.resume();
pinMode(pwmOutPin, PWM);
}
void loop() {
mypulse = 23456; // 0<=mypulse<=period, this is the High pulse of my length in useconds
duty = map((int32)mypulse, 0, (int32)period, 0, (int32)maxduty);
pwmWrite(pwmOutPin, duty); // 0<=duty<=maxduty
while(1){};
}
пионер
Сб 20 августа 2016 г. 12:43
Большое спасибо, пито. Я могу проверить с серийным монитором, чтобы увидеть Zero и One Out с разными данными. Для вашего последнего поста на диаграмме синхронизации серийного порта. Как вы думаете, чип A3992 слишком быстрый для моего микроконтроллера? Я использую STM32F103Vet6. Когда я увидел, что диаграмма синхронизации A3992 должна использовать NS (Nano Second) для работы с.
Rogerclark
Сб 20 августа 2016 г. 3:00 утра
@pioneer
Вы всегда можете замедлить данные о периферийных устройствах, которые не могут принять их с высокой скоростью.
Так что не беспокойтесь о том, что процессор слишком быстр.
Если вы действительно хотите, есть способ снизить скорость процессора до 48 МГц (вместо 72 МГц) и все же сохранить USB, но ниже USB не будет работать.
Самая низкая скорость, которую вы можете запустить, - это внешний часовой частот, который обычно составляет 8 МГц на этих платах. Но я не рекомендую вам снизить скорость процессора, просто вставьте небольшие задержки в свой код.
Самый простой способ сделать это - что -то вроде
Вы всегда можете замедлить данные о периферийных устройствах, которые не могут принять их с высокой скоростью.
Так что не беспокойтесь о том, что процессор слишком быстр.
Если вы действительно хотите, есть способ снизить скорость процессора до 48 МГц (вместо 72 МГц) и все же сохранить USB, но ниже USB не будет работать.
Самая низкая скорость, которую вы можете запустить, - это внешний часовой частот, который обычно составляет 8 МГц на этих платах. Но я не рекомендую вам снизить скорость процессора, просто вставьте небольшие задержки в свой код.
Самый простой способ сделать это - что -то вроде
#define sclk PB3
#define mosi PB5
#define cs PA10
#define rst PA8
#define dc PA9
// Color definitions
#define BLACK 0x0000
#define BLUE 0x001F
#define RED 0xF800
#define GREEN 0x07E0
#define CYAN 0x07FF
#define MAGENTA 0xF81F
#define YELLOW 0xFFE0
#define WHITE 0xFFFF
#include
#include
#include
// Option 1: use any pins but a little slower
Adafruit_SSD1331 display = Adafruit_SSD1331(cs, dc, mosi, sclk, rst);
// Option 2: must use the hardware SPI pins
// (for UNO thats sclk = 13 and sid = 11) and pin 10 must be
// an output. This is much faster - also required if you want
// to use the microSD card (see the image drawing example)
//Adafruit_SSD1331 display = Adafruit_SSD1331(cs, dc, rst);
float p = 3.1415926;
void setup(void) {
display.begin();
SPI.setDataMode(SPI_MODE0); //Set the SPI data mode 0
SPI.setClockDivider(SPI_CLOCK_DIV32); // 2.25 MHz
uint16_t time = millis();
display.fillScreen(BLACK);
time = millis() - time;
lcdTestPattern();
delay(1000);
display.fillScreen(BLACK);
display.setCursor(0,0);
display.print("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur adipiscing ante sed nibh tincidunt feugiat. Maecenas enim massa");
delay(1000);
// tft print function!
tftPrintTest();
delay(2000);
//a single pixel
display.drawPixel(display.width()/2, display.height()/2, GREEN);
delay(500);
// line draw test
testlines(YELLOW);
delay(500);
// optimized lines
testfastlines(RED, BLUE);
delay(500);
testdrawrects(GREEN);
delay(1000);
testfillrects(YELLOW, MAGENTA);
delay(1000);
display.fillScreen(BLACK);
testfillcircles(10, BLUE);
testdrawcircles(10, WHITE);
delay(1000);
testroundrects();
delay(500);
testtriangles();
delay(500);
Serial.println("done");
delay(1000);
}
void loop() {
}
void testlines(uint16_t color) {
display.fillScreen(BLACK);
for (int16_t x=0; x < display.width()-1; x+=6) {
display.drawLine(0, 0, x, display.height()-1, color);
}
for (int16_t y=0; y < display.height()-1; y+=6) {
display.drawLine(0, 0, display.width()-1, y, color);
}
display.fillScreen(BLACK);
for (int16_t x=0; x < display.width()-1; x+=6) {
display.drawLine(display.width()-1, 0, x, display.height()-1, color);
}
for (int16_t y=0; y < display.height()-1; y+=6) {
display.drawLine(display.width()-1, 0, 0, y, color);
}
display.fillScreen(BLACK);
for (int16_t x=0; x < display.width()-1; x+=6) {
display.drawLine(0, display.height()-1, x, 0, color);
}
for (int16_t y=0; y < display.height()-1; y+=6) {
display.drawLine(0, display.height()-1, display.width()-1, y, color);
}
display.fillScreen(BLACK);
for (int16_t x=0; x < display.width()-1; x+=6) {
display.drawLine(display.width()-1, display.height()-1, x, 0, color);
}
for (int16_t y=0; y < display.height()-1; y+=6) {
display.drawLine(display.width()-1, display.height()-1, 0, y, color);
}
}
void testdrawtext(char *text, uint16_t color) {
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
for (uint8_t i=0; i < 168; i++) {
if (i == '\n') continue;
display.write(i);
if ((i > 0) && (i % 21 == 0))
display.println();
}
}
void testfastlines(uint16_t color1, uint16_t color2) {
display.fillScreen(BLACK);
for (int16_t y=0; y < display.height()-1; y+=5) {
display.drawFastHLine(0, y, display.width()-1, color1);
}
for (int16_t x=0; x < display.width()-1; x+=5) {
display.drawFastVLine(x, 0, display.height()-1, color2);
}
}
void testdrawrects(uint16_t color) {
display.fillScreen(BLACK);
for (int16_t x=0; x < display.height()-1; x+=6) {
display.drawRect((display.width()-1)/2 -x/2, (display.height()-1)/2 -x/2 , x, x, color);
}
}
void testfillrects(uint16_t color1, uint16_t color2) {
display.fillScreen(BLACK);
for (int16_t x=display.height()-1; x > 6; x-=6) {
display.fillRect((display.width()-1)/2 -x/2, (display.height()-1)/2 -x/2 , x, x, color1);
display.drawRect((display.width()-1)/2 -x/2, (display.height()-1)/2 -x/2 , x, x, color2);
}
}
void testfillcircles(uint8_t radius, uint16_t color) {
for (uint8_t x=radius; x < display.width()-1; x+=radius*2) {
for (uint8_t y=radius; y < display.height()-1; y+=radius*2) {
display.fillCircle(x, y, radius, color);
}
}
}
void testdrawcircles(uint8_t radius, uint16_t color) {
for (int16_t x=0; x < display.width()-1+radius; x+=radius*2) {
for (int16_t y=0; y < display.height()-1+radius; y+=radius*2) {
display.drawCircle(x, y, radius, color);
}
}
}
void testtriangles() {
display.fillScreen(BLACK);
int color = 0xF800;
int t;
int w = display.width()/2;
int x = display.height();
int y = 0;
int z = display.width();
for(t = 0 ; t <= 15; t+=1) {
display.drawTriangle(w, y, y, x, z, x, color);
x-=4;
y+=4;
z-=4;
color+=100;
}
}
void testroundrects() {
display.fillScreen(BLACK);
int color = 100;
int i;
int t;
for(t = 0 ; t <= 4; t+=1) {
int x = 0;
int y = 0;
int w = display.width();
int h = display.height();
for(i = 0 ; i <= 24; i+=1) {
display.drawRoundRect(x, y, w, h, 5, color);
x+=2;
y+=3;
w-=4;
h-=6;
color+=1100;
}
color+=100;
}
}
void tftPrintTest() {
display.fillScreen(BLACK);
display.setCursor(0, 5);
display.setTextColor(RED);
display.setTextSize(1);
display.println("Hello World!");
display.setTextColor(YELLOW, GREEN);
display.setTextSize(2);
display.print("Hello Wo");
display.setTextColor(BLUE);
display.setTextSize(3);
display.print(1234.567);
delay(1500);
display.setCursor(0, 5);
display.fillScreen(BLACK);
display.setTextColor(WHITE);
display.setTextSize(0);
display.println("Hello World!");
display.setTextSize(1);
display.setTextColor(GREEN);
display.print(p, 5);
display.println(" Want pi?");
display.print(8675309, HEX); // print 8,675,309 out in HEX!
display.print(" Print HEX");
display.setTextColor(WHITE);
display.println("Sketch has been");
display.println("running for: ");
display.setTextColor(MAGENTA);
display.print(millis() / 1000);
display.setTextColor(WHITE);
display.print(" seconds.");
}
void mediabuttons() {
// play
display.fillScreen(BLACK);
display.fillRoundRect(25, 10, 78, 60, 8, WHITE);
display.fillTriangle(42, 20, 42, 60, 90, 40, RED);
delay(500);
// pause
display.fillRoundRect(25, 90, 78, 60, 8, WHITE);
display.fillRoundRect(39, 98, 20, 45, 5, GREEN);
display.fillRoundRect(69, 98, 20, 45, 5, GREEN);
delay(500);
// play color
display.fillTriangle(42, 20, 42, 60, 90, 40, BLUE);
delay(50);
// pause color
display.fillRoundRect(39, 98, 20, 45, 5, RED);
display.fillRoundRect(69, 98, 20, 45, 5, RED);
// play color
display.fillTriangle(42, 20, 42, 60, 90, 40, GREEN);
}
/**************************************************************************/
/*!
@brief Renders a simple test pattern on the LCD
*/
/**************************************************************************/
void lcdTestPattern(void)
{
uint32_t i,j;
display.goTo(0, 0);
for(i=0;i<64;i++)
{
for(j=0;j<96;j++)
{
if(i>55){display.writeData(WHITE>>8);display.writeData(WHITE);}
else if(i>47){display.writeData(BLUE>>8);display.writeData(BLUE);}
else if(i>39){display.writeData(GREEN>>8);display.writeData(GREEN);}
else if(i>31){display.writeData(CYAN>>8);display.writeData(CYAN);}
else if(i>23){display.writeData(RED>>8);display.writeData(RED);}
else if(i>15){display.writeData(MAGENTA>>8);display.writeData(MAGENTA);}
else if(i>7){display.writeData(YELLOW>>8);display.writeData(YELLOW);}
else {display.writeData(BLACK>>8);display.writeData(BLACK);}
}
}
}
Пито
Сб 20 августа 2016 г., 6:44
Не беспокойтесь, наконец, кажется, что код достаточно, чтобы водить чип .. Таким образом, все хорошо в спецификации чипа, кроме того, вы можете попытаться оптимизировать код, чтобы ускорить его.
Под выходом анализатора при выполнении (Bluepill при 72 МГц)
Под выходом анализатора при выполнении (Bluepill при 72 МГц)
#ifndef _ADAFRUIT_GFX_H
#define _ADAFRUIT_GFX_H
#include "Load_fonts.h"
#if ARDUINO >= 100
#include "Arduino.h"
#include "Print.h"
#else
#include "WProgram.h"
#endif
#define swap(a, b) { int16_t t = a; a = b; b = t; }
class Adafruit_GFX : public Print {
public:
Adafruit_GFX(int16 w, int16 h); // Constructor
// This MUST be defined by the subclass:
virtual void drawPixel(int16 x, int16 y, uint16 color) = 0;
// These MAY be overridden by the subclass to provide device-specific
// optimized code. Otherwise 'generic' versions are used.
virtual void
drawLine(int16 x0, int16 y0, int16 x1, int16 y1, uint16 color),
drawFastVLine(int16 x, int16 y, int16 h, uint16 color),
drawFastHLine(int16 x, int16 y, int16 w, uint16 color),
drawRect(int16 x, int16 y, int16 w, int16 h, uint16 color),
fillRect(int16 x, int16 y, int16 w, int16 h, uint16 color),
fillScreen(uint16 color),
invertDisplay(boolean i);
// These exist only with Adafruit_GFX (no subclass overrides)
void
drawCircle(int16 x0, int16 y0, int16 r, uint16 color),
drawCircleHelper(int16 x0, int16 y0, int16 r, uint8_t cornername,
uint16 color),
fillCircle(int16 x0, int16 y0, int16 r, uint16 color),
fillCircleHelper(int16 x0, int16 y0, int16 r, uint8_t cornername,
int16 delta, uint16 color),
drawTriangle(int16 x0, int16 y0, int16 x1, int16 y1,
int16 x2, int16 y2, uint16 color),
fillTriangle(int16 x0, int16 y0, int16 x1, int16 y1,
int16 x2, int16 y2, uint16 color),
drawRoundRect(int16 x0, int16 y0, int16 w, int16 h,
int16 radius, uint16 color),
fillRoundRect(int16 x0, int16 y0, int16 w, int16 h,
int16 radius, uint16 color),
drawBitmap(int16 x, int16 y, const uint8_t *bitmap,
int16 w, int16 h, uint16 color),
drawChar(int16 x, int16 y, unsigned char c, uint16 color,
uint16 bg, uint8_t size),
setCursor(int16 x, int16 y),
setTextColor(uint16 c),
setTextColor(uint16 c, uint16 bg),
setTextSize(uint8 s),
setTextWrap(boolean w),
setRotation(uint8 r);
int16 drawUnicode(uint16 uniCode, int16 x, int16 y, int16 size);
int16 drawNumber(long long_num,int16 poX, int16 poY, int16 size);
int16 drawChar(char c, int16 x, int16 y, int16 size);
int16 drawString(char *string, int16 poX, int16 poY, int16 size);
int16 drawCentreString(char *string, int16 dX, int16 poY, int16 size);
int16 drawRightString(char *string, int16 dX, int16 poY, int16 size);
int16 drawFloat(float floatNumber,int16 decimal,int16 poX, int16 poY, int16 size);
#if ARDUINO >= 100
virtual size_t write(uint8);
#else
virtual void write(uint8);
#endif
int16
height(void),
width(void);
uint8 getRotation(void);
protected:
const int16
WIDTH, HEIGHT; // This is the 'raw' display w/h - never changes
int16
_width, _height, // Display w/h as modified by current rotation
cursor_x, cursor_y;
uint16
textcolor, textbgcolor;
uint8
textsize,
rotation;
boolean
wrap; // If set, 'wrap' text at right edge of display
};
#endif // _ADAFRUIT_GFX_H
Пито
Сб 20 августа 2016 г. 8:47
Это с самой быстрой настройкой/очисткой контактов (в 6 раз быстрее сдвиг, чем предыдущий код):
- shift19bit_fast.JPG (45.42 киб) просмотрено 441 раза
пионер
Ср 29 ноября 2017 г. 16:46
Привет, пито,
Это делает что -то по -другому, если я использую:
Это делает что -то по -другому, если я использую:
/*
This is the core graphics library for all our displays, providing a common
set of graphics primitives (points, lines, circles, etc.). It needs to be
paired with a hardware-specific library for each display device we carry
(to handle the lower-level functions).
Adafruit invests time and resources providing this open source code, please
support Adafruit & open-source hardware by purchasing products from Adafruit!
Copyright (c) 2013 Adafruit Industries. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "Adafruit_GFX_AS.h"
#ifdef LOAD_GLCD
#include "glcdfont.c"
#endif
#ifdef LOAD_FONT2
#include "Font16.h"
#endif
#ifdef LOAD_FONT4
#include "Font32.h"
#endif
#ifdef LOAD_FONT6
#include "Font64.h"
#endif
#ifdef LOAD_FONT7
#include "Font7s.h"
#endif
#ifdef __AVR__
#include
#else
#define pgm_read_byte(addr) (*(const unsigned char *)(addr))
#endif
Adafruit_GFX::Adafruit_GFX(int16_t w, int16_t h):
WIDTH(w), HEIGHT(h)
{
_width = WIDTH;
_height = HEIGHT;
rotation = 0;
cursor_y = cursor_x = 0;
textsize = 1;
textcolor = textbgcolor = 0xFFFF;
wrap = true;
}
// Draw a circle outline
void Adafruit_GFX::drawCircle(int16_t x0, int16_t y0, int16_t r,
uint16_t color) {
int16_t f = 1 - r;
int16_t ddF_x = 1;
int16_t ddF_y = -2 * r;
int16_t x = 0;
int16_t y = r;
drawPixel(x0 , y0+r, color);
drawPixel(x0 , y0-r, color);
drawPixel(x0+r, y0 , color);
drawPixel(x0-r, y0 , color);
while (x= 0) {
y--;
ddF_y += 2;
f += ddF_y;
}
x++;
ddF_x += 2;
f += ddF_x;
drawPixel(x0 + x, y0 + y, color);
drawPixel(x0 - x, y0 + y, color);
drawPixel(x0 + x, y0 - y, color);
drawPixel(x0 - x, y0 - y, color);
drawPixel(x0 + y, y0 + x, color);
drawPixel(x0 - y, y0 + x, color);
drawPixel(x0 + y, y0 - x, color);
drawPixel(x0 - y, y0 - x, color);
}
}
void Adafruit_GFX::drawCircleHelper( int16_t x0, int16_t y0,
int16_t r, uint8_t cornername, uint16_t color) {
int16_t f = 1 - r;
int16_t ddF_x = 1;
int16_t ddF_y = -2 * r;
int16_t x = 0;
int16_t y = r;
while (x= 0) {
y--;
ddF_y += 2;
f += ddF_y;
}
x++;
ddF_x += 2;
f += ddF_x;
if (cornername & 0x4) {
drawPixel(x0 + x, y0 + y, color);
drawPixel(x0 + y, y0 + x, color);
}
if (cornername & 0x2) {
drawPixel(x0 + x, y0 - y, color);
drawPixel(x0 + y, y0 - x, color);
}
if (cornername & 0x8) {
drawPixel(x0 - y, y0 + x, color);
drawPixel(x0 - x, y0 + y, color);
}
if (cornername & 0x1) {
drawPixel(x0 - y, y0 - x, color);
drawPixel(x0 - x, y0 - y, color);
}
}
}
void Adafruit_GFX::fillCircle(int16_t x0, int16_t y0, int16_t r,
uint16_t color) {
drawFastVLine(x0, y0-r, 2*r+1, color);
fillCircleHelper(x0, y0, r, 3, 0, color);
}
// Used to do circles and roundrects
void Adafruit_GFX::fillCircleHelper(int16_t x0, int16_t y0, int16_t r,
uint8_t cornername, int16_t delta, uint16_t color) {
int16_t f = 1 - r;
int16_t ddF_x = 1;
int16_t ddF_y = -2 * r;
int16_t x = 0;
int16_t y = r;
while (x= 0) {
y--;
ddF_y += 2;
f += ddF_y;
}
x++;
ddF_x += 2;
f += ddF_x;
if (cornername & 0x1) {
drawFastVLine(x0+x, y0-y, 2*y+1+delta, color);
drawFastVLine(x0+y, y0-x, 2*x+1+delta, color);
}
if (cornername & 0x2) {
drawFastVLine(x0-x, y0-y, 2*y+1+delta, color);
drawFastVLine(x0-y, y0-x, 2*x+1+delta, color);
}
}
}
// Bresenham's algorithm - thx wikpedia
void Adafruit_GFX::drawLine(int16_t x0, int16_t y0,
int16_t x1, int16_t y1,
uint16_t color) {
int16_t steep = abs(y1 - y0) > abs(x1 - x0);
if (steep) {
swap(x0, y0);
swap(x1, y1);
}
if (x0 > x1) {
swap(x0, x1);
swap(y0, y1);
}
int16_t dx, dy;
dx = x1 - x0;
dy = abs(y1 - y0);
int16_t err = dx / 2;
int16_t ystep;
if (y0 < y1) {
ystep = 1;
} else {
ystep = -1;
}
for (; x0<=x1; x0++) {
if (steep) {
drawPixel(y0, x0, color);
} else {
drawPixel(x0, y0, color);
}
err -= dy;
if (err < 0) {
y0 += ystep;
err += dx;
}
}
}
// Draw a rectangle
void Adafruit_GFX::drawRect(int16_t x, int16_t y,
int16_t w, int16_t h,
uint16_t color) {
drawFastHLine(x, y, w, color);
drawFastHLine(x, y+h-1, w, color);
drawFastVLine(x, y, h, color);
drawFastVLine(x+w-1, y, h, color);
}
void Adafruit_GFX::drawFastVLine(int16_t x, int16_t y,
int16_t h, uint16_t color) {
// Update in subclasses if desired!
drawLine(x, y, x, y+h-1, color);
}
void Adafruit_GFX::drawFastHLine(int16_t x, int16_t y,
int16_t w, uint16_t color) {
// Update in subclasses if desired!
drawLine(x, y, x+w-1, y, color);
}
void Adafruit_GFX::fillRect(int16_t x, int16_t y, int16_t w, int16_t h,
uint16_t color) {
// Update in subclasses if desired!
for (int16_t i=x; i= y1 >= y0)
if (y0 > y1) {
swap(y0, y1); swap(x0, x1);
}
if (y1 > y2) {
swap(y2, y1); swap(x2, x1);
}
if (y0 > y1) {
swap(y0, y1); swap(x0, x1);
}
if(y0 == y2) { // Handle awkward all-on-same-line case as its own thing
a = b = x0;
if(x1 < a) a = x1;
else if(x1 > b) b = x1;
if(x2 < a) a = x2;
else if(x2 > b) b = x2;
drawFastHLine(a, y0, b-a+1, color);
return;
}
int16_t
dx01 = x1 - x0,
dy01 = y1 - y0,
dx02 = x2 - x0,
dy02 = y2 - y0,
dx12 = x2 - x1,
dy12 = y2 - y1,
sa = 0,
sb = 0;
// For upper part of triangle, find scanline crossings for segments
// 0-1 and 0-2. If y1=y2 (flat-bottomed triangle), the scanline y1
// is included here (and second loop will be skipped, avoiding a /0
// error there), otherwise scanline y1 is skipped here and handled
// in the second loop...which also avoids a /0 error here if y0=y1
// (flat-topped triangle).
if(y1 == y2) last = y1; // Include y1 scanline
else last = y1-1; // Skip it
for(y=y0; y<=last; y++) {
a = x0 + sa / dy01;
b = x0 + sb / dy02;
sa += dx01;
sb += dx02;
/* longhand:
a = x0 + (x1 - x0) * (y - y0) / (y1 - y0);
b = x0 + (x2 - x0) * (y - y0) / (y2 - y0);
*/
if(a > b) swap(a,b);
drawFastHLine(a, y, b-a+1, color);
}
// For lower part of triangle, find scanline crossings for segments
// 0-2 and 1-2. This loop is skipped if y1=y2.
sa = dx12 * (y - y1);
sb = dx02 * (y - y0);
for(; y<=y2; y++) {
a = x1 + sa / dy12;
b = x0 + sb / dy02;
sa += dx12;
sb += dx02;
/* longhand:
a = x1 + (x2 - x1) * (y - y1) / (y2 - y1);
b = x0 + (x2 - x0) * (y - y0) / (y2 - y0);
*/
if(a > b) swap(a,b);
drawFastHLine(a, y, b-a+1, color);
}
}
void Adafruit_GFX::drawBitmap(int16_t x, int16_t y,
const uint8_t *bitmap, int16_t w, int16_t h,
uint16_t color) {
int16_t i, j, byteWidth = (w + 7) / 8;
for(j=0; j> (i & 7))) {
drawPixel(x+i, y+j, color);
}
}
}
}
//#if ARDUINO >= 100
size_t Adafruit_GFX::write(uint8_t c) {
//#else
//void Adafruit_GFX::write(uint8_t c) {
//#endif
if (c == '\n') {
cursor_y += textsize*8;
cursor_x = 0;
} else if (c == '\r') {
// skip em
} else {
drawChar(cursor_x, cursor_y, c, textcolor, textbgcolor, textsize);
cursor_x += textsize*6;
if (wrap && (cursor_x > (_width - textsize*6))) {
cursor_y += textsize*8;
cursor_x = 0;
}
}
//#if ARDUINO >= 100
return 1;
//#endif
}
// Draw a character
void Adafruit_GFX::drawChar(int16_t x, int16_t y, unsigned char c,
uint16_t color, uint16_t bg, uint8_t size) {
#ifdef LOAD_GLCD
if((x >= _width) || // Clip right
(y >= _height) || // Clip bottom
((x + 6 * size - 1) < 0) || // Clip left
((y + 8 * size - 1) < 0)) // Clip top
return;
for (int8_t i=0; i<6; i++ ) {
uint8_t line;
if (i == 5)
line = 0x0;
else
line = pgm_read_byte(font+(c*5)+i);
for (int8_t j = 0; j<8; j++) {
if (line & 0x1) {
if (size == 1) // default size
drawPixel(x+i, y+j, color);
else { // big size
fillRect(x+(i*size), y+(j*size), size, size, color);
}
} else if (bg != color) {
if (size == 1) // default size
drawPixel(x+i, y+j, bg);
else { // big size
fillRect(x+i*size, y+j*size, size, size, bg);
}
}
line >>= 1;
}
}
#endif
}
void Adafruit_GFX::setCursor(int16_t x, int16_t y) {
cursor_x = x;
cursor_y = y;
}
void Adafruit_GFX::setTextSize(uint8_t s) {
textsize = (s > 0) ? s : 1;
}
void Adafruit_GFX::setTextColor(uint16_t c) {
// For 'transparent' background, we'll set the bg
// to the same as fg instead of using a flag
textcolor = textbgcolor = c;
}
void Adafruit_GFX::setTextColor(uint16_t c, uint16_t b) {
textcolor = c;
textbgcolor = b;
}
void Adafruit_GFX::setTextWrap(boolean w) {
wrap = w;
}
uint8_t Adafruit_GFX::getRotation(void) {
return rotation;
}
void Adafruit_GFX::setRotation(uint8_t x) {
rotation = (x & 3);
switch(rotation) {
case 0:
case 2:
_width = WIDTH;
_height = HEIGHT;
break;
case 1:
case 3:
_width = HEIGHT;
_height = WIDTH;
break;
}
}
// Return the size of the display (per current rotation)
int16_t Adafruit_GFX::width(void) {
return _width;
}
int16_t Adafruit_GFX::height(void) {
return _height;
}
void Adafruit_GFX::invertDisplay(boolean i) {
// Do nothing, must be subclassed if supported
}
/***************************************************************************************
** Function name: drawUnicode
** Descriptions: draw a unicode
***************************************************************************************/
int16_t Adafruit_GFX::drawUnicode(uint16_t uniCode, int16_t x, int16_t y, int16_t size)
{
if (size) uniCode -= 32;
uint16_t width = 0;
uint16_t height = 0;
uint32_t flash_address = 0;
int16_t gap = 0;
// if (size == 1) {
// flash_address = pgm_read_dword(&chrtbl_f8[uniCode]);
// width = pgm_read_byte(widtbl_f8+uniCode);
// height = chr_hgt_f8;
// gap = 1;
// }
#ifdef LOAD_FONT2
if (size == 2) {
flash_address = pgm_read_dword(&chrtbl_f16[uniCode]);
width = pgm_read_byte(widtbl_f16+uniCode);
height = chr_hgt_f16;
gap = 1;
}
#endif
// if (size == 3) {
// flash_address = pgm_read_dword(&chrtbl_f24[uniCode]);
// width = pgm_read_byte(widtbl_f24+uniCode);
// height = chr_hgt_f24;
// gap = 0;
// }
#ifdef LOAD_FONT4
if (size == 4) {
flash_address = pgm_read_dword(&chrtbl_f32[uniCode]);
width = pgm_read_byte(widtbl_f32+uniCode);
height = chr_hgt_f32;
gap = -3;
}
#endif
// if (size == 5) {
// flash_address = pgm_read_dword(&chrtbl_f48[uniCode]);
// width = pgm_read_byte(widtbl_f48+uniCode);
// height = chr_hgt_f48;
// gap = -3;
// }
#ifdef LOAD_FONT6
if (size == 6) {
flash_address = pgm_read_dword(&chrtbl_f64[uniCode]);
width = pgm_read_byte(widtbl_f64+uniCode);
height = chr_hgt_f64;
gap = -3;
}
#endif
#ifdef LOAD_FONT7
if (size == 7) {
flash_address = pgm_read_dword(&chrtbl_f7s[uniCode]);
width = pgm_read_byte(widtbl_f7s+uniCode);
height = chr_hgt_f7s;
gap = 2;
}
#endif
int16_t w = (width+7)/8;
int16_t pX = 0;
int16_t pY = y;
int16_t color = 0;
byte line = 0;
//fillRect(x,pY,width+gap,height,textbgcolor);
for(int16_t i=0; i0)
{
xPlus = drawChar('.',poX, poY, size);
poX += xPlus; /* Move cursor right */
sumX += xPlus;
}
else
{
return sumX;
}
decy = floatNumber - temp;
for(unsigned char i=0; i
victor_pv
Ср 29 ноября 2017 г., 19:20
Согласно собственной странице Allegro, этот драйвер использует SPI:
http: // www.Allegromicro.com/en/продукты ... Ivers.aspx
Поскольку он использует и необычайно лишню, 19 бит, мне интересно, можете ли вы наладить 0 с 0 с.
Я не смог найти ссылку на это, но если бы я был вами, я бы попробовал посмотреть, работает ли это.
Бьюсь об закладку, накладка 0s работает нормально, либо до MSB, либо после LSB. Вероятно, только в 1 случае, не оба, но этого достаточно. Если это так, вы можете отформатировать свои данные и отправить их с портом SPI.
http: // www.Allegromicro.com/en/продукты ... Ivers.aspx
Поскольку он использует и необычайно лишню, 19 бит, мне интересно, можете ли вы наладить 0 с 0 с.
Я не смог найти ссылку на это, но если бы я был вами, я бы попробовал посмотреть, работает ли это.
Бьюсь об закладку, накладка 0s работает нормально, либо до MSB, либо после LSB. Вероятно, только в 1 случае, не оба, но этого достаточно. Если это так, вы можете отформатировать свои данные и отправить их с портом SPI.
AG123
Чт 17 мая 2018 г., 16:38
Переплит эту старую ветку, я намереваюсь связываться с Shift Registers E, G, 74HC595, 74HC165
https: // активы.Nexperia.com/документы/D ... HCT595.PDF
Скорее всего, я просто потерте их. SPI хорош, но для начала я бы попробовал что -то «сырое».
Имеет ли это значение, если эти биловые часы, управляющие регистром смены, используйте те тонкие шипы, как в схеме синхронизации Пито?
Сделать часы похожи на эти равномерно распределенные часы / диаграммы синхронизации на листах данных, казалось, довольно сложно сделать сбитым ударом
& Это может сохранить скорости довольно низко, так как 1 прыжок вокруг петли, кажется, немного по сравнению с этим тонким тактовым импульсом
(О, у меня есть идея, я мог бы сделать тактовой импульс на тонкой ступеньке и оставить его высоким для паузы с большой жирной
Только что обнаружили, что 74HC595 Shift Registers довольно дешевы на AliexPress, и они получают около 10 штук за ~ 50C (доставка включена в некоторые случаи)
https: // www.aliexpress.com/w/wholesale-74hc595.HTML
Думаю, это делает довольно приличные «Expanders» E.глин. Как моторный щит Adafruit
https: // учиться.Адафрут.com/adafruit-motor-shield
https: // активы.Nexperia.com/документы/D ... HCT595.PDF
Скорее всего, я просто потерте их. SPI хорош, но для начала я бы попробовал что -то «сырое».
Имеет ли это значение, если эти биловые часы, управляющие регистром смены, используйте те тонкие шипы, как в схеме синхронизации Пито?
Сделать часы похожи на эти равномерно распределенные часы / диаграммы синхронизации на листах данных, казалось, довольно сложно сделать сбитым ударом
& Это может сохранить скорости довольно низко, так как 1 прыжок вокруг петли, кажется, немного по сравнению с этим тонким тактовым импульсом
(О, у меня есть идея, я мог бы сделать тактовой импульс на тонкой ступеньке и оставить его высоким для паузы с большой жирной
Только что обнаружили, что 74HC595 Shift Registers довольно дешевы на AliexPress, и они получают около 10 штук за ~ 50C (доставка включена в некоторые случаи)
https: // www.aliexpress.com/w/wholesale-74hc595.HTML
Думаю, это делает довольно приличные «Expanders» E.глин. Как моторный щит Adafruit
https: // учиться.Адафрут.com/adafruit-motor-shield
Rogerclark
Чт 17 мая 2018 г., 21:47
Если вы просто хотите больше io. С использованием. STM32F103V или STM32F103Z POARD даст вам гораздо больше IO.
Хотя по большей стоимости, чем регистры смены BP Plus
Хотя по большей стоимости, чем регистры смены BP Plus
Мадиас
Чт 17 мая 2018 г., 22:19
74HC595 был первым чипом, который я сыграл с началом обучения Arduino. Тем временем я больше не хочу паять через чипсы отверстия...И это беспорядок (проводка) с регистрами смены, если вы не сделаете его SMD с печатной платой. Роджер прав: нет реальной выгоды, потому что «большие» платы STM32F1 ничего не стоят почти и не тратят меньше места.
AG123
Пт 18 мая 2018 г. 1:54
Спасибо, у меня есть черная доска «супер быстро» STM32F407V & куча синих таблеток / maple mini,
Пришлось сказать, что форм -фактор BP/MM очень привлекателен как часть причины и после того, как наткнулся на $ 0.50 для регистров смены 10x74HC595, я стал достаточно импульсивным и получил несколько регистров смены. Планируйте использовать их на клавиатуре с BP/MM
Я думаю, что регистры Shift играют полезную роль с BP/MM, экономит много булавок для вещей, которые не нужны для скоростей MHZ (E.глин. Ключевые прокладки, светодиоды, 7 светодиодов SEG, 1602 ЖК -дисплей и т. Д.)
Другое дело, что регистры Shift позволяют разделить «конечности» (периферийные) от «мозга» (MCU), чтобы можно было поменять MCU по желанию и все еще подключаться к тому же периферическому модулю
Пришлось сказать, что форм -фактор BP/MM очень привлекателен как часть причины и после того, как наткнулся на $ 0.50 для регистров смены 10x74HC595, я стал достаточно импульсивным и получил несколько регистров смены. Планируйте использовать их на клавиатуре с BP/MM
Я думаю, что регистры Shift играют полезную роль с BP/MM, экономит много булавок для вещей, которые не нужны для скоростей MHZ (E.глин. Ключевые прокладки, светодиоды, 7 светодиодов SEG, 1602 ЖК -дисплей и т. Д.)
Другое дело, что регистры Shift позволяют разделить «конечности» (периферийные) от «мозга» (MCU), чтобы можно было поменять MCU по желанию и все еще подключаться к тому же периферическому модулю
Rogerclark
Пт 18 мая 2018 г., 2:03
ХОРОШО
Я просто думал, что упомяну, если у тебя не было ни одной из досок серии V
Я просто думал, что упомяну, если у тебя не было ни одной из досок серии V