closed_loop_speed_pid.py

M5Stack Encoder Motor Driver Unit (DRV8837DSGR) · File : closed_loop_speed_pid.py · Language : MicroPython · Use case : Régulation de vitesse en boucle fermée via PID pour maintenir une consigne stable malgré les charges variables.

Software PID controller implementation to maintain constant speed by reading the encoder and adjusting PWM.

Uses the I2C interface to read encoder data and write the PWM setpoint. The code assumes generic register addresses (0x10 for speed, 0x01 for PWM) which must be adapted to the M5Stack firmware datasheet. Requires a stable external motor power supply to avoid voltage drops that disturb encoder readings.

closed_loop_speed_pid.py

import time
from m5stack import i2c

# Adresse I2C par défaut du driver
ADDR = 0x2F
bus = i2c.I2C(1)

# Configuration PID simple
Kp, Ki, Kd = 2.0, 0.5, 0.1
setpoint = 150  # Vitesse cible (unités arbitraires ou RPM selon config)
integral = 0
last_error = 0

while True:
    # Lecture de la vitesse actuelle depuis le registre de l'encoder (ex: reg 0x10)
    # Note: Les registres exacts dépendent du firmware M5Stack spécifique
    current_speed = bus.readfrom_mem(ADDR, 0x10, 2)
    speed_val = int.from_bytes(current_speed, 'little')
    
    error = setpoint - speed_val
    integral += error
    derivative = error - last_error
    
    output = Kp * error + Ki * integral + Kd * derivative
    
    # Limitation de la sortie PWM (0-255)
    pwm_val = max(0, min(255, int(output)))
    
    # Écriture du duty cycle PWM (ex: reg 0x01)
    bus.writeto_mem(ADDR, 0x01, bytes([pwm_val]))
    
    last_error = error
    time.sleep(0.05)

← Back to the board