首页 > 解决方案 > 如何使用 python 3 从 arduino 获取模拟值?

问题描述

我正在尝试连接一个电位器,它返回 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)

谢谢!!!

标签: pythonarduinobluetooth

解决方案


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

而不是 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。对于更大的数字,您需要接收更多的咬。您确定您阅读了所有相关数据吗?

现在不碍事了,实际上数据是作为字节发送的,您必须将它们转换回整数:将字节转换为整数?


推荐阅读