我刚做了一个覆盆子皮刻度。下面的代码运行良好。皮重完成后,它准确地称出物体的重量,并同时在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()发布于 2020-06-06 17:14:03
检查文件夹和文件的权限,因为这可能是问题所在。我在我的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
https://stackoverflow.com/questions/62223181
复制相似问题