0

I'm trying to connect a potentiometer which returns values of integers between 0 and 1023. I'm trying to get this data over Bluetooth to python.

The data is indeed getting transmitted because I do get values on the screen when rotating the potentiometer. But instead of showing up as integers, it shows up like this: b'\xff'

I know in fact that 0 is b'\x00' and 1023 is b'\xff', I have no idea what that's supposed to mean. Can someone offer a fix so it would print numbers from 0 to 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)

Thanks!!!

JohanC
  • 59,187
  • 8
  • 19
  • 45
aniozen
  • 9
  • 1
  • See also https://stackoverflow.com/questions/13979764/python-converting-sock-recv-to-string – JohanC Dec 22 '19 at 00:22
  • data received via socket communication are in byte code. `print(data.decode('utf-8'))` will convert the byte code value received into a string representation of decimal. This is applicable to both micropython (since you are using arduino, I assumed your are using micro python) or Python 3. – hcheung Dec 22 '19 at 02:59

1 Answers1

0

It's sending the numbers in what appears to be hexadecimal format:

Instead of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 you count:

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

Now in this format, A means the number ten, B means the number 11, and so on. F is the number 15. And now 10 doesn't mean "1 * 10 + 0 * 1" as it would in our decimal system, but instead it means "1 * 16 + 0 * 1". So hexa-10 = deci-16.

But note that FF does not give 1023. Instead it gives 255. For that larger number you'd need to receive more bites. Are you sure you read all the relevant data?

Now with that out of the way, really the data is sent as bytes and you have to convert them back into ints: Convert bytes to int?

Lagerbaer
  • 7,272
  • 1
  • 20
  • 37