#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#define TFT_CS 10
#define TFT_DC 9
#define TFT_RST 8
Adafruit_ILI9341 display = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);
const int buttonPin = 7;
const int potPin = A0;
int prevMaxValue = -1;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
display.begin();
display.setRotation(0); // Portrait mode
display.fillScreen(ILI9341_BLACK);
display.setTextSize(3);
display.setTextColor(ILI9341_BLUE);
centerText("Dice Roller", 60);
delay(2000);
randomSeed(analogRead(A1));
display.fillScreen(ILI9341_BLACK);
}
void loop() {
int potValue = analogRead(potPin);
int maxValue = map(potValue, 0, 1023, 2, 100);
if (maxValue != prevMaxValue) {
prevMaxValue = maxValue;
displayMaxValue(maxValue);
}
if (digitalRead(buttonPin) == LOW) {
delay(50); // Debounce
if (digitalRead(buttonPin) == LOW) {
displayRollingDiamond();
delay(1000);
display.fillScreen(ILI9341_BLACK);
int diceRoll = random(1, maxValue);
displayDice(diceRoll);
delay(1000);
display.fillScreen(ILI9341_BLACK);
}
}
}
// ==== Display Functions ====
void centerText(String txt, int y) {
int16_t x1, y1;
uint16_t w, h;
display.getTextBounds(txt, 0, y, &x1, &y1, &w, &h);
display.setCursor((display.width() - w) / 2, y);
display.print(txt);
}
void displayMaxValue(int maxVal) {
display.fillRect(0, 10, display.width(), 30, ILI9341_BLACK);
display.setTextSize(2);
display.setTextColor(ILI9341_YELLOW);
centerText("Max: " + String(maxVal), 10);
}
void displayRollingDiamond() {
display.fillScreen(ILI9341_BLACK);
int cx = display.width() / 2;
int cy = display.height() / 2;
int size = 40;
display.drawLine(cx, cy - size, cx + size, cy, ILI9341_RED); // Top-right
display.drawLine(cx + size, cy, cx, cy + size, ILI9341_GREEN); // Bottom-right
display.drawLine(cx, cy + size, cx - size, cy, ILI9341_BLUE); // Bottom-left
display.drawLine(cx - size, cy, cx, cy - size, ILI9341_WHITE); // Top-left
}
void displayDice(int number) {
display.setTextSize(5);
display.setTextColor(ILI9341_WHITE);
int textY = (display.height() - 8 * 5) / 2;
int textWidth = 6 * 5 * ((number < 10) ? 1 : 2);
int textX = (display.width() - textWidth) / 2;
display.setCursor(textX, textY);
display.print(number);
}