🛠 Lire un capteur analogique du MCU depuis Python (Firmata)
Objectives
Use the official DFRobot method (tutorial "python_read_sensor") to read sensors from the x86 operating system: first upload the StandardFirmata firmware to the ATmega32U4, then a Python script with pyFirmata controls the pins remotely, without writing a single line of C. The method is identical on Windows and Linux — only the port name changes.
Hardware
- LattePanda Alpha + Arduino IDE + Python 3
pip install pyFirmataon the host- Analog sensor (potentiometer or light sensor) on A0
- Digital PIR motion sensor on D9 (0/1 output)
- Wiring according to the Arduino-compatible pins of the 50-pin connectors; power the sensors according to their datasheet (the pins follow the ATmega32U4/Leonardo characteristics)
Complete Code
Step 1 — In the Arduino IDE (board "Arduino Leonardo"): File → Examples → Firmata → StandardFirmata, then upload.
Step 2 — Host script:
# read_sensors.py — Python 3, Windows ou Linux
# Lit un capteur analogique sur A0 et un PIR numérique sur D9
# du coprocesseur Arduino intégré (StandardFirmata doit être téléversé).
import time
from pyfirmata import Arduino, util
PORT = 'COM5' # Windows : vérifier l'IDE Arduino ; Linux : '/dev/ttyACM0'
board = Arduino(PORT)
it = util.Iterator(board) # vide les entrées série pour que read ne bloque jamais
it.start
board.analog[0].enable_reporting
board.digital[9].enable_reporting
while True:
angle = board.analog[0].read # None au premier passage, puis 0.0..1.0
motion = board.digital[9].read # True/False venant du capteur PIR
print(f'A0={angle} D9(motion)={motion}')
time.sleep(0.5)
Expected Verification
After uploading StandardFirmata, the TX LED blinks briefly. The script first displays A0=None then floats between 0.0 and 1.0 that vary when turning the potentiometer; D9 changes to True when the PIR detects motion.
Common Errors
- Forgetting the
Iteratorfromutil: without it,readreturnsNoneindefinitely because Firmata frames are never consumed. - StandardFirmata not uploaded (or an old sketch occupying the pins): the pyFirmata connection hangs at startup.
- Interpreting
A0=Noneas a failure: this is normal during the first read cycle, while waiting for the analog report to arrive. - Confusing the pyFirmata normalized value (0.0–1.0) with the raw 0–1023 value of the Leonardo's 10-bit ADC.
Other tutorials for this board
Code examples for this board
clignotante.pyPythonbouton.pyPythonservo.pyPythonanalogique.pyPythonrespiration.pyPythonneopixel.pyPython