from machine import Pin, I2C, PWM, ADC #ADC = librairie analog to digital
import ssd1306
import time
# Hypothèse :
# Niveau de batterie lue sur la Pin 0 via ADV avec un diviseur de tension
# ----- CONFIG -----
#Pins
LED_PIN = 8 # built-in LED (adjust if needed)
LED_GREEN_PIN = 9 # built-in LED (adjust if needed
BUZZER_PIN = 10
SDA_PIN = 5 #Ecrans
SCL_PIN = 6 #Ecran
ENC_CLK = 2 #Hypothèse CLK du Rotary encoder en Pin 2
ENC_DT = 3 # et FT sur le Pin 3
ENC_SW = 4 #Switch encodeurs sur PIN 4
BAT_ADC_PIN = 0 # Lecture niveau de batterie sur Pin 0
# ---------- CONSTANTES ----------
MIN_BPM = 40
MAX_BPM = 240
MIN_VOL = 0
MAX_VOL = 100
MODES = ["BPM", "Volume", "Battery"]
#Screen
OLED_WIDTH = 72
OLED_HEIGHT = 40
MODES = ["BPM", "VOL", "BATT"]
# ---------- ETAT ----------
mode = 0 # 0=BPM, 1=Volume, 2=Battery
BPM = 60
volume = 50 # %
last_clk = 0
last_button = 1
# ------------------
# Setup LED
led = Pin(LED_PIN, Pin.OUT)
# Buzzer PWM
buzzer = PWM(Pin(BUZZER_PIN))
buzzer.freq(2000)
buzzer.duty(0)
# Setup I2C & OLED
i2c = I2C(0, scl=Pin(SCL_PIN), sda=Pin(SDA_PIN), freq=400000)
oled = ssd1306.SSD1306_I2C(OLED_WIDTH, OLED_HEIGHT, i2c)
# Encoder Input
clk = Pin(ENC_CLK, Pin.IN, Pin.PULL_UP)
dt = Pin(ENC_DT, Pin.IN, Pin.PULL_UP)
sw = Pin(ENC_SW, Pin.IN, Pin.PULL_UP)
last_clk = clk.value()
# Batterie ADC
bat_adc = ADC(Pin(BAT_ADC_PIN))
bat_adc.atten(ADC.ATTN_11DB) # jusqu’à ~3.6V
# ---------- FONCTIONS ----------
def read_battery_percent():
raw = bat_adc.read() # 0–4095
voltage = raw * 3.6 / 4095 # approx
percent = int((voltage - 3.0) / (4.2 - 3.0) * 100)
return max(0, min(100, percent))
def draw():
oled.fill(0)
if mode == 0:
text = "{} BPM".format(BPM)
elif mode == 1:
text = "Vol: {}%".format(volume)
else:
text = "Batt: {}V".format(read_battery_voltage())
# centrage horizontal simple
x = max(0, (OLED_WIDTH - len(text) * 8) // 2)
y = (OLED_HEIGHT - 8) // 2
oled.text(text, x, y)
oled.show()
def buzz(on):
if on and volume > 0:
duty = int(volume / 100 * 512)
buzzer.duty(duty)
else:
buzzer.duty(0)
# ---------- BOUCLE PRINCIPALE ----------
while True:
# --- Bouton : changer de mode ---
btn = sw.value()
if btn == 0 and last_button == 1:
mode = (mode + 1) % len(MODES)
time.sleep(0.2) # debounce
last_button = btn
# --- Encodeur : modifier valeur ---
clk_now = clk.value()
if clk_now != last_clk:
direction = 1 if dt.value() != clk_now else -1
if mode == 0: # BPM
BPM = max(MIN_BPM, min(MAX_BPM, BPM + direction))
elif mode == 1: # Volume
volume = max(MIN_VOL, min(MAX_VOL, volume + direction * 5))
last_clk = clk_now
beat_time = 60 / BPM
# --- ON ---
led.on()
buzz(True)
draw()
time.sleep(beat_time / 2)
# --- OFF ---
led.off()
buzz(False)
time.sleep(beat_time / 2)
Loading
grove-oled-sh1107
grove-oled-sh1107