Crypto prices in MicroPython on an ESP32 board

The objective of this tutorial is to capture real time crypto prices in MicroPython running on an ESP32 board. We will write Python code that will request real time Bitcoin or Ethereum crypto currency spot prices from Coinbase. Then, if the crypto currency price is over a specified amount the ESP32 board light will blink. This is a simple example of how blockchain and IOT (internet of things) can work together.

If this is your first time developing on an ESP32 microcontroller development board it is recommended to read this tutorial on developing with MicroPython and an ESP32 microcontroller development board. This introduction will explain what software to download, flashing the ESP32 board, and writing a simple program in Thonny.

ESP32 microcontroller development board

We will be using an ESP32 microcontroller development board for this project. The Arduino board has a dual core 32-bit microprocessor, internal memory and supports Wi-Fi / blue tooth. The predecessor of the ESP32 is the ESP8266.

For more detailed specifications for the ESP32 board visit Espressif or esp32.net. To buy an ESP32 board use one of the links below.

Amazon ESP32 microcontroller or ESP32 microcontroller with led

Program in Thonny IDE to capture crypto currency prices

The program that we will create and deploy on the ESP32 board will perform the following functions.

  1. Connect to the internet using WI-FI
  2. Request a real time crypto currency spot price from Coinbase
  3. Evaluate the crypto currency price and turn on the light on the ESP32 development board

To begin, copy and paste each line of code below in the shell section of Thonny. This will allow you to have a better understanding of what each line of code executes.

To begin, copy and paste each line of code in the shell section of the Thonny IDE. You will need to input you WI-FI ID and WI-FI password. Coinbase does not require an API key to obtain spot prices. Stepping through the process will be helpful to trouble shoot any potential problems.

Connecting to a WiFi Network

First connect the process to a Wi-Fi network using MicroPython. Import the network module to access the functions needed for establishing a connection to Wi-Fi.

import network

Our device will operate in station mode to connect to a WiFi network. We need to create an instance of the station WiFi interface . Call the constructor of the WLAN class and pass it the interface we want. In this case, we will use the network.STA_IF interface.

station = network.WLAN(network.STA_IF)

Now activate the network interface by calling the active method for our station object and pass True as an input argument.

station.active(True)

Use the connect method to establish a connection to your WiFi network. This method uses an SSID (network name) and your Wifi password as inputs.

station.connect("network_name", "password")

Finally confirm the connection to your WiFi network has been established by calling the isconnected method. The isconnected method will return true if the device is connected to a WiFi network. In addition call the ifconfig method to return the IP address, subnet mask, gateway and DNS addresses.

station.isconnected()

station.ifconfig()

The ip assigned to the ESP32 is an internal ip and it can not be used to receive connections from outside your network. If you would like to receive connections to your ESP32 board from outside the network you would need to configure port forwarding in your router.

HTTP GET requests to Coinbase for crypto currency prices

Coinbase offers a free HTTP request service to capture market data. The code will use this service to perform HTTP GET requests using MicroPython. To start install the urequests module in Thonny using the manage plug ins option under tools.

After running the commands above to connect to a Wi-Fi network import the urequests module. This module contains all the request functions we need for sending network GET requests.

import urequests

To perform an HTTP GET request we will call the get function of the urequests module. Pass in the URL of the destination as an input for the GET request. See the sample url below.

You can use any ticker that Coinbase supports as a url parameter. For more information about the Coinbase API visit their developer documentation website.

  • Bitcoin USD = BTC-USD
  • Ethereum USD = ETH-USD
  • etc.
response = urequests.get('https://api.coinbase.com/v2/prices/BTC-USD/spot')

After the GET request is made the response will return crypto spot price information. To access the content of the HTTP response we need to access its text property.

print(response.text)

The response of the request is returned in JSON format. So we can access the json property which will return a dictionary containing the parsed content.

parsed = response.json()

Finally we can access each individual JSON value by using its key from the dictionary object. Lets convert it to float and assign it to a variable (for later use).

btc_px = float(parsed["data"]["amount"])

Finally write the following code to turn the light on and off if the crypto currency price is greater then a specified value. Modify the float value of 1 below to meet your parameter.

    if crypto_px > float(1):
        led.on()
        sleep(0.5)
        led.off()
        sleep(0.5)
    else:
        led.off()

Crypto prices in MicroPython on an ESP32

The complete code for this project is listed below. Input your SSID, password and amount to compare to the Bitcoin / BTC crypto currency price. If the results compare to true the light on your ESP32 board will blink.

import network
import urequests
from time import sleep
from machine import Pin

led = Pin(2, Pin.OUT)

 

station = network.WLAN(network.STA_IF)
station.active(True)

station.disconnect()
station.connect("SSID", "PASSWORD")


#prints true if connected
station.isconnected()

#returns the IP address, subnet mask, gateway and DNS as output parameters
station.ifconfig()

while True:

    #get spot price of BTC from coinbase
    response = urequests.get('https://api.coinbase.com/v2/prices/BTC-USD/spot')

    #print the response
    print(response.text)

    #parse the response
    parsed = response.json()

    crypto_px = float(parsed["data"]["amount"])

    #print the price
    print(parsed["data"]["amount"])

    #if the crypto currency price is > value blink light
    if crypto_px > float(ENTERPRICE):
        led.on()
        sleep(0.5)
        led.off()
        sleep(0.5)
    else:
        led.off()

As seen in the video below the blue light on the board turns on when the price of the crypto currency is greater then the price specified in code.

Crypto prices in MicroPython running on an ESP32 board is an example of how blockchain and hardware with IOT capabilities can work together. Combining blockchain and hardware will result in solving many IOT (internet of things) use cases in the future.

Next – Ether balance in MicroPython on an ESP32 board

Ledger Nano X - The secure hardware wallet

2 thoughts on “Crypto prices in MicroPython on an ESP32 board

Leave a Reply