0

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?

  • are you sure it is not a problem every second run and not dependent on the write lines? – Juraj May 9 at 14:43
  • Hi Juraj, I'm not sure what you mean, can you clarify? – Greg G May 9 at 14:46
  • It runs reliably with 2 writes. It fails every time with 3 writes. – Greg G May 9 at 14:50
  • what if you send '0' and '2' or '1' and '2'. Same issue? – Chad G May 9 at 15:58
  • 3
    Hmm, I don't see a loop that is able to overflow any buffer. The python script just finishes after sending 3 bytes. The arduino sketch will only print if anything anything has been received. Also, from my experience an atmega running at 8Mhz is absolutely fast enough to poll for incoming bytes that are transmitted at a baudrate of 9600... – Sim Son May 10 at 16:49
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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.