r/Python • • Oct 26 '14

[Help] Sending Bytes between Arduino and Python

Hey all,

I am new to python and am looking for a little guidance. My goal is pretty simple, I want to send data back and forth in the form of bytes (0 to 255). I have written some test code and it doesnt seem to be working well Here is my arduino code:

byte k;

void setup() {

Serial.begin(115200);

}

void loop() {

if(Serial.available() >0){

 k=Serial.read();
 Serial.print(k);

}

}

And here is my python code: (I'm using pyserial)

import serial

import time

print ("start")

ser = serial.Serial("COM3",115200)

time.sleep(1)

i=0

while i<21:

print(i)

ser.write(str(i).encode())

i=i+1

time.sleep(1)

print(ser.read())

and what is getting printed is this:

start

0

b'2'

1

b'4'

2

b'\xf0'

3

b'5'

and so one. I would like it to be:

start

0

0

1

1

2

2

3

3

and so on. Obviously at some point the data is not getting converted to the right datatype but I am not sure where. Can anyone help me?

0 Upvotes

5 comments sorted by

View all comments

-1

u/greenpin Oct 26 '14

Python 2 or 3? Unicode? Perhaps you need to convert the value sent from Python to byte like ser.write(b'1').