在树莓派(Raspberry Pi)上使用Python将传感器数据写入独立的文本文件是一个常见的任务,通常涉及以下几个步骤:
以下是一个简单的示例,展示如何使用Python将模拟的温度传感器数据写入文本文件:
import time
import random
# 模拟传感器数据(例如温度)
def read_sensor_data():
return random.uniform(20.0, 30.0) # 返回一个20到30之间的随机温度值
# 将数据写入文件
def write_to_file(data, filename="sensor_data.txt"):
with open(filename, 'a') as file:
file.write(f"{data}\n")
# 主程序
def main():
while True:
temperature = read_sensor_data()
print(f"当前温度: {temperature}°C")
write_to_file(temperature)
time.sleep(5) # 每5秒记录一次数据
if __name__ == "__main__":
main()
sudo
运行脚本。'a'
模式打开文件,确保每次写入不会覆盖之前的数据。logging
)来记录操作日志,便于排查问题。通过以上步骤和建议,你应该能够在树莓派上成功地将传感器数据写入独立的文本文件。
领取专属 10元无门槛券
手把手带您无忧上云