1. The pySerial flushInput()
function empties any data that
happens to be in the Pi’s serial buffer
to make sure that the two ser.read()
functions fetch the most recent data.
It may not be absolutely necessary to
include this statement, but it does
avoid the possibility of extraneous
data accumulating in the buffer if a
program is run for a considerable
period of time.
2. As we already know, both the
ser.read() statements in this program
are non-blocking. If a data byte hasn’t
been received in the specified time, a
timeout occurs and the program
moves on. However, a timeout also
produces a Python exception. If our
program didn’t handle this exception,
the program would automatically
terminate immediately with an error
message. In this case, the message
would be something like “ord()
expected a character, but string of
length 0 found” because no data was
received. One way to handle the
exception (and avoid the program
termination) is to place the ser.read()
statement within a try/except block
as we have done here.
3. Just before the try/except block,
we initialized a Boolean “valid data”
flag (valid) as True. If an exception
occurs, the except block is executed,
so here we update valid as False.
4. Finally, in the if/else code, we
first check to see if the data is valid. If
it is, we carry out the necessary
computations and return the value of
tempF. If it’s not valid, the else code
executes and we return the value of
999 which indicates that the data is
not valid.
Let’s run the two programs and
see what happens. First, run the
requestReport.py program. (Don’t
forget: You need to run as root,
It seems like we’ve invested a
huge amount of effort just to know
what the temperature is. However,
the real point of all this work is that
we now have a programming
template that enables us to use any
PICAXE processor to collect a variety
of data (analog and/or digital), and
send it on to the Pi whenever it asks
for it. Since the Pi is easily connected
to the Web, this opens up a whole
new world of PICAXE programming
possibilities. Think about that and
have fun! NV
April 2014 15