Binary & Weather Clock

Binary Clock / Weather monitor

Prototype

Components Needed

ComponentQuantity
Raspberry Pi Pico W1
Micro USB Cable1
Breadboard1
WiresSeveral
Resistor2 - 220Ω , 1 - 330Ω
RGB LED1

Code

SSD1306

# MicroPython SSD1306 OLED driver, I2C and SPI interfaces
from micropython import const
import framebuf

# register definitions
SET_CONTRAST = const(0x81)
SET_ENTIRE_ON = const(0xA4)
SET_NORM_INV = const(0xA6)
SET_DISP = const(0xAE)
SET_MEM_ADDR = const(0x20)
SET_COL_ADDR = const(0x21)
SET_PAGE_ADDR = const(0x22)
SET_DISP_START_LINE = const(0x40)
SET_SEG_REMAP = const(0xA0)
SET_MUX_RATIO = const(0xA8)
SET_IREF_SELECT = const(0xAD)
SET_COM_OUT_DIR = const(0xC0)
SET_DISP_OFFSET = const(0xD3)
SET_COM_PIN_CFG = const(0xDA)
SET_DISP_CLK_DIV = const(0xD5)
SET_PRECHARGE = const(0xD9)
SET_VCOM_DESEL = const(0xDB)
SET_CHARGE_PUMP = const(0x8D)

# Subclassing FrameBuffer provides support for graphics primitives
# http://docs.micropython.org/en/latest/pyboard/library/framebuf.html
class SSD1306(framebuf.FrameBuffer):
    def __init__(self, width, height, external_vcc):
        self.width = width
        self.height = height
        self.external_vcc = external_vcc
        self.pages = self.height // 8
        self.buffer = bytearray(self.pages * self.width)
        super().__init__(self.buffer, self.width, self.height, framebuf.MONO_VLSB)
        self.init_display()

    def init_display(self):
        for cmd in (
            SET_DISP,  # display off
            # address setting
            SET_MEM_ADDR,
            0x00,  # horizontal
            # resolution and layout
            SET_DISP_START_LINE,  # start at line 0
            SET_SEG_REMAP | 0x01,  # column addr 127 mapped to SEG0
            SET_MUX_RATIO,
            self.height - 1,
            SET_COM_OUT_DIR | 0x08,  # scan from COM[N] to COM0
            SET_DISP_OFFSET,
            0x00,
            SET_COM_PIN_CFG,
            0x02 if self.width > 2 * self.height else 0x12,
            # timing and driving scheme
            SET_DISP_CLK_DIV,
            0x80,
            SET_PRECHARGE,
            0x22 if self.external_vcc else 0xF1,
            SET_VCOM_DESEL,
            0x30,  # 0.83*Vcc
            # display
            SET_CONTRAST,
            0xFF,  # maximum
            SET_ENTIRE_ON,  # output follows RAM contents
            SET_NORM_INV,  # not inverted
            SET_IREF_SELECT,
            0x30,  # enable internal IREF during display on
            # charge pump
            SET_CHARGE_PUMP,
            0x10 if self.external_vcc else 0x14,
            SET_DISP | 0x01,  # display on
        ):  # on
            self.write_cmd(cmd)
        self.fill(0)
        self.show()

    def poweroff(self):
        self.write_cmd(SET_DISP)

    def poweron(self):
        self.write_cmd(SET_DISP | 0x01)

    def contrast(self, contrast):
        self.write_cmd(SET_CONTRAST)
        self.write_cmd(contrast)

    def invert(self, invert):
        self.write_cmd(SET_NORM_INV | (invert & 1))

    def rotate(self, rotate):
        self.write_cmd(SET_COM_OUT_DIR | ((rotate & 1) << 3))
        self.write_cmd(SET_SEG_REMAP | (rotate & 1))

    def show(self):
        x0 = 0
        x1 = self.width - 1
        if self.width != 128:
            # narrow displays use centred columns
            col_offset = (128 - self.width) // 2
            x0 += col_offset
            x1 += col_offset
        self.write_cmd(SET_COL_ADDR)
        self.write_cmd(x0)
        self.write_cmd(x1)
        self.write_cmd(SET_PAGE_ADDR)
        self.write_cmd(0)
        self.write_cmd(self.pages - 1)
        self.write_data(self.buffer)


class SSD1306_I2C(SSD1306):
    def __init__(self, width, height, i2c, addr=0x3C, external_vcc=False):
        self.i2c = i2c
        self.addr = addr
        self.temp = bytearray(2)
        self.write_list = [b"\x40", None]  # Co=0, D/C#=1
        super().__init__(width, height, external_vcc)

    def write_cmd(self, cmd):
        self.temp[0] = 0x80  # Co=1, D/C#=0
        self.temp[1] = cmd
        self.i2c.writeto(self.addr, self.temp)

    def write_data(self, buf):
        self.write_list[1] = buf
        self.i2c.writevto(self.addr, self.write_list)


class SSD1306_SPI(SSD1306):
    def __init__(self, width, height, spi, dc, res, cs, external_vcc=False):
        self.rate = 10 * 1024 * 1024
        dc.init(dc.OUT, value=0)
        res.init(res.OUT, value=0)
        cs.init(cs.OUT, value=1)
        self.spi = spi
        self.dc = dc
        self.res = res
        self.cs = cs
        import time

        self.res(1)
        time.sleep_ms(1)
        self.res(0)
        time.sleep_ms(10)
        self.res(1)
        super().__init__(width, height, external_vcc)

    def write_cmd(self, cmd):
        self.spi.init(baudrate=self.rate, polarity=0, phase=0)
        self.cs(1)
        self.dc(0)
        self.cs(0)
        self.spi.write(bytearray([cmd]))
        self.cs(1)

    def write_data(self, buf):
        self.spi.init(baudrate=self.rate, polarity=0, phase=0)
        self.cs(1)
        self.dc(1)
        self.cs(0)
        self.spi.write(buf)
        self.cs(1)

Main

import utime
from machine import Pin, RTC, I2C
import urequests
import network, json
from ssd1306 import SSD1306_I2C
import time

WIDTH = 128
HEIGHT = 64

# Initialize I2C and OLED display
i2c = I2C(0, scl=Pin(17), sda=Pin(16), freq=400000)
display = SSD1306_I2C(WIDTH, HEIGHT, i2c)

# Load configuration
with open('config.json') as f:
    config = json.load(f)

if config['ssid'] == 'Enter_Wifi_SSID':
    raise ValueError("config.json has not been updated with your unique keys and data")

# Connect to WiFi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
print("Connecting to WiFi: {}".format(config['ssid']))
wlan.connect(config['ssid'], config['ssid_password'])

while not wlan.isconnected():
    time.sleep(1)  # Avoid busy-waiting

def sync_time_with_worldtimeapi_org(rtc):
    TIME_API = "http://worldtimeapi.org/api/timezone/Asia/Shanghai"
    retry_interval = 1  # seconds

    while True:
        try:
            response = urequests.get(TIME_API)
            data = response.json()
            response.close()

            current_time = data.get("datetime")
            if not current_time:
                raise ValueError("Datetime field is missing in response")

            date_part, time_part = current_time.split("T")
            year, month, day = date_part.split("-")
            year = int(year)
            month = int(month)
            day = int(day)
            time_part = time_part.split(".")[0]
            hours, minutes, seconds = time_part.split(":")
            hours = int(hours)
            minutes = int(minutes)
            seconds = int(seconds)
            week_day = data.get("day_of_week")
            if week_day is None:
                week_day = 0

            rtc.datetime((year, month, day, week_day, hours, minutes, seconds, 0))
            break

        except Exception as e:
            print(f"Error syncing time: {e}")
            time.sleep(retry_interval)  # Retry after a short delay

rtc = RTC()
sync_time_with_worldtimeapi_org(rtc)

def fetch_weather(api_key, city, country_code):
    WEATHER_API = f"http://api.openweathermap.org/data/2.5/weather?q={city},{country_code}&appid={api_key}&units=metric"
    try:
        response = urequests.get(WEATHER_API)
        data = response.json()
        response.close()
        if data['cod'] == 200:
            pressure = data['main']['pressure']
            temp_max = data['main']['temp_max']
            humidity = data['main']['humidity']
            weather_main = data['weather'][0]['main']
            return pressure, temp_max, humidity, weather_main
        else:
            return None, None, None, "Weather data not available"
    except Exception as e:
        print("Error fetching weather:", e)
        return None, None, None, "Error fetching weather"

def update_display(weather_data):
    # Get current time
    Y, M, D, W, H, M, S, SS = rtc.datetime()

    # Clear the display
    display.fill(0)
    
    # Display time
    display.text("Time:{:02}:{:02}:{:02}".format(H, M, S), 0, 0)
   
    # Display weather information
    pressure, temp_max, humidity, weather_main = weather_data
    if pressure is not None:
        display.text(f"Pressure: {pressure} hPa", 0, 20)
        display.text(f"Temp Max: {temp_max:.1f} C", 0, 30)
        display.text(f"Humidity: {humidity}%", 0, 40)
        display.text(f"Weather: {weather_main}", 0, 50)
    else:
        display.text(weather_main, 0, 20)
    
    # Show the updated display
    display.show()

# Define GPIO pins for LEDs
hour_msd_pins = [Pin(pin, Pin.OUT) for pin in [0, 1]]  # Most significant digit of hours
hour_lsd_pins = [Pin(pin, Pin.OUT) for pin in [2, 3, 4, 5]]  # Least significant digit of hours
minute_msd_pins = [Pin(pin, Pin.OUT) for pin in [6, 7, 8]]  # Most significant digit of minutes
minute_lsd_pins = [Pin(pin, Pin.OUT) for pin in [9, 10, 11, 12]]  # Least significant digit of minutes

def update_leds():
    # Get the current time
    Y, M, D, W, H, M, S, SS = rtc.datetime()

    # Calculate most significant and least significant digits for hours and minutes
    msd_hour = H // 10  # Most significant digit of the hour (0, 1, or 2)
    lsd_hour = H % 10  # Least significant digit of the hour (0-9)

    msd_minute = M // 10  # Most significant digit of minutes (0-5)
    lsd_minute = M % 10  # Least significant digit of minutes (0-9)

    # Convert to binary strings
    msd_hour_binary = '{:02b}'.format(msd_hour)  # 2 bits for most significant digit of hours
    lsd_hour_binary = '{:04b}'.format(lsd_hour)  # 4 bits for least significant digit of hours

    msd_minute_binary = '{:03b}'.format(msd_minute)  # 3 bits for most significant digit of minutes
    lsd_minute_binary = '{:04b}'.format(lsd_minute)  # 4 bits for least significant digit of minutes

    # Set the LED states based on the binary values for hours (most significant digit)
    for i in range(2):
        hour_msd_pins[i].value(int(msd_hour_binary[i]))
    
    # Set the LED states based on the binary values for hours (least significant digit)
    for i in range(4):
        hour_lsd_pins[i].value(int(lsd_hour_binary[i]))
    
    # Set the LED states based on the binary values for minutes (most significant digit)
    for i in range(3):
        minute_msd_pins[i].value(int(msd_minute_binary[i]))
    
    # Set the LED states based on the binary values for minutes (least significant digit)
    for i in range(4):
        minute_lsd_pins[i].value(int(lsd_minute_binary[i]))

# Main loop
last_weather_update = 0
weather_data = (None, None, None, "Fetching weather...")

while True:
    current_time = time.time()

    # Fetch weather data every 5 minutes
    if current_time - last_weather_update > 300:
        weather_data = fetch_weather(config['weather_api_key'], config['city'], config['country_code'])
        last_weather_update = current_time

    # Update display and LEDs
    update_display(weather_data)
    update_leds()
    time.sleep(1)  # Update every second

config

{
    "ssid": "Open_Internet",
    "ssid_password": "25802580",
    "query_interval_sec": 120,
    "weather_api_key": "ce54c4b03cfc0bd0fc037188def2d98e",
    "city": "Qingdao"
    "country_code": "CN"
}