As an Amazon Associate we earn from qualifying purchases.
Serial communication is one of the simplest ways to make a computer talk to a microcontroller, a radio module or another device. In Python, the pyserial library handles it in a few lines. This guide shows how to send data to a serial port, read serial data back, and test the connection with an Arduino or with XCTU.
What you need
- Python installed on your computer (the examples use Python 3).
- The pyserial library. Install it with
pip install pyserial. The project page is on PyPI under the name pyserial. - A device on a serial port: an Arduino, a USB-to-serial adapter, or an XBee module connected through a USB board.
- Optional: XCTU, Digi’s free tool for configuring and testing XBee modules. It also has a console for watching serial traffic.
Find your port name and baud rate
Before writing any code, you need two settings: the port name and the baud rate.
- Windows: ports are named like
COM2orCOM3. Check Device Manager under Ports (COM & LPT). - Linux: look for names like
/dev/ttyUSB0or/dev/ttyACM0. - macOS: look for names starting with
/dev/tty.usbor/dev/cu.usb.
The baud rate must match on both sides. If the device is set to 9600 and Python opens the port at 115200, you will see garbage or nothing at all. The examples below use 9600, a common default for Arduino sketches and XBee modules.
Sending data from Python
The video below walks through the sending side. The code that follows does the same thing.
import serial
# Enter the port name and baud rate
ser = serial.Serial(port='COM2', baudrate=9600)
ser.write(b'hai') # sends the text "hai"
ser.write(bytes([0x22])) # sends one byte with the value 0x22 (the " character)
ser.close() # always close the port when finished
A few points about this code:
- Creating
serial.Serial(...)with a port name opens the port straight away. You do not need to callclose()and thenopen()first, as older examples often did. - In Python 3,
write()needs bytes, not a normal string. That is why the text is written asb'hai'. You can also convert a string with'hai'.encode(). - Sending
0x22sends a single byte. In ASCII, that value is the double-quote character. To send a number as a byte, usebytes([value])with a value from 0 to 255.
Receiving data in Python
To read serial data, call read() or readline() on the same object. The next example sends a request and then reads the reply.
import serial
ser = serial.Serial(port='COM2', baudrate=9600, timeout=2)
ser.write(b'send data') # ask the other device for data
x = ser.read() # reads one byte
print(x)
ser.close()
The original version of this example used print x, which only works in Python 2. In Python 3, print is a function, so use print(x).
Choosing the right read method
ser.read()reads one byte.ser.read(10)reads up to 10 bytes.ser.readline()reads until a newline character. It works well when the other device sends lines of text, such as an Arduino usingSerial.println().ser.in_waitingtells you how many bytes are already waiting, so you can read without blocking.
Always set a timeout
Without a timeout, read() waits forever if nothing arrives, and your script appears frozen. Setting timeout=2 makes it give up after two seconds and return whatever it has, which may be empty bytes.
Turn bytes into text
Data arrives as bytes, such as b'hello\r\n'. To get a normal string, decode it:
line = ser.readline().decode('utf-8', errors='ignore').strip()
print(line)
Testing with an Arduino
An Arduino is an easy way to test both directions. Upload this sketch, which echoes back what it receives:
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
char c = Serial.read();
Serial.print("Got: ");
Serial.println(c);
}
}
Then run this Python script, using the port your Arduino shows up on:
import serial
import time
ser = serial.Serial('COM2', 9600, timeout=2)
time.sleep(2) # many Arduino boards reset when the port opens
ser.write(b'A')
print(ser.readline().decode().strip()) # prints: Got: A
ser.close()
The short pause matters. Many Arduino boards restart when a program opens the serial port, and anything sent during the restart is lost.
Once this works, you can build on it to control an LED from Python, or read a temperature sensor and show the value on your computer. If you want to test the Arduino side without hardware, our UART and LCD simulation in Proteus shows how serial data behaves on the Arduino end.
Testing with XCTU
XCTU is useful when your device is an XBee module. The video below shows the setup in practice.
A typical workflow looks like this:
- Connect the XBee module to your computer and add it to XCTU.
- Check that the module’s baud rate matches the value in your Python script.
- Open the XCTU console view and connect it to the module to see incoming and outgoing data.
- Close the XCTU connection to that port before running your Python script. Only one program can use a serial port at a time.
If you have two XBee modules, you can keep XCTU on one port and run Python on the other. Anything Python writes to one module then appears in the XCTU console of the other.
Common problems and fixes
- Access denied or port busy: another program, such as the Arduino Serial Monitor or XCTU, has the port open. Close it and try again.
- Port not found: check the name in Device Manager or in your system’s device list, and make sure the USB driver is installed.
- Garbled text: the baud rate does not match on both sides.
- TypeError when writing a string: you are on Python 3 and need to send bytes, as in
b'text'. - Nothing is read: check the timeout, the wiring (TX goes to RX and RX goes to TX), and that the other device actually sends data.
Next steps
After the basics work, you can log readings to a file, plot them live, or send commands to hardware. For a longer project, see how to analyse Arduino data with Python once it is arriving over serial.
FAQ
How do I send data to a serial port in Python?
Install pyserial, open the port with serial.Serial(port, baudrate), and call write() with bytes, for example ser.write(b'hello'). Close the port when you are done.
How do I read serial data in Python?
Use ser.read() for a set number of bytes or ser.readline() for a full line. Set a timeout so the script does not wait forever, and decode the bytes into text if needed.
Is UART the same as serial communication in Python?
UART is the hardware method that most serial ports and microcontroller pins use. Pyserial lets Python talk to a UART device through a COM port or a USB-to-serial adapter, so you do not handle the electrical details yourself.
Why does my Python code work with Arduino only after a delay?
Many Arduino boards reset when the serial port opens. Wait about two seconds after opening the port before you send data.