Saturday, February 11, 2023

Raspberry Pico W TM1637 display and JSON object

Raspberry Pico W project shows Bitcoin value on TM1637 display from JSON object.  

TM1637 LED 7-segment display you need the tm1627 library. Download it from Thonny plug-ins.

Code in MicroPython Thonny IDE

Data from a JSON object stored in the response variable. The json() method of the response object is used to parse the JSON data and convert it into a MicroPython dictionary.

JSON object:

The value of the "USD" rate is then being accessed using the following line of code: data["bpi"]["USD"]["rate_float"]. This line accesses the "bpi" key of the dictionary, then accesses the "USD" key within that dictionary, and finally accesses the "rate_float" key within the "USD" dictionary. The resulting value is stored in the price variable.

Create a new script by clicking the new button on Thonny IDE. Copy and paste the following code.

CODE secrets.py

SSD="SSID" PASS="PASSWORD"

Replace SSID and PASSWORD with your own Wi-Fi credentials.


CODE main.py

import network

import utime

from machine import I2C, Pin

import tm1637 

import secrets

import time

import urequests


led = machine.Pin("LED", machine.Pin.OUT)


wlan = network.WLAN(network.STA_IF)

wlan.active(True)

wlan.connect(secrets.SSD, secrets.PASS)

print(wlan.isconnected())


# Get the current Bitcoin price

def get_price():

    url = "https://api.coindesk.com/v1/bpi/currentprice/BTC.json"

    response = urequests.get(url)

    data = response.json()

    price = data["bpi"]["USD"]["rate_float"]

    return price


def round_to_even(n):

    if n % 2 == 0.5:

        return round(n) + 1 if round(n) % 2 == 1 else round(n)

    return round(n)


display = tm1637.TM1637(clk=Pin(0), dio=Pin(1)) # put the right pins


while True:

    price = get_price()

    result = round_to_even(price)

    if price is None:

        for i in range(3):

            led.value(not led.value())

            utime.sleep(0.5)

    else:

       led.value(1)

       print(result) # print result in Shell

       display.scroll(str(result))

       time.sleep(20)


Raspberry Pico W Pinouts and TM1637





No comments:

Post a Comment