An Arduino can send readings to your computer over the same USB cable you program it with. In Python, the pySerial library reads them, so you can log, graph or react to the data. This guide covers both ends.
1. The Arduino side
void setup() {
Serial.begin(9600);
}
void loop() {
int light = analogRead(A0);
Serial.print("light,");
Serial.println(light);
delay(1000);
}
This sends one line a second, like light,512. Serial.println() ends each line with a carriage return and a newline (\r\n), which is what Python uses to tell where each reading ends. Sending a name and a value separated by a comma keeps the data easy to split. Close the Arduino IDE's Serial Monitor before running Python: only one program can open the port at a time.
2. Install pySerial
pip install pyserial
The package is called pyserial, but you import it as serial. Install it into a virtual environment. Don't install the unrelated package called serial, which breaks the import.
3. Find the port
python -m serial.tools.list_ports
| System | Typical port name |
|---|---|
| Windows | COM3, COM4, ... (also shown in Device Manager) |
| Linux and Raspberry Pi | /dev/ttyACM0 (Uno, Leonardo) or /dev/ttyUSB0 (boards with a CH340 or FTDI chip) |
| macOS | /dev/cu.usbmodem... or /dev/cu.usbserial-... |
The Arduino IDE's Tools > Port menu shows the same name.
4. Read the lines in Python
import serial
PORT = "COM3" # or "/dev/ttyACM0" on Linux
with serial.Serial(PORT, 9600, timeout=2) as ser:
while True:
raw = ser.readline() # bytes, up to and including b"\n"
line = raw.decode("utf-8", errors="replace").strip()
if not line:
print("timed out, nothing received")
continue
name, value = line.split(",")
print(name, float(value))
Press Ctrl+C to stop. The baud rate, 9600 here, must match Serial.begin() in the sketch, or you'll get gibberish.
What each step does
readline()reads up to and including the next\n. Always set atimeout: without one, the pySerial documentation warns it can wait forever if no newline arrives. If it times out, it returns whatever it got, possibly nothing.- Serial data arrives as bytes, so
decode()turns it into text.errors="replace"stops one corrupted character crashing the program. strip()removes the\r\nfrom the end.
We tested this reading code with pySerial's loop:// test port, which echoes back whatever is written to it. Writing two Arduino-style lines gave:
b'temp,21.5\r\n'
temp 21.5
b'light,512\r\n'
light 512.0
b''
timed out, nothing received
You can try it with no board attached:
import serial
# loop:// echoes back whatever is written, so this runs without a board attached
ser = serial.serial_for_url("loop://", baudrate=9600, timeout=1)
ser.write(b"temp,21.5\r\nlight,512\r\n")
for _ in range(3):
raw = ser.readline() # bytes, up to and including b"\n"
print(raw)
line = raw.decode("utf-8", errors="replace").strip()
if not line:
print("timed out, nothing received")
continue
name, value = line.split(",")
print(name, float(value))
ser.close()
The board restarts when Python connects
Boards like the Uno are designed so that a computer can reset them through the USB serial connection, which is how uploading works. A side effect is that the board restarts each time a program opens the port, and the bootloader runs for about half a second first. Arduino's documentation advises waiting a second after opening the connection before you send anything to the board. If you only read, you'll just see the sketch start again from setup(). If Python sends commands, add time.sleep(2) after opening the port.
Fixing common errors
- "Access is denied" (Windows) or "Device or resource busy": another program has the port open, usually the Serial Monitor or another Python script. Close it.
- "Permission denied" on Linux: your account needs to be in the
dialoutgroup. Arduino's help centre givessudo usermod -a -G dialout <username>, then restart the computer. AttributeError: module 'serial' has no attribute 'Serial': the wrongserialpackage is installed, or your own file is calledserial.py. Runpip uninstall serial, reinstallpyserial, and rename your file.ValueErrorwhen splitting: the first line after connecting can be half a line. Wrap the split intry/except ValueErrorand skip lines that don't parse.
Save the readings
To log the data, write each reading to a CSV file with a timestamp. The Python CSV guide shows how to append rows so nothing is lost if the program stops, and f-strings format the time.
Sources
The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.
- pySerial 3.5 documentation: short introduction (opening ports, readline and timeouts, listing ports)
- pySerial 3.5 documentation: URL handlers (loop://)
- Arduino language reference: Serial.println()
- Arduino documentation: automatic (software) reset on connection (Duemilanove page; the Uno uses the same DTR reset)
- Arduino Help Center: Fix port access on Linux