/*
Forum: https://forum.arduino.cc/t/adafruit-320x240-mit-teensy-4-0-flickering/1350338
Wokwi: https://wokwi.com/projects/421983019578677249
ec2021
Draw Bars/Pointers with minimum erasure effort
*/
#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"
#define TFT_DC 9
#define TFT_CS 10
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
constexpr float pi = 3.1415926;
constexpr float Radius = 100.0;
unsigned long lastTime = 0;
void setup() {
Serial.begin(115200);
Serial.println("Graphics Example");
tft.begin();
clearScreen();
}
void loop(void) {
Bar();
if (millis() - lastTime > 100) {
lastTime = millis();
Pointer();
}
}
void clearScreen() {
tft.fillScreen(ILI9341_BLACK);
}
void Pointer() {
static int Angle = 180;
static int AngleDx = 10;
int x = int(cos(Angle * pi / 180) * Radius);
int y = int(sin(Angle * pi / 180) * Radius);
drawPointer(x, y, ILI9341_YELLOW);
Angle += AngleDx;
if ((Angle < 0) || (Angle > 180)) {
AngleDx = -AngleDx;
}
}
// *****************************************
// Removes previous line and draws new line
// *****************************************
void drawPointer(int nX, int nY, uint16_t color) {
constexpr int cX = 120;
constexpr int cY = 160;
static int oX = 1000;
static int oY = 1000;
if (oX < 1000) {
tft.drawLine(cX, cY, cX + oX, cY + oY, ILI9341_BLACK);
}
tft.drawLine(cX, cY, cX + nX, cY + nY, color);
oX = nX;
oY = nY;
}
// *****************************************
// Draws bar with minimum flicker effect
// *****************************************
void drawBar(int value, int16_t color) {
constexpr int startX = 100;
constexpr int startY = 20;
constexpr int width = 20;
static int oValue = 0;
int y0, y1;
int delta = value - oValue;
if (delta == 0) {
return;
}
if (delta > 0) {
// Longer
y0 = startY + oValue;
y1 = value - oValue;
tft.fillRect(startX, y0, width, y1, color);
} else {
// Shorter
y0 = startY + value;
y1 = oValue;
tft.fillRect(startX, y0, width, y1, ILI9341_BLACK);
}
oValue = value;
}
void Bar() {
static unsigned long lastT = 0;
static int i = 1;
static int d = 1;
if (millis() - lastT > 100) {
lastT = millis();
drawBar(i * 10, ILI9341_RED);
i += d;
if (i > 10 || i < 2) {
d = -d;
}
}
}