如何使用python3从arduino获取模拟值?

2024-05-26 07:47:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试连接一个电位器,它返回0到1023之间的整数值。我正在尝试通过蓝牙将这些数据传输到python

数据确实被传输了,因为我在旋转电位计的时候在屏幕上得到了值。但是它没有显示为整数,而是显示为:b'\xff'

我知道实际上0是b'\x00',1023是b'\xff',我不知道这是什么意思。有人能提供一个修复程序,让它打印从0到1023的数字吗

import bluetooth

print ("Searching for devices...")
print ("")
nearby_devices = bluetooth.discover_devices ()
num = 0
print ("Select your device by entering its coresponding number...")
for i in nearby_devices:
    num += 1
    print (num, ": ", bluetooth.lookup_name (i))

selection = int (input ("> ")) - 1
print ("You have selected", bluetooth.lookup_name (nearby_devices[selection]))
bd_addr = nearby_devices[selection]

port = 1

sock = bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((bd_addr, port))

while True:

    data = sock.recv(1)
    print (data)

谢谢


Tags: nameforport整数lookupnumbdsock
1条回答
网友
1楼 · 发布于 2024-05-26 07:47:09

它以十六进制格式发送数字:

你数的不是0、1、2、3、4、5、6、7、8、9、10:

0、1、2、3、4、5、6、7、8、9、A、B、C、D、E、F、10

在这个格式中,A代表数字10,B代表数字11,依此类推。F是数字15,现在10并不像我们的十进制那样是“1*10+0*1”,而是“1*16+0*1”。所以hexa-10=deci-16

但是请注意,FF并没有给出1023,而是给出255,对于这个较大的数字,你需要接受更多的比特。你确定你读了所有的相关数据吗

现在有了这个方法,数据实际上是以字节的形式发送的,您必须将它们转换回int:Convert bytes to int?

相关问题 更多 >