/*
Forum: https://forum.arduino.cc/t/flickering-tft-display-when-drawing-graphics/1363482
Wokwi: https://wokwi.com/projects/425674675562707969
ec2021
*/
#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 byte potiX {A0};
constexpr byte potiY {A1};
constexpr int radius {20};
unsigned long lastTime = 0;
int dispWidth;
int dispHeight;
class BallClass {
private:
int _x;
int _y;
int _rad = -1;
void fillSquare(){
tft.fillRect(_x-_rad-1, _y-_rad-1, 2*(_rad+1),2*(_rad+1), ILI9341_BLACK);
}
void paint(uint16_t color) {
tft.fillCircle(_x, _y, _rad, color);
}
public:
void set(int dx, int dy, int rad, boolean useRectAngle) {
if (_rad > -1) {
if (useRectAngle){
fillSquare();
} else {
paint(ILI9341_BLACK);
}
}
_x = dx;
_y = dy;
_rad = rad;
paint(ILI9341_RED);
}
};
BallClass ball;
void setup() {
Serial.begin(115200);
Serial.println("Graphics Example");
tft.begin();
tft.setRotation(1);
dispWidth = tft.width();
dispHeight = tft.height();
Serial.println(dispWidth);
Serial.println(dispHeight);
clearScreen();
}
void loop(void) {
if (millis() - lastTime > 100) {
lastTime = millis();
handleData();
}
}
void clearScreen() {
tft.fillScreen(ILI9341_BLACK);
}
void handleData() {
static int oldX = -1;
static int oldY = -1;
int val = analogRead(potiX);
int xPos = map(val,1023,0,radius,dispWidth-radius);
val = analogRead(potiY);
int yPos = map(val,0,1023,radius,dispHeight-radius);
if (xPos != oldX || yPos != oldY ){
oldX = xPos;
oldY = yPos;
ball.set(xPos,yPos,radius, true); // true = clear ball by rectangle else clear by redraw ball in black color
drawCrossHair();
}
}
void drawCrossHair(){
tft.drawFastVLine(dispWidth/2,0,dispHeight,ILI9341_YELLOW);
tft.drawFastHLine(0,dispHeight/2,dispWidth,ILI9341_YELLOW);
}