Go Down

Topic: Issue with Pyserial/Arduino Communication (Read 120 times) previous topic - next topic


Hello all, frustrated Arduino noob here.

I'm trying to communicate with an Arduino using pyserial, and they don't seem to be communicating. I'm attempting to isolate the issue by reducing the problem down to just trying to make the LED turn on and off, but I'm still finding no luck after hours of googling and fiddling. My Python code is as follows:

Code: [Select]
import serial, struct, time
ser = serial.Serial(port='/dev/ttyACM0')
a = 1
ser.write(struct.pack(">B", a))

and the Arduino code is

Code: [Select]

int ledPin = 13;

void setup() {
  pinMode(ledPin, OUTPUT);



void loop() {
    int input = Serial.read();
    if(input == 49 || input == 1){
      digitalWrite(stepPin, HIGH);
    if(input == 0 || input == 48){
      digitalWrite(stepPin, LOW);

The perplexing thing is that, if I open the serial port in a Python terminal, then open the Serial Monitor in the Arduino software, everything works fine. The light turns on and off with a 1 or a zero using the code above in the Python terminal...but if I don't open the Serial Monitor, or I exit the serial monitor then close and reopen the port, nothing at all...I've been trying every variation of struct.unpack or encode() in case it's how the input is being parsed, but it doesn't look like Serial.available() is ever evaluating as nonzero...I feel like I've been searching for hours and have tried everything I could find or think of, so I'd be really grateful if anyone could provide some insight as to what is happening here.


Try printing out  input to help you debug.


May 17, 2017, 03:22 am Last Edit: May 19, 2017, 01:17 am by ron_sutherland
Try this Python

Code: [Select]

import serial, struct, time
ser = serial.Serial('/dev/ttyACM0',115200, timeout=3)
if ser.in_waiting:
    junk = ser.readline().strip() # clean any junk from the buffer
    print("junk: " + junk[-10:].decode("utf-8"))
a = 1 # or send an 'a' which is an easy key to press e.g. a =ord('a')
# Python 3.6 strings are utf-8, they seem to need encode to ascii for Pyserial
echo = ser.readline().strip()
print("debug: " + echo[-10:].decode("utf-8"))

Update: tested and fixed


Two or three hours spent thinking and reading documentation solves most programming problems.


Which Arduino are you using? The issue you describe is almost always due to not opening the serial port correctly on the PC end.
The art of getting good answers lies in asking good questions.

Go Up