#include <WiFi.h>
#include <HTTPClient.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// OLED display TWI address
#define OLED_ADDR 0x3C
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// Declaration for SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// CoinGecko API URL
const char* apiURL = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=eur";
void setup() {
Serial.begin(115200);
// Initialize OLED
if(!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
display.display();
delay(2000); // Pause for 2 seconds
display.clearDisplay();
}
void loop() {
static float lastPrice = 0.0;
static float lastChange = 0.0;
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(apiURL);
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
float price = parsePrice(payload);
float change = calculateChange(price, lastPrice);
lastPrice = price;
lastChange = change;
// Now display the price and change
displayPriceChange(price, change);
} else {
Serial.println("Error on HTTP request");
}
http.end(); // Free the resources
}
delay(5000); // Update every 5 seconds
}
float parsePrice(const String& payload) {
// Parse the JSON payload for the price
int startIndex = payload.indexOf("eur\":") + 5;
int endIndex = payload.indexOf("}", startIndex);
return payload.substring(startIndex, endIndex).toFloat();
}
float calculateChange(float newPrice, float lastPrice) {
// Calculate the percentage change
if (lastPrice == 0) return 0;
return ((newPrice - lastPrice) / lastPrice) * 100;
}
void displayPriceChange(float price, float change) {
display.clearDisplay();
display.setTextSize(2); // Large text for the price
display.setTextColor(WHITE);
// Display the price
display.setCursor(0, 16);
display.print('$'); // Display the currency symbol
display.print(price, 2); // Two decimal places
// Display the percentage change
display.setTextSize(1); // Smaller text for the percentage
display.setCursor(0, 0);
if(change >= 0) {
display.print("+");
}
display.print(change, 2);
display.print("%");
//dispay currency types
display.setTextSize(1);
display.setCursor(100, 40);
display.print("LIVE");
// Display the label "BITCOIN" at the bottom
display.setTextSize(1);
display.setCursor((SCREEN_WIDTH - (6 * 7)) / 2, 56); // Center the text
display.print("BITCOIN");
display.display(); // Update the display with all the new graphics
}