This is only a preview of the July 2011 issue of Silicon Chip. You can view 30 of the 104 pages in the full issue, including the advertisments. For full access, purchase the issue for $10.00 or subscribe for access to the latest issues. Articles in this series:
Items relevant to "Ultra-LD Mk.3 200W Amplifier Module":
Items relevant to "A Portable Lightning Detector":
Items relevant to "Rudder Position Indicator For Power Boats":
Items relevant to "A Look At Amplifier Stability & Compensation":
Items relevant to "Build A Voice-Activated Relay (VOX)":
Purchase a printed copy of this issue for $10.00. |
Penguini with Mint: the Linux Mint desktop, from a
distribution supplied by P. J. Radcliffe of RMIT. The
root versions of the file browser and terminal provide
you with unlimited power but no handrails or safety
net. The tool bar pops up when the cursor hits the
bottom of the screen.
Control Your World
Using Linux
By NENAD
NENAD STOJADINOVIC
Microcontrollers are becoming more powerful and sophisticated, to
the point where they are challenging the supremacy of the PC. On the
other hand, PCs running Linux are quite open and accessible to the
experimenter. Yes, your computer can control your air-conditioning
and lights and this article will show you how.
T
HIS ARTICLE is basically the first
step (actually there are only two
steps) to embedded computing using
single-board computers (SBCs).
SBCs are generally just 5-8cm square
and cram a complete PC onto a single
circuit board. They are extensively
used in applications requiring small
size and/or resistance to vibration,
such as automated teller machines,
motor vehicles and portable machinery etc. These days, many run a version
of Linux as the operating system due
to its low cost, flexibility and range of
development tools (some instead use
one of the BSD-based Unix clones or
Microsoft Windows).
22 Silicon Chip
They do tend to be rather basic, so
it’s much easier to do all development
work in the luxury of your desktop
PC, then stuff the finished software
into the SBC when it’s all debugged
and running.
Technology directions
In the last year or two, SILICON CHIP
has presented several spectacular examples of just what can be done with
the newest generation of powerful
microcontrollers. There has been the
Web Server In A Box (WIB), the Data
Logger and just recently, the Maximite computer. It gives an indication
of the direction that technology has
taken and it’s amazing to think that a
tiny piece of plastic and metal with a
silicon “brain” can present you with
seemingly endless pages of full-colour
web content.
PCs have mirrored this upward
trend but in so doing, have made
themselves more and more inaccessible to the casual experimenter. It’s
harder to interface with USB than the
older serial and parallel ports; even
if you still have one of the latter, the
latest Microsoft operating systems
make writing software to access it a
difficult task.
But then there’s Linux. Linux is
most certainly not such a black box.
siliconchip.com.au
In fact, everything is out in the open
and it’s really quite easy to access the
various PC communication ports. By
using Linux as the operating system
(OS), you once again have a PC that
you can experiment with. Want to
log data, surf the web, flash LEDs or
switch relays in response to varying
light levels? No problem at all.
You may never have found much
need to use to Linux and I certainly
hadn’t. But during the course of this
work, I found that Linux is the number
one choice for an embedded operating
system, with “Android” (now commonly used in mobile phones) being
perhaps the most famous derivative.
This and many other embedded operating systems are based on the Linux
kernel, which is the core component
that provides all the basic functions.
The kernel is now up to version 2.6,
and has a well-deserved reputation for
functionality, stability and security.
CONTROL
SMART I/O
MODULE
SENSOR
DATA
SMART I/O
MODULE
SMART I/O
MODULE
CONTROL & DATA
CONTROLLING COMPUTER
Fig.1: a simple supervisory
control scenario. Smart modules
run a process while a central
supervisory computer provides
broad operating parameters and
responds to any alarms.
SMART I/O
MODULE
SENSOR
DATA
CONTROL
Linux control paths
There are three clear paths to Linux
control and it’s worth spending some
time to explore them.
The first is the simple, old-fashioned
use of the serial and parallel ports. Yes,
I know that they have been largely
phased out but rumours of their deaths
have been greatly exaggerated. Suitable interface cards are readily and
cheaply available (including USBto-serial or USB-to-parallel adaptors)
and the average desktop PC has lots
of space to fit them. Likewise, many
embedded applications still use them
and a glance through the Ocean Controls catalog will quickly illustrate
the point.
The second path involves the use of
USB I/O (input/output) devices. They
come in every imaginable configuration, from simple USB converter cables
to boxes full of relays, ADCs and digital outputs – all driven from the USB
port. For a (very) good example, take
a look at the Arduino-compatible I/O
controller featured in the April 2010
issue of SILICON CHIP.
However, while the above approach
is very useful, it has two failings: (1)
the devices are generally “brainless”;
and (2) it is difficult to use a PC in real
time for such tasks. Your controlled
system can be going haywire and overrunning its limit switches while the
computer is blithely servicing some
trivial interrupt.
A better approach is “supervisory
siliconchip.com.au
control” (see Fig 1). It can be used with
a bewildering variety of busses and
protocols but let’s assume for the moment that it’s all USB. In that case, the
PC and one or more USB I/O devices
are linked together in a network, except now the USB I/Os are intelligent.
An an analogy, imagine a ship’s
captain and engine room crew. The
captain (supervisory computer) drives
the boat according to a plan involving
high order functions such as navigation, sea state, schedule etc. The captain issues orders to the engine room
for a certain speed and the engine room
crew (USB I/O modules) takes care of
monitoring and adjusting for steam
pressure, engine operating parameters,
lubrication and all the myriad functions that the captain does not want
(or need) to worry about.
The point is that each control module can monitor and adjust for its own
feedbacks in real-time so the PC can
then interact with them on its own
schedule.
The battle plan
Let’s start with a simple example of
PC hardware control, a basic serial/
parallel control system. While there
are many more complex systems, this
has the potential to occupy the ardent
experimenter for some time.
As mentioned above, using Linux
is essential to making this easy. The
Linux interface is not hugely difficult
to master but it has some important
differences compared to Windows
(and many similarities). An article in
the March 2009 issue of SILICON CHIP
(“Reviving Old Laptops With Puppy
Linux”) covered the basics quite well
and is recommended for the new chum
(thanks Warrick).
In my case, I chose to purchase a
Linux disk from P. J. Radcliffe of RMIT,
who presented an intelligent USB I/O
Interface in the October 2009 SILICON
CHIP. As part of the development, he
produced a live DVD that is set up
specifically for this sort of work and
is furthermore stuffed with all sorts
of tools and data (see http://interestingbytes.wordpress.com/hello/openusb-io-interface-board/). Selling for
a paltry $8.80, it is one of the world’s
few remaining bargains.
For this project, I obtained a PC
built in 2005 with both parallel and
serial ports and set it up near my usual
computer so that I could hop onto the
net at any time to check up on some
arcane Linux command. It would also
let me experiment without the fear of
“killing” my good computer. The total
cost of the set-up was just the price
of the Linux DVD plus the computer,
which still came to a total of $8.80, ie,
the computer was scrounged for free (I
did have to duck the hordes of people
that also tried to “donate” their excess
computers).
Now Linux is available in many
July 2011 23
less familiar beyond this point (but if
you’re old enough to remember DOS,
this will be nostalgic). Open up a root
terminal using the desktop icon and
enter the following commands:
user ~ # cd /media
user media # cd work
user work #
A relay board with a parallel port interface. These are available from many
sources, eg, Ocean Controls. Setting an output bit high on the parallel port
closes the corresponding relay.
different “flavours” (called distributions). These contain the same basic
components (kernel, graphical user interface etc) but they are pre-configured
in various different ways.
Just about any distribution will do
for this task but I rather like Ubuntu.
Also many distributions (Ubuntu included) provide a “live CD” or “live
DVD” mode where the operating system is booted off the installation disk.
The advantage of working this way is
that if you make a mistake and cause it
to lock up or you mess up some critical
system file, you simply reboot and all
will be pristine again. And if you use
P. J. Radcliffe’s DVD in this manner,
you will find that the desktop and the
directories are prearranged for ease of
use in this mode.
Into the breach
The first step is to make sure you
can boot from the DVD. Reboot your
computer and watch for the message
that tells you how to get into BIOS –
generally you must press DEL, ESC or
F1 early on in the boot process. Once
in the BIOS menu, wade through the
options until you find the setting for
“Boot Order”, then follow the onscreen directions to move the DVDROM to the first line (if it isn’t there
already).
Next, go to the peripherals set-up
menu. There you will find several
options for the parallel port and you
will need to set it to “SPP” mode (or
bi-directional or compatible, depending on the BIOS).
Having done that, put the Linux
DVD in the drive, then save and exit
the BIOS settings, which should reboot
24 Silicon Chip
the computer. Booting from DVD is a
bit slow but you will eventually be
rewarded with the Linux Mint desktop (assuming that you are using the
recommended distribution; see lead
photo). Note the terminal and Dolphin
icons – they will become your friends.
Booting the machine from a DVD
means that you will have to store your
working files elsewhere. If you have
an old 1GB USB stick laying around,
it will be more than sufficient. Plug it
into your favourite computer and rename it something simple like “work”
because you’ll be typing it a lot (it’s
easier if there are no spaces in the
name). Watch out – unlike Windows,
Linux is also case sensitive, ie, “work”
and “Work” are treated differently.
Next, download the files you will
need from the SILICON CHIP website
(see the panel for a list of files and
sources) and save them to the USB
drive. That done, plug the USB stick
into the Linux machine and open up
the Dolphin (or other) file browser.
Note that Linux does NOT identify
disk drives with letters like Windows
(C:, D: etc), though it does show you
your disk as an icon for convenience.
The topmost directory level is root,
denoted by a single forward slash (/).
Everything else is then under root as
in /bin or /usr etc and you will find
your drive mounted as /media/work
(depending on what exact name you
assigned to it). Rummage around and
make sure it is there, as it’s harder for
beginners to do this when working in
the terminal.
Things now terminal
For Windows users, it all gets much
The hash (#) in the prompt shows
that you are working as root, which
means you have full access to the
computer. Otherwise, you would see
a $ (dollar) sign (a bit ironic given that
Linux is free) and would have more
limited access. You will need to learn
the following commands:
ls -1 (list the files and do it neatly)
pwd (print working directory, ie,
current location)
cd .. (go up one directory level)
./my_program (run my_program
from this directory)
Note that you don’t normally use the
root terminal, as it does not have any
safety constraints. Instead, it is more
usual to prefix a command with sudo,
which has the same effect but only
for that command. Linux has various
levels of permissions for reading and
writing files and executing programs
but the root (or “super user”/administrator) rules them all and can do
anything and everything (including
trashing important files!). That’s why
we’re operating from a DVD. Also,
some programs are not usable without
root access, so it’s easier in this case to
simply use the root account.
The terminal will now have access
to the directory that holds your USB
drive. Type ls -1 to see if your files are
all present and accounted for.
The provided programs are all written in the “C” language, so they will
need to be “compiled” into executable
program files before they can be run.
Linux generally has a C compiler ready
to go and you can invoke it by typing
“gcc” (which stands for Gnu Compiler
Collection) at the command prompt:
user work # gcc -O -o lp_tty_start
lp_tty_start.c
This compiles the C program lp_tty_
start.c into an executable binary file
called lp_tty_start. The “-O” flag tells
the compiler to perform an optimisation pass, producing a faster program.
This is not to be confused with “-o”
which tells it that the output file name
follows.
siliconchip.com.au
Sources For Information, Hardware & Software
(1). http://linuxgazette.net/118/chang.html (interface ADC with parallel port)
(2). http://linuxgazette.net/112/radcliffe.html (general introduction to interfacing serial and parallel ports)
(3). www.interestingbytes.wordpress.com (Linux Mint development system
on DVD-ROM and intelligent USB IO)
(4). www.oceancontrols.com.au (network and control hardware, for industry
and hobby users)
(5). www.siliconchip.com.au (download site for the software relating to this
article in zip format)
Do the same for port_write_then_
read.c, port_read.c and tx_rx_serial.c,
remembering to change both the C
source file and executable file names
for each; ie,
Now type in the following (mind the
spaces and underscores):
user work # ./pp_serial_check run
user work # gcc -O -o port_read
port_read.c
Note that the serial check part only
checks for the presence of a functioning serial port. It does not test the
data transfer (see below). If that’s all
successful, then try outputting a value
via the parallel port:
user work # gcc -O -o tx_rx_serial
tx_rx_serial.c
user work # ./lp_tty_start ./port_
write_then_read 888 85
Finally, create an executable called
pp_serial_check, which combines no
less than three separate C source files.
To compile it type:
That outputs a value of 85 (decimal)
or 55 (hex) or 01010101 (binary) onto
LPT1, which is located at port 888 (often written as 378 hexadecimal). You
can then connect the ground lead of
your multimeter to any of pins 18-25
(all ground) and measure the port’s
output. Pin 2 is the bottom bit (D0),
which should be 1 and the remaining
bits run through to pin 9 (D7). The
voltages should alternate as you scan
the pins.
For this type of programming, it
helps to become familiar with converting between decimal (base 10),
hexadecimal (base 16) and binary (base
two) numbers. Sending the number
1 (decimal) to the port will result in
00000001 (binary) going to the output
pins (D0 high). Sending 128 (decimal)
gives 1000000 (binary), ie, D7 high.
If your calculator can’t handle the
maths, there are lots of web sites that
will do the job.
You can read the state of the port
pins by invoking ./port_read; eg:
user work # gcc -O -o port_write_
then_read port_write_then_read.c
user work # gcc -O -o pp_serial_check
main.c pp_access.c serial_access.c
It is worth noting that the source
code listings of these serial programs
are useful items in themselves and are
neatly commented to make them as
easy as possible to understand and use.
Limited hair, proceed carefully
If, like me, you don’t have much
hair left, you can’t afford much in the
way of frustration and need to consider
each step with care.
First, check the operation of the
ports with a loopback test. To do this,
connect serial and parallel cables to
the PC and look closely at the free ends
of these cables (or peer into the ports
at the back of the computer if you’re a
masochist). You will see little numbers
and you need to connect pin 14 to pin
15 on the parallel cable and pin 6 to
pin 7 on a 9-pin serial cable (or pin 6
to pin 4 on a 25-pin serial cable).
In my case, I used a paper clip to
short the relevant pins for the parallel
port and I got my daughter to hold a
screwdriver to short out the relevant
serial pins.
siliconchip.com.au
user work # ./lp_tty_start ./port_
read 889
This will read the input of LPT1.
Why 889? Parallel ports were originally designed for printers and the
input port is at a different address to
the output port. There are only five
Helping to put you in Control
Control Equipment
Digital Spirit Level
Has the normal liquid bubble vials and
a digital inclinometer
to give you an accurate 0-360degree
readout. Also fitted
with a laser to assist
with alignment. SRS-105 $119.00+GST
Dual Axis Inclinometer
using the latest MEMS
technology the sensor
mounts flat and provides
two orthogonal 0 to 5 V
outputs for X and Y tilt
from -45º to +45º.
SRS-038 $159+GST
Infra-Red Temperature
Sensor Non contact
sensor measures temperature over 0 to
400degC. 4-20mA output
STW-080 $179.00+GST
CNC Controller
This is a 4 Axis stand
alone CNC Controller
which can execute GCode from a USB
memory stick or its
internal memory, eliminating the need for a separate PC running Mach3 or EMC.
CNC-703 $995+GST
MP3 Player Shield
Fitted with a SD micro
card your arduino controller can become a fully
functional MP3 player
SFA-405 $39+GST
JPEG Trigger
interfaces with the LinkSprite JPEG Color Camera to simplify picture
taking. Activate one of six
I/O lines to take a picture
and save it to a onboard SD micro card
SFC-060 $29.00+GST
Industrial Grade
Pushbuttons with screw
terminals and NO+NC
contact
HER-201 $9.95+GST
Contact Ocean Controls
Ph: 03 9782 5882
www.oceancontrols.com.au
July 2011 25
#409
N
6 CO
TRO L
6 DATA
#409
SENSOR
MODULE
#4096
MASTER SERIAL
MODULE
SENSOR
DATA
SENSOR
MODULE
#4097
CONTROLLING COMPUTER
SENSOR
DATA
PARALLEL PORT
RELAY BLOCK
SENSOR
MODULE
#4098
CONTROLLED
HARDWARE
Fig:2: a more advanced control system. In this case, a radio serial transceiver module (eg, from Ocean Controls or
Parallax) sends commands to remote stations which return data to be processed by the PC. A parallel port relay
interface then switches pumps, valves etc.
input bits for a parallel port, located at
pin 15 (D3), pin 13 (D4), pin 12 (D5),
pin 10 (D6) and pin 11 (D7). Yes they
are scrambled and the data for bit D7
is inverted!
There were plans afoot to make port
888 bidirectional but my computer
certainly doesn’t have that option. It’s
worth a try, though – just read port 888
while using a resistor to pull the pins
high or low.
Serial comes to us
Serial data is much harder to deal
with at first, because the data goes past
in a blink and so you must capture it
to debug it.
The solution is to use another computer to send and receive test messages. I scrounged an old laptop that
runs Windows 3.1 (guess how much
it cost!), with the Hyperterminal program for serial port I/O. I also splashed
out and bought a null-modem interface
cable (which connects one serial port’s
transmit pin to the other port’s receive
pin, and vice versa) from Jaycar for
about $12 (Cat. WC 7513).
Serial ports are composite in that
the serial data goes in and out of pins
2 & 3 while the rest of the pins are for
handshaking signals and so are in fact
quite like a little parallel port! However, it’s complicated by the fact that
the application must decide which is
26 Silicon Chip
the master and which is the slave; the
master cues up data and signals when
it is ready to transmit, while the slave
is generally sending data and must
signal when it’s ready to receive.
This can make life a bit complicated,
especially when sending from peer to
peer, but it’s usually possible to simply
ignore the physical handshaking functions and arrange for control signals to
be embedded in the data if it becomes
really necessary.
Linux serial ports are prefixed with
“tty”, which is from its early days as
Unix, where the ports were used to
drive teletypes. What is referred to as
COM1 in Windows is ttyS0 in Linux
(S is for serial). For USB, it is ttyUSB.
Linux also differs in that the serial
ports are accessible as files, eg, the first
port is /dev/ttyS0.
There is a huge variety of serial
software available for Linux, most
from amateur programmers who
needed a particular function or had a
good idea that they pursued. I found
that GTKterm (an improved version
of Hyperterminal) is very useful for
testing, as it will display any data that
passes by. It is included in many Linux
distributions (or “distros”) and Mint
makes it available from the toolbar
which is at the bottom of the screen
(under “Utilities”).
Fig.2 shows a sample system that I
built, with a number of microcontroller modules sending serial data to my
control program which then switches
pumps, heaters or valves as appropriate. I used radio modules for the serial
link, because the remote sensors were
in awkward positions.
For the serial communications,
I started by running the program
tx_rx_serial with port pins 2 & 3
linked together so that the data sent
was immediately looped around to
the data input. Once I knew that the
port was running correctly, I simplified
the program and set it up to send the
appropriate commands to each sensor.
This version is called serialstim.c and
it will need to be compiled in the usual
way. Run the compiled program and
immediately the number 4096 should
appear on the screen (why 4096? In
binary it is 100000000000).
To test this, I then connected the
laptop via the null modem cable and
fired up Hyperterminal. With the appropriate port speed selected, I made
up a text file with a number in it (actually it was the number 11) and cued
it up with “send a file”. It was then a
simple matter of starting serialstim at
the same time as I pressed the <enter> key on the laptop. Success was
getting the number 4096 to appear on
the laptop and the number 11 on the
Linux machine.
siliconchip.com.au
LISTING 1: BASIC SCRIPT FILE (PASSWORDNDATA)
#!/bin/bash
set_val=11
#Preset value
return=$( ./serialstim )
#Send command, get data in response
echo $return
#Print received data to screen
if [ $return -ge $set_val ]
# Is reading above preset value?
then (./lp_tty_start ./port_write_then_read 888 1)
#Yes it is, set D0
else (./lp_tty_start ./port_write_then_read 888 128) #No it’s not, set D7
fi
This basic script file (passwordndata.sh) sends a command to a remote terminal,
receives data in return and switches a relay if a condition is met.
The command went one way and
data came back the other. Cool.
Close the loop with a script
Passing data back and forth is all
very well but nobody wants to sit
around and operate stuff manually.
How about controlling those pumps
and valves? To achieve that, I tied it
all together with script files.
When you type commands into the
terminal, they are actually interpreted
by a program called BASH (which
stands for Bourne Again SHell). BASH
is basically the command line interface
between you and Linux and it was
the only way of doing things in this
operating system before its graphical
user interfaces were developed.
Some clever person(s) realised that
to save effort, it would be useful to
be able to run common sets of commands without having to type them
in every time. This is achieved using
files called “shell scripts” which are a
bit like DOS/Windows batch (*.BAT)
or command (*.CMD) files. Additional
commands were added to BASH to
allow these scripts to be smarter; commands like “if”, “while”, “do” etc.
Suddenly the command line had a form
of programming called “BASH shell
programming”, based on script files.
With a shell script, you can do most
of the things you expect from any
program, with the added advantage
of being able to easily utilise other
programs, written in other languages
such as “C” or Python (as well as other
shell scripts). Furthermore, you can
“pipe” the output from one program
(say, your serial reception program) to
the input of another program, perhaps
a data analysis and control program.
Simple script file
The subject of BASH programming
is much too large for an article such as
this. The Linux community has obviously spent a lot of time developing
the software and there are boundless
references on the internet, though it
can take a bit of hunting to find stuff
that’s written by a native of Earth.
However, to demonstrate, I’ve written a short script that uses all of the
aspects covered so far – see Listing 1.
It does not need to be compiled and
it is run by typing:
user work # sh ./passwordndata.sh
The script calls serialstim to send
a command and then receives data
transmitted from the remote sensor,
which is then echoed (printed) to the
screen. It compares the returned data
to a set value. If it is equal to or above
this value (ge = Greater than or Equal
to), it activates the parallel port enabling program and the control program
to send binary 00000001 to the port,
thus activating the relay connected
to D0. Conversely, if it’s below the set
value, it sends 1000000 to activate the
relay on D7 and make sure that D0 is
switched off.
It’s a simple script and it demonstrates what can be done by unskilled
labour. Remember though that you are
only pottering around in one corner
of a powerful computer. This simple
script could easily be extended to,
say, write the data to a file with a time
stamp and then FTP the files to an address of your choosing. Then it would
be easy to install web server software
like Xampp so that you can access
the system from all over the world
(remote control is also possible using
a program called ssh or Secure SHell).
In short, the applications are limitless, the software and support is all out
SC
there, and the price is right!
Are Your Issues
Getting Dog-Eared?
Are your SILICON CHIP copies getting damaged or dog-eared just
lying around in a cupboard or on a shelf? Can you quickly find
a particular issue that you need to refer to?
REAL
VALUE
AT
$14.95
PLUS P
&
P
Keep your copies of SILICON CHIP safe, secure and
always available with these handy binders
Available Aust, only. Price: $A14.95 plus $10 p&p per order (includes GST). Just
fill in and mail the handy order form in this issue; or fax (02) 9939 2648; or call (02)
9939 3295 and quote your credit card number.
siliconchip.com.au
July 2011 27
|