Basic ESP8266 and bitcoin price example

This example was sent to me via one of my electronics sites, this example use an ESP8266 development board, there are many examples of these on the net that can be bought, I personal use the Wemos range

In the code example below we use the coindesk api, the json is parsed and then the results are displayed via the serial monitor. You will need a wifi connection for this example and need to update the following lines with your wifi details

const char* ssid = “your ssid here”; // insert your SSID
const char* password = “your password here”; // insert your password

There are better examples, we will look at them later using the ESP8266 and many other development boards such as ESP32, Arduino and Raspberry Pi.

Code


#include <ESP8266WiFi.h>

const char* ssid = "your ssid here"; // insert your SSID
const char* password = "your password here"; // insert your password

const char* host = "api.coindesk.com";
String url = "/v1/bpi/currentprice.json";

String id;
String value;

void setup()
{
Serial.begin(115200);
delay(10);

Serial.println("Bitcoin Prices");

//We start by connecting to a WiFi network

Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}

Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

void loop()
{
Serial.println();
Serial.print("connecting to ");
Serial.println(host);

WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort))
{
Serial.println("connection failed");
return;
}

Serial.print("Requesting URL: ");
Serial.println(url);

// This will send the request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
delay(10);

unsigned int i = 0;
int n = 1;
char json[500] ="{";
while (!client.find("\"USD\":{")){}
while (i<600)
{
if(client.available())
{
char c = client.read();
json[n]=c;
if(c=='}') break;
n++;
i=0;
}
i++;
}

Serial.println(json);
id += json;
value += json;

id = id.substring(9,12);
Serial.print(id);
Serial.print("= ");

value = value.substring(99,106);
Serial.println(value);

id="";
value="";

Serial.println("closing");
delay(60000);
}

Testing

Open the serial monitor and you should see something like this

Connecting to **********
…..
WiFi connected
IP address:
192.168.1.15

connecting to api.coindesk.com
Requesting URL: /v1/bpi/currentprice.json
{“code”:”USD”,”symbol”:”&#36;”,”rate”:”9,644.0638″,”description”:”United States Dollar”,”rate_float”:9644.0638}
USD= “:9644.
closing connection

connecting to api.coindesk.com
Requesting URL: /v1/bpi/currentprice.json
{“code”:”USD”,”symbol”:”&#36;”,”rate”:”9,640.6238″,”description”:”United States Dollar”,”rate_float”:9640.6238}
USD= “:9640.
closing connection