#include <SoftwareSerial.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <SPI.h>
// Define pins for the TFT display
#define TFT_CS 10
#define TFT_RST 9
#define TFT_DC 8
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);
// Bluetooth setup
SoftwareSerial BTSerial(2, 3); // RX, TX for battery percentage
SoftwareSerial JoystickBTSerial(10, 11); // RX, TX for joystick
const int joyXPin = A0; // Joystick X-axis pin
const int joyYPin = A1; // Joystick Y-axis pin
int indicator_length = 200;
int indicator_height = 60;
int offset = 5;
int x_margin = 10;
int previousBattery1Percentage = -1;
int previousBattery2Percentage = -1;
void setup() {
tft.begin();
tft.setRotation(1); // Adjust rotation if necessary
tft.fillScreen(ILI9341_BLACK);
BTSerial.begin(9600);
JoystickBTSerial.begin(9600);
pinMode(joyXPin, INPUT);
pinMode(joyYPin, INPUT);
}
void loop() {
// Joystick handling
int joyX = analogRead(joyXPin);
int joyY = analogRead(joyYPin);
String direction = getDirection(joyX, joyY);
JoystickBTSerial.println(direction);
// Battery percentage handling
if (BTSerial.available()) {
String data = BTSerial.readStringUntil('\n');
int separatorIndex = data.indexOf(',');
int battery1Percentage = data.substring(0, separatorIndex).toInt();
int battery2Percentage = data.substring(separatorIndex + 1).toInt();
if (battery1Percentage != previousBattery1Percentage) {
drawBattery(battery1Percentage, 20);
previousBattery1Percentage = battery1Percentage;
}
if (battery2Percentage != previousBattery2Percentage) {
drawBattery(battery2Percentage, 100);
previousBattery2Percentage = battery2Percentage;
}
}
delay(100); // Wait for 100ms
}
String getDirection(int x, int y) {
int centerX = 512; // Center value for X
int centerY = 512; // Center value for Y
int threshold = 100; // Threshold to detect movement
if (x > centerX + threshold) {
if (y > centerY + threshold) {
return "UP_RIGHT";
} else if (y < centerY - threshold) {
return "DOWN_RIGHT";
} else {
return "RIGHT";
}
} else if (x < centerX - threshold) {
if (y > centerY + threshold) {
return "UP_LEFT";
} else if (y < centerY - threshold) {
return "DOWN_LEFT";
} else {
return "LEFT";
}
} else {
if (y > centerY + threshold) {
return "UP";
} else if (y < centerY - threshold) {
return "DOWN";
} else {
return "CENTER";
}
}
}
void drawBattery(int level, int y_position) {
tft.fillRect(x_margin, y_position, indicator_length + offset + 12, indicator_height, ILI9341_BLACK); // Clear the previous battery indicator
tft.drawRect(x_margin, y_position, indicator_length + offset, indicator_height, ILI9341_WHITE); // Draw the outline of the battery
for (int i = 0; i < 5; i++) {
if (level > i * 20) {
tft.fillRect(x_margin + offset + i * indicator_length / 5, y_position + offset, indicator_length / 5 - offset, indicator_height - 2 * offset, ILI9341_GREEN);
}
}
tft.fillRect(indicator_length + offset + x_margin, y_position + (indicator_height - 20) / 2, 12, 20, ILI9341_WHITE); // Draw the battery edge
}