#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <SPI.h>
#define TFT_DC 2
#define TFT_CS 15
#define TFT_RST 4
#define TFT_MOSI 23
#define TFT_CLK 18
#define TFT_MISO 19
#define BTN_UP 5
#define BTN_DOWN 18
#define BTN_LEFT 19
#define BTN_RIGHT 21
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK, TFT_RST, TFT_MISO);
int pixelX = 160; // Initial X position
int pixelY = 120; // Initial Y position
const int pixelSize = 10; // Size of the pixel
const uint16_t pixelColor = ILI9341_GREEN; // Color of the pixel
const uint16_t bgColor = ILI9341_CYAN; // Background color
void setup() {
Serial.begin(115200);
// Increase SPI clock speed for faster drawing
SPI.begin();
SPI.setFrequency(40000000);
tft.begin();
tft.setRotation(1); // Landscape mode
// Fast fill screen
tft.startWrite();
tft.writeColor(bgColor, 320 * 240);
tft.endWrite();
// Draw border using fast horizontal and vertical line drawing
tft.startWrite();
tft.writeFastHLine(0, 0, tft.width(), ILI9341_WHITE);
tft.writeFastHLine(0, tft.height() - 1, tft.width(), ILI9341_WHITE);
tft.writeFastVLine(0, 0, tft.height(), ILI9341_WHITE);
tft.writeFastVLine(tft.width() - 1, 0, tft.height(), ILI9341_WHITE);
tft.endWrite();
// Set up button pins
pinMode(BTN_UP, INPUT_PULLUP);
pinMode(BTN_DOWN, INPUT_PULLUP);
pinMode(BTN_LEFT, INPUT_PULLUP);
pinMode(BTN_RIGHT, INPUT_PULLUP);
drawPixel();
Serial.println("Setup complete");
}
void loop() {
int dx = 0, dy = 0;
// Check button states
if (digitalRead(BTN_UP) == LOW) dy = -1;
if (digitalRead(BTN_DOWN) == LOW) dy = 1;
if (digitalRead(BTN_LEFT) == LOW) dx = -1;
if (digitalRead(BTN_RIGHT) == LOW) dx = 1;
if (dx != 0 || dy != 0) {
movePixel(dx, dy);
delay(50); // Add a small delay to debounce and control speed
}
}
void movePixel(int dx, int dy) {
// Calculate new position
int newX = constrain(pixelX + dx, 1, tft.width() - pixelSize - 1);
int newY = constrain(pixelY + dy, 1, tft.height() - pixelSize - 1);
// Only redraw if the position has changed
if (newX != pixelX || newY != pixelY) {
tft.startWrite();
// Erase old pixel
tft.writeFillRect(pixelX, pixelY, pixelSize, pixelSize, bgColor);
// Update position
pixelX = newX;
pixelY = newY;
// Draw new pixel
tft.writeFillRect(pixelX, pixelY, pixelSize, pixelSize, pixelColor);
tft.endWrite();
}
}
void drawPixel() {
tft.startWrite();
tft.writeFillRect(pixelX, pixelY, pixelSize, pixelSize, pixelColor);
tft.endWrite();
}