/*
Forum: https://forum.arduino.cc/t/flickering-tft-display-when-drawing-graphics/1363482
Wokwi: https://wokwi.com/projects/425675367664915457
ec2021
Based on the sketch from sumguy
Forum: https://forum.arduino.cc/t/flickering-tft-display-when-drawing-graphics/1363482/14
Changed to work with ILI9341
Separated the sprite creation from the function bounceBall()
Added a function that changes the sprite color with every bounce
Added a cross hair
*/
#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"
constexpr byte TFT_DC {9};
constexpr byte TFT_CS {10};
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
constexpr int canvasWidth {26};
constexpr int canvasHeight {26};
constexpr int size {10};
int xlimit;
int ylimit;
int xvelocity = 1;
int yvelocity = 1;
int x = 0;
int y = 0;
GFXcanvas1 canvas(canvasWidth, canvasHeight);
void setup() {
tft.begin();
tft.setRotation(1);
tft.fillScreen(ILI9341_BLACK);
xlimit = tft.width() - canvasWidth;
ylimit = tft.height() - canvasHeight;
createBall();
bounceBall();
}
void createBall() {
canvas.fillScreen(0);
canvas.fillCircle(canvasWidth / 2, canvasHeight / 2, size, 0x01);
}
uint16_t colors[] = {ILI9341_RED, ILI9341_BLUE, ILI9341_GREEN, ILI9341_YELLOW};
constexpr int noOfColors = sizeof(colors) / sizeof(uint16_t);
void bounceBall() {
int index = 0;
while (1) {
tft.drawBitmap(x, y, canvas.getBuffer(), canvasWidth, canvasHeight, colors[index], 0);
drawCrossHair();
x += xvelocity;
if (x == xlimit or x == 0) {
xvelocity = -xvelocity;
next(index);
}
y += yvelocity;
if (y == ylimit or y == 0) {
yvelocity = -yvelocity;
next(index);
}
}
}
void next(int &idx) {
idx++;
if (idx >= noOfColors) {
idx = 0;
}
}
void drawCrossHair() {
int dispWidth = tft.width();
int dispHeight = tft.height();
tft.drawFastVLine(dispWidth / 2, 0, dispHeight, ILI9341_YELLOW);
tft.drawFastHLine(0, dispHeight / 2, dispWidth, ILI9341_YELLOW);
}
void loop() {
// put your main code here, to run repeatedly:
}