analogique.py

LattePanda Alpha · File : analogique.py · Language : Python · Use case : Acquitter un capteur analogique sur le MCU

The ATmega's 10-bit ADC flows into a timestamped CSV on the PC disk: a €20 acquisition card with unlimited storage, calibration corrections in pandas instead of C.

Hardware required

A LattePanda Alpha (x86 Intel m3-7Y30, Windows 10 or Linux) with its ATmega32U4 co-processor, Arduino Leonardo compatible, on the 50-pin headers. 1 0-5 V analog sensor (the 32U4 is 5 V, unlike 3.3 V SBCs).

Wiring

Signal on the header's A0, common GND. 5 V max input — 0-10 V sensors need a divider.

How it works

read_analog triggers a conversion on the MCU and returns the raw value over the serial bridge; the CSV writes with continuous flush. 10 Hz is the bridge's comfortable zone. The ATmega32U4 is a genuine Leonardo: flash it as « Arduino Leonardo » in the IDE through its internal COM port. Host-side, DFRobot's lattepanda Python library talks to it over serial.

Going further

A live matplotlib plot (the PC allows it), or threshold alerts via desktop notifications.

analogique.py

#!/usr/bin/env python3
# Capteur analogique sur A0 du MCU -> CSV cote hote, 10 Hz.
from pinpong.board import Board, Pin
import time, csv, datetime

Board().begin()
capteur = Pin(Pin.A0, Pin.IN)

with open("mesures.csv", "a", newline="") as f:
    w = csv.writer(f)
    if f.tell() == 0:
        w.writerow(["horodatage", "brut", "volts"])
    print("Acquisition 10 Hz (Ctrl-C pour finir)")
    try:
        while True:
            brut = capteur.read_analog()          # 0..1023 (10 bits MCU)
            volts = brut * 5.0 / 1023.0           # reference 5 V du 32U4
            w.writerow([datetime.datetime.now().isoformat(timespec="seconds"),
                        brut, round(volts, 3)])
            f.flush()                              # survit a un crash
            time.sleep(0.1)
    except KeyboardInterrupt:
        print("\nJournal clos.")

← Back to the board