Sending Serial Data to Arduino Using Python Script

2019-09-06 02:43发布

问题:

I am facing a peculiar issue while writing characters to Arduino using python serial communication on macOS 10.14.

The Arduino is programmed to read a string, parse it and take PWM action to run a car.

Ardiuno's serial communication channel is configured to receive the strings in the format < A, B, C, D > where ABCD are numbers which denote car direction, speed, steering direction and steering position.

The problem is, when I send a string from the serial monitor or through the Python Development environment the string is received, parsed properly and command executed successfully.

However if I write a simple program in a file write.py and execute it from the command line, nothing happens.

import serial
ser = serial.Serial('/dev/cu.usbmodem14301', 9600)
data = '<1,150,0,0>'
ser.write(data.encode())

If I run this script from the macOS terminal using the command:

python write.py

nothing happens. What am I missing here?

回答1:

A new USB connection with ser=serial.Serial('/dev/cu.usbmodem14301',9600) resets the Arduino. The data sent right after connection are lost because the Arduino boots.



回答2:

It may be that the port is in text mode and will not send the data until a newline is sent:

data = '<1,150,0,0>\n'
ser.write(data.encode())

or flush() is called.

data = '<1,150,0,0>'
ser.write(data.encode())
ser.flush()


回答3:

The most probably thing happening here is that the data is not being sent to the serial port.

There is a simple method to check this. Connect the Arduino to your laptop (I suspect it to be a mac), and start the serial monitor on the Arduino IDE. In the serial monitor type in <1,150,0,0> and press send.

The tx LED on the Arduino will blink. Now that you know how the pattern looks, repeat the same experiment with the Python code.

If the LED does not blink in the same manner you have a Serial port access issue, which you can fix using the instructions in the following link Access USB serial ports using Python and pyserial

If not, I am stumped.