How to send and receive serial in python


I am running the following code in python. The Microcontroller is connected to the USB UART COM 7. I am sending the character “S” from python to Microcontroller and I expect a line from Microcontroller but there is nothing on the python shell. I am not sure if I am sending it properly or not and whether I am reading the line from Microcontroller the right way or not.

import serial
ser = serial.Serial("COM7", 9600)
# Send character 'S' to start the program

# Read line   
while True:
bs = ser.readline()


In principle, it looks like the writing should work, though you could just write


instead of creating a bytearray. (Though it looks like your indentation got messed up during copy and pasting somewhere for the last two lines!)

Now let’s think about what’s going wrong.

  1. Maybe you’re not sending the byte b'S' correctly, or using the wrong serial port settings.
  2. Maybe the device does not respond when you send just the byte b'S'. (I notice you’re not sending any sort of new line character)
  3. Maybe the device is responding, but it isn’t ending its response with a line feed. (try for starters?)

What I like to do when I’m writing a program to communicate with a serial device is to first of all talk to the device by hand with a terminal program (I used to use something called TeraTerm on Windows, that always worked well). Figure out what settings (baud rate etc) you need, what exactly you have to send, and what exactly you can expect to get back. Then, you can write a Python program that does the exact thing you’ve already tested.

I actually need to send Enter from python to Microcontroller, which is the return button from keyboard because Microcontroller is waiting to read string from python until Enter is pressed or send.

while (EUSART1_Read() != 0x0d);

What should I write in place of S in python ?


0xd (13) is a carriage return character, which is \r in Python. (CR is a fairly common end-of-line character in serial protocols, but in other situations 0xa (10) / line feed / \n is more common, or alternatively the combinartion \r\n.)

So, I guess… ser.write(b'S\r)`?

Note that .readline() waits for a line feed (\n), so it won’t return if your device only ever sends a carriage return (\r) back.