chess-timer/firmware or whatever!.py
2025-07-11 13:22:36 -07:00

109 lines
3 KiB
Python

import board
import busio
import digitalio
import adafruit_ssd1306
import time
i2c = busio.I2C(board.GP1, board.GP0)
oled = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c)
oled.fill(0)
oled.show()
switch1 = digitalio.DigitalInOut(board.GP14)
switch1.direction = digitalio.Direction.INPUT
switch1.pull = digitalio.Pull.UP
switch2 = digitalio.DigitalInOut(board.GP13)
switch2.direction = digitalio.Direction.INPUT
switch2.pull = digitalio.Pull.UP
player1_time = 300.0
player2_time = 300.0
current_turn = 0
last_update_time = 0.0
game_over = False
last_sw1_state = True
last_sw2_state = True
debounce_delay = 0.2
last_press_time = 0.0
oled.text("PRESS ANY BUTTON", 0, 12, 1)
oled.show()
while True:
current_monotonic_time = time.monotonic()
if not game_over:
if current_turn == 1:
elapsed = current_monotonic_time - last_update_time
player1_time -= elapsed
last_update_time = current_monotonic_time
if player1_time <= 0:
player1_time = 0.0
game_over = True
current_turn = 0
elif current_turn == 2:
elapsed = current_monotonic_time - last_update_time
player2_time -= elapsed
last_update_time = current_monotonic_time
if player2_time <= 0:
player2_time = 0.0
game_over = True
current_turn = 0
sw1_current_state = switch1.value
sw2_current_state = switch2.value
if (
not sw1_current_state
and last_sw1_state
and (current_monotonic_time - last_press_time) > debounce_delay
):
if not game_over:
if current_turn == 1:
current_turn = 2
last_update_time = current_monotonic_time
elif current_turn == 0:
current_turn = 2
last_update_time = current_monotonic_time
last_press_time = current_monotonic_time
if (
not sw2_current_state
and last_sw2_state
and (current_monotonic_time - last_press_time) > debounce_delay
):
if not game_over:
if current_turn == 2:
current_turn = 1
last_update_time = current_monotonic_time
elif current_turn == 0:
current_turn = 1
last_update_time = current_monotonic_time
last_press_time = current_monotonic_time
last_sw1_state = sw1_current_state
last_sw2_state = sw2_current_state
oled.fill(0)
p1_minutes = int(player1_time // 60)
p1_seconds = int(player1_time % 60)
p1_display = "{:02d}:{:02d}".format(p1_minutes, p1_seconds)
p2_minutes = int(player2_time // 60)
p2_seconds = int(player2_time % 60)
p2_display = "{:02d}:{:02d}".format(p2_minutes, p2_seconds)
oled.text("P1: {}".format(p1_display), 0, 0, 1)
oled.text("P2: {}".format(p2_display), 0, 16, 1)
if game_over:
if player1_time <= 0:
oled.text("P2 WINS!", 70, 0, 1)
elif player2_time <= 0:
oled.text("P1 WINS!", 70, 16, 1)
oled.show()