from machine import Pin, I2C, ADC
import time
from ssd1306 import SSD1306_I2C
# ── Composants ──────────────────────────────────────────
led = Pin(13, Pin.OUT) # LED indicateur (GP13)
bouton = Pin(3, Pin.IN, Pin.PULL_UP)
i2c = I2C(0, scl=Pin(1), sda=Pin(0))
oled = SSD1306_I2C(128, 64, i2c)
pot = ADC(27)
# ── État du chronomètre ──────────────────────────────────
running = False # en cours / arrêté
start_ms = 0 # ticks_ms au dernier démarrage
elapsed_ms = 0 # millisecondes accumulées
was_pressed = False # anti-rebond bouton
was_max = False # anti-rebond potentiomètre (réinit.)
# ── Fonctions utilitaires ────────────────────────────────
def format_time(ms):
"""Retourne (mm, ss, cs) depuis ms."""
total_s = ms // 1000
minutes = total_s // 60
seconds = total_s % 60
centisec = (ms % 1000) // 10
return minutes, seconds, centisec
def display(minutes, seconds, centisec, running, reset_msg=False):
oled.fill(0)
oled.text("Chronometre", 10, 0)
oled.text("-" * 16, 0, 10)
time_str = "{:02d}:{:02d}.{:02d}".format(minutes, seconds, centisec)
oled.text(time_str, 24, 28)
if reset_msg:
oled.text("REINITIALISE", 8, 50)
else:
status = "En cours..." if running else "Arrete"
oled.text(status, 0, 50)
oled.show()
# ── Boucle principale ────────────────────────────────────
while True:
now = time.ticks_ms()
# 1. Lecture bouton (bascule démarrage/arrêt)
pressed = bouton.value() == 0
if pressed and not was_pressed:
if running:
# Arrêt : on fige le temps accumulé
elapsed_ms += time.ticks_diff(now, start_ms)
running = False
else:
# Démarrage
start_ms = now
running = True
was_pressed = pressed
# 2. Lecture potentiomètre (réinitialisation si max)
pot_val = pot.read_u16()
reset_msg = False
if pot_val >= 65000 and not was_max:
elapsed_ms = 0
running = False
start_ms = 0
was_max = True
reset_msg = True
elif pot_val < 65000:
was_max = False
# 3. Calcul du temps courant
if running:
current_ms = elapsed_ms + time.ticks_diff(now, start_ms)
else:
current_ms = elapsed_ms
# 4. LED : allumée si running
led.value(1 if running else 0)
# 5. Affichage OLED
m, s, cs = format_time(current_ms)
display(m, s, cs, running, reset_msg)
time.sleep_ms(30)