我正在尝试制作一个连续监控传感器的系统,包括注册传感器离线(服务器无法访问)的时间。
该系统基于 Raspberry Pi 作为服务器,Arduino Leonardo 作为带有传感器的节点,数据通过 XRF 从 Arduino 传输到 Raspberry。
我使用 Python 脚本和 pySerial 来收集数据。我的 Python 技能很差,我需要帮助来弄清楚当 Arduino 和 Raspberry 之间的连接丢失时如何继续监控,以及当重新建立连接时可以再次收集传感器数据而无需重新启动脚本。
Python 脚本如下:
import serial
from datetime import datetime
ser = serial.Serial('/dev/ttyAMA0', 9600)
while True:
#Arduino sends sensor analog reading when receiving the letter "k"
ser.write('k')
datetime = str(datetime.now())
print(datetime)
print(ser.readline())
此时,一旦服务器失去与客户端的连接,脚本就会停止。
最佳答案
我想您需要定期重新打开连接,并记录连接丢失的时刻?像这样的东西...
import serial
import time
from datetime import datetime
ser = serial.Serial('/dev/ttyAMA0', 9600)
while True:
if ser.isOpen()==True:
ser.write('k') # Arduino sends sensor analog reading when receiving the letter "k"
datetime = str(datetime.now())
print(datetime)
print(ser.readline())
time.sleep(1) # take a break so that you dont thrash the sensor with requests all the time
else:
try:
print "Lost connection at %s" % str(datetime.now())
ser.open()
except:
print "Cannot open port."
exit(-1)
关于python - Raspberry Pi 通过 XRF 连续传感器监控与 Arduino 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24282500/