I have written a small program to send serial commands from Python to the Arduino Micro. This is my code for both:
Python
import serial
ser = serial.Serial('COM5', 9600)
ser.write(b'0')
ser.write(b'1')
# ser.write(b'2')
print('done')
Arduino
void setup()
{
Serial.begin(9600);
}
void loop()
{
while (!Serial.available()){}
Serial.println(Serial.read()-48);
}
If I keep the ser.write(b'2')
line in the Python code commented out, the code executes nearly instantly, and I am able to see both transmissions in the serial monitor. If I uncomment it, the Python code takes about 5-7 seconds to execute, and none of the data comes through the serial monitor.
I've tried different baud rates but that hasn't helped. I've also tried sending an integer rather than b'#'
, and the same thing happens, no data is transmitted if I have all three serial commands active.
What is happening in my code? Is the serial buffer overloaded by the three successive writes and the buffer ends up flushing?
1 Answer 1
The problem is that your code works but you substract 48 from what you received.
Which if python sends a char
with values: '0'
'1'
'2'
it will result in the serially outputted values of NUL
SOH
STX
which are invisible.
If python transmits the raw byte value (aka 0x00
0x01
0x02
) this would result in 0x00 - 48 = undefined behaviour
with a underflow (same goes for 0x01
and 0x02
)
write
lines?