#include <WiFi.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Defining the WiFi channel speeds up the connection:
#define WIFI_CHANNEL 10
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// Initialize the OLED display
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// Array of cryptocurrencies you want to track
const char* cryptoSymbols[] = {
"bitcoin",
"ethereum",
"litecoin",
"ripple",
"cardano",
"polkadot",
};
// Number of cryptocurrencies in the array
const int numCryptoSymbols = sizeof(cryptoSymbols) / sizeof(cryptoSymbols[0]);
void setup() {
// Start Serial for debugging
Serial.begin(115200);
// Initialize OLED display with I2C address 0x3C
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println("SSD1306 allocation failed");
while (1);
}
Serial.println();
Serial.print("ESP Board MAC Address: ");
Serial.println(WiFi.macAddress());
WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL);
Serial.print("Connecting to WiFi ");
Serial.print(WIFI_SSID);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println(" Connected!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println();
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
}
void loop() {
// put your main code here, to run repeatedly:
// Loop through all the cryptocurrencies
Serial.println("Getting data from APIs");
for (int i = 0; i < numCryptoSymbols; i++) {
// Clear the display
display.clearDisplay();
Serial.println("Cleaning display...");
// Get crypto price from API
float price = getCryptoPrice(cryptoSymbols[i]);
Serial.print("Get price: ");
Serial.println(price);
// Display the price on the OLED
display.setCursor(0, 0);
display.setTextSize(2);
display.println(cryptoSymbols[i]);
display.print("Price: $");
display.setTextSize(2);
display.println(price, 2); // Display two decimal places
display.display();
delay(4000); // Delay in milliseconds between each cryptocurrency display
}
}
float getCryptoPrice(const char* cryptoSymbol) {
String url = "https://api.coingecko.com/api/v3/simple/price";
url += "?ids=";
url += cryptoSymbol;
url += "&vs_currencies=usd";
HTTPClient http;
http.begin(url);
int httpResponseCode = http.GET();
float price = 0;
if (httpResponseCode == 200) {
String payload = http.getString();
const size_t capacity = JSON_OBJECT_SIZE(1) + JSON_OBJECT_SIZE(1) + 20;
DynamicJsonDocument doc(capacity);
deserializeJson(doc, payload);
price = doc[cryptoSymbol]["usd"].as<float>();
}
http.end();
return price;
}