将重量传感器数据获取到csv文件时出现问题

2024-06-16 13:56:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚做了一个树莓皮秤。下面的代码运行良好。皮重完成后,它会准确称量物体,同时在rasp pi屏幕上显示时间/日期和重量值。但是,它对csv文件没有任何作用。列上没有名称,没有数据。奇怪的是,代码运行时没有显示错误。谁能看看出了什么问题吗? 谢谢 波琳娜

#! /usr/bin/python2
import csv
import datetime
import time

#tare and use the scale
EMULATE_HX711=False

referenceUnit = 1

if not EMULATE_HX711:
    import RPi.GPIO as GPIO
    from hx711 import HX711
else:
    from emulated_hx711 import HX711

def cleanAndExit():
    print("Cleaning...")

    if not EMULATE_HX711:
        GPIO.cleanup()

    print("Bye!")
    sys.exit()

hx = HX711(5, 6)

hx.set_reading_format("MSB", "MSB")

#CALCULATE THE REFFERENCE UNIT
hx.set_reference_unit(1903.3090)

hx.reset()

hx.tare()

print("Tare done! Add weight now...")
#measure weight and write it to csv
while True:
    try:
       # gets the weight. 
        val = hx.get_weight(5)
       # problems here, doesn't write to csv 
        with open('/home/pi/Desktop/sensor2.csv', 'w') as csv_file:
            writer = csv.writer(csv_file)
    # Write a header row with the name of each column.
            writer.writerow(['Time', 'weight'])
    # loop generating new sensor readings every and writing them
    # to the CSV file.
            while True:
        # Make some sensor data.
                reading_time = datetime.datetime.now()
                weight = hx.get_weight(5)   
        # Print out the data and write to the CSV file.
                print('Time: {0} weight: {1}'.format(reading_time, weight))
                writer.writerow([reading_time, weight])
        hx.power_down()
        hx.power_up()
        time.sleep(0.05)

    except (KeyboardInterrupt, SystemExit):
        cleanAndExit()

Tags: andcsvthetoimportdatetimetimefile
1条回答
网友
1楼 · 发布于 2024-06-16 13:56:33

检查文件夹和文件的权限,因为这可能是问题所在。我在我的RPI3b+上运行了你的代码(没有下面的比例部分),它运行得非常好。确保文件和文件夹都是可写的。我的传感器文件以前不存在,已按预期创建和填充。这就是我测试的:

    #! /usr/bin/python2
    import csv
    import datetime
    import time

    with open('sensor.csv', 'w') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow(['Time', 'weight'])
        reading_time = datetime.datetime.now()
        weight = 150
        writer.writerow([reading_time, weight])

sensor.csv的内容是:

Time,weight
2020-06-06 04:59:16.840512,150

相关问题 更多 >