首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将重量传感器数据获取到csv文件时出现问题

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

Stack Overflow用户
提问于 2020-06-06 03:51:35
回答 1查看 85关注 0票数 0

我刚做了一个覆盆子皮刻度。下面的代码运行良好。皮重完成后,它准确地称出物体的重量,并同时在rasp-pi屏幕上显示时间/日期和权重值。但是,它不会对csv文件做任何操作。列上没有名称,没有数据。奇怪的是,代码运行时没有显示任何错误。能请任何人看看出了什么问题吗?谢谢!宝琳娜

代码语言:javascript
复制
#! /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()
EN

回答 1

Stack Overflow用户

发布于 2020-06-06 17:14:03

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

代码语言:javascript
复制
    #! /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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62223181

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档