在 python 中从各种 USB 设备读取和存储各种数据
read and stock various data from various usb devices in python
我是 python 的初学者,我正在尝试从通过 USB 集线器连接到计算机的多个传感器(湿度、温度、压力传感器......)读取数据。我的主要目标是每五分钟记录一次这些传感器的不同值,然后将其存储起来进行分析。
我有我的传感器(来自 Hygrosens Instruments)的所有数据表和手册,我知道它们是如何工作的以及它们发送什么样的数据。但我不知道如何阅读它们。下面是我尝试过的,使用 pyserial.
|
1
2 3 4 5 6 7 8 9 10 |
import serial #import the serial library
from time import sleep #import the sleep command from the time library import binascii output_file = open('hygro.txt', 'w') #create a file and allow you to write in it only. The name of this file is hygro.txt ser = serial.Serial("/dev/tty.usbserial-A400DUTI", 9600) #load into a variable 'ser' the information about the usb you are listening. /dev/tty.usbserial.... is the port after plugging in the hygrometer, 9600 is for bauds, it can be diminished |
所以现在我想找到数据行的结尾,因为我需要的测量信息在以"V"开头的行中,如果我的传感器的数据表,它说一行结束by ,所以我想一次读取一个字节并查找''。所以我想这样做:
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
while 1:
read_byte = ser.read(size=8) #read a byte read_byte_hexa =binascii.hexlify(read_byte) #convert the byte into hexadecimal trad_hexa = int(read_byte_hexa , 16) #convert the hexadecimal into an int in purpose to compare it with another int |
但我不确定它是否有效,我的意思是我认为它没有时间读取第二个字节,我正在读取的第二个字节,它不完全是第二个字节。所以这就是我想使用缓冲区的原因,但我真的不明白我该怎么做。我要去寻找它,但如果有人知道一种更简单的方法来做我想做的事,我已经准备好尝试了!
谢谢
相关讨论
- 请向我们展示您的代码示例,以便我们可以看到您到目前为止所做的尝试。
- 如果您举例说明传感器如何通过 USB 传输数据,也会很方便。
- 我添加了一些信息,希望现在对您来说更好!
您似乎认为该传感器的通信协议的行尾字符是 4 个不同的字符:
由于协议是结构化的,因此您可以通过逐行读取传感器的数据来大大简化您的代码。以下内容可帮助您入门:
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import time
def parse_info_line(line): def parse_value_line(line): def twos_comp(val, bits): def listen_on_serial(ser): |
作为测试,以下代码摘录模拟传感器发送一些数据(以行分隔,使用回车作为行尾标记),这些数据是我从您链接到的 pdf 中复制的 (FAQ_terminalfenster_E. pdf).
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
>>> import serial
>>> import io >>> >>> ser = serial.serial_for_url('loop://', timeout=1) >>> serio = io.TextIOWrapper(io.BufferedRWPair(ser, ser), newline='\ ', line_buffering=True) >>> serio.write(u'A1A0\ ' # simulation of starting to listen halfway between 2 records ... '$\ ' # marks the end of the previous record ... '@\ ' # marks the start of a new sensor record ... 'I0101010000000000001B\ ' # info about a sensor's probe ... 'V0109470D\ ' # data matching that probe ... 'I0202010000000000002B\ ' # other probe, same sensor ... 'V021BB55C\ ') # data corresponding with 2nd probe 73L >>> >>> listen_on_serial(serio) 23.75 70.93 >>> |
请注意,当行尾字符不是
相关讨论
- 非常感谢你!现在可以了!我什么都看不到,因为我的波特率(9600)错误,文档的第一部分是基于这个波特率的。如果有人想查看我的(丑陋的)代码,请告诉我我仍在改进它。