I bought a device (inclinometer) that produces data which I want to attach to my post in a readable format. How can I do this using python?
I have the following script:
import binascii
import serial
ser = serial.Serial('COM1', 9600)
s = ser.read()
hex_string = binascii.hexlify(s).decode('utf-8')
print(hex_string)
I have added an example of how the inclinometer is sending data over COM port.
答案 0 :(得分:0)
由于并非所有信息都能提供最佳答案,因此需要做出一些假设以缩小可能的答案。
在该示例中,假设倾斜仪给出的数据流不仅仅包括x轴和y轴协调。因此,引入了while循环。内置倾斜度计还会有一个数据请求暂停,以防止运行此python脚本(raspberry-pi?)的目标设备中发生数据泛滥。
也许此脚本用于多处理模式?然后,您可能想包括一个步骤,将当前的x,y坐标与定义的参考值进行比较(不包括在内,但应在while循环的结尾)。
import binascii
import serial
import time
set_sloop = 0 # control flag for result
loop_checks = 0 # control flag to prevent data-flooding.
ser = serial.Serial('COM1', 9600)
while set_sloop == 0: # get hex-data from device every 2 seconds (see pause interval)
s = ser.read()
hex_string = binascii.hexlify(s).decode('utf-8')
print(hex_string)
if str(hex_string[0:9]) == '680D008400': # used (x,y) string identifier based on example 0x84.
xh = hex_string[10:13]
yh = hex_string[16:19]
x = '%s.%s' % xh[0:1], xh[2:3]
y = '%s.%s' % yh[0:1], yh[2:3]
xt = 'x = %s deg' % x
yt = 'y = %s deg' % y
print (xt, yt)
set_sloop = 1
loop_checks += 1
if loop_checks == 10:
time.sleep(2) # pause interval: wait 2 seconds before requesting new data.
loop_checks = 0
print ('got inclination: (%s , %s) deg' % x, y)
# ... remaining code to "auto-post inclination" goes here ...
注意:考虑到搜索字符串'680D008400'并不完全符合示例中给出的描述。缺少一组数字。公司文字中有错字?