将体重传感器数据获取到csv文件中的问题

问题描述 投票:0回答:1

我刚刚建立了一个树莓派秤。该代码(如下)效果很好。完成皮重处理后,它会精确称量物体,并同时在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()
python python-3.x python-2.7 raspberry-pi scale
1个回答
0
投票

检查文件夹和文件的权限,因为这可能是问题。我在RPi 3B +上运行了您的代码(没有缩放部分,请参见下文),并且运行良好。确保文件和文件夹均可写。我的传感器文件以前不存在,并且已按预期创建和填充。这是我测试过的:

    #! /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的内容是:

时间,体重2020-06-06 04:59:16.840512,150

© www.soinside.com 2019 - 2024. All rights reserved.