import machine
import ssd1306
import time
# Constants for modes
MODE_NORMAL_CLOCK = 0
MODE_STOPWATCH = 1
MODE_TIMER = 2
# Constants for button pins
BUTTON_MODE_PIN = 5
BUTTON_SELECTOR_PIN = 4
BUTTON_INCREASE_PIN = 0
BUTTON_DECREASE_PIN = 2
# Constants for SSD1306 display
DISPLAY_WIDTH = 128
DISPLAY_HEIGHT = 64
DISPLAY_SCL_PIN = 22
DISPLAY_SDA_PIN = 21
# Global variables
mode = MODE_NORMAL_CLOCK
stopwatch_running = False
stopwatch_start_time = 1
timer_seconds = 60
# Initialize SSD1306 display
i2c = machine.SoftI2C(scl=machine.Pin(DISPLAY_SCL_PIN), sda=machine.Pin(DISPLAY_SDA_PIN))
oled = ssd1306.SSD1306_I2C(DISPLAY_WIDTH, DISPLAY_HEIGHT, i2c)
# Initialize buttons
button_mode = machine.Pin(BUTTON_MODE_PIN, machine.Pin.IN, machine.Pin.PULL_UP)
button_selector = machine.Pin(BUTTON_SELECTOR_PIN, machine.Pin.IN, machine.Pin.PULL_UP)
button_increase = machine.Pin(BUTTON_INCREASE_PIN, machine.Pin.IN, machine.Pin.PULL_UP)
button_decrease = machine.Pin(BUTTON_DECREASE_PIN, machine.Pin.IN, machine.Pin.PULL_UP)
# Helper functions
def update_display(value):
oled.fill(0)
oled.text(value, 0, 0)
oled.show()
def change_mode(pin):
global mode
mode = (mode + 1) % 3
def select_action(pin):
global mode, stopwatch_running, stopwatch_start_time, timer_seconds
if mode == MODE_NORMAL_CLOCK:
pass
elif mode == MODE_STOPWATCH:
if stopwatch_running:
stopwatch_running = False
else:
stopwatch_running = True
stopwatch_start_time = time.ticks_ms()
elif mode == MODE_TIMER:
timer_seconds = 60 # Reset timer to 60 seconds
def increase_value(pin):
global timer_seconds
if mode == MODE_TIMER and timer_seconds < 3600:
timer_seconds += 1
def decrease_value(pin):
global timer_seconds
if mode == MODE_TIMER and timer_seconds > 0:
timer_seconds -= 1
button_mode.irq(trigger=machine.Pin.IRQ_FALLING, handler=change_mode)
button_selector.irq(trigger=machine.Pin.IRQ_FALLING, handler=select_action)
button_increase.irq(trigger=machine.Pin.IRQ_FALLING, handler=increase_value)
button_decrease.irq(trigger=machine.Pin.IRQ_FALLING, handler=decrease_value)
# Main loop
while True:
if mode == MODE_NORMAL_CLOCK:
current_time = time.localtime()
hours = current_time[3]
minutes = current_time[4]
seconds = current_time[5]
update_display("CLOCK: {:02d}:{:02d}:{:02d}".format(hours, minutes, seconds))
time.sleep_ms(500)
elif mode == MODE_STOPWATCH:
if stopwatch_running:
elapsed_time = time.ticks_diff(time.ticks_ms(), stopwatch_start_time)
update_display("{:02d}:{:02d}:{:02d}".format(elapsed_time // 3600000, (elapsed_time // 60000) % 60, (elapsed_time // 1000) % 60))
time.sleep_ms(500)
elif mode == MODE_TIMER:
update_display("Timer: {:02d}:{:02d}".format(timer_seconds // 60, timer_seconds % 60))
time.sleep_ms(1000)
if timer_seconds > 0:
timer_seconds -= 1