So I have a program set up on my arduino nano which reads a single byte from the serial port and turns on an LED depending on whether or not the byte received was 1 or 0. I thoroughly tested this program, both on the Serial monitor and with pySerial in the python 3 shell, and it worked fine. But when I have a simple program like this:
import serial SERIAL = serial.Serial("COM4", 9600) SERIAL.write(b'1')
The board doesn’t do anything. What am I doing wrong that pySerial works in the python shell but not in a python program?
Advertisement
Answer
After you open the serial port, delay it for minimum a second, because the Arduino resets itself when you open the serial connection and doesn’t start reading from the serial immediately.
Example:
import serial import time SERIAL = serial.Serial(baudrate='115200', timeout=.2, port='com4') #this edit is not important time.sleep(3) #sleep 3 seconds SERIAL.write(b'1')