You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MicroPython数据记录仪SD卡文件无法循环追加数据问题排查

问题分析与解决方案

核心问题原因

  • 文件存在性判断逻辑错误:原代码用file_name not in uos.listdir("/sd")检查文件是否存在,但uos.listdir("/sd")返回的是文件名(如temperature_log.txt),而非完整路径(/sd/temperature_log.txt),导致判断永远为真。每次循环都会以'w'模式创建文件,直接覆盖原有内容,最终仅保留最后一条记录。
  • SD卡数据同步不彻底:部分SD卡控制器需要强制同步文件系统才能将缓存数据写入物理介质,仅靠flush()可能无法保证数据持久化。

修复步骤

1. 修正文件存在性判断

替换log_temperature函数中的文件检查逻辑,使用uos.path.exists()直接判断完整路径的文件是否存在:

# 检查文件是否存在,不存在则创建并写入表头
if not uos.path.exists(file_name):
    with open(file_name, 'w') as file:
        file.write('日期,时间,内部温度(°C),DS18B20_1温度(°C),DS18B20_2温度(°C),土壤湿度(%)\n')

2. 强制同步文件系统

在追加写入后,调用uos.sync()强制将缓存数据写入SD卡物理介质,避免数据丢失:

with open(file_name, 'a') as file:
    file.write(...)
    file.flush()
uos.sync()  # 确保数据写入SD卡

3. 脚本退出时安全卸载SD卡

添加异常捕获逻辑,在手动终止脚本时卸载SD卡,防止文件系统损坏:

# 主循环改为带异常捕获的结构
try:
    wlan = connect_to_wifi()
    initialize_sd_card()
    while True:
        # 原主循环所有内容
except KeyboardInterrupt:
    print("脚本终止,正在卸载SD卡...")
    uos.umount("/sd")
    print("SD卡已安全卸载。")

完整修复后的log_temperature函数

def log_temperature(data_to_send):
    file_name = "/sd/temperature_log.txt"

    try:
        # 修正文件存在性判断逻辑
        if not uos.path.exists(file_name):
            with open(file_name, 'w') as file:
                file.write('日期,时间,内部温度(°C),DS18B20_1温度(°C),DS18B20_2温度(°C),土壤湿度(%)\n')

        # 追加写入数据
        with open(file_name, 'a') as file:
            file.write('{},{},{:.2f},{:.2f},{:.2f},{:.2f}\n'.format(
                data_to_send['date'], 
                data_to_send['time'], 
                data_to_send['temperature'], 
                data_to_send['temperature_ds1'],
                data_to_send['temperature_ds2'],
                data_to_send['Soil_moisture']
            ))
            file.flush()
        uos.sync()  # 强制同步到物理介质

    except Exception as e:
        print("记录温度时出错:", e)

额外建议

  • 仅在脚本启动时挂载一次SD卡,避免重复挂载导致的文件系统异常。
  • 测试时缩短循环间隔(如time.sleep(5)),快速验证追加功能是否正常。
  • 使用正品SD卡,劣质存储卡可能存在写入缓存异常、数据丢失等问题。

内容的提问来源于stack exchange,提问作者Tom Armstrong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 10:29:55