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

BeagleBone项目Python实现每秒写入温度传感器数据到CSV文件问题

BeagleBone温度数据每秒写入CSV实现方案

你现有代码的核心问题是每次循环用覆写模式打开CSV文件,导致之前写入的数据全部被清空,只能保留最新一次的采集结果。以下是修复后的可直接运行代码:

import Adafruit_BBIO.ADC as ADC
import time
import csv
import os

sensor_pin = 'P9_40'
ADC.setup()

filename = "temperature_log.csv"
# 提前定义表头,仅在文件不存在首次创建时写入
fields = ['Timestamp', 'Milivolts', 'Celsius', 'Fahrenheit']
# 检查文件是否存在,不存在就先写表头
file_exists = os.path.isfile(filename)

with open(filename, 'a', newline='', encoding='utf-8') as csvfile:
    csvwriter = csv.writer(csvfile)
    if not file_exists:
        csvwriter.writerow(fields)

    while True:
        # 采集数据
        reading = ADC.read(sensor_pin)
        millivolts = reading * 1800  # 1.8V参考电压 = 1800 mV
        temp_c = (millivolts - 500) / 10
        temp_f = (temp_c * 9/5) + 32
        # 取当前时间戳
        current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print(f'{current_time} mv={millivolts:.1f} C={temp_c:.1f} F={temp_f:.1f}')

        # 写入数据,无需手动加分隔符
        csvwriter.writerow([current_time, millivolts, temp_c, temp_f])
        # 强制刷新缓冲区,避免数据缓存在内存中没写入磁盘
        csvfile.flush()

        time.sleep(1)

核心修改说明

  • 把文件打开模式从w(覆写)改为a(追加),每次新采集的数据会添加到文件末尾,不会覆盖历史数据
  • 仅在首次创建CSV文件时写入表头,避免每次循环都重复写入表头行
  • 移除了数据中多余的|字符,csv.writer会自动用逗号分隔每列数据,无需手动添加分隔符
  • 增加了时间戳字段,方便后续查看每条数据的采集时间
  • 增加了flush()操作,确保每次采集的数据立即写入磁盘,不会因为程序意外退出丢失缓存中的数据
  • 把文件打开操作移到了循环外部,避免每秒重复打开关闭文件,减少IO开销
  • 调整了sleep的位置,确保两次采集的间隔稳定在1秒左右

内容的提问来源于stack exchange,提问作者Nicholai Mørch Rindarøy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 21:54:05