#include <Adafruit_SSD1306.h>
#include <Wire.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include "secrets.h" // WiFi Configuration (WiFi name and Password)
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Powered by CoinGecko - https://www.coingecko.com/
const String url = "https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd";
const String cryptoCode = "ETH";
HTTPClient http;
String lastPrice;
void setup() {
Serial.begin(115200);
if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;); // Don't proceed, loop forever
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0,0);
display.println("Connecting to WiFi...");
display.display();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
}
Serial.print("CONNECTED to SSID: ");
Serial.println(ssid);
display.print("Connected to ");
display.println(ssid);
display.display();
delay(5000);
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
Serial.println("Getting current data...");
http.begin(url);
int httpCode = http.GET();
Serial.print("HTTP Code: ");
Serial.println(httpCode);
if (httpCode > 0) {
String payload = http.getString();
Serial.println("Received payload: ");
Serial.println(payload);
StaticJsonDocument<256> doc;
DeserializationError error = deserializeJson(doc, payload);
if (error) {
Serial.print(F("deserializeJson failed: "));
Serial.println(error.f_str());
delay(2500);
return;
}
Serial.print("HTTP Status Code: ");
Serial.println(httpCode);
if (!doc["ethereum"]["usd"].isNull()) {
String ETHUSDPrice = doc["ethereum"]["usd"].as<String>();
if(ETHUSDPrice != lastPrice) {
lastPrice = ETHUSDPrice;
display.clearDisplay();
display.setTextSize(1);
printCenter("ETH/USD", 0, 0);
printCenter("$" + ETHUSDPrice, 0, 32);
display.display();
} else {
Serial.print("Price hasn't changed (Current/Last): ");
Serial.print(ETHUSDPrice);
Serial.print(" : ");
Serial.println(lastPrice);
}
} else {
Serial.println("Failed to get ETH price from JSON.");
}
http.end();
} else {
Serial.println("Failed to connect to CoinGecko API");
}
delay(1250);
}
}
void printCenter(const String buf, int x, int y)
{
int16_t x1, y1;
uint16_t w, h;
display.getTextBounds(buf, x, y, &x1, &y1, &w, &h); //calc width of new string
display.setCursor((x - w / 2) + (128 / 2), y);
display.print(buf);
}