Created
September 26, 2024 16:34
-
-
Save thetrung/281d3ea6a2b401cfc7180a1fd27a57b3 to your computer and use it in GitHub Desktop.
ESP32 Fetch BTC price from CoinDesk API
This file contains 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 <LiquidCrystal_I2C.h> | |
#include <ESP8266WiFi.h> | |
#include <WiFiClient.h> | |
#include <ArduinoJson.h> | |
// Change ID/PWD | |
const char* ssid = "YOUR_SSID"; | |
const char* password = "YOUR_PASSWORD"; | |
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C Address of LCD 16x02 | |
void setup() { | |
Serial.begin(115200); | |
lcd.begin(); | |
lcd.backlight(); | |
WiFi.begin(ssid, password); | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
Serial.println("Connecting to WiFi..."); | |
} | |
Serial.println("Connected to WiFi"); | |
lcd.print("Connected"); | |
delay(2000); | |
} | |
void loop() { | |
WiFiClient client; | |
const char* host = "api.coindesk.com"; | |
const char* url = "/v1/bpi/currentprice/BTC.json"; | |
if (client.connect(host, 80)) { | |
client.print(String("GET ") + url + " HTTP/1.1\r\n" + | |
"Host: " + host + "\r\n" + | |
"Connection: close\r\n\r\n"); | |
delay(500); | |
String line; | |
while (client.available()) { | |
line = client.readStringUntil('\n'); | |
if (line.startsWith("{")) { | |
DynamicJsonDocument doc(1024); | |
deserializeJson(doc, line); | |
float price = doc["bpi"]["USD"]["rate_float"]; | |
lcd.clear(); | |
lcd.print("BTC Price: "); | |
lcd.print(price); | |
break; | |
} | |
} | |
} else { | |
Serial.println("Connection failed"); | |
} | |
client.stop(); | |
delay(60000); //ms | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment