1
votes

So I am having an issue with my serial communication between Python and an Arduino Uno. I have Python sending the number 38 (along with other numbers) through serial communication by a bytearray to Arduino and then back to Python.

The array I am sending is:

 [230, 0, 0, 0, 38] 

And the array it is printing out (when using print()) is:

bytearray(b'\xe6\x00\x00\x00&

The ampersand is there because there is a weird nuance in the printing of the bytearray that when the number is between a certain range (sorry I can't remember the range) it prints it out in ASCII rather then hexidecimal, so the array I am sending to Arduino should still have all of the information needed.

I am receiving the information in Arduino by:

char values[5];    
Serial.readbytes(values, 5);

Once arduino reveives the information, I use Serial.write to send it back to Python, where I print them out to ensure I have received the correct information. This output received in Python is:

b'\xe6\x00\x00\x00\xf6' 

where the 0xe6 is 230 (correct) and 0xf6 is 246 which is incorrect, it should be the hex value for 38 which is 0x26.

Does anyone have any suggestions as to how to fix this? Any suggestions or help would be appreciated!

EDIT: Found my problem, I accidentally had a misplaced minus '0' because at one point I thought that I had to transform the information from ASCII to hex, but it turns out that I don't. Thanks for the help!

1
in c/c++ bytestrings typically must end with "\0" (ive used lots and lots of arduino serial and pyserial and I can tell you it works just fine in every case I have tried...)Joran Beasley
Can you also try sending something else besides '0' in the other array index positions? (just to see if those are coming back as expected.) Also, is this python 3 or python 2?Dan
Also try sending 38 first, and 230 last and let us know what the results of that wereDan
you could also put a minimal example that shows completely a reproducible issueJoran Beasley
@Dan, I am using Python 3. Tried sending [0, 255, 0, 85, 0] as a bytearray, and received the correct numbers aside from the last, which should have been \x00 and it instead gave me \xd0.rtmurad

1 Answers

0
votes

test.ino

char buffer[10] = {0,0,0,0,0,0,0,0,0,0};
void setup(){
    Serial.begin(9600);
}
void loop(){
    Serial.println(Serial.readBytes(buffer,5));
}

test.py

import serial
s=serial.Serial("COM5",timeout=5)
time.sleep(5) # wait a couple seconds
s.write(b"\xe6\x00\x00\x00&")
# or alternatively
# s.write(bytes(bytearray([0xe6,0x00,0x00,0x00,0x26])))
print(repr(s.read(1000)));

this is what a minimum code example looks like ... it should also work...