Error swap was not declared in this scope

I'm using arduino IDE 1.6.6 with arduino uno. All examples sort the same error C:UsersEraldoDocumentsArduinolibrariesSWTFTSWTFT.cpp: In member function 'void SWTFT::drawLine3Byte(int...

@ik5qpw

I’m using arduino IDE 1.6.6 with arduino uno. All examples sort the same error

C:UsersEraldoDocumentsArduinolibrariesSWTFTSWTFT.cpp: In member function ‘void SWTFT::drawLine3Byte(int16_t, int16_t, int16_t, int16_t, uint8_t, uint8_t, uint8_t)’:

C:UsersEraldoDocumentsArduinolibrariesSWTFTSWTFT.cpp:629:16: error: ‘swap’ was not declared in this scope

C:UsersEraldoDocumentsArduinolibrariesSWTFTSWTFT.cpp:634:16: error: ‘swap’ was not declared in this scope

exit status 1
Errore durante la compilazione

Anyone has an idea? Thanks

@donpedro43

Hi,
You just have to add bottom line in SWIFT.cpp file.
#define swap(a, b) { int16_t t = a; a = b; b = t; }

Cheers!

@christopherlange1110

Tried that didn’t work for me?`
#ifndef writeRegister8
void SWTFT::writeRegister8(uint8_t a, uint8_t d) {
writeRegister8inline(a, d);
}
#endif

#ifndef writeRegister16
void SWTFT::writeRegister16(uint16_t a, uint16_t d) {
writeRegister16inline(a, d);
}
#endif

#ifndef writeRegisterPair
void SWTFT::writeRegisterPair(uint8_t aH, uint8_t aL, uint16_t d) {
writeRegisterPairInline(aH, aL, d);
}
#endif

#define swap(a, b) { int16_t t = a; a = b; b = t; }`

@donpedro43

You have to add this line at the top of file for example like this:
`// Code provided by Smoke And Wires
// http://www.smokeandwires.co.nz
// This code has been taken from the Adafruit TFT Library and modified
// by us for use with our TFT Shields / Modules
// For original code / licensing please refer to
// https://github.com/adafruit/TFTLCD-Library

#include <avr/pgmspace.h>

#include «pins_arduino.h»
#include «wiring_private.h»
#include «SWTFT.h»

// Use the include which corresponde to your arduino
//#include «mega_24_shield.h»
#include «uno_24_shield.h»

#define TFTWIDTH 240
#define TFTHEIGHT 320
#define swap(a, b) { int16_t t = a; a = b; b = t; }

// Constructor for breakout board (configurable LCD control lines).
// Can still use this w/shield, but parameters are ignored.
SWTFT::SWTFT() : Adafruit_GFX(TFTWIDTH, TFTHEIGHT) {
`

@Reuben673

I tried this, but still no luck- help!
here is the file’s contents (it said the error was in SWTFT.cpp):
// Code provided by Smoke And Wires
// http://www.smokeandwires.co.nz
// This code has been taken from the Adafruit TFT Library and modified
// by us for use with our TFT Shields / Modules
// For original code / licensing please refer to
// https://github.com/adafruit/TFTLCD-Library

#include <avr/pgmspace.h>

#include «pins_arduino.h»
#include «wiring_private.h»
#include «SWTFT.h»

// Use the include which corresponde to your arduino
//#include «mega_24_shield.h»
#include «uno_24_shield.h»

#define TFTWIDTH 240
#define TFTHEIGHT 320
#define swap(a, b) { int16_t t = a; a = b; b = t; }
// Constructor for breakout board (configurable LCD control lines).
// Can still use this w/shield, but parameters are ignored.
SWTFT::SWTFT() : Adafruit_GFX(TFTWIDTH, TFTHEIGHT) {

// Convert pin numbers to registers and bitmasks
_reset = LCD_RESET;

csPort     = portOutputRegister(digitalPinToPort(LCD_CS));
cdPort     = portOutputRegister(digitalPinToPort(LCD_CD));
wrPort     = portOutputRegister(digitalPinToPort(LCD_WR));
rdPort     = portOutputRegister(digitalPinToPort(LCD_RD));

csPinSet = digitalPinToBitMask(LCD_CS);
cdPinSet = digitalPinToBitMask(LCD_CD);
wrPinSet = digitalPinToBitMask(LCD_WR);
rdPinSet = digitalPinToBitMask(LCD_RD);
csPinUnset = ~csPinSet;
cdPinUnset = ~cdPinSet;
wrPinUnset = ~wrPinSet;
rdPinUnset = ~rdPinSet;

*csPort   |=  csPinSet; // Set all control bits to HIGH (idle)
*cdPort   |=  cdPinSet; // Signals are ACTIVE LOW
*wrPort   |=  wrPinSet;
*rdPort   |=  rdPinSet;

pinMode(LCD_CS, OUTPUT); // Enable outputs
pinMode(LCD_CD, OUTPUT);
pinMode(LCD_WR, OUTPUT);
pinMode(LCD_RD, OUTPUT);
// if(reset) {
digitalWrite(LCD_RESET, HIGH);
pinMode(LCD_RESET, OUTPUT);
// }

init();
}

void SWTFT::init(void) {

setWriteDir(); // Set up LCD data port(s) for WRITE operations

rotation = 0;
cursor_y = cursor_x = 0;
textsize = 1;
textcolor = 0xFFFF;
_width = TFTWIDTH;
_height = TFTHEIGHT;
}

// // Initialization command table for LCD controller
#define TFTLCD_DELAY 0xFF

static const uint16_t ST7781_regValues[] PROGMEM = {
0x0001,0x0100,
0x0002,0x0700,
0x0003,0x1030,
0x0008,0x0302,
0x0009,0x0000,
0x000A,0x0008,
//_POWER CONTROL REGISTER INITIAL__//
0x0010,0x0790,
0x0011,0x0005,
0x0012,0x0000,
0x0013,0x0000,
//delayms(50,
//
_****_POWER SUPPPLY STARTUP 1 SETTING****//
0x0010,0x12B0,
// delayms(50,
0x0011,0x0007,
//delayms(50,
//_****_POWER SUPPLY STARTUP 2 SETTING**//
0x0012,0x008C,
0x0013,0x1700,
0x0029,0x0022,
// delayms(50,
//_GAMMA CLUSTER SETTING**_//
0x0030,0x0000,
0x0031,0x0505,
0x0032,0x0205,
0x0035,0x0206,
0x0036,0x0408,
0x0037,0x0000,
0x0038,0x0504,
0x0039,0x0206,
0x003C,0x0206,
0x003D,0x0408,
// ————DISPLAY WINDOWS 240_320————-//
0x0050,0x0000,
0x0051,0x00EF,
0x0052,0x0000,
0x0053,0x013F,
//——FRAME RATE SETTING——-//
0x0060,0xA700,
0x0061,0x0001,
0x0090,0x0033, //RTNI setting
//——-DISPLAY ON——//
0x0007,0x0133, 0x0001,0x0100,
0x0002,0x0700,
0x0003,0x1030,
0x0008,0x0302,
0x0009,0x0000,
0x000A,0x0008,
//
_POWER CONTROL REGISTER INITIAL__//
0x0010,0x0790,
0x0011,0x0005,
0x0012,0x0000,
0x0013,0x0000,
//delayms(50,
//
_****_POWER SUPPPLY STARTUP 1 SETTING****//
0x0010,0x12B0,
// delayms(50,
0x0011,0x0007,
// delayms(50,
//_****_POWER SUPPLY STARTUP 2 SETTING**//
0x0012,0x008C,
0x0013,0x1700,
0x0029,0x0022,
// delayms(50,
//_GAMMA CLUSTER SETTING****_//
0x0030,0x0000,
0x0031,0x0505,
0x0032,0x0205,
0x0035,0x0206,
0x0036,0x0408,
0x0037,0x0000,
0x0038,0x0504,
0x0039,0x0206,
0x003C,0x0206,
0x003D,0x0408,
// ————DISPLAY WINDOWS 240_320————-//
0x0050,0x0000,
0x0051,0x00EF,
0x0052,0x0000,
0x0053,0x013F,
//——FRAME RATE SETTING——-//
0x0060,0xA700,
0x0061,0x0001,
0x0090,0x0033, //RTNI setting
//——-DISPLAY ON——//
0x0007,0x0133,
};

void SWTFT::begin(uint16_t id) {
uint8_t i = 0;

reset();

// driver = ID_932X;
CS_ACTIVE;
while(i < sizeof(ST7781_regValues) / sizeof(uint16_t)) {
a = pgm_read_word(&ST7781_regValues[i++]);
d = pgm_read_word(&ST7781_regValues[i++]);
if(a == TFTLCD_DELAY) delay(d);
else writeRegister16(a, d);
}
setRotation(rotation);
setAddrWindow(0, 0, TFTWIDTH-1, TFTHEIGHT-1);

}

void SWTFT::reset(void) {

CS_IDLE;
// CD_DATA;
WR_IDLE;
RD_IDLE;

if(_reset) {
digitalWrite(_reset, LOW);
delay(2);
digitalWrite(_reset, HIGH);
}

// Data transfer sync
CS_ACTIVE;
CD_COMMAND;
write8(0x00);
for(uint8_t i=0; i<3; i++) WR_STROBE; // Three extra 0x00s
CS_IDLE;
}

// Sets the LCD address window (and address counter, on 932X).
// Relevant to rect/screen fills and H/V lines. Input coordinates are
// assumed pre-sorted (e.g. x2 >= x1).
void SWTFT::setAddrWindow(int x1, int y1, int x2, int y2) {

CS_ACTIVE;

// Values passed are in current (possibly rotated) coordinate
// system.  932X requires hardware-native coords regardless of
// MADCTL, so rotate inputs as needed.  The address counter is
// set to the top-left corner -- although fill operations can be
// done in any direction, the current screen rotation is applied
// because some users find it disconcerting when a fill does not
// occur top-to-bottom.
int x, y, t;
switch(rotation) {
 default:
  x  = x1;
  y  = y1;
  break;
 case 1:
  t  = y1;
  y1 = x1;
  x1 = TFTWIDTH  - 1 - y2;
  y2 = x2;
  x2 = TFTWIDTH  - 1 - t;
  x  = x2;
  y  = y1;
  break;
 case 2:
  t  = x1;
  x1 = TFTWIDTH  - 1 - x2;
  x2 = TFTWIDTH  - 1 - t;
  t  = y1;
  y1 = TFTHEIGHT - 1 - y2;
  y2 = TFTHEIGHT - 1 - t;
  x  = x2;
  y  = y2;
  break;
 case 3:
  t  = x1;
  x1 = y1;
  y1 = TFTHEIGHT - 1 - x2;
  x2 = y2;
  y2 = TFTHEIGHT - 1 - t;
  x  = x1;
  y  = y2;
  break;
}
writeRegister16(0x0050, x1); // Set address window
writeRegister16(0x0051, x2);
writeRegister16(0x0052, y1);
writeRegister16(0x0053, y2);
writeRegister16(0x0020, x ); // Set address counter to top left
writeRegister16(0x0021, y );

CS_IDLE;
}

// Unlike the 932X drivers that set the address window to the full screen
// by default (using the address counter for drawPixel operations), the
// 7575 needs the address window set on all graphics operations. In order
// to save a few register writes on each pixel drawn, the lower-right
// corner of the address window is reset after most fill operations, so
// that drawPixel only needs to change the upper left each time.
void SWTFT::setLR(void) {
CS_ACTIVE;
// writeRegisterPair(HX8347G_COLADDREND_HI, HX8347G_COLADDREND_LO, _width — 1);
// writeRegisterPair(HX8347G_ROWADDREND_HI, HX8347G_ROWADDREND_LO, _height — 1);
CS_IDLE;
}

// Fast block fill operation for fillScreen, fillRect, H/V line, etc.
// Requires setAddrWindow() has previously been called to set the fill
// bounds. ‘len’ is inclusive, MUST be >= 1.
void SWTFT::flood(uint16_t color, uint32_t len) {
uint16_t blocks;
uint8_t i, hi = color >> 8,
lo = color;

CS_ACTIVE;
CD_COMMAND;
write8(0x00); // High byte of GRAM register…
write8(0x22); // Write data to GRAM

// Write first pixel normally, decrement counter by 1
CD_DATA;
write8(hi);
write8(lo);
len—;

blocks = (uint16_t)(len / 64); // 64 pixels/block
if(hi == lo) {
// High and low bytes are identical. Leave prior data
// on the port(s) and just toggle the write strobe.
while(blocks—) {
i = 16; // 64 pixels/block / 4 pixels/pass
do {
WR_STROBE; WR_STROBE; WR_STROBE; WR_STROBE; // 2 bytes/pixel
WR_STROBE; WR_STROBE; WR_STROBE; WR_STROBE; // x 4 pixels
} while(—i);
}
// Fill any remaining pixels (1 to 64)
for(i = (uint8_t)len & 63; i—; ) {
WR_STROBE;
WR_STROBE;
}
} else {
while(blocks—) {
i = 16; // 64 pixels/block / 4 pixels/pass
do {
write8(hi); write8(lo); write8(hi); write8(lo);
write8(hi); write8(lo); write8(hi); write8(lo);
} while(—i);
}
for(i = (uint8_t)len & 63; i—; ) {
write8(hi);
write8(lo);
}
}
CS_IDLE;
}

void SWTFT::drawFastHLine(int16_t x, int16_t y, int16_t length,
uint16_t color)
{
int16_t x2;

// Initial off-screen clipping
if((length <= 0 ) ||
(y < 0 ) || ( y >= _height) ||
(x >= _width) || ((x2 = (x+length-1)) < 0 )) return;

if(x < 0) { // Clip left
length += x;
x = 0;
}
if(x2 >= _width) { // Clip right
x2 = _width — 1;
length = x2 — x + 1;
}

setAddrWindow(x, y, x2, y);
flood(color, length);
setAddrWindow(0, 0, _width — 1, _height — 1);

}

void SWTFT::drawFastVLine(int16_t x, int16_t y, int16_t length,
uint16_t color)
{
int16_t y2;

// Initial off-screen clipping
if((length <= 0 ) ||
(x < 0 ) || ( x >= _width) ||
(y >= _height) || ((y2 = (y+length-1)) < 0 )) return;
if(y < 0) { // Clip top
length += y;
y = 0;
}
if(y2 >= _height) { // Clip bottom
y2 = _height — 1;
length = y2 — y + 1;
}

setAddrWindow(x, y, x, y2);
flood(color, length);
setAddrWindow(0, 0, _width — 1, _height — 1);

}

void SWTFT::fillRect(int16_t x1, int16_t y1, int16_t w, int16_t h,
uint16_t fillcolor) {
int16_t x2, y2;

// Initial off-screen clipping
if( (w <= 0 ) || (h <= 0 ) ||
(x1 >= _width) || (y1 >= _height) ||
((x2 = x1+w-1) < 0 ) || ((y2 = y1+h-1) < 0 )) return;
if(x1 < 0) { // Clip left
w += x1;
x1 = 0;
}
if(y1 < 0) { // Clip top
h += y1;
y1 = 0;
}
if(x2 >= _width) { // Clip right
x2 = _width — 1;
w = x2 — x1 + 1;
}
if(y2 >= _height) { // Clip bottom
y2 = _height — 1;
h = y2 — y1 + 1;
}

setAddrWindow(x1, y1, x2, y2);
flood(fillcolor, (uint32_t)w * (uint32_t)h);
setAddrWindow(0, 0, _width — 1, _height — 1);

}

void SWTFT::fillScreen(uint16_t color) {

// For the 932X, a full-screen address window is already the default
// state, just need to set the address pointer to the top-left corner.
// Although we could fill in any direction, the code uses the current
// screen rotation because some users find it disconcerting when a
// fill does not occur top-to-bottom.
uint16_t x, y;
switch(rotation) {
  default: x = 0            ; y = 0            ; break;
  case 1 : x = TFTWIDTH  - 1; y = 0            ; break;
  case 2 : x = TFTWIDTH  - 1; y = TFTHEIGHT - 1; break;
  case 3 : x = 0            ; y = TFTHEIGHT - 1; break;
}
CS_ACTIVE;
writeRegister16(0x0020, x);
writeRegister16(0x0021, y);

flood(color, (long)TFTWIDTH * (long)TFTHEIGHT);
}

void SWTFT::drawPixel(int16_t x, int16_t y, uint16_t color) {

// Clip
if((x < 0) || (y < 0) || (x >= _width) || (y >= _height)) return;

CS_ACTIVE;

int16_t t;
switch(rotation) {
 case 1:
  t = x;
  x = TFTWIDTH  - 1 - y;
  y = t;
  break;
 case 2:
  x = TFTWIDTH  - 1 - x;
  y = TFTHEIGHT - 1 - y;
  break;
 case 3:
  t = x;
  x = y;
  y = TFTHEIGHT - 1 - t;
  break;
}
writeRegister16(0x0020, x);
writeRegister16(0x0021, y);
writeRegister16(0x0022, color );

CS_IDLE;
}

// Issues ‘raw’ an array of 16-bit color values to the LCD; used
// externally by BMP examples. Assumes that setWindowAddr() has
// previously been set to define the bounds. Max 255 pixels at
// a time (BMP examples read in small chunks due to limited RAM).
void SWTFT::pushColors(uint16_t *data, uint8_t len, boolean first) {
uint16_t color;
uint8_t hi, lo;
CS_ACTIVE;
if(first == true) { // Issue GRAM write command only on first call
CD_COMMAND;
write8(0x00);
write8(0x22);
}
CD_DATA;
while(len—) {
color = *data++;
hi = color >> 8; // Don’t simplify or merge these
lo = color; // lines, there’s macro shenanigans
write8(hi); // going on.
write8(lo);
}
CS_IDLE;
}

void SWTFT::setRotation(uint8_t x) {

// Call parent rotation func first — sets up rotation flags, etc.
Adafruit_GFX::setRotation(x);
// Then perform hardware-specific rotation operations…

CS_ACTIVE;

// uint16_t t;
// switch(rotation) {
// default: t = 0x1030; break;
// case 1 : t = 0x1028; break;
// case 2 : t = 0x1000; break;
// case 3 : t = 0x1018; break;
// }
// writeRegister16(0x0003, t ); // MADCTL
// For 932X, init default full-screen address window:
// setAddrWindow(0, 0, _width — 1, _height — 1); // CS_IDLE happens here

}

#ifdef read8isFunctionalized
#define read8(x) x=read8fn()
#endif

// Because this function is used infrequently, it configures the ports for
// the read operation, reads the data, then restores the ports to the write
// configuration. Write operations happen a LOT, so it’s advantageous to
// leave the ports in that state as a default.
uint16_t SWTFT::readPixel(int16_t x, int16_t y) {

if((x < 0) || (y < 0) || (x >= _width) || (y >= _height)) return 0;

CS_ACTIVE;

uint8_t hi, lo;
int16_t t;
switch(rotation) {
 case 1:
  t = x;
  x = TFTWIDTH  - 1 - y;
  y = t;
  break;
 case 2:
  x = TFTWIDTH  - 1 - x;
  y = TFTHEIGHT - 1 - y;
  break;
 case 3:
  t = x;
  x = y;
  y = TFTHEIGHT - 1 - t;
  break;
}
writeRegister16(0x0020, x);
writeRegister16(0x0021, y);
// Inexplicable thing: sometimes pixel read has high/low bytes
// reversed.  A second read fixes this.  Unsure of reason.  Have
// tried adjusting timing in read8() etc. to no avail.
for(uint8_t pass=0; pass<2; pass++) {
  CD_COMMAND; write8(0x00); write8(0x22); // Read data from GRAM
  CD_DATA;
  setReadDir();  // Set up LCD data port(s) for READ operations
  read8(hi);     // First 2 bytes back are a dummy read
  read8(hi);
  read8(hi);     // Bytes 3, 4 are actual pixel value
  read8(lo);
  setWriteDir(); // Restore LCD data port(s) to WRITE configuration
}
CS_IDLE;
return ((uint16_t)hi << 8) | lo;

}

// Ditto with the read/write port directions, as above.
uint16_t SWTFT::readID(void) {

uint8_t hi, lo;

CS_ACTIVE;
CD_COMMAND;
write8(0x00);
WR_STROBE; // Repeat prior byte (0x00)
setReadDir(); // Set up LCD data port(s) for READ operations
CD_DATA;
read8(hi);
read8(lo);
setWriteDir(); // Restore LCD data port(s) to WRITE configuration
CS_IDLE;

return (hi << 8) | lo;
}

// Pass 8-bit (each) R,G,B, get back 16-bit packed color
uint16_t SWTFT::color565(uint8_t r, uint8_t g, uint8_t b) {
return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
}

//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
void SWTFT::writeA16B3(uint16_t address, uint8_t ub, uint8_t mb, uint8_t lb){
uint8_t hi , lo;
CS_ACTIVE;
hi = (address) >> 8; lo = (address);
CD_COMMAND;
write8(hi);
write8(lo);
CD_DATA;
write8(ub);
write8(ub);
write8(mb);
write8(mb);
write8(lb);
write8(lb);
}
void SWTFT::drawLine3Byte(int16_t x0, int16_t y0,
int16_t x1, int16_t y1,
uint8_t r, uint8_t g, uint8_t b) {
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) {
drawPixel3(y0, x0, r, g, b);
} else {
drawPixel3(x0, y0, r, g, b);
}
err -= dy;
if (err < 0) {
y0 += ystep;
err += dx;
}
}
}

void SWTFT::drawPixel3(int16_t x, int16_t y, uint8_t r, uint8_t g, uint8_t b)
{
if((x < 0) || (y < 0) || (x >= _width) || (y >= _height)) return;

CS_ACTIVE;

int16_t t;
switch(rotation) {
 case 1:
  t = x;
  x = TFTWIDTH  - 1 - y;
  y = t;
  break;
 case 2:
  x = TFTWIDTH  - 1 - x;
  y = TFTHEIGHT - 1 - y;
  break;
 case 3:
  t = x;
  x = y;
  y = TFTHEIGHT - 1 - t;
  break;
}
// writeRegister16(0x0020, x);
// writeRegister16(0x0021, y);
// writeRegister16(0x0022, x );

writeRegister16(0x0020, x);
writeRegister16(0x0021, y);
writeA16B3(0x0022, r , g, b);

CS_IDLE;
}
//}

// For I/O macros that were left undefined, declare function
// versions that reference the inline macros just once:

#ifndef write8
void SWTFT::write8(uint8_t value) {
write8inline(value);
}
#endif

#ifdef read8isFunctionalized
uint8_t SWTFT::read8fn(void) {
uint8_t result;
read8inline(result);
return result;
}
#endif

#ifndef setWriteDir
void SWTFT::setWriteDir(void) {
setWriteDirInline();
}
#endif

#ifndef setReadDir
void SWTFT::setReadDir(void) {
setReadDirInline();
}
#endif

#ifndef writeRegister8
void SWTFT::writeRegister8(uint8_t a, uint8_t d) {
writeRegister8inline(a, d);
}
#endif

#ifndef writeRegister16
void SWTFT::writeRegister16(uint16_t a, uint16_t d) {
writeRegister16inline(a, d);
}
#endif

#ifndef writeRegisterPair
void SWTFT::writeRegisterPair(uint8_t aH, uint8_t aL, uint16_t d) {
writeRegisterPairInline(aH, aL, d);
}
#endif


1 similar comment

@Reuben673

I tried this, but still no luck- help!
here is the file’s contents (it said the error was in SWTFT.cpp):
// Code provided by Smoke And Wires
// http://www.smokeandwires.co.nz
// This code has been taken from the Adafruit TFT Library and modified
// by us for use with our TFT Shields / Modules
// For original code / licensing please refer to
// https://github.com/adafruit/TFTLCD-Library

#include <avr/pgmspace.h>

#include «pins_arduino.h»
#include «wiring_private.h»
#include «SWTFT.h»

// Use the include which corresponde to your arduino
//#include «mega_24_shield.h»
#include «uno_24_shield.h»

#define TFTWIDTH 240
#define TFTHEIGHT 320
#define swap(a, b) { int16_t t = a; a = b; b = t; }
// Constructor for breakout board (configurable LCD control lines).
// Can still use this w/shield, but parameters are ignored.
SWTFT::SWTFT() : Adafruit_GFX(TFTWIDTH, TFTHEIGHT) {

// Convert pin numbers to registers and bitmasks
_reset = LCD_RESET;

csPort     = portOutputRegister(digitalPinToPort(LCD_CS));
cdPort     = portOutputRegister(digitalPinToPort(LCD_CD));
wrPort     = portOutputRegister(digitalPinToPort(LCD_WR));
rdPort     = portOutputRegister(digitalPinToPort(LCD_RD));

csPinSet = digitalPinToBitMask(LCD_CS);
cdPinSet = digitalPinToBitMask(LCD_CD);
wrPinSet = digitalPinToBitMask(LCD_WR);
rdPinSet = digitalPinToBitMask(LCD_RD);
csPinUnset = ~csPinSet;
cdPinUnset = ~cdPinSet;
wrPinUnset = ~wrPinSet;
rdPinUnset = ~rdPinSet;

*csPort   |=  csPinSet; // Set all control bits to HIGH (idle)
*cdPort   |=  cdPinSet; // Signals are ACTIVE LOW
*wrPort   |=  wrPinSet;
*rdPort   |=  rdPinSet;

pinMode(LCD_CS, OUTPUT); // Enable outputs
pinMode(LCD_CD, OUTPUT);
pinMode(LCD_WR, OUTPUT);
pinMode(LCD_RD, OUTPUT);
// if(reset) {
digitalWrite(LCD_RESET, HIGH);
pinMode(LCD_RESET, OUTPUT);
// }

init();
}

void SWTFT::init(void) {

setWriteDir(); // Set up LCD data port(s) for WRITE operations

rotation = 0;
cursor_y = cursor_x = 0;
textsize = 1;
textcolor = 0xFFFF;
_width = TFTWIDTH;
_height = TFTHEIGHT;
}

// // Initialization command table for LCD controller
#define TFTLCD_DELAY 0xFF

static const uint16_t ST7781_regValues[] PROGMEM = {
0x0001,0x0100,
0x0002,0x0700,
0x0003,0x1030,
0x0008,0x0302,
0x0009,0x0000,
0x000A,0x0008,
//_POWER CONTROL REGISTER INITIAL__//
0x0010,0x0790,
0x0011,0x0005,
0x0012,0x0000,
0x0013,0x0000,
//delayms(50,
//
_****_POWER SUPPPLY STARTUP 1 SETTING****//
0x0010,0x12B0,
// delayms(50,
0x0011,0x0007,
//delayms(50,
//_****_POWER SUPPLY STARTUP 2 SETTING**//
0x0012,0x008C,
0x0013,0x1700,
0x0029,0x0022,
// delayms(50,
//_GAMMA CLUSTER SETTING**_//
0x0030,0x0000,
0x0031,0x0505,
0x0032,0x0205,
0x0035,0x0206,
0x0036,0x0408,
0x0037,0x0000,
0x0038,0x0504,
0x0039,0x0206,
0x003C,0x0206,
0x003D,0x0408,
// ————DISPLAY WINDOWS 240_320————-//
0x0050,0x0000,
0x0051,0x00EF,
0x0052,0x0000,
0x0053,0x013F,
//——FRAME RATE SETTING——-//
0x0060,0xA700,
0x0061,0x0001,
0x0090,0x0033, //RTNI setting
//——-DISPLAY ON——//
0x0007,0x0133, 0x0001,0x0100,
0x0002,0x0700,
0x0003,0x1030,
0x0008,0x0302,
0x0009,0x0000,
0x000A,0x0008,
//
_POWER CONTROL REGISTER INITIAL__//
0x0010,0x0790,
0x0011,0x0005,
0x0012,0x0000,
0x0013,0x0000,
//delayms(50,
//
_****_POWER SUPPPLY STARTUP 1 SETTING****//
0x0010,0x12B0,
// delayms(50,
0x0011,0x0007,
// delayms(50,
//_****_POWER SUPPLY STARTUP 2 SETTING**//
0x0012,0x008C,
0x0013,0x1700,
0x0029,0x0022,
// delayms(50,
//_GAMMA CLUSTER SETTING****_//
0x0030,0x0000,
0x0031,0x0505,
0x0032,0x0205,
0x0035,0x0206,
0x0036,0x0408,
0x0037,0x0000,
0x0038,0x0504,
0x0039,0x0206,
0x003C,0x0206,
0x003D,0x0408,
// ————DISPLAY WINDOWS 240_320————-//
0x0050,0x0000,
0x0051,0x00EF,
0x0052,0x0000,
0x0053,0x013F,
//——FRAME RATE SETTING——-//
0x0060,0xA700,
0x0061,0x0001,
0x0090,0x0033, //RTNI setting
//——-DISPLAY ON——//
0x0007,0x0133,
};

void SWTFT::begin(uint16_t id) {
uint8_t i = 0;

reset();

// driver = ID_932X;
CS_ACTIVE;
while(i < sizeof(ST7781_regValues) / sizeof(uint16_t)) {
a = pgm_read_word(&ST7781_regValues[i++]);
d = pgm_read_word(&ST7781_regValues[i++]);
if(a == TFTLCD_DELAY) delay(d);
else writeRegister16(a, d);
}
setRotation(rotation);
setAddrWindow(0, 0, TFTWIDTH-1, TFTHEIGHT-1);

}

void SWTFT::reset(void) {

CS_IDLE;
// CD_DATA;
WR_IDLE;
RD_IDLE;

if(_reset) {
digitalWrite(_reset, LOW);
delay(2);
digitalWrite(_reset, HIGH);
}

// Data transfer sync
CS_ACTIVE;
CD_COMMAND;
write8(0x00);
for(uint8_t i=0; i<3; i++) WR_STROBE; // Three extra 0x00s
CS_IDLE;
}

// Sets the LCD address window (and address counter, on 932X).
// Relevant to rect/screen fills and H/V lines. Input coordinates are
// assumed pre-sorted (e.g. x2 >= x1).
void SWTFT::setAddrWindow(int x1, int y1, int x2, int y2) {

CS_ACTIVE;

// Values passed are in current (possibly rotated) coordinate
// system.  932X requires hardware-native coords regardless of
// MADCTL, so rotate inputs as needed.  The address counter is
// set to the top-left corner -- although fill operations can be
// done in any direction, the current screen rotation is applied
// because some users find it disconcerting when a fill does not
// occur top-to-bottom.
int x, y, t;
switch(rotation) {
 default:
  x  = x1;
  y  = y1;
  break;
 case 1:
  t  = y1;
  y1 = x1;
  x1 = TFTWIDTH  - 1 - y2;
  y2 = x2;
  x2 = TFTWIDTH  - 1 - t;
  x  = x2;
  y  = y1;
  break;
 case 2:
  t  = x1;
  x1 = TFTWIDTH  - 1 - x2;
  x2 = TFTWIDTH  - 1 - t;
  t  = y1;
  y1 = TFTHEIGHT - 1 - y2;
  y2 = TFTHEIGHT - 1 - t;
  x  = x2;
  y  = y2;
  break;
 case 3:
  t  = x1;
  x1 = y1;
  y1 = TFTHEIGHT - 1 - x2;
  x2 = y2;
  y2 = TFTHEIGHT - 1 - t;
  x  = x1;
  y  = y2;
  break;
}
writeRegister16(0x0050, x1); // Set address window
writeRegister16(0x0051, x2);
writeRegister16(0x0052, y1);
writeRegister16(0x0053, y2);
writeRegister16(0x0020, x ); // Set address counter to top left
writeRegister16(0x0021, y );

CS_IDLE;
}

// Unlike the 932X drivers that set the address window to the full screen
// by default (using the address counter for drawPixel operations), the
// 7575 needs the address window set on all graphics operations. In order
// to save a few register writes on each pixel drawn, the lower-right
// corner of the address window is reset after most fill operations, so
// that drawPixel only needs to change the upper left each time.
void SWTFT::setLR(void) {
CS_ACTIVE;
// writeRegisterPair(HX8347G_COLADDREND_HI, HX8347G_COLADDREND_LO, _width — 1);
// writeRegisterPair(HX8347G_ROWADDREND_HI, HX8347G_ROWADDREND_LO, _height — 1);
CS_IDLE;
}

// Fast block fill operation for fillScreen, fillRect, H/V line, etc.
// Requires setAddrWindow() has previously been called to set the fill
// bounds. ‘len’ is inclusive, MUST be >= 1.
void SWTFT::flood(uint16_t color, uint32_t len) {
uint16_t blocks;
uint8_t i, hi = color >> 8,
lo = color;

CS_ACTIVE;
CD_COMMAND;
write8(0x00); // High byte of GRAM register…
write8(0x22); // Write data to GRAM

// Write first pixel normally, decrement counter by 1
CD_DATA;
write8(hi);
write8(lo);
len—;

blocks = (uint16_t)(len / 64); // 64 pixels/block
if(hi == lo) {
// High and low bytes are identical. Leave prior data
// on the port(s) and just toggle the write strobe.
while(blocks—) {
i = 16; // 64 pixels/block / 4 pixels/pass
do {
WR_STROBE; WR_STROBE; WR_STROBE; WR_STROBE; // 2 bytes/pixel
WR_STROBE; WR_STROBE; WR_STROBE; WR_STROBE; // x 4 pixels
} while(—i);
}
// Fill any remaining pixels (1 to 64)
for(i = (uint8_t)len & 63; i—; ) {
WR_STROBE;
WR_STROBE;
}
} else {
while(blocks—) {
i = 16; // 64 pixels/block / 4 pixels/pass
do {
write8(hi); write8(lo); write8(hi); write8(lo);
write8(hi); write8(lo); write8(hi); write8(lo);
} while(—i);
}
for(i = (uint8_t)len & 63; i—; ) {
write8(hi);
write8(lo);
}
}
CS_IDLE;
}

void SWTFT::drawFastHLine(int16_t x, int16_t y, int16_t length,
uint16_t color)
{
int16_t x2;

// Initial off-screen clipping
if((length <= 0 ) ||
(y < 0 ) || ( y >= _height) ||
(x >= _width) || ((x2 = (x+length-1)) < 0 )) return;

if(x < 0) { // Clip left
length += x;
x = 0;
}
if(x2 >= _width) { // Clip right
x2 = _width — 1;
length = x2 — x + 1;
}

setAddrWindow(x, y, x2, y);
flood(color, length);
setAddrWindow(0, 0, _width — 1, _height — 1);

}

void SWTFT::drawFastVLine(int16_t x, int16_t y, int16_t length,
uint16_t color)
{
int16_t y2;

// Initial off-screen clipping
if((length <= 0 ) ||
(x < 0 ) || ( x >= _width) ||
(y >= _height) || ((y2 = (y+length-1)) < 0 )) return;
if(y < 0) { // Clip top
length += y;
y = 0;
}
if(y2 >= _height) { // Clip bottom
y2 = _height — 1;
length = y2 — y + 1;
}

setAddrWindow(x, y, x, y2);
flood(color, length);
setAddrWindow(0, 0, _width — 1, _height — 1);

}

void SWTFT::fillRect(int16_t x1, int16_t y1, int16_t w, int16_t h,
uint16_t fillcolor) {
int16_t x2, y2;

// Initial off-screen clipping
if( (w <= 0 ) || (h <= 0 ) ||
(x1 >= _width) || (y1 >= _height) ||
((x2 = x1+w-1) < 0 ) || ((y2 = y1+h-1) < 0 )) return;
if(x1 < 0) { // Clip left
w += x1;
x1 = 0;
}
if(y1 < 0) { // Clip top
h += y1;
y1 = 0;
}
if(x2 >= _width) { // Clip right
x2 = _width — 1;
w = x2 — x1 + 1;
}
if(y2 >= _height) { // Clip bottom
y2 = _height — 1;
h = y2 — y1 + 1;
}

setAddrWindow(x1, y1, x2, y2);
flood(fillcolor, (uint32_t)w * (uint32_t)h);
setAddrWindow(0, 0, _width — 1, _height — 1);

}

void SWTFT::fillScreen(uint16_t color) {

// For the 932X, a full-screen address window is already the default
// state, just need to set the address pointer to the top-left corner.
// Although we could fill in any direction, the code uses the current
// screen rotation because some users find it disconcerting when a
// fill does not occur top-to-bottom.
uint16_t x, y;
switch(rotation) {
  default: x = 0            ; y = 0            ; break;
  case 1 : x = TFTWIDTH  - 1; y = 0            ; break;
  case 2 : x = TFTWIDTH  - 1; y = TFTHEIGHT - 1; break;
  case 3 : x = 0            ; y = TFTHEIGHT - 1; break;
}
CS_ACTIVE;
writeRegister16(0x0020, x);
writeRegister16(0x0021, y);

flood(color, (long)TFTWIDTH * (long)TFTHEIGHT);
}

void SWTFT::drawPixel(int16_t x, int16_t y, uint16_t color) {

// Clip
if((x < 0) || (y < 0) || (x >= _width) || (y >= _height)) return;

CS_ACTIVE;

int16_t t;
switch(rotation) {
 case 1:
  t = x;
  x = TFTWIDTH  - 1 - y;
  y = t;
  break;
 case 2:
  x = TFTWIDTH  - 1 - x;
  y = TFTHEIGHT - 1 - y;
  break;
 case 3:
  t = x;
  x = y;
  y = TFTHEIGHT - 1 - t;
  break;
}
writeRegister16(0x0020, x);
writeRegister16(0x0021, y);
writeRegister16(0x0022, color );

CS_IDLE;
}

// Issues ‘raw’ an array of 16-bit color values to the LCD; used
// externally by BMP examples. Assumes that setWindowAddr() has
// previously been set to define the bounds. Max 255 pixels at
// a time (BMP examples read in small chunks due to limited RAM).
void SWTFT::pushColors(uint16_t *data, uint8_t len, boolean first) {
uint16_t color;
uint8_t hi, lo;
CS_ACTIVE;
if(first == true) { // Issue GRAM write command only on first call
CD_COMMAND;
write8(0x00);
write8(0x22);
}
CD_DATA;
while(len—) {
color = *data++;
hi = color >> 8; // Don’t simplify or merge these
lo = color; // lines, there’s macro shenanigans
write8(hi); // going on.
write8(lo);
}
CS_IDLE;
}

void SWTFT::setRotation(uint8_t x) {

// Call parent rotation func first — sets up rotation flags, etc.
Adafruit_GFX::setRotation(x);
// Then perform hardware-specific rotation operations…

CS_ACTIVE;

// uint16_t t;
// switch(rotation) {
// default: t = 0x1030; break;
// case 1 : t = 0x1028; break;
// case 2 : t = 0x1000; break;
// case 3 : t = 0x1018; break;
// }
// writeRegister16(0x0003, t ); // MADCTL
// For 932X, init default full-screen address window:
// setAddrWindow(0, 0, _width — 1, _height — 1); // CS_IDLE happens here

}

#ifdef read8isFunctionalized
#define read8(x) x=read8fn()
#endif

// Because this function is used infrequently, it configures the ports for
// the read operation, reads the data, then restores the ports to the write
// configuration. Write operations happen a LOT, so it’s advantageous to
// leave the ports in that state as a default.
uint16_t SWTFT::readPixel(int16_t x, int16_t y) {

if((x < 0) || (y < 0) || (x >= _width) || (y >= _height)) return 0;

CS_ACTIVE;

uint8_t hi, lo;
int16_t t;
switch(rotation) {
 case 1:
  t = x;
  x = TFTWIDTH  - 1 - y;
  y = t;
  break;
 case 2:
  x = TFTWIDTH  - 1 - x;
  y = TFTHEIGHT - 1 - y;
  break;
 case 3:
  t = x;
  x = y;
  y = TFTHEIGHT - 1 - t;
  break;
}
writeRegister16(0x0020, x);
writeRegister16(0x0021, y);
// Inexplicable thing: sometimes pixel read has high/low bytes
// reversed.  A second read fixes this.  Unsure of reason.  Have
// tried adjusting timing in read8() etc. to no avail.
for(uint8_t pass=0; pass<2; pass++) {
  CD_COMMAND; write8(0x00); write8(0x22); // Read data from GRAM
  CD_DATA;
  setReadDir();  // Set up LCD data port(s) for READ operations
  read8(hi);     // First 2 bytes back are a dummy read
  read8(hi);
  read8(hi);     // Bytes 3, 4 are actual pixel value
  read8(lo);
  setWriteDir(); // Restore LCD data port(s) to WRITE configuration
}
CS_IDLE;
return ((uint16_t)hi << 8) | lo;

}

// Ditto with the read/write port directions, as above.
uint16_t SWTFT::readID(void) {

uint8_t hi, lo;

CS_ACTIVE;
CD_COMMAND;
write8(0x00);
WR_STROBE; // Repeat prior byte (0x00)
setReadDir(); // Set up LCD data port(s) for READ operations
CD_DATA;
read8(hi);
read8(lo);
setWriteDir(); // Restore LCD data port(s) to WRITE configuration
CS_IDLE;

return (hi << 8) | lo;
}

// Pass 8-bit (each) R,G,B, get back 16-bit packed color
uint16_t SWTFT::color565(uint8_t r, uint8_t g, uint8_t b) {
return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
}

//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
void SWTFT::writeA16B3(uint16_t address, uint8_t ub, uint8_t mb, uint8_t lb){
uint8_t hi , lo;
CS_ACTIVE;
hi = (address) >> 8; lo = (address);
CD_COMMAND;
write8(hi);
write8(lo);
CD_DATA;
write8(ub);
write8(ub);
write8(mb);
write8(mb);
write8(lb);
write8(lb);
}
void SWTFT::drawLine3Byte(int16_t x0, int16_t y0,
int16_t x1, int16_t y1,
uint8_t r, uint8_t g, uint8_t b) {
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) {
drawPixel3(y0, x0, r, g, b);
} else {
drawPixel3(x0, y0, r, g, b);
}
err -= dy;
if (err < 0) {
y0 += ystep;
err += dx;
}
}
}

void SWTFT::drawPixel3(int16_t x, int16_t y, uint8_t r, uint8_t g, uint8_t b)
{
if((x < 0) || (y < 0) || (x >= _width) || (y >= _height)) return;

CS_ACTIVE;

int16_t t;
switch(rotation) {
 case 1:
  t = x;
  x = TFTWIDTH  - 1 - y;
  y = t;
  break;
 case 2:
  x = TFTWIDTH  - 1 - x;
  y = TFTHEIGHT - 1 - y;
  break;
 case 3:
  t = x;
  x = y;
  y = TFTHEIGHT - 1 - t;
  break;
}
// writeRegister16(0x0020, x);
// writeRegister16(0x0021, y);
// writeRegister16(0x0022, x );

writeRegister16(0x0020, x);
writeRegister16(0x0021, y);
writeA16B3(0x0022, r , g, b);

CS_IDLE;
}
//}

// For I/O macros that were left undefined, declare function
// versions that reference the inline macros just once:

#ifndef write8
void SWTFT::write8(uint8_t value) {
write8inline(value);
}
#endif

#ifdef read8isFunctionalized
uint8_t SWTFT::read8fn(void) {
uint8_t result;
read8inline(result);
return result;
}
#endif

#ifndef setWriteDir
void SWTFT::setWriteDir(void) {
setWriteDirInline();
}
#endif

#ifndef setReadDir
void SWTFT::setReadDir(void) {
setReadDirInline();
}
#endif

#ifndef writeRegister8
void SWTFT::writeRegister8(uint8_t a, uint8_t d) {
writeRegister8inline(a, d);
}
#endif

#ifndef writeRegister16
void SWTFT::writeRegister16(uint16_t a, uint16_t d) {
writeRegister16inline(a, d);
}
#endif

#ifndef writeRegisterPair
void SWTFT::writeRegisterPair(uint8_t aH, uint8_t aL, uint16_t d) {
writeRegisterPairInline(aH, aL, d);
}
#endif

@cdtsilva

Someone should shoot you for posting that…. TWICE… Attach it instead!!

@RRavina

I have connected this tft with mega and installed the SWTFT library with all the corrections, so it doesn’t showing any error.But also it doesn’t display any thing on the lcd,just lcd light is on everytime.

PLZZZZZZZZZZZZ HELP ME………………….

@KyleGass

@antoniomusico

I finally got it….
I found a post where a guy named Buhosoft uploaded a MCUFried S6D0154 TFT Display UNO y MEGA libraries.zip file that solved my problem. I deleted all the libraries related (Adafruit……, SD, Touchscreen, TFT, …) and after that I installed the 4 libraries that the file contains and I plugged my Arduino MEGA board and it worked.
Here the link:
http://forum.arduino.cc/index.php?topic=292777.15
Good luck mates!

@Nooshaa

Hi Guyes

i test the code but it give me filliped display as mirror !!!!
any one can help ???

@vipint99

Mirror problem was solved by changing GS=0 in SWTFT FILE
//0x0060,0xA700, Gs=0
0x0060,0x2700,

@buddhika-ranasinghe

Hi @vipint99

I am facing the same issue.
I don’t see a line with code «0x0060,0x2700»

Can you please explain the fix futher/

Thanks
Buddhika

@pigravity

I am facing the same issue.
I don’t see a line with code «0x0060,0x2700»

Can you please explain the fix futher/

lines ~ 122, 165 after //——FRAME RATE SETTING——-//

is: 0x0060,0xA700,
change to: 0x60, 0x2700,

and voila

Ср, 09/08/2017 — 11:54

#1

b707

Offline

Зарегистрирован: 26.05.2017

swap(x,y) — это, очевидно, макрос или функция, обменивающая значения x и y. Если ее нет в библиотеке — напишите ее сами

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 12:00

#2

DetSimen

DetSimen аватар

Offline

Зарегистрирован: 25.01.2017

держы

template <typename T> static inline void swap(T& a, T& b) { T t = a; a = b; b = t; }

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 12:04

#3

brokly

brokly аватар

Offline

Зарегистрирован: 08.02.2014

Ну компилятор не может найти функцию swap.

Что это: http://ru.cppreference.com/w/cpp/algorithm/swap

В вашем случае она используется в RGBmatrixPanelAlternative.cpp

Возможно вам стоит попробывать добавить где нибудь что то типа :  #include <stdio.h>

Или воткнуть с файл RGBmatrixPanelAlternative.cpp что то типа

void swap(int16_t &x, int16_t &y)
      {
           if (&x == &y) 
              return;
           x ^= y;
           y ^= x;
           x ^= y;
      }

PS Ну а я совсем опоздал, но стирать не буду :)

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 13:06

#4

fixa

Offline

Зарегистрирован: 09.08.2017

Просто автор выложил готовый проект — и не верится, что он пропустил функцию

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 13:12

#5

Клапауций 112

Клапауций 112 аватар

Offline

Зарегистрирован: 01.03.2017

fixa пишет:

Просто автор выложил готовый проект — и не верится, что он пропустил функцию

а, как ты понял, что это готовый проект?

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 13:59

#6

fixa

Offline

Зарегистрирован: 09.08.2017

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 14:00

#7

DetSimen

DetSimen аватар

Offline

Зарегистрирован: 25.01.2017

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 14:24

#8

b707

Offline

Зарегистрирован: 26.05.2017

fixa пишет:

Просто автор выложил готовый проект — и не верится, что он пропустил функцию

Ну не верится — сиди и жди, пока он ответит (если).

Предложили же решение — чего бы не попробовать? Зачем тогда спрашивал?

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 15:57

#9

fixa

Offline

Зарегистрирован: 09.08.2017

DetSimen пишет:

а зачем нам это?

Спросили же — как я понял, что готовый проект — вот, все написано

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 16:03

#10

wdrakula

wdrakula аватар

Offline

Зарегистрирован: 15.03.2016

задолбали, хоть в ООН жалуйся!!!

в СТАРЫХ версиях ИДЕ был определен макрос swap().

В новых — нет.

Многие старые программы и библиотеки нужно корректировать, добавляя этот макрос.

Еще раз: ЗАДОЛБАЛИ херню обсуждать.

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 16:07

#11

fixa

Offline

Зарегистрирован: 09.08.2017

Понятно — а теперь для непрограммистов — как точно он должен быть написан — и куда точно его добавить? Если это не военная тайна…  

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 16:08

#12

wdrakula

wdrakula аватар

Offline

Зарегистрирован: 15.03.2016

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 16:27

#13

brokly

brokly аватар

Offline

Зарегистрирован: 08.02.2014

А что тут делает НЕПРОГРАММИСТ  ?

Выносит мосх программистам ?

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 16:48

#14

wdrakula

wdrakula аватар

Offline

Зарегистрирован: 15.03.2016

fixa пишет:

Понятно — а теперь для непрограммистов — как точно он должен быть написан — и куда точно его добавить? Если это не военная тайна…  

рехнулся? тебе три раза  выше уже ответили.

Мне нравится вариант от DetSimen. Этаки «высокотехнологичный». Можно взять классику от Брукли.

Если ты не по-нарошку задаешь вопрос»куда его засунуть», то ответ — в задницу. В этом случае продай ардуину и не ипи людЯм моск. Дворнику контроллеры не нужны.

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 16:50

#15

b707

Offline

Зарегистрирован: 26.05.2017

fixa пишет:

Понятно — а теперь для непрограммистов

 «Придется вам заплатить, чтобы вы ушли» (с)

На ваш вопрос аж 2 ответа — в сообщениях #2 и #3

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 17:41

#16

fixa

Offline

Зарегистрирован: 09.08.2017

Ну, естественно, я сам решу — быть мне тут или нет. И продавать или не продавать контроллер — тоже без советчиков обойдусь. Не нравится Вам присутствие тут неучей — заведите им песочницу. Или тест какой при регистрации на форуме. Нету? Ну тогда жалуйтесь модератору на надоевших дворников. Теперь про тему — может, все-таки, поможет кто? Или — какая там версия ИДЕ еще свап поддерживала?

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 18:06

#17

wdrakula

wdrakula аватар

Offline

Зарегистрирован: 15.03.2016

вариант от ДетСимена или Брукли в певую строку(-ки) своего скетча.

….

Но при ваших знаниях у вас все равно нихера не выйдет. Не нужно вам это. Семки и Яга … ну и русский репчик — самое то!

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 18:11

#18

b707

Offline

Зарегистрирован: 26.05.2017

откройте файл RGBmatrixPanelAlternative.cpp

вставьте начиная со строки 77 код brokly из третьего сообщения ветки

void swap(int16_t &x, int16_t &y)
      {
           if (&x == &y) 
              return;
           x ^= y;
           y ^= x;
           x ^= y;
      }

потом в файл RGBmatrixPanelAlternative.h вставьте примерно на строку 7

void swap(int16_t &x, int16_t &y);

все, ошибка должна пропасть

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 18:15

#19

wdrakula

wdrakula аватар

Offline

Зарегистрирован: 15.03.2016

Если человеку дать рыбу, то попросит еще.

Если человку дать удочкой по заднице, то он, скорее всего, от тебя отстанет.

(древняя мудрость рыбаков озера Кенэрет)

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 18:16

#20

b707

Offline

Зарегистрирован: 26.05.2017

wdrakula пишет:

в первую строку(-ки) своего скетча.

А сработает? Например, дефайны из скетча в библиотеках не работают.

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 18:17

#21

b707

Offline

Зарегистрирован: 26.05.2017

wdrakula пишет:

Если человеку дать рыбу, то попросит еще.

да ладно, пусть пользуется

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 18:47

#22

b707

Offline

Зарегистрирован: 26.05.2017

зато теперь, кажется. ушел :)

  • Войдите на сайт для отправки комментариев

Ср, 09/08/2017 — 19:11

#23

Клапауций 112

Клапауций 112 аватар

Offline

Зарегистрирован: 01.03.2017

b707 пишет:

зато теперь, кажется. ушел :)

рыбу в кустах дожрёт и вернётся.

  • Войдите на сайт для отправки комментариев
  • Forum
  • General C++ Programming
  • swap is not declared

swap is not declared

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
void sort(int &small, int &mid , int &large);
void swap1(int, int);
void swap2(int, int);
int small, mid, large;
cout << "please enter a number";
cin >> small;
cout << "please enter onather number";
cin >> mid;
cout << "please enter the third number";
cin >> large;
sort (small, mid, large);
cout << "small = " << small << "middle = " << mid << "large = " << large << endl;
getch();
}
void sort (int small, int mid, int large)
{
    if (small > mid)
    swap1 (small, mid);
    if (mid > large)
    swap2 (mid, large);
}

void swap1 (int &small, int &mid)
{
int a = small;
small = mid;
mid = a;
}

void swap2 (int &mid, int &large)
{
int b = mid;
mid = large;
large = b;
}

appears that error on line 25 & 30 where swap1 & swap2 is not declared in this scope.. anyone can help?..thanx in advance

Look at the functions declaration and definition parameter types. See the difference?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <conio.h>
using namespace std;

void sort(int small, int mid , int large);
void swap1(int, int);
void swap2(int, int);
int main()
{

int small, mid, large;
cout << "please enter a number";
cin >> small;
cout << "please enter onather number";
cin >> mid;
cout << "please enter the third number";
cin >> large;
sort (small, mid, large);
cout << "small = " << small << "middle = " << mid << "large = " << large << endl;
getch();
}
void sort (int small, int mid, int large)
{
    if (small > mid)
    swap1 ( small, mid);
    if (mid > large)
    swap2 ( mid, large);
}

void swap1 (int small, int mid)
{
int a = small;
small = mid;
mid = a;
}

void swap2 (int mid, int large)
{
int b = mid;
mid = large;
large = b;
}

i’ve change the function sort and swap as global function…it fix the problem…but it wont swap…have any idea?

Look again at the type of parameters!
You have pass them by value which mean that intended variables wont be changed.

Lets make simple example so you can see what is happening and why

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

void function1( int number)
{
    number = 10;
}

void function2( int& number)
{
    number = 10;
}

int main()
{
    int var = 3;

    function1( var ); // this wont change var since it is passed by value (param type is int)
    std::cout << var << std::endl; // 3 is printed
    function2( var ); // this will change var since it is passed by reference (param type is reference to int)
    std::cout << var << std::endl; // 10 is printed
};

You declared two pairs of functions

void swap1(int, int);
void swap1 (int &small, int &mid);

void swap2(int, int);
void swap2 (int &mid, int &large);

The second functions in the pairs were defined but the first functions were not defined.

At the moment of calls of the functions the compiler sees the first declarations that have no corresponding definitions. So it issues the errors.

Last edited on

Last edited on

Thank you so much guys…now I understand more on this problems..

Topic archived. No new replies allowed.

Прерывания. Урок 11. Ардуино

Привет! Наверное, вы помните, как в уроках про мультинажание на кнопку нам нужно было решить проблему подсчета количества нажатий в одной серии. Тогда мы использовали функцию delay() и задерживали выполнение программы. Но что, если делать такую паузу нельзя, а необходимо получать данные с датчиков постоянно. Но при этом управлять программой с помощью кнопок или других датчиков. Для этого в Ардуино существуют прерывания.

В одном из последних обзоров датчиков, мы рассматривали датчик препятствий KY-033. Посмотрите тот обзор если вы пропустили или уже забыли, потому что в этом уроке мы будем его использовать.

Итак, прерывания. Они позволяют выполнять программу асинхронно. При наступлении определенного события — нажатия на кнопку, сигнала от датчика, они дают возможность остановить ход текущей программы, выполнить код прерывания, а затем вернуться к прерванной задаче.

Для того, чтобы выполнить этот урок нам понадобиться.

  • Ардуино UNO
  • Макетная плата
  • Перемычки
  • Датчик KY-033
  • 3 светодиода разного цвета
  • 3 резистора 220 Ом
  • Кабель USB

Прерывания

Аппаратные прерывания — это альтернатива постоянного сканирования состояния контактов в цикле loop(). Они не лучше и не хуже, вы всегда можете выбрать тот способ, который будет лучше работать в вашем проекте.

С аппаратной точки зрения, опрос контактов в цикле и прерывание абсолютно одинаковы. Однако, существуют моменты, когда использовать прерывания будет невозможно.

Например, устранение дребезга. Внутри прерывания не может быть использована функция delay(), а это значит, что программы подтверждающие состояние датчика должны быть спроектированы по-другому.

Программа

Проблему дребезга кнопки можно решить аппаратно. Мы сделаем это в другом уроке, а пока займемся работой с прерываниями.

В этом проекте мы хотим использовать бесконечный цикл в главном цикле loop() и использовать прерывание для запуска дополнительной подпрограммы, которая вмешается в работу цикла.

Кроме того, используем датчик препятствий из последнего обзора, он будет выполнять функцию бесконтактной кнопки.

Соберем на макетной плате схему. Используем уже знакомую схему подключения датчика препятствий, но добавим в нее три светодиода.

Принципиальная схема подключения датчика

В цикле loop() будем бесконечно изменять яркость одного светодиода с помощью шим. А при срабатывании прерывания от датчика будем заменять один светодиод на другой, при этом яркость изменяться не будет.

volatile

В первую очередь нам нужно будет объявить переменную, которая отвечает за контакт активного светодиода. Она будет изменяться в процессе программы, а значит ее следует объявить как volatile.

attachInterrupt

Далее создадим 0 прерывание. 0 прерывание связано с пином 2 на плате Ардуино Uno, поэтому датчик препятствий подключен именно ко 2 контакту.

Теперь напишем функцию swap(), чтобы вызвать ее по прерыванию. Она будет переключать активный светодиод.

И в конце осталось только написать бесконечный цикл в основном цикле программы. Он будет изменять яркость светодиодов.

Результат работы программы прерывания

Полный текст программы

Заключение

Мы рассмотрели прерывания в Ардуино. Это одна из сложных тем в изучении Ардуино, но она поможет нам создавать сложные устройства с несколькими датчиками и большие программы отвечающие за несколько устройств сразу.

Источник

Arduino.ru

Помогите разобраться почему ошибка при компиляции, а то автор молчит :(

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

error: ‘swap’ was not declared in this scope

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

swap(x,y) — это, очевидно, макрос или функция, обменивающая значения x и y. Если ее нет в библиотеке — напишите ее сами

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Ну компилятор не может найти функцию swap.

В вашем случае она используется в RGBmatrixPanelAlternative.cpp

Возможно вам стоит попробывать добавить где нибудь что то типа : # include stdio . h >

Или воткнуть с файл RGBmatrixPanelAlternative.cpp что то типа

PS Ну а я совсем опоздал, но стирать не буду :)

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Просто автор выложил готовый проект — и не верится, что он пропустил функцию

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Просто автор выложил готовый проект — и не верится, что он пропустил функцию

а, как ты понял, что это готовый проект?

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии
  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

а зачем нам это?

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Просто автор выложил готовый проект — и не верится, что он пропустил функцию

Ну не верится — сиди и жди, пока он ответит (если).

Предложили же решение — чего бы не попробовать? Зачем тогда спрашивал?

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

а зачем нам это?

Спросили же — как я понял, что готовый проект — вот, все написано

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

задолбали, хоть в ООН жалуйся.

в СТАРЫХ версиях ИДЕ был определен макрос swap().

Многие старые программы и библиотеки нужно корректировать, добавляя этот макрос.

Еще раз: ЗАДОЛБАЛИ херню обсуждать.

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Понятно — а теперь для непрограммистов — как точно он должен быть написан — и куда точно его добавить? Если это не военная тайна.

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

А что тут делает НЕПРОГРАММИСТ ?

Выносит мосх программистам ?

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Понятно — а теперь для непрограммистов — как точно он должен быть написан — и куда точно его добавить? Если это не военная тайна.

рехнулся? тебе три раза выше уже ответили.

Мне нравится вариант от DetSimen. Этаки «высокотехнологичный». Можно взять классику от Брукли.

Если ты не по-нарошку задаешь вопрос»куда его засунуть», то ответ — в задницу. В этом случае продай ардуину и не ипи людЯм моск. Дворнику контроллеры не нужны.

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Понятно — а теперь для непрограммистов

«Придется вам заплатить, чтобы вы ушли» (с)

На ваш вопрос аж 2 ответа — в сообщениях #2 и #3

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Ну, естественно, я сам решу — быть мне тут или нет. И продавать или не продавать контроллер — тоже без советчиков обойдусь. Не нравится Вам присутствие тут неучей — заведите им песочницу. Или тест какой при регистрации на форуме. Нету? Ну тогда жалуйтесь модератору на надоевших дворников. Теперь про тему — может, все-таки, поможет кто? Или — какая там версия ИДЕ еще свап поддерживала?

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

вариант от ДетСимена или Брукли в певую строку(-ки) своего скетча.

Но при ваших знаниях у вас все равно нихера не выйдет. Не нужно вам это. Семки и Яга . ну и русский репчик — самое то!

Источник

swap not declared #7

I’m using arduino IDE 1.6.6 with arduino uno. All examples sort the same error

C:UsersEraldoDocumentsArduinolibrariesSWTFTSWTFT.cpp: In member function ‘void SWTFT::drawLine3Byte(int16_t, int16_t, int16_t, int16_t, uint8_t, uint8_t, uint8_t)’:

C:UsersEraldoDocumentsArduinolibrariesSWTFTSWTFT.cpp:629:16: error: ‘swap’ was not declared in this scope

C:UsersEraldoDocumentsArduinolibrariesSWTFTSWTFT.cpp:634:16: error: ‘swap’ was not declared in this scope

exit status 1
Errore durante la compilazione

Anyone has an idea? Thanks

The text was updated successfully, but these errors were encountered:

Hi,
You just have to add bottom line in SWIFT.cpp file.
#define swap(a, b)

Tried that didn’t work for me?`
#ifndef writeRegister8
void SWTFT::writeRegister8(uint8_t a, uint8_t d) <
writeRegister8inline(a, d);
>
#endif

#ifndef writeRegister16
void SWTFT::writeRegister16(uint16_t a, uint16_t d) <
writeRegister16inline(a, d);
>
#endif

#ifndef writeRegisterPair
void SWTFT::writeRegisterPair(uint8_t aH, uint8_t aL, uint16_t d) <
writeRegisterPairInline(aH, aL, d);
>
#endif

You have to add this line at the top of file for example like this:
`// Code provided by Smoke And Wires
// http://www.smokeandwires.co.nz
// This code has been taken from the Adafruit TFT Library and modified
// by us for use with our TFT Shields / Modules
// For original code / licensing please refer to
// https://github.com/adafruit/TFTLCD-Library

#include «pins_arduino.h»
#include «wiring_private.h»
#include «SWTFT.h»

// Use the include which corresponde to your arduino
//#include «mega_24_shield.h»
#include «uno_24_shield.h»

#define TFTWIDTH 240
#define TFTHEIGHT 320
#define swap(a, b)

// Constructor for breakout board (configurable LCD control lines).
// Can still use this w/shield, but parameters are ignored.
SWTFT::SWTFT() : Adafruit_GFX(TFTWIDTH, TFTHEIGHT) <
`

I tried this, but still no luck- help!
here is the file’s contents (it said the error was in SWTFT.cpp):
// Code provided by Smoke And Wires
// http://www.smokeandwires.co.nz
// This code has been taken from the Adafruit TFT Library and modified
// by us for use with our TFT Shields / Modules
// For original code / licensing please refer to
// https://github.com/adafruit/TFTLCD-Library

#include «pins_arduino.h»
#include «wiring_private.h»
#include «SWTFT.h»

// Use the include which corresponde to your arduino
//#include «mega_24_shield.h»
#include «uno_24_shield.h»

#define TFTWIDTH 240
#define TFTHEIGHT 320
#define swap(a, b) < int16_t t = a; a = b; b = t; >
// Constructor for breakout board (configurable LCD control lines).
// Can still use this w/shield, but parameters are ignored.
SWTFT::SWTFT() : Adafruit_GFX(TFTWIDTH, TFTHEIGHT) <

// Convert pin numbers to registers and bitmasks
_reset = LCD_RESET;

csPinSet = digitalPinToBitMask(LCD_CS);
cdPinSet = digitalPinToBitMask(LCD_CD);
wrPinSet = digitalPinToBitMask(LCD_WR);
rdPinSet = digitalPinToBitMask(LCD_RD);
csPinUnset =

pinMode(LCD_CS, OUTPUT); // Enable outputs
pinMode(LCD_CD, OUTPUT);
pinMode(LCD_WR, OUTPUT);
pinMode(LCD_RD, OUTPUT);
// if(reset) <
digitalWrite(LCD_RESET, HIGH);
pinMode(LCD_RESET, OUTPUT);
// >

setWriteDir(); // Set up LCD data port(s) for WRITE operations

rotation = 0;
cursor_y = cursor_x = 0;
textsize = 1;
textcolor = 0xFFFF;
_width = TFTWIDTH;
_height = TFTHEIGHT;
>

// // Initialization command table for LCD controller
#define TFTLCD_DELAY 0xFF

static const uint16_t ST7781_regValues[] PROGMEM = <
0x0001,0x0100,
0x0002,0x0700,
0x0003,0x1030,
0x0008,0x0302,
0x0009,0x0000,
0x000A,0x0008,
//_POWER CONTROL REGISTER INITIAL__//
0x0010,0x0790,
0x0011,0x0005,
0x0012,0x0000,
0x0013,0x0000,
//delayms(50,
//
_****_POWER SUPPPLY STARTUP 1 SETTING****//
0x0010,0x12B0,
// delayms(50,
0x0011,0x0007,
//delayms(50,
//_****_POWER SUPPLY STARTUP 2 SETTING**//
0x0012,0x008C,
0x0013,0x1700,
0x0029,0x0022,
// delayms(50,
//_GAMMA CLUSTER SETTING**_//
0x0030,0x0000,
0x0031,0x0505,
0x0032,0x0205,
0x0035,0x0206,
0x0036,0x0408,
0x0037,0x0000,
0x0038,0x0504,
0x0039,0x0206,
0x003C,0x0206,
0x003D,0x0408,
// ————DISPLAY WINDOWS 240_320————-//
0x0050,0x0000,
0x0051,0x00EF,
0x0052,0x0000,
0x0053,0x013F,
//——FRAME RATE SETTING——-//
0x0060,0xA700,
0x0061,0x0001,
0x0090,0x0033, //RTNI setting
//——-DISPLAY ON——//
0x0007,0x0133, 0x0001,0x0100,
0x0002,0x0700,
0x0003,0x1030,
0x0008,0x0302,
0x0009,0x0000,
0x000A,0x0008,
//
_POWER CONTROL REGISTER INITIAL__//
0x0010,0x0790,
0x0011,0x0005,
0x0012,0x0000,
0x0013,0x0000,
//delayms(50,
//
_****_POWER SUPPPLY STARTUP 1 SETTING****//
0x0010,0x12B0,
// delayms(50,
0x0011,0x0007,
// delayms(50,
//_****_POWER SUPPLY STARTUP 2 SETTING**//
0x0012,0x008C,
0x0013,0x1700,
0x0029,0x0022,
// delayms(50,
//_GAMMA CLUSTER SETTING****_//
0x0030,0x0000,
0x0031,0x0505,
0x0032,0x0205,
0x0035,0x0206,
0x0036,0x0408,
0x0037,0x0000,
0x0038,0x0504,
0x0039,0x0206,
0x003C,0x0206,
0x003D,0x0408,
// ————DISPLAY WINDOWS 240_320————-//
0x0050,0x0000,
0x0051,0x00EF,
0x0052,0x0000,
0x0053,0x013F,
//——FRAME RATE SETTING——-//
0x0060,0xA700,
0x0061,0x0001,
0x0090,0x0033, //RTNI setting
//——-DISPLAY ON——//
0x0007,0x0133,
>;

void SWTFT::begin(uint16_t id) <
uint8_t i = 0;

// driver = ID_932X;
CS_ACTIVE;
while(i = x1).
void SWTFT::setAddrWindow(int x1, int y1, int x2, int y2) <

// Unlike the 932X drivers that set the address window to the full screen
// by default (using the address counter for drawPixel operations), the
// 7575 needs the address window set on all graphics operations. In order
// to save a few register writes on each pixel drawn, the lower-right
// corner of the address window is reset after most fill operations, so
// that drawPixel only needs to change the upper left each time.
void SWTFT::setLR(void) <
CS_ACTIVE;
// writeRegisterPair(HX8347G_COLADDREND_HI, HX8347G_COLADDREND_LO, _width — 1);
// writeRegisterPair(HX8347G_ROWADDREND_HI, HX8347G_ROWADDREND_LO, _height — 1);
CS_IDLE;
>

// Fast block fill operation for fillScreen, fillRect, H/V line, etc.
// Requires setAddrWindow() has previously been called to set the fill
// bounds. ‘len’ is inclusive, MUST be >= 1.
void SWTFT::flood(uint16_t color, uint32_t len) <
uint16_t blocks;
uint8_t i, hi = color >> 8,
lo = color;

CS_ACTIVE;
CD_COMMAND;
write8(0x00); // High byte of GRAM register.
write8(0x22); // Write data to GRAM

// Write first pixel normally, decrement counter by 1
CD_DATA;
write8(hi);
write8(lo);
len—;

blocks = (uint16_t)(len / 64); // 64 pixels/block
if(hi == lo) <
// High and low bytes are identical. Leave prior data
// on the port(s) and just toggle the write strobe.
while(blocks—) <
i = 16; // 64 pixels/block / 4 pixels/pass
do <
WR_STROBE; WR_STROBE; WR_STROBE; WR_STROBE; // 2 bytes/pixel
WR_STROBE; WR_STROBE; WR_STROBE; WR_STROBE; // x 4 pixels
> while(—i);
>
// Fill any remaining pixels (1 to 64)
for(i = (uint8_t)len & 63; i—; ) <
WR_STROBE;
WR_STROBE;
>
> else <
while(blocks—) <
i = 16; // 64 pixels/block / 4 pixels/pass
do <
write8(hi); write8(lo); write8(hi); write8(lo);
write8(hi); write8(lo); write8(hi); write8(lo);
> while(—i);
>
for(i = (uint8_t)len & 63; i—; ) <
write8(hi);
write8(lo);
>
>
CS_IDLE;
>

void SWTFT::drawFastHLine(int16_t x, int16_t y, int16_t length,
uint16_t color)
<
int16_t x2;

// Initial off-screen clipping
if((length = _height) ||
(x >= _width) || ((x2 = (x+length-1)) = _width) < // Clip right
x2 = _width — 1;
length = x2 — x + 1;
>

setAddrWindow(x, y, x2, y);
flood(color, length);
setAddrWindow(0, 0, _width — 1, _height — 1);

void SWTFT::drawFastVLine(int16_t x, int16_t y, int16_t length,
uint16_t color)
<
int16_t y2;

// Initial off-screen clipping
if((length = _width) ||
(y >= _height) || ((y2 = (y+length-1)) = _height) < // Clip bottom
y2 = _height — 1;
length = y2 — y + 1;
>

setAddrWindow(x, y, x, y2);
flood(color, length);
setAddrWindow(0, 0, _width — 1, _height — 1);

void SWTFT::fillRect(int16_t x1, int16_t y1, int16_t w, int16_t h,
uint16_t fillcolor) <
int16_t x2, y2;

// Initial off-screen clipping
if( (w = _width) || (y1 >= _height) ||
((x2 = x1+w-1) = _width) < // Clip right
x2 = _width — 1;
w = x2 — x1 + 1;
>
if(y2 >= _height) < // Clip bottom
y2 = _height — 1;
h = y2 — y1 + 1;
>

setAddrWindow(x1, y1, x2, y2);
flood(fillcolor, (uint32_t)w * (uint32_t)h);
setAddrWindow(0, 0, _width — 1, _height — 1);

void SWTFT::fillScreen(uint16_t color) <

flood(color, (long)TFTWIDTH * (long)TFTHEIGHT);
>

void SWTFT::drawPixel(int16_t x, int16_t y, uint16_t color) <

// Clip
if((x = _width) || (y >= _height)) return;

// Issues ‘raw’ an array of 16-bit color values to the LCD; used
// externally by BMP examples. Assumes that setWindowAddr() has
// previously been set to define the bounds. Max 255 pixels at
// a time (BMP examples read in small chunks due to limited RAM).
void SWTFT::pushColors(uint16_t *data, uint8_t len, boolean first) <
uint16_t color;
uint8_t hi, lo;
CS_ACTIVE;
if(first == true) < // Issue GRAM write command only on first call
CD_COMMAND;
write8(0x00);
write8(0x22);
>
CD_DATA;
while(len—) <
color = *data++;
hi = color >> 8; // Don’t simplify or merge these
lo = color; // lines, there’s macro shenanigans
write8(hi); // going on.
write8(lo);
>
CS_IDLE;
>

void SWTFT::setRotation(uint8_t x) <

// Call parent rotation func first — sets up rotation flags, etc.
Adafruit_GFX::setRotation(x);
// Then perform hardware-specific rotation operations.

// uint16_t t;
// switch(rotation) <
// default: t = 0x1030; break;
// case 1 : t = 0x1028; break;
// case 2 : t = 0x1000; break;
// case 3 : t = 0x1018; break;
// >
// writeRegister16(0x0003, t ); // MADCTL
// For 932X, init default full-screen address window:
// setAddrWindow(0, 0, _width — 1, _height — 1); // CS_IDLE happens here

#ifdef read8isFunctionalized
#define read8(x) x=read8fn()
#endif

// Because this function is used infrequently, it configures the ports for
// the read operation, reads the data, then restores the ports to the write
// configuration. Write operations happen a LOT, so it’s advantageous to
// leave the ports in that state as a default.
uint16_t SWTFT::readPixel(int16_t x, int16_t y) <

if((x = _width) || (y >= _height)) return 0;

// Ditto with the read/write port directions, as above.
uint16_t SWTFT::readID(void) <

CS_ACTIVE;
CD_COMMAND;
write8(0x00);
WR_STROBE; // Repeat prior byte (0x00)
setReadDir(); // Set up LCD data port(s) for READ operations
CD_DATA;
read8(hi);
read8(lo);
setWriteDir(); // Restore LCD data port(s) to WRITE configuration
CS_IDLE;

//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
void SWTFT::writeA16B3(uint16_t address, uint8_t ub, uint8_t mb, uint8_t lb) <
uint8_t hi , lo;
CS_ACTIVE;
hi = (address) >> 8; lo = (address);
CD_COMMAND;
write8(hi);
write8(lo);
CD_DATA;
write8(ub);
write8(ub);
write8(mb);
write8(mb);
write8(lb);
write8(lb);
>
void SWTFT::drawLine3Byte(int16_t x0, int16_t y0,
int16_t x1, int16_t y1,
uint8_t r, uint8_t g, uint8_t b) <
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 = _width) || (y >= _height)) return;

// For I/O macros that were left undefined, declare function
// versions that reference the inline macros just once:

#ifndef write8
void SWTFT::write8(uint8_t value) <
write8inline(value);
>
#endif

#ifdef read8isFunctionalized
uint8_t SWTFT::read8fn(void) <
uint8_t result;
read8inline(result);
return result;
>
#endif

#ifndef setWriteDir
void SWTFT::setWriteDir(void) <
setWriteDirInline();
>
#endif

#ifndef setReadDir
void SWTFT::setReadDir(void) <
setReadDirInline();
>
#endif

#ifndef writeRegister8
void SWTFT::writeRegister8(uint8_t a, uint8_t d) <
writeRegister8inline(a, d);
>
#endif

#ifndef writeRegister16
void SWTFT::writeRegister16(uint16_t a, uint16_t d) <
writeRegister16inline(a, d);
>
#endif

#ifndef writeRegisterPair
void SWTFT::writeRegisterPair(uint8_t aH, uint8_t aL, uint16_t d) <
writeRegisterPairInline(aH, aL, d);
>
#endif

Источник

Recently I purchased an Adafruit SSD1306 128 x 64 Monochrome OLED display and connected it to a Teensy 3.2 to try and get it up and running as a small display for a temperature measurement project.

following the guide for Monochrome OLED breakouts and trying to run in I2C mode I did the following:

Downloaded the latest Adafruit GFX library from Github 1.2.2

And downloaded the Adafruit_SSD1306 library and loaded them into my Arduino library folder by .zip extraction

And then the example program 128 x 64 I2C would not compile so edited the .h file to suit 128 x 64 and ran the i2c scanner and saw the device address was
0x3D so changed the define from 0x3C to 0x3D

/*********************************************************************
This is a library for our Monochrome OLEDs based on SSD1306 drivers

Pick one up today in the adafruit shop!
——> http://www.adafruit.com/category/63_98

These displays use SPI to communicate, 4 or 5 pins are required to
interface

Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!

Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, check license.txt for more information
All text above, and the splash screen must be included in any redistribution
*********************************************************************/

#if ARDUINO >= 100
#include «Arduino.h»
#else
#include «WProgram.h»
#endif

#ifdef __SAM3X8E__
typedef volatile RwReg PortReg;
typedef uint32_t PortMask;
#else
typedef volatile uint8_t PortReg;
typedef uint8_t PortMask;
#endif

#include <SPI.h>
#include <Adafruit_GFX.h>

#define BLACK 0
#define WHITE 1

#define SSD1306_I2C_ADDRESS 0x3D // 011110+SA0+RW — 0x3C or 0x3D
// Address for 128×32 is 0x3C
// Address for 128×64 is 0x3D (default) or 0x3C (if SA0 is grounded)

/*=========================================================================
SSD1306 Displays
————————————————————————
The driver is used in multiple displays (128×64, 128×32, etc.).
Select the appropriate display below to create an appropriately
sized framebuffer, etc.

SSD1306_128_64 128×64 pixel display

SSD1306_128_32 128×32 pixel display

————————————————————————*/
#define SSD1306_128_64
// #define SSD1306_128_32
/*=========================================================================*/

#if defined SSD1306_128_64 && defined SSD1306_128_32
#error «Only one SSD1306 display can be specified at once in SSD1306.h»
#endif
#if !defined SSD1306_128_64 && !defined SSD1306_128_32
#error «At least one SSD1306 display must be specified in SSD1306.h»
#endif

#if defined SSD1306_128_64
#define SSD1306_LCDWIDTH 128
#define SSD1306_LCDHEIGHT 64
#endif
#if defined SSD1306_128_32
#define SSD1306_LCDWIDTH 128
#define SSD1306_LCDHEIGHT 32
#endif

#define SSD1306_SETCONTRAST 0x81
#define SSD1306_DISPLAYALLON_RESUME 0xA4
#define SSD1306_DISPLAYALLON 0xA5
#define SSD1306_NORMALDISPLAY 0xA6

**************************************************

Tried to compile and got:

Arduino: 1.6.13 (Windows 7), TD: 1.33, Board: «Teensy 3.2 / 3.1, Serial, 96 MHz optimize speed (overclock), US English»

WARNING: Category ‘Real-time clock’ in library DS3231 is not valid. Setting to ‘Uncategorized’
C:UsersJim VDocumentsArduinolibrariesAdafruit_SSD1306Adafruit_SSD1306.cpp: In member function ‘virtual void Adafruit_SSD1306::drawPixel(int16_t, int16_t, uint16_t)’:

C:UsersJim VDocumentsArduinolibrariesAdafruit_SSD1306Adafruit_SSD1306.cpp:123:14: error: ‘swap’ was not declared in this scope

swap(x, y);

^

C:UsersJim VDocumentsArduinolibrariesAdafruit_SSD1306Adafruit_SSD1306.cpp: At global scope:

C:UsersJim VDocumentsArduinolibrariesAdafruit_SSD1306Adafruit_SSD1306.cpp:402:6: error: prototype for ‘void Adafruit_SSD1306::dim(boolean)’ does not match any in class ‘Adafruit_SSD1306’

void Adafruit_SSD1306::dim(boolean dim) {

^

In file included from C:UsersJim VDocumentsArduinolibrariesAdafruit_SSD1306Adafruit_SSD1306.cpp:28:0:

C:UsersJim VDocumentsArduinolibrariesAdafruit_SSD1306Adafruit_SSD1306.h:142:8: error: candidate is: void Adafruit_SSD1306::dim(uint8_t)

void dim(uint8_t contrast);

^

C:UsersJim VDocumentsArduinolibrariesAdafruit_SSD1306Adafruit_SSD1306.cpp: In member function ‘virtual void Adafruit_SSD1306::drawFastHLine(int16_t, int16_t, int16_t, uint16_t)’:

C:UsersJim VDocumentsArduinolibrariesAdafruit_SSD1306Adafruit_SSD1306.cpp:526:16: error: ‘swap’ was not declared in this scope

swap(x, y);

^

C:UsersJim VDocumentsArduinolibrariesAdafruit_SSD1306Adafruit_SSD1306.cpp: In member function ‘virtual void Adafruit_SSD1306::drawFastVLine(int16_t, int16_t, int16_t, uint16_t)’:

C:UsersJim VDocumentsArduinolibrariesAdafruit_SSD1306Adafruit_SSD1306.cpp:594:16: error: ‘swap’ was not declared in this scope

swap(x, y);

^

Error compiling for board Teensy 3.2 / 3.1.

This report would have more information with
«Show verbose output during compilation»
option enabled in File -> Preferences.

Can anyone help?

Thanks

Jim the Kiwi

  1. Здравствуйте пытаюсь прошить Arduino UNO для S4A но вовремя компиляции пишет ошибку:

    C:UsersАдминистраторDesktopРђСЂРґСѓРёРЅРѕS4AFirmware15S4AFirmware15.ino:10:1: warning: ‘typedef’ was ignored in this declaration

    C:UsersАдминистраторDesktopРђСЂРґСѓРёРЅРѕS4AFirmware15S4AFirmware15.ino: In function ‘void setup()’:

    S4AFirmware15:20: error: ‘configurePins’ was not declared in this scope

    S4AFirmware15:21: error: ‘resetPins’ was not declared in this scope

    C:UsersАдминистраторDesktopРђСЂРґСѓРёРЅРѕS4AFirmware15S4AFirmware15.ino: In function ‘void loop()’:

    S4AFirmware15:30: error: ‘sendUpdateServomotors’ was not declared in this scope

    S4AFirmware15:31: error: ‘sendSensorValues’ was not declared in this scope

    S4AFirmware15:35: error: ‘readSerialPort’ was not declared in this scope

    C:UsersАдминистраторDesktopРђСЂРґСѓРёРЅРѕS4AFirmware15S4AFirmware15.ino: In function ‘void resetPins()’:

    S4AFirmware15:65: error: ‘servo’ was not declared in this scope

    C:UsersАдминистраторDesktopРђСЂРґСѓРёРЅРѕS4AFirmware15S4AFirmware15.ino: In function ‘void sendSensorValues()’:

    S4AFirmware15:85: error: ‘insertionSort’ was not declared in this scope

    S4AFirmware15:91: error: ‘ScratchBoardSensorReport’ was not declared in this scope

    S4AFirmware15:94: error: ‘ScratchBoardSensorReport’ was not declared in this scope

    C:UsersАдминистраторDesktopРђСЂРґСѓРёРЅРѕS4AFirmware15S4AFirmware15.ino: In function ‘void insertionSort(unsigned int*, unsigned int)’:

    S4AFirmware15:102: error: ‘swap’ was not declared in this scope

    C:UsersАдминистраторDesktopРђСЂРґСѓРёРЅРѕS4AFirmware15S4AFirmware15.ino: In function ‘void readSerialPort()’:

    S4AFirmware15:150: error: ‘updateActuator’ was not declared in this scope

    S4AFirmware15:155: error: ‘checkScratchDisconnection’ was not declared in this scope

    C:UsersАдминистраторDesktopРђСЂРґСѓРёРЅРѕS4AFirmware15S4AFirmware15.ino: In function ‘void sendUpdateServomotors()’:

    S4AFirmware15:174: error: ‘servo’ was not declared in this scope

    C:UsersАдминистраторDesktopРђСЂРґСѓРёРЅРѕS4AFirmware15S4AFirmware15.ino: In function ‘void servo(byte, byte)’:

    S4AFirmware15:180: error: ‘pulse’ was not declared in this scope

    exit status 1
    ‘configurePins’ was not declared in this scope

  2. а хотя бы с переводчиком не пытались разобраться что вам написали в ошибках ?

  3. вы пытаетесь использовать незнакомые компилятору слова. проверьте подключение библиотек и объявление переменных

  4. typedef enum {
    input, servomotor, pwm, digital }
    pinType;

    typedef struct pin {
    pinType type; //Type of pin
    int state; //State of an output
    //byte value; //Value of an input. Not used by now. TODO
    };

    pin arduinoPins[14]; //Array of struct holding 0-13 pins information

    unsigned long lastDataReceivedTime = millis();

    void setup()
    {
    Serial.begin(38400);
    Serial.flush();
    configurePins();// На него ругается.
    resetPins();
    }

    void loop()
    {
    static unsigned long timerCheckUpdate = millis();

    if (millis()-timerCheckUpdate>=20)
    {
    sendUpdateServomotors();
    sendSensorValues();
    timerCheckUpdate=millis();
    }

    readSerialPort();
    }

    void configurePins()
    {
    arduinoPins[0].type=input;
    arduinoPins[1].type=input;
    arduinoPins[2].type=input;
    arduinoPins[3].type=input;
    arduinoPins[4].type=servomotor;
    arduinoPins[5].type=pwm;
    arduinoPins[6].type=pwm;
    arduinoPins[7].type=servomotor;
    arduinoPins[8].type=servomotor;
    arduinoPins[9].type=pwm;
    arduinoPins[10].type=digital;
    arduinoPins[11].type=digital;
    arduinoPins[12].type=digital;
    arduinoPins[13].type=digital;
    }

    void resetPins() {
    for (byte index=0; index <=13; index++)
    {
    if (arduinoPins[index].type!=input)
    {
    pinMode(index, OUTPUT);
    if (arduinoPins[index].type==servomotor)
    {
    arduinoPins[index].state = 255;
    servo (index, 255);
    }
    else
    {
    arduinoPins[index].state=0;
    digitalWrite(index,LOW);
    }
    }
    }
    }

    void sendSensorValues()
    {
    unsigned int sensorValues[6], readings[5];
    byte sensorIndex;

    for (sensorIndex = 0; sensorIndex < 6; sensorIndex++) //for analog sensors, calculate the median of 5 sensor readings in order to avoid variability and power surges
    {
    for (byte p = 0; p < 5; p++)
    readings[p] = analogRead(sensorIndex);
    insertionSort(readings, 5); //sort readings
    sensorValues[sensorIndex] = readings[2]; //select median reading
    }

    //send analog sensor values
    for (sensorIndex = 0; sensorIndex < 6; sensorIndex++)
    ScratchBoardSensorReport(sensorIndex, sensorValues[sensorIndex]);

    //send digital sensor values
    ScratchBoardSensorReport(6, digitalRead(2)?1023:0);
    ScratchBoardSensorReport(7, digitalRead(3)?1023:0);
    }

    void insertionSort(unsigned int* array, unsigned int n)
    {
    for (int i = 1; i < n; i++)
    for (int j = i; (j > 0) && ( array[j] < array[j-1] ); j—)
    swap( array, j, j-1 );
    }

    void swap(unsigned int* array, unsigned int a, unsigned int b)
    {
    unsigned int temp = array[a];
    array[a] = array;
    array = temp;
    }

    void ScratchBoardSensorReport(byte sensor, int value) //PicoBoard protocol, 2 bytes per sensor
    {
    Serial.write( B10000000
    | ((sensor & B1111)<<3)
    | ((value>>7) & B111));
    Serial.write( value & B1111111);
    }

    void readSerialPort()
    {
    byte pin;
    int newVal;
    static byte actuatorHighByte, actuatorLowByte;
    static byte readingSM = 0;

    if (Serial.available())
    {
    if (readingSM == 0)
    {
    actuatorHighByte = Serial.read();
    if (actuatorHighByte >= 128) readingSM = 1;
    }
    else if (readingSM == 1)
    {
    actuatorLowByte = Serial.read();
    if (actuatorLowByte < 128) readingSM = 2;
    else readingSM = 0;
    }

    if (readingSM == 2)
    {
    lastDataReceivedTime = millis();
    pin = ((actuatorHighByte >> 3) & 0x0F);
    newVal = ((actuatorHighByte & 0x07) << 7) | (actuatorLowByte & 0x7F);

    if(arduinoPins[pin].state != newVal)
    {
    arduinoPins[pin].state = newVal;
    updateActuator(pin);
    }
    readingSM = 0;
    }
    }
    else checkScratchDisconnection();
    }

    void reset() //with xbee module, we need to simulate the setup execution that occurs when a usb connection is opened or closed without this module
    {
    resetPins(); // reset pins
    sendSensorValues(); // protocol handshaking
    lastDataReceivedTime = millis();
    }

    void updateActuator(byte pinNumber)
    {
    if (arduinoPins[pinNumber].type==digital) digitalWrite(pinNumber, arduinoPins[pinNumber].state);
    else if (arduinoPins[pinNumber].type==pwm) analogWrite(pinNumber, arduinoPins[pinNumber].state);
    }

    void sendUpdateServomotors()
    {
    for (byte p = 0; p < 10; p++)
    if (arduinoPins[p].type == servomotor) servo(p, arduinoPins[p].state);
    }

    void servo (byte pinNumber, byte angle)
    {
    if (angle != 255)
    pulse(pinNumber, (angle * 10) + 600);
    }

    void pulse (byte pinNumber, unsigned int pulseWidth)
    {
    digitalWrite(pinNumber, HIGH);
    delayMicroseconds(pulseWidth);
    digitalWrite(pinNumber, LOW);
    }

    void checkScratchDisconnection() //the reset is necessary when using an wireless arduino board (because we need to ensure that arduino isn’t waiting the actuators state from Scratch) or when scratch isn’t sending information (because is how serial port close is detected)
    {
    if (millis() — lastDataReceivedTime > 1000) reset(); //reset state if actuators reception timeout = one second
    }

  5. вы всё сообщение прочтите, он у вас через строчку ругается. «pulse»,»servo»….

  6. ах да. вы должны писать функцию ДО её вызова. или ставить вначале кода её объявление.

  7. Но почему она не работает ? я ее с официального сайта скачал. Да и с других тоже не работает. До функций мне еще далеко.

  8. вы должны объявить функцию до того, как её вызовите. т.е. написать что делать до того как скажете, что надо это делать.
    http://cppstudio.com/post/6471/

  9. В Arduino IDE этого делать не обязательно. При подготовке исходников из скетча *.ino среда сама сделает нужные объявления, что бы компилятор не ругался.Чем сборку (компиляцию) производите? Arduino IDE v 1.6.11 прекрасно справляется со скетчем S4A с официального сайта.

  10. Если я бы это знал то не рвался бы за S4A . Надо просто начать ..

  11. а почему не на с??
    там же всё кристально, и на амперковой вики лежат очень годные статьи….

  12. Надо проста начать с простого. Поэтому мне надо S4A но пока не найду выход чтобы S4A заработал!

  13. а. э. нет. надо с нормального. перейти с этой штуки на что-то нормальное будет оооочень сложно. инфа 110%.

  14. Я все это прекрасно понимаю. Главное это понять принцип. И я вообще то тут для решения проблемы. Все остальное успеется.

  15. Это не стабильная версия, но всё равно S4A в ней собирается без ошибок.
    Есть одно предположение, связанное с непонятными символами в пути к скетчу:

    Это кириллица в названиях каталогов. Надо кириллицу убрать, т.е. файл скетча поместить в каталог, в пути к которому не будет русских буковок. Например, C:/arduino/s4a/S4AFirmware15.ino.
    И возьмите 16-ю версию S4A с официального сайта.

  16. Большое СПАСИБО помогло, но arduino сам создает папку и перемещает его туда и только от туда можно загрузить. У меня получилось с 3 раз так как до этого выдавал нет доступа к порту или он заблокирован.

  17. У меня такая же проблема:
    C:UsersAlexDocumentsArduinoS4AFirmware16S4AFirmware16.ino:51:1: warning: ‘typedef’ was ignored in this declaration

    };

    ^
    Причем как видно не в кирилице дело, пробовал уже на двух компьютерах. При этом скет можно и залить, вот только S4a платку не видит…

  18. Если проблема только в этом warning, то это не проблема. И отсутствие/присутствие кириллицы здесь не при чём. Может кроме этого предупреждения есть ошибки (errors)?
    Хотя если:

    то скорее всего ошибок нет и проблема у Вас в другом.

compiler error trying OLED library on swap(x, y)

Moderator: igrr

Wed Dec 09, 2015 3:10 pm
#36079

Hello everybody.

I try to get an OLED SSD1306 running
I did download an example programm and the ESP_Adafruit_SSD1306 librarie.

I do receive an compiler error on swap function in the library part of the programm:

    :/Documenten/Arduino/libraries/ESP_Adafruit_SSD1306-master/ESP_Adafruit_SSD1306.cpp: In member function ‘virtual void Adafruit_SSD1306::drawPixel(int16_t, int16_t, uint16_t)’:
    D:/Documenten/Arduino/libraries/ESP_Adafruit_SSD1306-master/ESP_Adafruit_SSD1306.cpp:109:14: error: ‘swap’ was not declared in this scope
    swap(x, y);

The library is using severall times the command: swap(x, y)
I don’t know why this error occurs.
Is a part of the library missing?
Or is swap a kind of standard function?
How to solve this compiler error?

Thanks
Is swap a standard function?

Wed Dec 09, 2015 4:11 pm
#36086

reaper7 wrote:yes, swap is a core function
so…try my fixed mod:
https://github.com/reaper7/ESP_SSD1306

Thanks for the answer.

I tried your example: basic_oled_i2c
Including your librarie.
I still do recieve a compiler error in the file in the library: ESP_SSD1306.cpp

The compile error is:

    D:/Documenten/Arduino/libraries/ESP_SSD1306-master/ESP_SSD1306.cpp:130:17: error: ‘swapint’ was not declared in this scope
    swapint(x, y);
    ^
    D:/Documenten/Arduino/libraries/ESP_SSD1306-master/ESP_SSD1306.cpp: In member function ‘virtual void ESP_SSD1306::drawFastHLine(int16_t, int16_t, int16_t, uint16_t)’:
    D:/Documenten/Arduino/libraries/ESP_SSD1306-master/ESP_SSD1306.cpp:592:19: error: ‘swapint’ was not declared in this scope
    swapint(x, y);
    ^
    D:/Documenten/Arduino/libraries/ESP_SSD1306-master/ESP_SSD1306.cpp: In member function ‘virtual void ESP_SSD1306::drawFastVLine(int16_t, int16_t, int16_t, uint16_t)’:
    D:/Documenten/Arduino/libraries/ESP_SSD1306-master/ESP_SSD1306.cpp:660:19: error: ‘swapint’ was not declared in this scope
    swapint(x, y);
    ^
    Libraries/ESP_SSD1306-master/subdir.mk:18: recipe for target ‘Libraries/ESP_SSD1306-master/ESP_SSD1306.cpp.o’ failed
    make: *** [Libraries/ESP_SSD1306-master/ESP_SSD1306.cpp.o] Error 1

Do I need to include an kind of standard lib like math.h where swap will be declared?

If swap is a core function why is my compiler not recognize it?

Wed Dec 09, 2015 5:33 pm
#36098

swap (or new swapint) is placed inside Adafruit_GFX library (file Adafruit_GFX.h)

download this lib and change:
from

Code: Select all#define swap(a, b) { int16_t t = a; a = b; b = t; }

to

Code: Select all#define swapint(a, b) { int16_t t = a; a = b; b = t; }

SergeyKagen

3 / 4 / 2

Регистрация: 02.04.2018

Сообщений: 315

1

19.04.2019, 22:16. Показов 132175. Ответов 14

Метки нет (Все метки)


Простой код, но Arduino IDE напрочь отказывается принимать переменные. Что за глюк или я что-то неправильно делаю?

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void setup() {
  
  Serial.begin(9600);
  int count = 0;
  pinMode(7, INPUT);
  pinMode(13, OUTPUT);
 
}
 
void loop() {
 
  if( digitalRead(7) == HIGH ){ 
    
    while(1){ 
      delayMicroseconds(2); 
      count++;  
      if( digitalRead(7) == LOW ){ Serial.println(count); count = 0; break; }
      }
    }  
}

ошибка при компиляции «‘count’ was not declared in this scope», что не так?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



marat_miaki

495 / 389 / 186

Регистрация: 08.04.2013

Сообщений: 1,688

19.04.2019, 23:26

2

Лучший ответ Сообщение было отмечено SergeyKagen как решение

Решение

C++
1
2
3
4
5
6
7
8
  int count = 0; //глобальная переменная
 
  void setup() {
   Serial.begin(9600);
  pinMode(7, INPUT);
  pinMode(13, OUTPUT);
 
}



1



Lavad

0 / 0 / 0

Регистрация: 03.10.2015

Сообщений: 25

14.09.2019, 22:33

3

Доброго времени суток!
У меня то же сообщение, но на функцию :-(
Создал функцию (за пределами setup и loop), которая только принимает вызов, ничего не возвращает:

C++
1
2
3
4
5
void myDispay(byte x, byte y, char str) {
  lcd.setCursor(x, y);
  lcd.print(temp, 1);   // выводим данные, с точностью до 1 знака после запятой
  lcd.print(str);   // выводим писанину
  }

В loop() делаю вызов:

C++
1
myDisplay(0,0,"C");

При компиляции выделяется этот вызов, с сообщением:

‘myDisplay’ was not declared in this scope

Замучился искать инфу о декларации/обьявлении функции. Везде, что находил, понимал одно: если ты вызываешь функцию, это и есть обьявление функции
Что делаю не так? В чем моя ошибка? Помогите, пожалуйста.

P.S. Код, что использовал в качестве функции, работоспособен. Раньше находился в loop(). Скетч постепенно разрастается, много однотипных обращений к дисплею…



0



Эксперт С++

8385 / 6147 / 615

Регистрация: 10.12.2010

Сообщений: 28,683

Записей в блоге: 30

14.09.2019, 23:57

4

Цитата
Сообщение от Lavad
Посмотреть сообщение

Создал функцию (за пределами setup и loop),

Перевидите на нормальный язык.
Какие еще пределы?

В другом файле что ли?

Добавлено через 1 минуту

Цитата
Сообщение от Lavad
Посмотреть сообщение

Замучился искать инфу о декларации/обьявлении функции. Везде, что находил, понимал одно: если ты вызываешь функцию, это и есть обьявление функции
Что делаю не так? В чем моя ошибка? Помогите, пожалуйста

Читать учебники по С++ не пробовали?

https://metanit.com/cpp/tutorial/3.1.php
http://cppstudio.com/post/5291/

Специфика Arduino лишь отличается тем что пред объявления не всегда нужны.

Добавлено через 7 минут
Кроме того иногда потеряй скобок {} приводят к таким ошибкам.



0



ValeryS

Модератор

Эксперт по электронике

8759 / 6549 / 887

Регистрация: 14.02.2011

Сообщений: 22,972

15.09.2019, 00:09

5

Цитата
Сообщение от Lavad
Посмотреть сообщение

Везде, что находил, понимал одно: если ты вызываешь функцию, это и есть обьявление функции

это где ж такое написано?
функцию нужно объявить перед первым вызовом, сиречь сверху
можно и просто декларировать сверху

C++
1
void myDispay(byte x, byte y, char str);

а объявить уже в удобном месте



0



0 / 0 / 0

Регистрация: 03.10.2015

Сообщений: 25

15.09.2019, 00:48

6

Неделю назад ВПЕРВЫЕ включил Arduino Uno.
Задолго до этого писал программы под Windows (БейсикВизуал) и AVR (Basic, немного Assembler). Т.е. имеется некоторое представление об объявлении переменных, функций,… От Си всегда держался как можно дальше. Это первая и последняя причина «нечитания» книг по Си. За неделю экспериментов на Arduino мнение об этом пока не изменилось — легче вернуться к Ассму, чем копаться в Си.

Написал на том же языке, что и читал на всяких форумах и справочниках по Arduino :-). За пределами этих функций — значит не внутри них.

Обе приведенных Вами ссылок просмотрел, проверил в скетче… В итоге вылезла другая ошибка:
function ‘void myDisplay(byte, byte, char)’ is initialized like a variable

void myDisplay(byte x, byte y, char str) тоже пробовал. Та же ошибка.

Что не так на этот раз? :-(



0



Модератор

Эксперт по электронике

8759 / 6549 / 887

Регистрация: 14.02.2011

Сообщений: 22,972

15.09.2019, 01:26

7

Цитата
Сообщение от Lavad
Посмотреть сообщение

В итоге вылезла другая ошибка:
function ‘void myDisplay(byte, byte, char)’ is initialized like a variable

точку с запятой в конце поставил?



1



Lavad

0 / 0 / 0

Регистрация: 03.10.2015

Сообщений: 25

15.09.2019, 08:46

8

Вот скетч. Проще некуда.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <PCD8544.h>
 
float temp = 0;
static PCD8544 lcd;   // даем имя подключенному дисплею (lcd)
static const byte Lm35Pin = 14;   // аналоговый пин (A0) Arduino, к которому подключен LM35
 
//void myDisplay() = 0;
//void myDisplay(byte, byte, char, float) = 0;
//void myDisplay(byte x, byte y, char str, float temp) = 0;
 
void myDispay(byte x, byte y, char str, float temp) {
  lcd.setCursor(x, y);   // начиная с (x,y)...
  lcd.print(temp, 1);   // выводим temp
  lcd.print(str);   // выводим писанину
}
 
void setup() {
  lcd.begin(84, 48);   // инициализируем дисплей
  analogReference(INTERNAL);   // подключаем внутренний ИОН на 1.1V
}
 
void loop() {
  float temp = analogRead(Lm35Pin) / 9.31;  // подсчитываем температуру (в Цельсиях)...
  myDisplay(0, 0, "C", temp);   // отправляем данные на экран
  delay(500);   // ждем 500 мсек
}

Любое из трех так называемых «объявлений» (строки 7…9) выдает одну и ту же ошибку — я пытаюсь объявить функцию как переменную.

Добавлено через 9 минут
Попробовал так:

C++
1
void myDisplay(byte x, byte y, char str, float temp);

Компилятор задумался (я успел обрадоваться), но, зараза :-), он снова поставил свой автограф :-)

undefined reference to `myDisplay(unsigned char, unsigned char, char, float)

На этот раз он пожаловался на строку вызова функции.

Добавлено через 34 минуты
Когда что-то новое затягивает, забываешь о нормальном отдыхе, теряешь концентрацию…
Нашел ошибку. Чистейшая грамматика

C++
1
void myDispay(byte x,...

Dispay вместо Display

Добавлено через 8 минут
ValeryS, благодарю за попытку помощи!



0



ValeryS

Модератор

Эксперт по электронике

8759 / 6549 / 887

Регистрация: 14.02.2011

Сообщений: 22,972

15.09.2019, 10:36

9

Цитата
Сообщение от Lavad
Посмотреть сообщение

void myDisplay(byte, byte, char, float) = 0;

вот так не надо делать(приравнивать функцию к нулю)
так в классическом С++ объявляют чисто виртуальные функции, и класс в котором объявлена чисто виртуальная функция становится абстрактным. Означает что у функции нет реализации и в дочернем классе нужно обязательно реализовать функцию. А из абстрактного класса нельзя создать объект

Добавлено через 5 минут

Цитата
Сообщение от Lavad
Посмотреть сообщение

void myDispay(byte x, byte y, char str, float temp)

Цитата
Сообщение от Lavad
Посмотреть сообщение

myDisplay(0, 0, «C», temp);

просишь чтобы функция принимала символ char str, а передаешь строку "C"
или передавай символ

C++
1
myDisplay(0, 0, 'C', temp);

или проси передавать строку, например так

C++
1
void myDispay(byte x, byte y, char * str, float temp);



1



Avazart

Эксперт С++

8385 / 6147 / 615

Регистрация: 10.12.2010

Сообщений: 28,683

Записей в блоге: 30

15.09.2019, 12:02

10

Кроме того наверное лучше так:

C++
1
2
3
4
5
6
7
8
void myDispay(PCD8544& lcd,byte x, byte y, char str, float temp) 
{
  lcd.setCursor(x, y);   // начиная с (x,y)...
  lcd.print(temp, 1);   // выводим temp
  lcd.print(str);   // выводим писанину
}
 
myDisplay(lcd,0, 0, 'C', temp);

Тогда можно будет вынести ф-цию в отдельный файл/модуль.



1



locm

15.09.2019, 21:07

Не по теме:

Цитата
Сообщение от Lavad
Посмотреть сообщение

Arduino Uno.

Цитата
Сообщение от Lavad
Посмотреть сообщение

AVR (Basic, немного Assembler).

Arduino Uno это AVR, для которого можете писать на бейсике или ассемблере.



0



Avazart

15.09.2019, 21:21

Не по теме:

Цитата
Сообщение от locm
Посмотреть сообщение

Arduino Uno это AVR, для которого можете писать на бейсике или ассемблере.

Но лучше не надо …



0



Lavad

0 / 0 / 0

Регистрация: 03.10.2015

Сообщений: 25

16.09.2019, 12:12

13

Цитата
Сообщение от ValeryS
Посмотреть сообщение

это где ж такое написано?
функцию нужно объявить перед первым вызовом, сиречь сверху
можно и просто декларировать сверху
а объявить уже в удобном месте

Оказалось, что я верно понял чтиво по справочникам: если ты вызываешь функцию, это и есть обьявление функции. А сама функция может располагаться по скетчу в ЛЮБОМ месте (но за пределами setup, loop и любых других функций). И больше никаких специфических строк.

Цитата
Сообщение от ValeryS
Посмотреть сообщение

вот так не надо делать(приравнивать функцию к нулю)…

Методом проб и ошибок уже понял :-).

Цитата
Сообщение от ValeryS
Посмотреть сообщение

или передавай символ… 'C'

Если передаю в одинарных кавычках

более одного

символа, а функция ждет как char str, то выводятся на экран только самый правый из отправленных символов. Отправил «абв», а выводится «в».
Выкрутился, прописав в функции char str[], а символы отправляю через двойные кавычки.

Цитата
Сообщение от ValeryS
Посмотреть сообщение

или проси передавать строку, например так… char * str

Буквально вчера попалось это в справочнике, но как-то не дошло, что тоже мой вариант :-).

Цитата
Сообщение от Avazart
Посмотреть сообщение

Кроме того наверное лучше так:

C++
1
void myDispay(PCD8544& lcd,byte x, byte y, char str, float temp) {...}

Тогда можно будет вынести ф-цию в отдельный файл/модуль.

Благодарю за совет! Как-нибудь проверю…



0



Эксперт С++

8385 / 6147 / 615

Регистрация: 10.12.2010

Сообщений: 28,683

Записей в блоге: 30

16.09.2019, 12:54

14

Цитата
Сообщение от Lavad
Посмотреть сообщение

Оказалось, что я верно понял чтиво по справочникам: если ты вызываешь функцию, это и есть обьявление функции

Нафиг выкиньте эти справочники.
Почитайте мои ссылки.



0



0 / 0 / 0

Регистрация: 03.10.2015

Сообщений: 25

16.09.2019, 13:00

15

Ссылки Ваши добавлены в закладки. Время от времени заглядываю.
Но теория для меня — всего лишь набор понятий. Я же высказался после практической проверки. А как я понял, так оно и работает :-)



0



Понравилась статья? Поделить с друзьями:
  • Error svg image
  • Error suppressible vsim 12110
  • Error supported eeprom not found
  • Error suggest parentheses around assignment used as truth value
  • Error subscript used with non array variable как исправить