簡體   English   中英

Python-將傳感器數據寫入文件

[英]Python- writing sensor data to a file

我正在嘗試編寫一個代碼,我可以在其中接收來自模擬傳感器的數據,並希望將數據寫入 .txt 文件。 我做了一些研究並編寫了這段代碼-

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import spidev
import time

spi = spidev.SpiDev()
spi.open(0, 0)
datafile = file.open("temperature.txt", "w")

def ReadChannel(channel):
    adc = spi.xfer2([1, 8+channel <<4, 0])
    data = ((adc[1]& 3) << 8) + adc[2]
    return data

def ConvertVolts(data, places):
    volts = (data*3.3)/float(1023)
    volts = round(volts, places)
    return volts

def ConvertTemp(data, places):
    temp = ((data*200)/float(1023))-50
    temp = round(temp, places)
    return temp

temp_channel = 0
delay = 5

while True:
    temp_level = ReadChannel(temp_channel)
    temp_volts = ConvertVolts(temp_level, 2)
    temp = ConvertTemp(temp_level, 2)

    print"Temperature (deg F): ", temp
    datafile.write(str(temp)+"\n")
    time.sleep(delay)

datafile.close()

但是當我運行這段代碼時,它會形成一個沒有文本的文件“溫度.txt”。 有人可以指出我的錯誤嗎? 如果有幫助,我從以下網站中獲得了一些靈感 - https://www.cl.cam.ac.uk/projects/raspberrypi/tutorials/temperature/step10.py http://www.raspberrypi-spy.co .uk/2013/10/analog-sensors-on-the-raspberry-pi-using-an-mcp3008/提前致謝

我認為您的文件輸出流永遠不會刷新到磁盤,因為您只是寫入文件然后用 control-c 結束循環,對嗎?

也許嘗試讓循環運行 10 次然后關閉文件,作為嘗試。 您是否獲得正確的打印溫度輸出?

為什么不使用內置的日志功能?? 那么它可能看起來像這樣!

import logging

logging.basicConfig(filename=PATHTOFILE, loglevel=logging.INFO)

那么你可以:

logging.info("TEXTTOWRITETOTHEFILEHERE")

而不是 datafile.write(......) 如果存在,它將附加到文件並添加日期/時間。 它還將處理文件,例如。 關閉()等。 應該不需要延遲!

換行:

datafile = file.open("temperature.txt", "w")

對此:

datafile = open("temperature.txt", "w")

因為它現在對我有用。 如果仍然沒有寫入文件,請檢查傳感器數據的獲取。 如果臨時變量打印正確,請閱讀以下內容。

為了您的目的,最好使用with關鍵字,因為它包括 .close() 甚至 try/finally 塊(非常適合循環公式)。 您可能希望使用“a”模式添加數據,然后使用“w”模式重寫它們:

while True:
    #read temp here
    with open("temperature", "a") as datafile:
        datafile.write(temp)

而不是不太一致:

datafile = open("temperature.txt", "w")
while True:
    #temp here
    datafile.write(temp)
datafile.close()

實際上從不關閉文件...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM