journalisation.py

Raspberry Pi Pico · File : journalisation.py · Language : Python · Use case : Journaliser des mesures en CSV dans la mémoire flash de la carte

MicroPython exposes the internal flash as a filesystem: this script writes a temperature CSV there every 5 s, in append mode so data is never overwritten. The file is later retrieved like a USB stick.

Hardware

A Raspberry Pi Pico (RP2040 dual Cortex-M0+ @ 133 MHz) with MicroPython installed, powered over USB. No external part; the board flash is the storage (a few MB available).

Wiring

No wiring: internal readings only. Add a sensor (DHT, ADC) keeping the same line format.

How it works

open(FICHIER, "a") opens in append; each line holds seconds since boot and the temperature. os.stat()[6] gives the size to watch the fill-up.

Running it

Install MicroPython if needed (hold BOOTSEL, plug USB, drop the .uf2 file), then copy the script to the board drive or via Thonny. The script auto-starts when named main.py.

Variants

Add rotation (rename journal.csv to journal-1.csv past 100 KB), or timestamp with an external RTC such as DS3231.

journalisation.py

# Journal CSV dans le systeme de fichiers interne (flash) de la carte.
import time
import os
import machine

FICHIER = "journal.csv"
ENTETE = "timestamp,temperature_c
"

def temperature():
    adc = machine.ADC(4)   # capteur thermique interne
    v = adc.read_u16() * 3.3 / 65535.0
    return 27.0 - (v - 0.706) / 0.001721

# Creer le fichier avec l'entete s'il n'existe pas.
if FICHIER not in os.listdir():
    with open(FICHIER, "w") as f:
        f.write(ENTETE)

print("Journalisation toutes les 5 s")
while True:
    t = temperature()
    horodatage = time.ticks_ms() // 1000
    with open(FICHIER, "a") as f:      # append : pas d'ecrasement
        f.write("%d,%.2f
" % (horodatage, t))
    taille = os.stat(FICHIER)[6]
    print("+1 ligne (%d octets au total)" % taille)
    time.sleep(5)

# Recuperer le CSV : ouvrir le lecteur de la carte ou "Thonny > Fichiers".

← Back to the board