# ==========================================
# Pico_DataLogger -> microSD (SPI1)
# Hardware:
# SPI1: SCK=14, MOSI=15, MISO=12, CS=13
# Buzzer: GP22 (opcional)
# ==========================================
import time
import uos
from machine import Pin, SPI, PWM
# -----------------------------
# Memoria SD (SPI)
# -----------------------------
SPI_ID = 1
PIN_SCK = 14
PIN_MOSI = 15
PIN_MISO = 12
PIN_SD_CS = 13
# -----------------------------
# Buzzer (opcional)
# -----------------------------
PIN_BUZZER = 22
buzzer = PWM(Pin(PIN_BUZZER))
buzzer.duty_u16(0)
def beep(ms=60, freq=2000):
try:
buzzer.freq(freq)
buzzer.duty_u16(1200)
time.sleep_ms(ms)
finally:
buzzer.duty_u16(0)
# -----------------------------
# SD mount helpers
# -----------------------------
def ensure_dir(path):
try:
uos.stat(path)
except OSError:
uos.mkdir(path)
def mount_sd(mount_point="/sd"):
"""
Monta la SD en /sd.
Requiere sdcard.py (módulo sdcard).
"""
import sdcard # debe existir en el filesystem del Pico
spi = SPI(
SPI_ID,
baudrate=10_000_000,
polarity=0,
phase=0,
sck=Pin(PIN_SCK),
mosi=Pin(PIN_MOSI),
miso=Pin(PIN_MISO),
)
cs = Pin(PIN_SD_CS, Pin.OUT)
sd = sdcard.SDCard(spi, cs)
# crear punto de montaje si no existe
try:
uos.stat(mount_point)
except OSError:
uos.mkdir(mount_point)
# montar
uos.mount(sd, mount_point)
return mount_point
# -----------------------------
# Logger
# -----------------------------
def write_data_to_file(filepath):
"""Escribe la fecha y hora en un archivo en la SD."""
try:
t = time.localtime()
dia, mes = t[2], t[1]
hora, minuto, segundo = t[3], t[4], t[5]
info_tiempo = "{:02}/{:02} {:02}:{:02}:{:02}".format(
dia, mes, hora, minuto, segundo
)
print("Escribiendo:", info_tiempo)
with open(filepath, "a") as f:
f.write(info_tiempo + "\n")
beep(25, 2500)
except OSError as e:
print("Error SD/archivo:", e)
beep(200, 600)
def main():
led = Pin("LED", Pin.OUT)
# Montar SD y preparar carpeta
mp = mount_sd("/sd")
data_dir = mp + "/logs"
ensure_dir(data_dir)
filepath = data_dir + "/datos1.dat"
print("Guardando en:", filepath)
print("Contenido /sd:", uos.listdir("/sd"))
while True:
write_data_to_file(filepath)
# Heartbeat LED
led.value(1)
time.sleep(0.2)
led.value(0)
# Periodo de muestreo (1s)
time.sleep(0.8)
if __name__ == "__main__":
main()