Linux Format - UK (2020-03)

(Antfer) #1
http://www.techradar.com/pro/linux March 2020 LXF260 45

Raspberry Pi projects


We’ll start the code for this project In a new blank file,
using the same lines to import and configure the pin
being used on the Arduino.
from pyfirmata import Arduino, util
from time import sleep
board = Arduino('/dev/ttyUSB0')
led = 12
To read the analogue values from the Arduino we
need to create a thread that will run and not interrupt
the main code. We should create an object called it and
then connect this to the Arduino, before then starting
the thread.
it = util.Iterator(board)
it.start()
board.analog[0].enable_reporting()
The main body of code is a while True loop, which
will read the current value of analogue pin 0, which is
connected to the potentiometer, and store the value in a
variable, value. This value will then be printed to the
Python shell.
while True:
value = board.analog[0].read()
print(value)
A conditional test is now applied to the value
variable. If the value has no data, then it will return
none, and this will crash the code. Therefore an if
condition checks the value, and if it is none, it changes

it to 0.
if value == None:
value = 0
Another condition to test this is if the value is greater
than 0.05, the analogue values returned are between
0.0 and 1.0. If the value’s greater than 0.05 the LED is
turned on, and the sleep interval, used to keep the LED
on/off by pausing the code, is controlled by the value.
elif value > 0.05:
board.digital[led].write(1)
sleep(value)
board.digital[led].write(0)
sleep(value)
The final lines of code are an else condition, which
turns the LED off if the value is less than 0.05. Save the
code and run. Now turn the potentiometer and watch
the LED come to life.

COMMUNICATION


PyFirmata is not the only way to communicate between Arduino and
Pi, but it is the easiest! Another way is to read data that is printed to
a serial console – the serial monitor in Arduino parlance. Here is a
quick line to print a sentence to the Arduino serial monitor:
Serial.println(“Hey bigles wrote this for the Arduino\n”);
Then, using a Python library called pySerial, we can read the data
coming into an open port, such as ttyUSB0. We need to connect at
the correct speed and then listen out for the data, which is then
printed to the Python shell. So using this method we could use a
sensor to take a reading and then send that reading to the serial
monitor, which is then read by our Python code. We can also send
data to the Arduino from Python, which will enable some control of
the live code.
The benefit of this method is that we write pure Arduino code to
the Arduino, and that means the Arduino can be connected to
another computer and used with no issues. We don’t need to load
any special sketches to control the Arduino, unlike pyFirmata, which
requires us to have a constant connection from our computer in
order for the code to run. Find out more about pySerial via this blog
post https://bigl.es/tooling-tuesday-pyserial/.

Potentiometers are
variable resistors,
and by turning
the knob we can
alter the resistance
output to the
analogue pin which
is output to the
Python shell.

To test that our project will work we need to use an LED to ensure that
we can control devices using Python and pyFirmata.

3332March 0 h2rSenshSnigtom March 2020LXF260 45


Raspberry Pi projects


We’llstartthecodeforthisprojectInanewblankfile,
using the same lines to import and configure the pin
being used on the Arduino.
from pyfirmata import Arduino, util
from time import sleep
board = Arduino('/dev/ttyUSB0')
led = 12
To read the analogue values from the Arduino we
need to create a thread that will run and not interrupt
the main code. We should create an object called it and
then connect this to the Arduino, before then starting
the thread.
it = util.Iterator(board)
it.start()
board.analog[0].enable_reporting()
The main body of code is a while True loop, which
will read the current value of analogue pin 0, which is
connected to the potentiometer, and store the value in a
variable, value. This value will then be printed to the
Python shell.
while True:
value = board.analog[0].read()
print(value)
Aconditionaltestisnowappliedtothevalue
variable.Ifthevaluehasnodata,thenitwillreturn
none, and this will crash the code. Therefore an if
condition checks the value, and if it is none, it changes


it to 0.
if value == None:
value = 0
Another condition to test this is if the value is greater
than 0.05, the analogue values returned are between
0.0 and 1.0. If the value’s greater than 0.05 the LED is
turned on, and the sleep interval, used to keep the LED
on/off by pausing the code, is controlled by the value.
elif value > 0.05:
board.digital[led].write(1)
sleep(value)
board.digital[led].write(0)
sleep(value)
The final lines of code are an else condition, which
turns the LED off if the value is less than 0.05. Save the
code and run. Now turn the potentiometer and watch
the LED come to life.

COMMUNICATION


PyFirmataisnottheonlywaytocommunicatebetweenArduinoand
Pi,butitistheeasiest!Anotherwayistoreaddatathatisprintedto
aserialconsole–theserialmonitorinArduinoparlance.Hereisa
quicklinetoprintasentencetotheArduinoserialmonitor:
Serial.println(“HeybigleswrotethisfortheArduino\n”);
Then,usingaPythonlibrarycalledpySerial,wecanreadthedata
comingintoanopenport,suchasttyUSB0.Weneedtoconnectat
thecorrectspeedandthenlistenoutforthedata,whichisthen
printedtothePythonshell.Sousingthismethodwecouldusea
sensortotakeareadingandthensendthatreadingtotheserial
monitor,whichisthenreadbyourPythoncode.Wecanalsosend
datatotheArduinofromPython,whichwillenablesomecontrolof
thelivecode.
ThebenefitofthismethodisthatwewritepureArduinocodeto
theArduino,andthatmeanstheArduinocanbeconnectedto
anothercomputerandusedwithnoissues.Wedon’tneedtoload
anyspecialsketchestocontroltheArduino,unlikepyFirmata,which
requiresustohaveaconstantconnectionfromourcomputerin
orderforthecodetorun.FindoutmoreaboutpySerialviathisblog
posthttps://bigl.es/tooling-tuesday-pyserial/.

Potentiometers are
variable resistors,
and by turning
the knob we can
alter the resistance
output to the
analogue pin which
is output to the
Python shell.

To test that our project will work we need to use an LED to ensure that
we can control devices using Python and pyFirmata.
Free download pdf