"""
simple code to demo using the display for a virtual battery.
"""
from machine import Pin, I2C
import ssd1306
import time
time.sleep(0.1) # Wait for USB to become ready
print("Hello, CIT!")
# Setup OLED
i2c = I2C(0, scl=Pin(9), sda=Pin(8))
oled = ssd1306.SSD1306_I2C(128, 32, i2c)
# Constants
WIDTH = 128
HEIGHT = 32
BAR_Y = 24
BAR_HEIGHT = 8
DISCHARGE_TIME = 120
CHARGE_TIME = 60
FPS = 20
discharge_speed = WIDTH / (DISCHARGE_TIME * FPS)
charge_speed = WIDTH / (CHARGE_TIME * FPS)
charge = WIDTH
charging = False
def draw_battery_outline():
for x in range(WIDTH):
oled.pixel(x, BAR_Y, 1) # Top
oled.pixel(x, BAR_Y + BAR_HEIGHT - 1, 1) # Bottom
for y in range(BAR_Y, BAR_Y + BAR_HEIGHT):
oled.pixel(0, y, 1) # Left
oled.pixel(WIDTH - 1, y, 1) # Right
def draw_battery_fill(level):
limit = int(level)
if limit <= 2:
return
for x in range(1, limit - 1): # Inside the outline
for y in range(BAR_Y + 1, BAR_Y + BAR_HEIGHT - 1):
oled.pixel(x, y, 1)
# Main loop
while True:
oled.fill(0)
oled.text("Battery Demo", 0, 0)
draw_battery_outline()
draw_battery_fill(charge)
oled.text(f"{int(charge/128*100)}%", 90, 16)
oled.show()
if charging:
charge += charge_speed
if charge >= WIDTH:
charge = WIDTH
charging = False
else:
charge -= discharge_speed
if charge <= 0:
charge = 0
charging = True
time.sleep(1 / FPS)