You won’t be able to upload to the Arduino when
Python has the serial port open, so make sure you kill
the Python program with Ctrl-C before you upload the
sketch again. You will be able to upload to an Arduino
Micro, but doing so will break the connection with the
Python script, so you’ll need to restart it anyhow.
The Arduino is sending a number to the Python script, which
interprets that number as a string. The input variable will contain
whatever character maps to that number in the ASCII table (bit.
ly/ZS47D0). To get a better idea, try replacing the last line of the
Python script with this
:
print(str(ord(input)), " = the ASCII character ", input, ".")
Setting the Serial Port as an Argument
If you want to set the port as a command-line argument in the
Python sketch, use the sys module to grab the first argument:
import serial, sys
if (len(sys.argv) != 2):
print("Usage:pythonReadSerial.pyport")
sys.exit()
port = sys.argv[1]
After you do this, you can run the program like this:
python SerialEcho.py /dev/ttyACM0
The first simple example just sent a single byte; this could be fine
if you are only sending a series of event codes from the Arduino.
For example, if you have two buttons connected and
the left button
is pushed, send a 1; if the right, send 2. That’s only good for 255
discrete events, though; more often you’ll want to send arbitrarily
large numbers or strings. If you’re reading analog sensors with the
Arduino, for example, you’ll want to send numbers in the range of
0 to 1,023.
84 Getting Started with Raspberry Pi
GSW_RASPI_4ED_FIN.indd 84GSW_RASPI_4ED_FIN.indd 84 10/28/21 10:54 AM10/28/21 10:54 AM