|
| 1 | +#include <ArduinoJson.h> |
| 2 | +#include <ESP8266WiFi.h> |
| 3 | + |
| 4 | +const char* ssid = "TP-Link_408"; |
| 5 | +const char* password = "84570550"; |
| 6 | + |
| 7 | +#define CD_API "/v1/bpi/currentprice.json" |
| 8 | +#define CD_URL "api.coindesk.com" |
| 9 | + |
| 10 | +static char respBuffer[4096]; |
| 11 | +WiFiClient client; |
| 12 | + |
| 13 | +void setup() { |
| 14 | + Serial.begin(115200); |
| 15 | + delay(10); |
| 16 | + Serial.print("Connecting to "); |
| 17 | + Serial.println(ssid); |
| 18 | + WiFi.begin(ssid, password); |
| 19 | + while (WiFi.status() != WL_CONNECTED) { |
| 20 | + delay(500); |
| 21 | + Serial.print("."); |
| 22 | + } |
| 23 | + Serial.println("WiFi connected"); |
| 24 | + Serial.print("IP address: "); |
| 25 | + Serial.println(WiFi.localIP()); |
| 26 | +} |
| 27 | + |
| 28 | +void loop() { |
| 29 | + getData(); |
| 30 | + delay(7650); |
| 31 | +} |
| 32 | + |
| 33 | +void getData() { |
| 34 | + const char request[] = |
| 35 | + "GET " CD_API " HTTP/1.1\r\n" |
| 36 | + "User-Agent: ESP8266/0.1\r\n" |
| 37 | + "Accept: */*\r\n" |
| 38 | + "Host: " CD_URL "\r\n" |
| 39 | + "Connection: close\r\n" |
| 40 | + "\r\n"; |
| 41 | + delay(100); |
| 42 | + |
| 43 | + if (!client.connect(CD_URL, 80)) { |
| 44 | + Serial.println("Connection failed"); |
| 45 | + return; |
| 46 | + } |
| 47 | + |
| 48 | + client.print(request); |
| 49 | + client.flush(); |
| 50 | + delay(1000); |
| 51 | + uint16_t index = 0; |
| 52 | + while(client.connected() || client.available()) { |
| 53 | + if(client.available()) { |
| 54 | + respBuffer[index++] = client.read(); |
| 55 | + delay(1); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + char * json = strchr(respBuffer,'{'); |
| 60 | + String json_str = String(json); |
| 61 | + uint16_t idx_d = json_str.lastIndexOf('d'); |
| 62 | + json_str.remove(idx_d,3); |
| 63 | + DynamicJsonDocument doc(1024); |
| 64 | + DeserializationError error = deserializeJson(doc, json); |
| 65 | + |
| 66 | + JsonObject bpi = doc["bpi"]; |
| 67 | + JsonObject usd = bpi["USD"]; |
| 68 | + String rate_float = usd["rate_float"]; |
| 69 | + |
| 70 | + Serial.print(rate_float); |
| 71 | +} |
0 commit comments