Improving the User Experience
While you’re getting set up, you may notice that the quality of
the default font in the Arduino editor is less than ideal. You can
improve it by downloading the open-source font Inconsolata.
To install (when the Arduino IDE is closed), type:
sudo apt-get install fonts-inconsolata
Then edit the Arduino preferences file:
nano ~/.arduino/preferences.txt
and change the following lines to:
editor.font=Inconsolata,medium,14
editor.antialias=true
When you restart the Arduino IDE, the editor will use the
new font.
Talking in Serial
To communicate between the Raspberry Pi and the Arduino over a
serial connection, you’ll use the built-in
Serial
library on the Arduino
side, and the Python pySerial (github.com/ pyserial/pyserial) mod-
ule on the Raspberry Pi side. It comes pre-installed in Jessie and
subsequent releases, but if you ever need to install it, the package
names are:
sudo apt-get install python-serial python3-serial
Open the Arduino IDE and upload this code to the Arduino:
void setup() {
Serial.begin(9600);
}
void loop() {
for(byte n = 0; n < 255; n++){
Serial.write(n);
delay(50);
}
}
82 Getting Started with Raspberry Pi
GSW_RASPI_4ED_FIN.indd 82GSW_RASPI_4ED_FIN.indd 82 10/28/21 10:54 AM10/28/21 10:54 AM
This counts upward and sends each number over the serial
connection.
Note that in Arduino, Serial.write() sends the actual
number, which will get translated on the other side as
an ASCII character code. If you want to send the string
“123” instead of the number 123, use the Serial.print()
command.
Next, you’ll need to write a small Python script that will read the USB
serial port the Arduino is connected to (see “Finding the Serial Port”
on page 81). Here’s the Python script; if the port isn’t
/dev/ttyACM0
,
change the value of port. (See Chapter 4 for more on Python). Save
it as
SerialEcho.py
and run it with python SerialEcho.py:
import serial
port = "/dev/ttyACM0"
serialFromArduino = serial.Serial(port,9600)
serialFromArduino.ushInput()
while True:
if serialFromArduino.inWaiting() > 0:
input = serialFromArduino.read(1)
print(ord(input))
Open the serial port connected to the Arduino.
Clear out the input buffer.
Read one byte from the serial buffer.
Change the incoming byte into an actual number with ord().
Arduino and the Pi 83
GSW_RASPI_4ED_FIN.indd 83GSW_RASPI_4ED_FIN.indd 83 10/28/21 10:54 AM10/28/21 10:54 AM
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
Parsing arbitrary numbers that come in one byte at a time is trivial,
the way Python and pySerial handle strings. As a simple example,
update your Arduino with the following code that counts from 0 to
1,024:
void setup() {
Serial.begin(9600);
}
void loop() {
for(int n = 0; n < 1024; n++)
Serial.println(n, DEC);
delay(50);
}
}
The key difference is in the println() command. In the previous
example, the Serial.write() function was used to write the raw
number to the serial port. With println(), the Arduino formats
the number as a decimal string and sends the ASCII codes for
the string. So instead of sending a single byte with the value 254,
it sends the string 254 . The represents a carriage return, and
the represents a new line (these are concepts that carried over
from the teletypewriter into computing: carriage return moves to
the start of the line; new line starts a new line of text).
On the Python side, you can use readline() instead of read(), which
will read all of the characters up until (and including) the carriage
return and new line. Python has a flexible set of functions for con-
verting between the various data types and strings. It turns out you
can just use the int() function to change the formatted string into an
integer:
import serial
port = "/dev/ttyACM0"
serialFromArduino = serial.Serial(port,9600)
serialFromArduino.ushInput()
while True:
input = serialFromArduino.readline()
inputAsInteger = int(input)
print(inputAsInteger * 10)
Arduino and the Pi 85
GSW_RASPI_4ED_FIN.indd 85GSW_RASPI_4ED_FIN.indd 85 10/28/21 10:54 AM10/28/21 10:54 AM
Note that it is simple to adapt this example so that it will read ana-
log input and send the result; just change the loop to:
void setup() {
Serial.begin(9600);
}
void loop(){
int n = analogRead(A0);
Serial.println(n, DEC);
delay(100);
}
Assuming you change the Python script to just print inputAsInte-
ger instead of inputAsInteger * 10, you should get some floating
values in the 200 range if nothing is connected to analog pin 0. With
some jumper wire, connect the Arduino’s pin 0 to GND and the val-
ue should be 0. Connect it to the 3V3 pin and you’ll see a value
around 715, and 1,023 when connected to the 5V pin.
Using Arduino Compatibles
Many microcontroller boards are compatible with the Arduino
IDE. Some use a special adapter from FTDI that handles all
of the USB-to-TTL serial communication. To connect to these
(often more inexpensive) boards, you would use an FTDI cable
or an adapter board like the USB BUB or FTDI Friend. In the Jes-
sie and subsequent releases, the FTDI driver for these boards
is
already installed, so they should work right out of the box.
These boards typically show up as the
/dev/ttyUSB0
device.
Using Firmata
As you go deeper, many projects will look the same as far as the-
code for basic communication goes. As with any form of commu-
nication, things get tricky once you get past “Hello, world”; you’ll
need to create
protocols
(or find an existing protocol and imple-
ment it) so that each side understands the other.
86 Getting Started with Raspberry Pi
GSW_RASPI_4ED_FIN.indd 86GSW_RASPI_4ED_FIN.indd 86 10/28/21 10:54 AM10/28/21 10:54 AM
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset