Last modified: Feb 06, 2026 By Alexander Williams
Python Read Arduino Serial Data Guide
Connecting Python to an Arduino opens a world of possibilities. You can log sensor data, create dashboards, or control hardware. This guide shows you how.
We will cover reading from a saved Arduino data file and reading live data from the serial port. Both methods are useful for different projects.
Understanding the Communication
Arduino boards communicate via a serial protocol. Data is sent as text over a USB connection. Python can listen to this serial port.
You can also save this data to a file on your computer. Python can then read and analyze that file later. We will explore both workflows.
Prerequisites and Setup
Before you start, ensure you have the right tools. You need Python installed on your computer. You also need an Arduino board, like an Uno.
Install the PySerial library. This library lets Python talk to serial ports. Open your terminal and run the install command.
pip install pyserial
For writing and running your Python scripts, knowing How to Run Python File in Terminal is essential.
Method 1: Reading a Saved Arduino Data File
Often, you log Arduino sensor readings to a file. This file might be a .txt or .csv. Python can read this data for analysis.
First, let's see a simple Arduino sketch. It writes sensor values to the Serial Monitor. You can copy this output into a file.
// Arduino Sketch: Basic Data Logger
void setup() {
Serial.begin(9600); // Start serial communication
}
void loop() {
int sensorValue = analogRead(A0); // Read from analog pin A0
Serial.println(sensorValue); // Send value to Serial Monitor
delay(1000); // Wait one second
}
Run this on your Arduino. Open the Serial Monitor. You will see numbers scrolling. Copy a few lines and save them as arduino_data.txt.
Now, use Python to read this file. We use the built-in open() function. This is a simple and effective method.
# Python script to read a saved Arduino data file
file_path = "arduino_data.txt"
try:
with open(file_path, 'r') as file:
lines = file.readlines()
print("Data read from file:")
for line in lines:
value = line.strip() # Remove extra whitespace/newline
print(f"Raw value: {value}")
except FileNotFoundError:
print(f"Error: The file '{file_path}' was not found.")
Data read from file:
Raw value: 512
Raw value: 523
Raw value: 498
The with open() statement is crucial. It ensures the file is properly closed after reading. Always handle the FileNotFoundError.
Method 2: Reading Live Data from Arduino Serial Port
Reading live data is more dynamic. Python connects directly to the Arduino's serial port. You get real-time updates.
First, upload a simple Arduino program. This program sends a "Hello from Arduino" message every two seconds.
// Arduino Sketch: Live Serial Sender
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println("Hello from Arduino");
delay(2000); // Send a message every 2 seconds
}
Now, write the Python script. We use the PySerial library. You must know your Arduino's serial port name.
On Windows, it's like COM3. On Mac/Linux, it's like /dev/tty.usbmodem14101. Check your Arduino IDE for the port.
import serial
import time
# Configure the serial connection
# Replace 'COM3' with your actual port
ser = serial.Serial('COM3', 9600, timeout=1)
time.sleep(2) # Wait for connection to establish
print("Reading live data from Arduino...")
try:
while True:
if ser.in_waiting > 0: # Check if data is available
line = ser.readline().decode('utf-8').rstrip()
print(f"Received: {line}")
except KeyboardInterrupt:
print("\nProgram stopped by user.")
finally:
ser.close() # Always close the port
print("Serial port closed.")
Reading live data from Arduino...
Received: Hello from Arduino
Received: Hello from Arduino
The serial.Serial() object is the core of the connection. The parameters are port name, baud rate (must match Arduino), and timeout. Always close the port with ser.close().
Processing and Using the Data
Raw data is just text. You usually need to convert it. For numbers, use int() or float(). This lets you perform calculations.
Here is an example. We read a temperature value from the serial port. Then we convert it and print a formatted message.
import serial
ser = serial.Serial('COM3', 9600, timeout=1)
try:
while True:
if ser.in_waiting > 0:
raw_data = ser.readline().decode('utf-8').rstrip()
try:
# Convert the string to a float (number)
temperature_c = float(raw_data)
temperature_f = (temperature_c * 9/5) + 32
print(f"{temperature_c:.1f}°C is {temperature_f:.1f}°F")
except ValueError:
print(f"Could not convert '{raw_data}' to a number.")
except KeyboardInterrupt:
print("Stopping.")
ser.close()
This structure is very common. You read a line, decode it, clean it, and then try to convert it. Error handling with try...except is important for stability.
You can also write this data to a file for long-term logging. Combine the first and second methods. This creates a powerful data pipeline from sensor to analysis.
Common Issues and Troubleshooting
You might encounter problems. Here are common fixes.
Serial Port Not Found or Access Denied: Ensure the port name is correct. Close the Arduino Serial Monitor or any other program using the port.
Baud Rate Mismatch: The baud rate in Python (9600) must match the Arduino's Serial.begin(9600).
Garbage or Incomplete Data: Add a small time.sleep(2) after opening the port. This gives the Arduino time to reset. Ensure you are using .decode('utf-8') on the read data.
For more complex script execution, reviewing the process of How to Run Python File in Terminal can help debug runtime issues.
Conclusion
Getting Python to read Arduino data is a fundamental skill for makers. You can read from saved files or live serial ports.
The key steps are installing PySerial, finding the correct port, and properly opening/closing the connection. Always handle errors and data conversion carefully.
Start with the simple examples here. Then expand to log data, create graphs, or build interactive projects. The combination of Python and Arduino is very powerful for prototyping and automation.