#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED width, in pixels
#define SCREEN_HEIGHT 64 // OLED height, in pixels
// create an OLED display object connected to I2C
Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
#define BUTTON 13 // PullUP Button
#define SCBUTTON 12 // Second PullUP Button
#include <WiFi.h> // Wifi librairie
#include <HTTPClient.h> // Http Librairie to request GET
// Data to connect on WIFI
const char* ssid = "Wokwi-GUEST";
const char* password = ""; // Empty for WokWi
void setup() {
Serial.begin(9600);
// initialize OLED display with I2C address 0x3C
if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("failed to start SSD1306 OLED"));
while (1);
}
// Set pinMode for button
pinMode(BUTTON, INPUT_PULLUP);
// Set pinMode for second button
pinMode(SCBUTTON, INPUT_PULLUP);
// Connect to wifi
WiFi.mode(WIFI_STA); //Optional
WiFi.begin(ssid, password);
// Wait for WiFi
while(WiFi.status() != WL_CONNECTED){
Serial.print(".");
delay(100);
}
// Show wifi status
Serial.println("\nConnected to the WiFi network");
Serial.print("Local ESP32 IP: ");
Serial.println(WiFi.localIP());
}
void showOled(String value){
oled.clearDisplay(); // clear display
oled.setTextSize(1); // set text size
oled.setTextColor(WHITE); // set text color
oled.setCursor(0, 2); // set position to display (x,y)
oled.println(value); // set text
oled.display();
}
// Function to send request and return value
String sendRequest(String range){
// URL to request
String serverName = "https://guardia-dice.glitch.me/" + range;
// Get HTTP Client
HTTPClient http;
// Begin GET Request with a rand (6 or 20)
http.begin(serverName.c_str());
// Get status code of the request
int httpResponseCode = http.GET();
// Check url respons
if(httpResponseCode>0){
// Get result
String result = http.getString();
// Return data if ok
if(result == "Critical error"){
// Recurcive method
return sendRequest(range);
}else{
return result;
}
}else{
// Recurcive method
return sendRequest(range);
}
}
void loop() {
// Delay to handle system
delay(10);
// Detect when we click on the button
if(digitalRead(BUTTON) == 0){
// Send request
Serial.print("Rolling a 6 sided dice....... ");
String result = sendRequest("6");
// Show result
Serial.println("You got a " + result +" !");
showOled("You rolled: "+result+" ! ");
// Delay to avoid spam or second request
delay(1000);
}else if(digitalRead(SCBUTTON) == 0){
// Send request
Serial.print("Rolling a 20 sided dice....... ");
String result = sendRequest("20");
// Show result
Serial.println("You got a " + result +" !");
showOled("You rolled: "+result+" ! ");
// Delay to avoid spam or second request
delay(1000);
}
}