Created
August 12, 2025 07:25
-
-
Save EDISON-SCIENCE-CORNER/ab2648068e10295fa2a785d613741b1d to your computer and use it in GitHub Desktop.
Arduino dice OLED
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <Wire.h> | |
| #include <Adafruit_GFX.h> | |
| #include <Adafruit_SSD1306.h> | |
| #define SCREEN_WIDTH 128 | |
| #define SCREEN_HEIGHT 32 | |
| #define OLED_RESET -1 | |
| Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); | |
| #define BUTTON_PIN 2 | |
| // Dice face patterns (5×5 grid) stored in PROGMEM | |
| const uint8_t diceFaces[6][5][5] PROGMEM = { | |
| { {0,0,0,0,0}, // 1 | |
| {0,0,0,0,0}, | |
| {0,0,1,0,0}, | |
| {0,0,0,0,0}, | |
| {0,0,0,0,0} }, | |
| { {1,0,0,0,0}, // 2 | |
| {0,0,0,0,0}, | |
| {0,0,0,0,0}, | |
| {0,0,0,0,0}, | |
| {0,0,0,0,1} }, | |
| { {1,0,0,0,0}, // 3 | |
| {0,0,0,0,0}, | |
| {0,0,1,0,0}, | |
| {0,0,0,0,0}, | |
| {0,0,0,0,1} }, | |
| { {1,0,0,0,1}, // 4 | |
| {0,0,0,0,0}, | |
| {0,0,0,0,0}, | |
| {0,0,0,0,0}, | |
| {1,0,0,0,1} }, | |
| { {1,0,0,0,1}, // 5 | |
| {0,0,0,0,0}, | |
| {0,0,1,0,0}, | |
| {0,0,0,0,0}, | |
| {1,0,0,0,1} }, | |
| { {1,0,0,0,1}, // 6 | |
| {0,0,0,0,0}, | |
| {1,0,0,0,1}, | |
| {0,0,0,0,0}, | |
| {1,0,0,0,1} } | |
| }; | |
| void drawDiceFace(uint8_t value, int x, int y, int size) { | |
| // value: 1 to 6 | |
| for (int row = 0; row < 5; row++) { | |
| for (int col = 0; col < 5; col++) { | |
| if (pgm_read_byte(&diceFaces[value - 1][row][col])) { | |
| display.fillCircle(x + col * size, y + row * size, size / 2, SSD1306_WHITE); | |
| } | |
| } | |
| } | |
| } | |
| void setup() { | |
| pinMode(BUTTON_PIN, INPUT_PULLUP); | |
| randomSeed(analogRead(A0)); // Seed for randomness | |
| if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { | |
| for (;;); // Don't proceed if display init fails | |
| } | |
| display.clearDisplay(); | |
| display.setTextColor(SSD1306_WHITE); | |
| display.setTextSize(1); | |
| display.setCursor(0, 0); | |
| display.println("Dice Roller Ready"); | |
| display.display(); | |
| } | |
| void loop() { | |
| static bool lastState = HIGH; | |
| bool currentState = digitalRead(BUTTON_PIN); | |
| if (lastState == HIGH && currentState == LOW) { // Button pressed | |
| int diceValue = random(1, 7); // Random number 1-6 | |
| display.clearDisplay(); | |
| display.setTextSize(1); | |
| display.setCursor(0, 0); | |
| display.print("You rolled: "); | |
| display.println(diceValue); | |
| drawDiceFace(diceValue, 90, 5, 4); // Draw dice at right side | |
| display.display(); | |
| } | |
| lastState = currentState; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment