Вы находитесь на странице: 1из 52

TOC - Jan 17_TOC NV Mar 15.

qxd 12/6/2016 12:07 AM Page 4

Subscription Information

January 2017
08 TechKnowledgey 2017 48 The Spin Zone
Nuts & Volts — PO Box 15277
North Hollywood, CA 91615-9218
Call 877-525-2539 or go to www.nutsvolts.com
Subscribe • Gift • Renewal • Change of Info

Events, Advances, and News Adventures in Propeller Programming


Read about pollutants becoming fuel, printer problems, Making Menus
building your own Tesla, plus other interesting stuff. Menus are important — in restaurants and in consumer
devices — and we should never take them for granted. Big
12 Q&A project or small, take your time when it comes to the user
interface, and design a system that is sensible and easy to
Reader Questions Answered Here use.
Find answers to questions on phantom power, extending
Wi-Fi range on the cheap, and PBX and auto dialers.
56 The Design Cycle
Advanced Techniques for Design Engineers
16 The Ham’s Wireless A Look at the nRF52832’s SPI Peripheral
Workbench The Nordic Semiconductor nRF52832 isn’t just a BLE
radio. It’s a full-blown ARM microcontroller as well.
Practical Technology from the Ham World This time, we will take an in-depth look at the nRF52832’s
Ham Metrics and the Decibel SPI peripheral. Along the way, we’re going to “generate”
The “dee-bee” is everywhere in ham radio, and is used a bit of eight-bit SPI Slave
for characterizing everything from antenna performance PIC code too.
to nano-sized signals. Learn the decibel, and you and your
Page 32
signal will go a long way! Page 27

06 DEVELOPING
Departments 54 NV WEBSTORE
PERSPECTIVES 62 TECH FORUM
The Zombie Apocalypse 64 CLASSIFIEDS
— Are You Ready? 65 ELECTRO-NET
07 READER FEEDBACK
65 AD INDEX
07 SHOWCASE

20 An Electronic Chessboard 32 An ESP8266 RSS News Reader


Are you a fanatic when it comes to keeping up with
Using RGB LED Strips and Hall current events? Then, you’re gonna love this reader that
will continuously display headlines from selected news
Effect Sensors feeds that’s constructed from the same circuit that also
The game of chess is considered by many to be very allows you to build an auto setting clock and/or weather
complicated and played by people who enjoy a challenge. clock.
However, with this game board that is set up for two ■ By Craig A. Lindley
human players, you’ll be able to actually see the various
allowable moves for each chess piece.
■ By Theron Wierenga
36 REVIEW: Bench Werx Offers a
Versatile PCB Holder
27 Vintage Computing — The Ever need a “third hand” when soldering your circuit
boards? Perhaps the PCB Rax system is just what you’re
Retro PIC Single-Board Computer looking for.
■ By Dane Weston
Over the years, I have accumulated a bunch of chips from
before the era of true PCs when computers with names
like Altair, KIM-1, and Cosmac ELF were popular. I’ve been
looking for a way to use them in new projects, so I
40 Computer Control and
designed a system around a 40-pin PIC16F887. I figured
this would put some of my historic chips to work and be a
Interfacing with the NI MyRIO
Part 2: As we continue our series on using the National
great learning tool for understanding how a Instruments’ MyRIO, we will build and deploy the VI we
microcomputer works. created last month as an embedded program, and will
■ By Dan Gravatt control the MyRIO wirelessly with an iPad.
■ By David Ward
Nuts & Volts (ISSN 1528-9885/CDN Pub Agree #40702530) is published monthly for $26.95 per year by T & L Publications, Inc., 430 Princeland Court, Corona, CA 92879. PERIODICALS POSTAGE PAID AT
CORONA, CA AND AT ADDITIONAL MAILING OFFICES. POSTMASTER: Send address changes to Nuts & Volts, P.O. Box 15277, North Hollywood, CA 91615 or Station A, P.O. Box 54, Windsor ON N9A
6J5; cpcreturns@nutsvolts.com.

4 January 2017
Bergeron - Developing Perspectives - Jan 17_Dev Perspectives - ReadFeed Feb15.qxd 12/5/2016 10:04 PM Page 6

DEVELOPING
PERSPECTIVES
by
Bryan
Bergeron,
Editor Published Monthly By
T & L Publications, Inc.
430 Princeland Ct.
Corona, CA 92879-1300
(951) 371-8497
FAX (951) 371-3052

The Zombie Apocalypse — Are Webstore orders only 1-800-783-4624


www.nutsvolts.com
You Ready? Subscription Orders
Toll Free 1-877-525-2539
fault or other problem with the
T he power grid is down, no
Internet, no cellular, and no
landline communications, and killer
emergency electrical system? Do you
know how to administer CPR?
Outside US 1-818-487-4545
P.O. Box 15277
North Hollywood, CA 91615
zombies are on the loose. Now Let’s say your friendly
FOUNDER
what? Well, let’s replace the zombie neighborhood nuclear power station Jack Lemieux
attack with a hurricane, tornado, or has an event. Do you have a Geiger
PUBLISHER
earthquake. Is that any better? Could counter and do you know how to Larry Lemieux
you make do? Could you leverage use it? Do you know how to clean publisher@nutsvolts.com
your skills in electronics to call for the probe if it becomes ASSOCIATE PUBLISHER/
help, cook and preserve your food, contaminated? Do you know how to ADVERTISING SALES
and provide light? use your Geiger counter to Robin Lemieux
robin@nutsvolts.com
One of my favorite activities distinguish between the different
related to ham radio is ARRL Field types of radiation? EDITOR
Bryan Bergeron
Day. Once a year, hams throughout The bottom line is that you techedit-nutsvolts@yahoo.com
the US set up a tent or other should be ready for anything — from
VP OF OPERATIONS
temporary structure and — using solar angry aliens to mudslides. Plan ahead Vern Graner
power or gasoline powered now, while you have time to think vern@nutsvolts.com
generators — cook, have lights, things through. What’s the most CONTRIBUTING EDITORS
perhaps an electric cooler or two, likely scenario (hopefully not Fred Eady Kristen McIntyre
and of course communicate with zombies)? What skills should you David Ward Jon McPhalen
Jeff Eckert Ward Silver
each other. The goal of Field Day is have? What equipment do you need Craig Lindley Dane Weston
to test every ham’s preparedness and to have on hand? Clearly, if you live Theron Wierenga
ability to function in the event of a on the Gulf coast, you’ll need to
CIRCULATION DEPARTMENT
natural or manmade disaster. consider a scenario dominated by subscribe@nutsvolts.com
So, let’s say you have an electric hurricanes. If you’re in the Bay area,
SHOW COORDINATOR
generator in your basement and then the aftermath of earthquakes Audrey Lemieux
perhaps a portable bank of solar deserves your attention.
WEBSTORE MARKETING
cells. Can you change the points in As an electronics enthusiast, you COVER GRAPHICS
the generator? Adjust the carburetor? have a vast skill set that lends itself to Brian Kirkpatrick
Do you know how to ground the recovering from any number of sales@nutsvolts.com
system? What about load disasters, but you have to plan ahead WEBSTORE MANAGER/
distribution? Do you have the and practice those skills so that you PRODUCTION
Sean Lemieux
equipment and know-how to can bring them to bear when they’re sean@nutsvolts.com
combine the output of your solar needed. If you’re a ham, don’t forget
panel and gasoline powered the annual ARRL Field Day, held ADMINISTRATIVE STAFF
Re Gandara
generator? every fourth weekend in June.
What about electrical repairs to If you’re not a ham, then Copyright © 2017 by T & L Publications, Inc.
radios, vehicles, and other electrical consider practicing your skills within All Rights Reserved
All advertising is subject to publisher’s approval. We
equipment? Do you have a butane the context of a club, neighborhood are not responsible for mistakes, misprints, or
powered torch or soldering iron so group, local Civil Defense, or other typographical errors. Nuts & Volts Magazine assumes
no responsibility for the availability or condition of
that you can work without 120 VAC? group. You could practice on your advertised items or for the honesty of the advertiser.
Do you have spare parts? If your own, but my Field Day experiences The publisher makes no claims for the legality of
basement pump fails, do you have taught me that competition is the any item advertised in Nuts & Volts. This is the sole
responsibility of the advertiser. Advertisers and their
the parts and know-how to fix it? best way to sharpen emergency agencies agree to indemnify and protect the publisher
What if someone in your group gets response skills. NV from any and all claims, action, or expense arising from
advertising placed in Nuts & Volts. Please send all
a nasty shock because of a ground editorial correspondence, UPS, overnight mail, and
artwork to: 430 Princeland Court, Corona, CA 92879.
6 January 2017
Q&A
n WITH KRISTEN A. McINTYRE

In this column, Kristen answers questions • Phantom Power and Stopping a Cough
about all aspects of electronics, including
hardware, software, circuits, theory, radio • Extending Wi-Fi Range on the Cheap
troubleshooting, and anything else of interest • PBX and Auto Dialer
to the hobbyist. Send all questions and
comments to: Q&A@nutsvolts.com. shield/ground wire. There’s a whole article that could be
written on whether the shield is the same as the ground,
or even if they should be connected to each other. Ward
Phantom Power and Stopping a Cough Silver’s article from the November 2016 Nuts & Volts tells
the story well. An example of a simple circuit to implement

Q
I am interested in creating a mute (a.k.a., phantom power on a balanced three-wire system is shown
“cough”) button for the microphones used in Figure 1. n
by the hosts in our podcasting studio. The As a side note, loop-start telephone systems like POTS c
microphones are Audio Technica AT831B (Plain Old Telephone Service) lines are an example of a
Lavalier phantom powered from our mixer. I would like to phantom power that isn’t balanced. The phone company
build the circuit in a small desktop box with a button on supplies roughly 48 volts open-circuit to the telephone E
top and XLR IN and XLR OUT on the back to insert the instrument. That becomes a power supply that’s used to

Q
box between the mixing board and the microphone. I have pass current through a carbon microphone where the
seen a few “mute” schematics that suggest shorting pins 2 resistance varies with sound pressure. A certain impedance
and 3, but I think this might short out the phantom power. across the incoming pair causes the phone switch to sense
Do you have a schematic that might work for me? that the phone is off-hook, and the audio is impressed
Lance Harvey as small AC variations on the line. There are many more a
Midland, TX things (ring voltage, hook flash, DTMF, etc.) that can be lo
signaled in a loop-start system. It’s a really clever design. re

A
I think that the schematics you’ve found are Of course, when we build equipment, we are never M
on the right track. I have a collection of Nagra sure what will be connected to any terminals that we
audio tape recorders (beautiful machines with expose, so we have to plan for wires to be shorted and
superb audio quality, by the way), and that’s other bad situations. Phantom power is no exception, so

A
where my experience with this comes from. Let’s first take that is why there are resistors shown in the figure to limit
a look at how phantom power works. the worst case current supplied by the phantom power
Since some types of microphones and accessories supply. Even if you were to short all of the wires from the
require voltage and a little bit of power to operate, XLR connector together, a properly designed device should
engineers came up with the idea of impressing a little be fine. We never know for sure if things are properly
power supply voltage on the signal wires. Since the audio designed, though. Let’s just assume that for the moment. d
signal is changing with time, it can be separately extracted The audio signal coming from a microphone in a in
or injected with either inductors or capacitors, depending balanced or differential audio system is derived from p
on the implementation. In the case of balanced audio such subtracting the voltages from the two differential audio c
as we see in three-wire systems using XLR connectors, pins. In the case of XLR connectors, that’s pins 2 and 3. If th
we can take advantage of the three conductors to further there is a voltage between the shield/ground (pin 1) and
separate the AC component from the DC component. the other two, it is not considered to be part of the audio w
The convention for these balanced systems is to raise signal. What this implies is that pins 2 and 3 will generally o
the two differential audio signals roughly equally above the be close to each other in voltage. im
In order to build our cough button, we don’t need in
to short the entire phantom power system. All we need e
to do is bring the voltage difference between pins 2 and th
3 to zero. That means we can indeed simply short them d
together with a switch (Figure 2). To be a little paranoid, th
you might use a very low impedance — but not zero — to th
connect them together.
An important consideration, though, is making sure a
that noise can’t leak into the system from the switch. so
It is probably a good idea to use a metal box to shield th
the switch from stray electromagnetic fields, and to c
n FIGURE 1. One way to supply Phantom Power connect that box to the shield/ground on pin 1 of the XLR w
12 January 2017

McIntyre - Q&A - Jan 17.indd 12 12/6/2016 2:33:39 AM


QUESTIONS and ANSWERS
Post comments on this article and find any associated files and/or downloads at
www.nutsvolts.com/magazine/article/January2017_QA.
h of-thumb calculation to determine the length is shown in
Figure 3, where A is this velocity factor. When I run the
numbers with a frequency of 5.5 GHz, I get 0.026 meters,
or 26 millimeters. That’s the entire length of the dipole, so
each leg is half of that.
Cable TV coax is usually terminated with F connectors.
She could get some solderable F connectors and then
construct the dipole from copper wire. The skin effect
is the tendency for electromagnetic energy to flow on
t the surface of a conductor at AC. This effect is more
pronounced with increased frequency. As less depth of the
n FIGURE 2. Example Cough Button Circuit. conductor is used, the effective resistance increases.
connectors. If an electromagnetically shielded switch is The skin effect is quite big at the frequencies used for
available, that would be a good choice. Wi-Fi, so low resistivity material is important, and copper
is one of the metals with the lowest resistivity (though not
Extending Wi-Fi Range on the Cheap the lowest). RG-6 coax is usually made with aluminum
which is also quite good, but not as good as copper. It’s

Q
My (step) granddaughter wants to make a significantly less expensive, though. So, building the dipole
e Wi-Fi signal extender for a science fair. I was out of copper wire is recommended.
e wondering if a purely passive circuit might work.
Could we put a dipole at one end of some coax
and then at the far end just have the thing loop back? If the n FIGURE 3. Dipole length rule of thumb.
loop was big and part of it passed near a laptop, would it Supporting structures should be made with something
rebroadcast? Would it help if the circuit was tuned to 2.4 that exhibits a low relative dielectric constant so that the
MHz or 5.whateveritis MHz? Am I being crazy? pattern and impedance aren’t distorted much. While the
Randy Smith dimensions are important, they aren’t critical. A dipole
Palo Alto, CA has a fairly low Q (quality factor — a measure of how
narrow its operational bandwidth is) given its high radiation

A
No Randy, you’re not being crazy at all! What resistance, so it works without too much impedance shift
you propose is close to what you want. It’s over a fairly wide range. Even if it’s off, it’s not fatal. There
called a passive repeater. I’ve done it myself on is just a slightly higher loss in the coax and changes to
d the two-meter amateur band. the antenna’s field strength pattern. Careful construction
Instead of a loop at the far end, you’d want another is warranted because of the skin effect, though. Figure 4
dipole. The idea is to construct a dipole that is resonant gives you a basic idea of what the passive repeater looks
in the middle of the Wi-Fi channel spectrum (or on a like electrically.
particular channel that she’s using), pass it through some With this arrangement, place one dipole near the Wi-Fi
coax, and then build a dipole of the same dimensions at base station’s antenna — preferably polarized the same
the other end of the coax. way as its antenna for maximum coupling — then place
If the dipole is resonant, in other words 1/2l (or the other one in another room and take signal strength
wavelength), then the feed point impedance would be 72 measurements both with and without the apparatus.
ohms resistive, which is very close to the characteristic Almost all Wi-Fi transceivers have a way to measure relative
impedance of RG-6 75 ohm low loss coax — what’s used field strength, often called RSSI. It is usually displayed in
in cable television everywhere. One dipole would couple dBm (decibels against 1 mW).
energy from the propagating electromagnetic energy from A similar measurement of noise is usually available
the Wi-Fi base station into the coax. The energy would flow from the transceiver. Measurements of the RSSI and
down the coax, shielded from radiating externally. Then, noise can be combined to produce a signal-to-noise ratio.
the dipole at the far end would reradiate that energy into Another study for the science fair might be how critical
the destination area. the dipole dimensions are to performance; both the dipole
Calculating the dipole length requires a slight length and the separation of the wires at the feed point.
adjustment to the speed of light in a vacuum. This is a To refine the passive repeater a bit, you’d want to
somewhat complicated calculation that is dependent on put around two or three ferrite beads (little toroids) on
the thickness of the wire relative to the wavelength. We the coax near the feed point, or even just loop the coax
call this unit-less number the velocity factor, and for this we tightly two or three turns near the feed point to decouple
will just guess that it will be around 0.95. A simple rule- the outer side of the coax shield from the dipole and
January 2017 13

McIntyre - Q&A - Jan 17.indd 13 12/6/2016 2:33:39 AM


A
This seems like a bit of a complicated device
that will require some careful programming
to make sure that the right thing happens.
It’s possible to detect DTMF (dual-tone multi-
frequency) dial signals in software if the audio signal is
n FIGURE 4. Schematic representation of a Passive digitized, using what’s called the Goertzel algorithm. That
Repeater. is a very sharp IIR (or infinite impulse response) digital filter.
improve the pattern. The shield actually looks like two It’s also possible to build some hardware band pass filters
conductors because of the skin effect, so you can increase that could be monitored with a controller. Lastly, there are
the inductance of the outer part near the feed point to some specialized DTMF decoder devices like the MT8870
keep current from flowing from the outer side of the shield from Mitel. Then, you’d need some isolation transformers
to the dipole. If you don’t do that, the coax is part of the and relays to switch the circuit from pass-through to a way
antenna and radiates along its length. to inject generated DTMF signaling into the CO line. The
This could be good or bad, depending on what gain algorithms for what you want to do could be written for a
pattern is desired. It sounds a little crazy that the coax has microcontroller like an Arduino or Raspberry Pi.
two effective conductors along the shield, but you really Sadly, I think this is a rather complicated thing to both
see it in practice, even below 30 MHz. Of course, at lower construct and implement both in hardware and software
frequencies like 160 meters or 1.8 MHz, you need lots of — particularly as an add-on. Unless your PBX system has
ferrite beads to make enough inductance. a software upgrade to provide the desired functionality,
There are other antenna designs that could change the constructing an add-on won’t be simple. That’s not to say
gain pattern for different results, but dipoles are simple to it’s impossible by any means. How to build such a device
build and they conveniently have a feed point impedance does exceed the extent of what I could write here, though
close to common RG-6 coax. I hope she gives it a try. it would be a fun undertaking if you had the time.
It turns out, though, that building up a new PBX from
PBX and Auto Dialer scratch isn’t hard. There’s an open source PBX called
Asterisk (www.asterisk.org) that runs on an ordinary PC

Q
I love my small PBX system and want to add an running Linux. Asterisk is designed to work with VoIP
auto dialer between the CO line and the PBX. phones, but there are also POTS interface cards available.
I want to detect outgoing digits (if more than The website has a section under “Products” that can
two digits, no action). If they are 1, 1, then the direct you to manufacturers of hardware POTS interfaces
dialer should add prefix 9 and dial 911 (or disconnect compatible with Asterisk. Being open source, if you aren’t
and dial 911) as is required by new laws. Are there simple happy with how it works, you can change it in software.
commercially available devices or can you suggest some While you’re on the Web, if you are plagued by
simple circuit to achieve such a thing? unwanted marketing calls, be sure to search for “PBX” and
Ankur Bhakta “Lenny” ... NV

Development Tools and Learning Systems for


PIC Microcontrollers PBP3
PICBASIC PRO™ Compiler

Check out our popular products for PIC® developers including:


U2 Programmer
PICBASIC PRO 3.0 Compiler
Prototyping Boards
Experimenter Boards
ME Labs Trainer Board and Programming Tutorial

ME Labs has been been a global leader in the creation of


development tools for PIC microcontrollers for 20 years.

www.melabs.com Contact us at info@melabs.com or go to melabs.com


PICBASIC PRO is a trademark of Microchip Technology Inc. in the USA and other countries.
PIC is a registered trademark of Microchip Technology Inc. in the USA and other countries.

14 January 2017

McIntyre - Q&A - Jan 17.indd 14 12/6/2016 2:33:52 AM


Silver - Ham's Wireless Workbench - Jan 17_Hams Wireless Workbench - Sep 15.qxd 12/5/2016 10:09 PM Page 16

THE HAM’S WIRELESS WORKBENCH


PRACTICAL TECHNOLOGY FROM THE HAM WORLD hwardsil@gmail.com

Ham Metrics and the Decibel


Knowing the language of metrics is not optional!

e’ve all experienced the feeling of visiting a group dB is just a number that describes how much bigger or
W outside of our own background and being
completely flummoxed by the rapid-fire jargon being
smaller one quantity is compared to the other. Both
quantities themselves must have the same base units,
thrown around. Just as confusing are the measurements in though — watts, for example. If P2 is larger than P1, the dB
this alternate universe. Wireless communication seems to value is positive, such as for amplifier gain. If P2 is less, the
involve many such terms, but many seem to be calculated value is negative and represents attenuation or loss.
or expressed in terms of the decibel. This column covers a (Somewhat confusingly, it’s common to specify an amount
number of these measurements and values, and shows of attenuation as a positive value of dB. For example, “This
you how to use decibels for them. filter attenuates the signal by 20 dB.”)
If you want to compare voltage (or current) levels, you
The Decibel have to account for the relationship between voltage (or
current) and power not being linear — doubling voltage
The “dee-bee” is everywhere in ham radio, and is (or current) is a quadrupling of power:
used for characterizing everything from antenna
performance to nano-sized signals. Learn the decibel P = V2/R = I2R so dB = 20 log10 (V2/V1)
(abbreviated as lower-case ‘d’ followed by an upper-case
‘B’ or ‘dB’) and you and your signal will go a long way! You don’t necessarily have to have a calculator at the
From the ARRL Ham Radio License Manual’s online ready. Just memorizing the few power dB relationships in
math tutorials for beginning hams (arrl.org/chpt-2-radio- Table 1 is easy. Remembering a simple rule for factors of
signal-fundamentals), we introduce the decibel. “You 10 will come in quite handy, too. Speaking in terms of
have probably recognized deci as the metric prefix that power, any change by an exponent of 10 is a change in
means one-tenth. The unit we are really talking about here dB of 10 times the exponent. A change of 100 (102) is a
is the bel (a ratio of sound levels named for Alexander change of 20 (2 x 10) dB; a change of 1000 (103) is a
Graham Bell), so a decibel is just 1/10th of a bel. We use change of 30 (3 x 10) dB; and so forth.
a decibel instead of a whole bel because the bel Another handy thing to remember is that multiplying
represents a rather large change in levels. The dB is a just- the ratio by a factor allows you to add the dB equivalent
perceptible change and more useful as a unit of of that factor. For example, from Table 1, a change of 20
measurement.” As used in wireless, the decibel is the ratio is the same as a change of 5 x 4, so a change of 20 in dB
of two power levels: is equal to 7 + 6 = 13 dB. You could also figure that out
from 20 = 10 x 2, so the dB equivalent is 10 + 3 = 13 dB.
dB = 10 log10 (P2/P1) Doubling power — another common situation — is a
change of 3 dB. By memorizing a few values and rules,
Note that the dB has no units because it is a ratio. The you can navigate dB quite easily!

Table 1 — Decibel Values for Common Power and


Voltage Ratios. Decibel-defined Values (dBm,
P2/P1 dB V2/V1 dB dBW, dBV, dBuV)
0.1 –10 0.1 -20 It’s quite common to need an “absolute” power level,
0.25 –6 0.25 -12
0.5 –3 0.5 -6 Online Glossary
1 0 1 0 The ARRL’s Technical Portal (arrl.org/tech-portal) includes
2 3 2 6 several references, and you’ll also find an online glossary
(www.arrl.org/ham-radio-glossary) that explains terms as hams
4 6 4 12
use and understand them. If you are studying for your ham radio
5 7 5 14 license, these would be good websites to bookmark in your
10 10 10 20 browser.
16 January 2017
Silver - Ham's Wireless Workbench - Jan 17_Hams Wireless Workbench - Sep 15.qxd 12/5/2016 10:12 PM Page 17

■ BY WARD SILVER N0AX


Post comments on this article and find any associated files and/or downloads at
www.nutsvolts.com/magazine/article/January2017_HamsWirelessWorkbench_Ham-Metrics-and-Decibels.

yet need to work with gain and attenuation in dB. The Noise in Analog-to-Digital Converters (ADCs)
solution is to use a single fixed reference level for all It’s the norm these days to digitize analog signals and
measurements. The value for P1 in the equation shown manipulate them in software. As such, it’s important to understand
(the one in the denominator) is the ratio’s reference level. the noise performance of ADCs. The Analog Devices’ tutorial —
By using the same absolute reference value for all of your “Understand SINAD, ENOB, SNR, THD, THD + N, and SFDR So You
calculations, you also know the absolute power of the Don't Get Lost in the Noise Floor” (AD MT-003) — is an excellent
measurement. tutorial on different noise metrics of ADCs.
For example, if you use one milliwatt (1 mW) as your You can download it for free at www.analog.com/media/en/
training-seminars/tutorials/MT-003.pdf.
reference level, all of your dB values will be calculated
“with respect to one milliwatt.” This is so common in
wireless that the abbreviation dBm was created. A power Gain: Power or Pattern
level of 10 dBm is 10 times 1 mW or 10 mW; 3 dBm is 2 I have mentioned “gain” several times so far in this
mW; -20 dBm is 0.01 mW; and so forth. Because values in column and it’s time to explain there are two common
dB are added or subtracted when the quantities are definitions, both specified in dB. The most used definition
multiplied or divided, you can easily use dBm values and probably the one you imagine when you see the
throughout your radio system. word is power gain. This is what happens when an active
For example, when a 1W transmitter signal (30 dBm) device such as an op-amp or transistor or vacuum tube
is amplified with a gain of 15 dB, it becomes a 30 + 15 = uses a low level input signal to control a more powerful
45 dBm signal. A received signal of -47 dBm experiencing output signal. The output signal has more power than the
a cable loss of 6.2 dB is reduced to -47 – 6.2 = -53.2 dBm. input signal. That input-to-output power ratio is the gain of
Other common abbreviations you’ll encounter in the the circuit or device — pretty straightforward.
wireless world are the dBW (reference level of one watt), The other type of gain is created by antenna
dBV (reference level of one volt), and dBuV (reference designers. You’ll frequently see antennas specified to have
level of 1 µV). When you see a letter appended to “dB,” it some value of gain in dB. The antennas themselves do not
is specifying a common reference value. add any power to the signal applied to their feed point. In
fact, due to resistance, the antenna has a slight loss. The
Signal-to-Noise Ration gain being referred to — pattern gain — comes from
focusing the signal in a certain direction so that it appears
Another common measurement expressed in dB is the stronger in the favored direction. This is equivalent to
signal-to-noise ratio, or SNR or S/N. SNR compares the having amplified the signal by the same amount.
signal power to the power of the background noise: SNR An antenna’s pattern gain, however, is always
= 10 log10 (PSIGNAL / PNOISE). Often left out of the measured or specified with respect to some standard
discussion is the bandwidth of the channel over which reference antenna. The two most common references are
noise is measured. the isotropic antenna which radiates equally in all three-
For example, a telephony circuit (mobile or landline) dimensional directions, and the dipole which radiates best
may be assumed to have a communications-quality broadside to the antenna and very weakly off the ends.
bandwidth of 3 kHz. It’s usually assumed to be the (Dipoles and their radiation patterns were discussed in the
receiver or amplifier bandwidth, but don’t assume that’s September 2016 column.)
always the case. If you really need to know SNR with full If you imagine the isotropic antenna’s radiation
accuracy, specify the bandwidth of the measurement. pattern as a spherical balloon filled with radiated power, a
In the case where interfering signals are also present directional antenna like a beam or dish creates pattern
— such as for a data link in a shared unlicensed frequency gain by “squeezing” the sphere. Where the signal is
band like 900 MHz or 2.4 GHz — a better measurement focused, the sphere extends farther from the center than
might be signal-to-noise plus interference ratio or SNIR. without focusing. The ratio between the focused direction
(This measurement is also written as signal-to-interference and the original equal-in-all-directions is the antenna’s gain
plus noise ratio, or SINR.) If your data link will be in that direction.
operating in a crowded band, this might be a better way Since the ratio depends on the reference antenna’s
to measure and plan your communications link. pattern, antenna gain must always be specified with
Finally, each step in the modulation/demodulation and respect to the reference antenna. If the reference was an
signal amplification chain adds some distortion products isotropic antenna, the abbreviation dBi is used; dB with
to the desired signal. The measurement signal-to-noise plus respect to an isotropic antenna. If a dipole was used, the
interference and distortion, or SINAD accounts for these abbreviation dBd is used with the understanding that the
effects: SINAD = 10 log10 [(PSIGNAL + PNOISE + PDIST) / dipole’s pattern is used where the dipole’s radiation is
(PNOISE + PDIST)]. strongest: broadside to the dipole. In fact, a dipole has a
January 2017 17
Silver - Ham's Wireless Workbench - Jan 17_Hams Wireless Workbench - Sep 15.qxd 12/5/2016 10:09 PM Page 18

losses throughout the entire antenna system, from the


FIGURE 1. transmitter to the antenna. The resulting value
represents how much power it would take to create the
same signal strength using a standard reference
antenna. The standard antenna can be an isotropic
antenna with no pattern gain in any direction or a
dipole antenna which has 2.2 dB more gain broadside
to the antenna than an isotropic antenna. Like the
decibel-defined value discussed earlier, a letter can be
added to ERP to indicate which reference is used. EIRP
is the ERP calculated with respect to an isotropic
antenna; if no letter is added (ERP), then a dipole is
assumed to be the reference. To convert ERP to EIRP,
add 2.2 dB to account for the dipole’s higher gain.
gain of 2.2 dBi, so you can convert dBd to dBi by adding An example is useful in explaining how ERP works.
2.2 dB and vice versa by subtracting dBi. When you see Figure 1 shows a typical transmitting installation that
an antenna advertised as having “x dB of gain,” you have might be installed at a shared communications site. Let’s
to ask, “With respect to what?” start with the transmitter power output, or TPO of 1.5 kW.
This is an absolute power level of 10 log10 (1500) = 31.7
SWR and Return Loss dBW. The transmitter is connected to a filter that removes
any harmonics but also has an insertion loss, or IL of 0.5
The notion of standing wave ratio, or SWR was dB. (This loss is due to losses in the inductors and
introduced in the January 2016 column. Basically, it is a capacitors and connecting wires.) To prevent other
measure of how much power in a feed line is transferred transmitted signals from coming down the feed line and
to the load and how much is reflected back toward the getting into our transmitter output, an isolator is used that
signal source. Reflections occur because of a mismatch only allows power to flow toward the antenna. It, too, has
between the load impedance and the feed line’s insertion loss, and the amount of loss is 0.8 dB. Feed lines
characteristic impedance. SWR can have a value of 1:1 also have loss, and at the frequency of the transmitted
(no reflection, all power transferred to the load) and ∞ (all signal (for this length of feed line) the loss is 2.5 dB.
power reflected, as at an open- or short-circuit). Finally, the antenna is a bay of folded dipoles with a
Such a wide range (1 to ∞, but not beyond) is okay pattern gain of 6 dBi. So, what is our EIRP and ERP?
for the relatively imprecise world of amateur radio and
most hobby applications. Typically, if the SWR a • EIRP = TPO – Filter IL – Isolator IL – Feed Line IL +
transmitter “sees” looking into a feed line is less than Antenna Gain
1.5:1, everything works well. Professionals, however, want • EIRP = 31.5 dBW – 0.5 dB – 0.8 dB – 3.5 dB + 6 dBi =
a more precise measurement at both high and low values 32.7 dBW = 1862W
of SWR. They use return loss, or RL. • ERP = EIRP – 2.2 dB = 32.7 dBW – 2.2 dB = 30.5 dBW
RL is measured in dB as the ratio between power = 1122W
reflected back toward the signal source and the forward
power from the source: RL = -10 log (PREFL / PFWD). If PREFL This makes sense because our transmitter would have
= 0, then RL = ∞ and SWR is 1:1. If PREFL = PFWD, then RL to work 2.2 dB harder to create the same signal strength
= 0 dB and SWR is ∞. There is a handy online converter at the receiver if it only used an isotropic antenna. As you
for RL and SWR at the Microwaves101 website at can see, it’s quite easy to work with dBW and dB instead
www.microwaves101.com/calculators/872-vswr- of having to calculate everything in watts.
calculator.
Bandwidth and Spurious
Effective Radiated Power (ERP) Emissions
When planning a wireless communications system or Finally, interference is a fact of life with wireless
broadcast installation, you have to know the strength of systems. Sometimes it’s accidental, but it’s always
the transmitted signal in order to figure out how well it will annoying. The FCC (Federal Communications
be received. With so many different factors affecting Commission) sets standards for how transmitters must
radiated signal strength, it’s hard to compare “apples to behave in order to be good neighbors and share
apples.” As a result, the concept of effective radiated spectrum. Key to establishing common ground is a clear
power, or ERP was devised. ERP accounts for gains and definition of terms, and one of the most important is
18 January 2017
Silver - Ham's Wireless Workbench - Jan 17_Hams Wireless Workbench - Sep 15.qxd 12/5/2016 10:09 PM Page 19

bandwidth. While there are lots of different


definitions of bandwidth floating around, there’s
only one that matters on the air and that is the
FCC’s definition! For the amateur service,
bandwidth is defined in the FCC’s rules, Part
97.3(8): The width of a frequency band outside of
which the mean power of the transmitted signal is
attenuated at least 26 dB below the mean power
of the transmitted signal within the band. What
that means is for whatever signal you are
transmitting — data, AM voice, FM voice — the
FCC will average (take the mean of) the
transmitted signal power and find the frequencies
on either side of the signal at which the signal’s FIGURE 2.
strength is 400 times (26 dB = 20 dB + 3 + 3 dB =
100 x 2 x 2 = 400) weaker. The difference
between those two frequencies is the signal’s bandwidth.
Signing Off
Figure 2 gives you an idea of how this works. Decibels are everywhere in wireless communications.
Spurious emission is the term for any component of They allow us to compare and discuss signals many orders
the transmitted signal that is unnecessary or unintentional, of magnitudes different in amplitude without having to use
and which is stronger than 26 dB below the signal’s mean cumbersome notation or lots of zeroes! Getting
power. As you can see from the figure, spurious emissions comfortable with the “dee-bee” is a great first step in
far from the signal can cause interference to signals on understanding radio signals and the systems that produce
adjacent channels and, in fact, this is quite common. them. NV
Perhaps the transmitter is
overmodulated, causing extra
sidebands to appear to either side.
Perhaps a speech processing circuit
isn’t operating properly and distorts
the signal and creates these extra
signals. Harmonics of a signal are
also spurious emissions. These are
almost always present because no
transmitter is perfect. There are
always some minor non-linearities
that produce harmonics. If you have
an AM broadcast station nearby with
a frequency below 800 kHz, set your
car or portable radio to twice the
station’s frequency and drive toward
the transmitter. At some point, you’ll
hear a distorted version of the same
programming from the second
harmonic of the transmitted
fundamental. (There is no “first”
harmonic — that’s the fundamental.)
If you have a general-coverage short-
wave or “world band” receiver, you
can probably find the third harmonic
as well. Don’t get too close to the
transmitter or your receiver will be
overloaded and start generating
harmonics internally all by itself!
“Spurs” aren’t always the fault of the
transmitter!
January 2017 19
Wierenga - LED Chess - Jan 17 - part 1_Blank Project NV.qxd 12/5/2016 10:18 PM Page 20

BUILD IT YOURSELF
By Theron Wierenga

An Electronic Chessboard
Using RGB LED Strips and
HALL
EFFECT
SENSORS
King moves. Queen moves.
The game of chess is considered by
many to be very complicated and
played by people who enjoy a
challenge. Actually, the rules of how
the chess pieces can move are fairly
simple and easily learned. What makes
things complicated is the total number
of different ways a game can progress.
After each side has played three Bishop moves. Rook moves.
moves, the pieces could form any one
of over nine million possible positions
on the board. The number of distinct
40 move games is far greater than the
number of electrons in the observable
universe. If you are not familiar with
chess, Wikipedia has an excellent
introduction to the game at
https://en.wikipedia.org/wiki/Chess.
The chessboard layouts shown here Knight moves. Pawn moves.
illustrate the various allowable moves
for each chess piece. The more
esoteric castling, en passant, and
promotion moves are not included in
this project, although they could be
added to the software.
20 January 2017
Wierenga - LED Chess - Jan 17 - part 1_Blank Project NV.qxd 12/5/2016 10:18 PM Page 21

Post comments on this article and find any associated files and/or downloads at www.nutsvolts.com
/magazine/article/January2017_Electronic-Chessboard-LEDs-Hall-Effect-Sensors.

T he black circles
represent the squares
where each piece can
move. The knight is the
only piece that can jump
over other pieces. The
pawn’s first move can be
either one or two squares
forward if those squares are
empty. After the pawn’s
first move, it can only move
forward one square if
empty. The X positions
mark where the pawn can
capture an opponent’s
piece, which is limited to a
diagonal move forward of
one square.

My Path to
Building
This
Some time back, my
grandson mentioned a
■ FIGURE 1.
circuit board for gaming he Schematic of the
was working on in his complete
college program. Our chessboard circuit.
discussion led me to
thinking about building a
chessboard using an array
of RGB LEDs and some
sort of detector to monitor (Full size schematic
the position of the chess available at article link.)
pieces. I experimented with
an array of 256 individual
RGB LEDs placed in a 16 x 16 array, using a block of 2 x turned on, it does not need to be continually refreshed.
2 LEDs for each board square. For the detector, I tried My previous experience had me deciding against using IR
using reflective IR sensors. After many attempts, I got a detectors, so I went instead with Hall effect sensors.The
prototype to barely work. Scanning 256 LEDs is not chess pieces have a small magnet in their base to trigger
simple, but worked fairly well. The problem was the IR the Hall effect sensors. I also moved from using an
detectors. Their output was read with an Arduino Mega Arduino Mega 2560 to a Teensy 3.1, which has more
2560 analogRead() which gave differing values for each IR RAM and a 72 MHz clock, as opposed to 16 MHz for the
detector. This coupled with the fact that as the ambient Arduino. It can also be easily programmed with the
light in the room changed, the IR detector’s values Arduino GUI. You will need to download and install the
changed as well, it was just a matter of a few chess moves Teensyduino software package to program the Teensy 3.1
before the IR detectors gave an error. with the Arduino GUI. Download information and
After some experience using RGB LED strips, it instructions can be found at https://www.pjrc.com/
occurred to me that this might be an easier way of driving teensy/teensyduino.html.
the LEDs on an electronic chessboard. Once an LED is This chessboard does not play a chess game against
you. The chessboard is used by two players, and the basic
Arduino Mega 2560 Teensy 3.1 objective is to keep track of the board and the rules of the
RAM 8K 64K game for both players. This makes it a nice learning device
Program Space 256K 256K for the beginning chess player. The LEDs light up to show
Clock Speed 16 MHz 72 MHz a player where a piece can be moved, and whether there
January 2017 21
Wierenga - LED Chess - Jan 17 - part 1_Blank Project NV.qxd 12/5/2016 10:18 PM Page 22

necessary. As for the


software, it is already
written and is available
at the article link. What
the circuit basically
consists of is an 8 x 8
array of Hall effect
switches that are
scanned a row at a
time. The results of this
scan produce an 8 x 8
■ FIGURE 2. Layout of the first four RGB LED strips on the chessboard. array indicating where
the chess pieces are
is an opponent’s piece that can be taken. Illegal moves are currently placed. Surrounding each Hall effect switch is a
detected, as well as when the king is in check. square of four RGB LEDs which represents a square on
The chessboard operation does not include the three the chessboard. The LEDs are laid out and glued down as
more esoteric moves — castling, en passant, and 16 strips that wind back and forth across the board.
promotion — although these could be added. This project Connections are also available on the board to
can be expanded upon and if you are interested in chess optionally connect a four-line LCD display and a Real Time
programming, it has the potential to add intelligent Clock (RTC) using an I2C interface. The LCD display has
responses or even game play. Teensy 3.1 pins 0, 1, 9, and been incorporated in my software, but the RTC was not.
10, RX1, TX1, RX2, and TX2 were left unused and brought
out to pads, allowing for an interface to a PC. The The Build
hardware for this project is fairly minimal. The main cost
was the printed circuit board. I designed mine using the I have provided two different versions of the printed
free software available from ExpressPCB and then circuit board layout for an ExpressPCB board at the article
uploaded my design to them when ordering the boards. link. The only difference is that one uses a standard DIP
Their web address is https://www.expresspcb.com. This (Dual Inline Package) layout for the 74HTC138 and the
board is 11-1/2 x 11-1/2 inches, and a minimum of two other an SMT (Surface-Mount Technology) layout for this
boards must be ordered. If you can make your own board, integrated circuit. The RGB LED strips were laid out
that will save you some money. It might be possible to starting at the top of the printed circuit board (PCB),
build the hardware on a breadboard of some sort, but it alternately going left to right and then right to left as
will take some effort with all the connections that are shown in Figure 2. This simplified the layout of the PCB,
reducing the length of the traces between strips.
The RGB LED strips have adhesive on the bottom to
attach them, and my first thought was just to stick them
down on the PCB. Since these strips would be placed over
various circuit board traces on the top of the board, I
became concerned about creating a possible short on the
PCB. I ended up gluing a strip of very thin tag board to the
bottom of the RGB LED strips with Super Corona Dope™
from MG Chemicals, which is an excellent insulating
varnish. The tag board surface was then glued down to the
PCB with the Super Corona Dope. (Perhaps a little overkill,
but it guaranteed no short circuits.) These strips are
connected to the PCB by short pieces of wire soldered
from the tabs on the LED strip to pads on the board.
There are two caveats when using these strips. I found
that a short delay (I used one millisecond) was necessary
between setting individual pixel colors. An example is in
the colorSquare() function. Without this delay, the pixel
color appears to be off by one position. This error was
intermittent and the higher clock rate of the Teensy 3.1
may be the issue here. The other precaution I took with
driving the RGB LED strip was not to drive the signal input
directly from the Teensy 3.1 3.3 volt output. I placed a
■ FIGURE 3.The circuit board mounted in a small wooden 7413 dual NAND Schmidt Trigger inline between the
frame with the LCD display and restart switch. Teensy and the signal input. These are four input NANDs
22 January 2017
Wierenga - LED Chess - Jan 17 - part 1_Blank Project NV.qxd 12/5/2016 10:18 PM Page 23

and because one will invert the signal, the two NAND
gates were used is series. With this in place, the strip is
driven by a five volt line.
The Teensy 3.1 is essentially a faster replacement for
the Arduino line of microcontrollers with added features. It
was chosen because of its higher speed, adequate
program space, and additional RAM, which is needed for
the software that drives the chessboard. I elected to use
an IC socket for the 28-pin Teensy 3.1, with the thought of
ease of removal if the Teensy is damaged. Unsoldering a
bad 28-pin IC is inviting damage to the PCB. The Teensy
3.1 can be powered by a 3.7 to 5.5 volt source, but its
I/O is at the 3.3 volt level. While this will interface directly
with five volt ICs like the 7400 TTL and HTC series, it
should be noted that its output will not directly drive a
PNP transistor powered with five volts. This is because the
3.3 volt high output does not come close enough to the
five volts to turn off a PNP transistor. The chessboard
circuit has a five volt powered 74HCT138 three- to eight-
bit decoder between the Teensy and the PNP transistors
that power the rows of Hall effect sensors, which takes
care of this problem. The 74HCT138 also reduces the
number of I/O lines needed on the Teensy 3.1.
■ FIGURE 4. Prototype printed circuit board before installing
Allegro 3144 Hall effect sensors were chosen because the 64 Hall effect sensors.
they are inexpensive and readily available. They have a
Schmidt trigger open collector output with a little representing the chessboard squares.
hysteresis which gives noise-free switching when the After mounting the single 3144, I cut a small strip of
magnet moves into or out of the field of the sensor. Small wood that just fit snugly under a row of the 3144s and
neodymium disk magnets — 10 x 3 mm graded N50 — taped it down with blue masking tape. This served as a jig
were glued into the bottom of a set of plastic chess when soldering in a row of 3144s such that they would all
pieces, with the correct magnet face placed at the bottom be the same height above the PCB and is shown in Figure
of the piece. I put together a single 3144 on a breadboard 6. The 3144 has an open collector output and all the
with an LED for output to determine the correct magnet outputs of a column of eight are connected together. A
face to place toward the 3144 to switch it on (see Figure row of 3144s is then powered by the PNP transistor and
5). The pins on the 3144 are bent at a right angle so that each column read one at a time by the Teensy 3.1.
the face of the 3144 with the part number on it points The chess piece set I used was purchased from
upward when mounted on the PCB. Care needs to be https://www.wholesalechess.com and is their Analysis
taken to insure that the 3144 stands high enough off the Chess Pieces set. They are inexpensive and small; the king
circuit board to allow the magnet to switch this sensor; is 2-1/2 inches tall and the pawns are 1-1/4 inches, but are
therefore, I used the full length of the 3144 leads. just the right size for the chessboard. The bottom has a 10
I mounted a piece of 1/4 inch Plexiglas to the top of mm hole which perfectly fits a 10 mm diameter by 3 mm
the circuit board using 5/8 inch spacers and 4-40 machine thick neodymium disk magnet. The magnets press-fit into
screws. I soldered in one 3144 to a height where I was the base of the chess pieces very easily. However, there is
confident the magnets in the bottom of the pieces would a problem — especially with the lightweight pawns.
activate the 3144 through the Plexigas surface. The chess When another piece gets near a pawn or you place a
pieces sit on the Plexiglas with the LEDs underneath, piece slightly off center, the magnets repel each other and

■ FIGURE 5. Hall effect test circuit.

■ FIGURE 6. Wooden strip used to hold a row of 3144s in place for


soldering.
January 2017 23
Wierenga - LED Chess - Jan 17 - part 1_Blank Project NV.qxd 12/5/2016 10:18 PM Page 24

you can unintentionally move a piece causing the {


for (int x = 0; x < 4; x++)
chessboard to throw an error. My solution was to glue {
down thin cork disks to the bottom of the pawns creating colorSquare(x * 2, y * 2, colors[RED], false);
a little friction. This keeps them from sliding away from colorSquare(x * 2 + 1, y * 2, colors[BLUE],
other nearby pieces unless they are nearly touching. The false);
colorSquare(x * 2, y * 2 + 1, colors[BLUE],
pieces must be placed directly above the Hall effect false);
sensors to work. A piece well off center will not be read colorSquare(x * 2 + 1, y * 2 + 1, colors[RED],
by the sensor, causing an error. false);
}
}
Software pixels.show();
}
The first thing the program must do is turn on the
LEDs to display a chessboard. This is made quite easy by Note that instead of turning on each square as it is
using Adafruit’s Neopixel library to drive the RGB LED created, we wait until all the squares have been set to
strip. For complete information on this library, visit their desired colors and then turn them on at once. This
Adafruit’s website at https://learn.adafruit.com/adafruit- reduces flicker in the display:
neopixel-uberguide/arduino-library. All operations on
LEDs will operate on squares of four LEDs. A little simple // Color all squares, red for error alert, blue for
// checkmate
math is needed to go from one of the 8 x 8 positions on // Seems to work OK without a delay
the board to the linear strip of 256 RGB LEDs. void colorBoard(uint32_t color)
The LEDs were mounted starting at the top of the {
board going left to right, with the next row going right to for (int i = 0; i < NUMPIXELS; i++)
left, and then repeating eight times. This minimizes the {
pixels.setPixelColor(i, color);
length of the traces on the PCB that connects each row of }
LEDs. The colorSquare() function takes the x,y position of pixels.show();
the square, its color, and whether it should be turned on }
immediately, and with a little math, turns on the four LEDs. When an error occurs — like trying to make two
Note that I went from using multiplication in my formulas moves in a row — the function colorBoard() is used to
to bit shifting, which is faster: color the entire chessboard in red. No math is needed in
this case. Each RGB LED is simply set to red using a 32-bit
// Color an x,y square with a specific color color code, and then turned on. Writing the software to
void colorSquare(byte x, byte y, uint32_t color, bool on)
{
respond to moves on the chessboard is a challenge. After
if ((x >= 0) && (x < 8) && (y >= 0) && (y < 8)) doing a little research on the Internet to make a decision
// is it a legal square ? on how best to represent the chessboard in a program,
{ my impression was that there are as many ways to do this
int num1 = (y << 5) + (x << 1); as there are programmers writing chess programs. The
// same as num1 = y * 32 + x * 2;
int num2 = num1 + 1; basic math structure chosen to represent the chessboard
int num3 = (y << 5) + 31 - (x << 1); greatly affects how the program will operate on its data.
// same as num3 = (y * 32 + 32) - (x * 2) - 1; Because many programs run on PCs (or even faster
int num4 = num3 - 1; computers) that actually play chess, there is a push
// Needs a short delay, otherwise intermittent
// errors on position towards speed. With 64-bit computers, the match to the
pixels.setPixelColor(num1, color); delay(1); 64 squares on a chessboard works well, and “bitboard”
pixels.setPixelColor(num2, color); delay(1); structures are common.
pixels.setPixelColor(num3, color); delay(1); A board representation called “0x88” might have
pixels.setPixelColor(num4, color); delay(1);
if (on) pixels.show(); been a better choice for my program. The name comes
} from the fact that ANDing hexadecimal 0x88 with a board
} location in this structure and getting a result that is not
The colorSquare() function not only displays the zero tells you if you are off the edge of the board. The
standard chessboard layout, but by using other colors can code of the 0x88 structure is efficient and brief. However,
show the correct positions that pieces can occupy with a it consists of a lot of bitwise operations. Reading the code
move, or positions where pieces can be taken. using this structure is not intuitive and can be confusing —
From here, a function is created that lights up all the especially if you are not a seasoned programmer or are
LEDs in a chessboard array of blue and red: new to chess.
For ease in understanding the logic of my code, I
// Color a chessboard with blue (for black) and red selected 8 x 8 and 12 x 12 arrays of bytes to represent the
// squares
void standBoard()
chessboard, which helps visualization and keeps the math
{ structure simple. This board representation may not be the
for (int y = 0; y < 4; y++) most efficient, but I really wasn’t too concerned about
24 January 2017
Wierenga - LED Chess - Jan 17 - part 1_Blank Project NV.qxd 12/5/2016 10:18 PM Page 25

speed since the chessboard is not going to look at all can jump two spaces over. So, for example, in code we
possible plays several moves ahead. Due to the different could use:
sizes of the two different types of arrays, the program
code does contain a large number of array indices that if (piecesValCur[y][x]) == BORDER)
// We are off the board in one comparison
add a -2 or +2 to the index. Some of the worst bugs in my
program code were simply due to forgetting this point. instead of:
There are two key arrays that represent the board. The
first — which I label piecesVal[12][12] — identifies each if ((y < 0) || (y > 7) || (x < 0) || (x > 7))
// We are off the board in possibly four comparisons
piece and their placement on the board at startup. A
second array — piecesValCur[12][12] — maintains the Instead of using numbers like 255 and 16 in the
piece’s current positions and identifies each piece as they software, it is much more understandable to use the
are moved. Various 8 x 8 arrays are used when reading defines like BORDER and BLACK_KING. This has been
the Hall effect sensors to determine where pieces are done wherever possible in the software.
located. Just about any set of numbers could be used to The piecesValCur[y][x] array contains not only the
represent the different pieces. The 1 through 16 numbers I position using the indices, but the number values that
chose supposedly represent the relative values of the identify the exact piece as well. However, when we read
pieces. The number 128 was added to the byte value (bit the Hall effect sensors, we will only get a reading that tells
7 set) to indicate the white pieces. These values are us where pieces are located — not their values. So, when
placed in #define statements so the piece names can be reading the Hall effect sensors, we can find that position
used in place of the numbers: 3,4 has changed and there is not a piece there compared
to a previous reading. We then use the 3,4 indices in the
// White = 128, white at bottom, starting positions piecesValCur[y][x] array to find which exact piece was
// Black = 0, add color to piece value
//
removed. Reading the Hall effect sensors gives us this
// Black White array on startup:
// Pawn = 1 and 129
// Knight = 3 131 byte piecesCurrent[8][8] = {{1, 1, 1, 1, 1, 1, 1, 1},
// Bishop = 4 132 // [y][x] Where current piece are located
// Rook = 5 133 {1, 1, 1, 1, 1, 1, 1, 1},
// Queen = 9 137 {0, 0, 0, 0, 0, 0, 0, 0},
// King = 16 144 {0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
// Defines for chess pieces and spaces {0, 0, 0, 0, 0, 0, 0, 0},
#define BORDER 255 {1, 1, 1, 1, 1, 1, 1, 1},
#define EMPTY 0 {1, 1, 1, 1, 1, 1, 1, 1}};
#define BLACK_PAWN 1
#define BLACK_KNIGHT 3 In addition to the piecesCurrent[y][x] array, similar
#define BLACK_BISHOP 4 arrays are maintained that are used when doing the actual
#define BLACK_ROOK 5
#define BLACK_QUEEN 9 reading of the Hall effect sensors. The two arrays are then
#define BLACK_KING 16 compared to determine what piece has been moved.
#define WHITE_PAWN 129 Notice that these arrays do not need the two rows and
#define WHITE_KNIGHT 131 columns of additional values to denote positions off the
#define WHITE_BISHOP 132
#define WHITE_ROOK 133
board:
#define WHITE_QUEEN 137
#define WHITE_KING 144 // Read a row of 8 Hall Effect sensors
int readLine(int row, byte piecesTemp[][8])
byte piecesVal[12][12] = {
{{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, // Read each sensor in a row looking for a zero,
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, // which means a piece is there.
{255, 255, 5, 3, 4, 9, 16, 4, 3, 5, 255, 255}, // The 3144 Hall Effect sensors are open collector
{255, 255, 1, 1, 1, 1, 1, 1, 1, 1, 255, 255}, // output and pull to ground when activated.
{255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255}, // We invert the zero to place a one in our array if
{255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255}, // a piece is on a square.
{255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255}, // After each read we add to count to keep a running
{255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255}, // total.
{255, 255, 129, 129, 129, 129, 129, 129, 129, 129, 255, 255}, int count = 0;
{255, 255, 133, 131, 132, 137, 144, 132, 131, 133, 255, 255}, piecesTemp[row][0] = !digitalRead(2);
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, count += piecesTemp[row][0];
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}}; piecesTemp[row][1] = !digitalRead(3);
count += piecesTemp[row][1];
The 8 x 8 array is surrounded by two rows and piecesTemp[row][2] = !digitalRead(4);
count += piecesTemp[row][2];
columns of values set to 255 or 0xFF Hex. This boundary piecesTemp[row][3] = !digitalRead(5);
makes it a little easier to check for pieces moving off the count += piecesTemp[row][3];
board. The bank of two was necessary because a knight piecesTemp[row][4] = !digitalRead(6);
January 2017 25
Wierenga - LED Chess - Jan 17 - part 1_Blank Project NV.qxd 12/5/2016 10:18 PM Page 26

count += piecesTemp[row][4]; unused by circuitry external to the microcontroller. Being


piecesTemp[row][5] = !digitalRead(7);
count += piecesTemp[row][5]; able to use Serial.print() statements in your code to be
piecesTemp[row][6] = !digitalRead(8); read in real time using the embedded serial monitor in the
count += piecesTemp[row][6]; Arduino GUI is a great aid in debugging code. Pins 9 and
piecesTemp[row][7] = !digitalRead(12); 10 were also left unconnected and brought out to pads
// Oddball because we skipped 9, 10
count += piecesTemp[row][7];
on the PCB. This pair of pins implements RX2 and TX2 on
// for serial RX, TX, Serial2 on Teensy 3.1 the Teensy 3.1 and can be used to connect the
return count; chessboard to other external circuits or a PC.
// return number of pieces found in this row Instead of a D port read, we use eight digitalRead()
}
statements that are negated to read a single row of
// Read all 8 lines of the Hall Effect Sensors sensors. The Hall effect sensors are open collector, and
int readHall(byte piecesTemp[][8]) when activated they read as a 0. So, for clarity, this is
{ negated to a 1, representing a chess piece in that location.
// The function calls readLine() 8 times to read all The readHall() function calls readLine() eight times,
// 8 rows of Hall Effect sensors
// When finished piecesTemp[8][8] has positions of after setting the three-bit address to the 74HCT138 to
// pieces on board select each row. Here again, a port C output could have
// Before each read we set the 3 bit address to the simplified things a little, but that could have interfered
// 74138 with the A4 (SDA) and A5 (SCL) I2C signals which are
// The total number of pieces on the board is
// returned reserved for communicating with an LCD display or RTC.
int count = 0; After the call to readHall(), the piecesTemp array will show
digitalWrite(A0, LOW); the locations of all the pieces on the chessboard and
digitalWrite(A1, LOW); return the total number of pieces found on the board.
digitalWrite(A2, LOW); // 000
delay(1); // let 3144 settle At this point, all of the functions that interact with the
count += readLine(0, piecesTemp); hardware need to be described.
digitalWrite(A0, HIGH); // 001 We will pause here for this month. Next time, there
delay(1); will be an overview of the main sections of the software
count += readLine(1, piecesTemp);
digitalWrite(A0, LOW); // 010
that contain the logic for supervising a chess game
digitalWrite(A1, HIGH); between two players. The loop() section of the program
delay(1); takes you through the first player's turn and then, on the
count += readLine(2, piecesTemp); next pass through, changes the turn to the second person.
digitalWrite(A0, HIGH); // 011
Inside the logic is the ability to detect which piece is lifted
delay(1);
count += readLine(3, piecesTemp); and display all its possible moves. There will also be some
digitalWrite(A0, LOW); // 100 error checking and looking for a king in check or
digitalWrite(A1, LOW); checkmate. If you just can't wait, you can obtain the entire
digitalWrite(A2, HIGH); Arduino program from the download section. Keep in
delay(1);
count += readLine(4, piecesTemp); mind that this program is intended to run on a Teensy 3.1.
digitalWrite(A0, HIGH); // 101 NV
delay(1);
count += readLine(5, piecesTemp);
digitalWrite(A0, LOW); // 110 Teensy 3.1 microcontroller
digitalWrite(A1, HIGH); 74HCT138 3-to 8 decoder
PARTS
delay(1); 7414 Dual Schmidt trigger
count += readLine(6, piecesTemp); Allegro 3144 Hall effect sensors (64)
LIST
digitalWrite(A0, HIGH); // 111 2N3906 PNP transistors (8)
delay(1); 470 ohm Resistors (8)
count += readLine(7, piecesTemp); 2700 μF 6.3 volt Electrolytic capacitor
delay(100); 0.1 μF Disk capacitors (2)
return count; Five volt/two amp Power supply, wall wart type
// return count of all pieces on the board Power jack to match power supply
} LCD display, four-line/20 character with I2C two-wire
interface
The functions readLine() and readHall() do the work of Momentary pushbutton switch
scanning the 64 board positions and creating an 8 x 8 Programmable RGB LED strip, five meters, 60 LEDs per
array telling us where pieces are located, and also return meter
the number of pieces found. The readLine() function scans (You'll need 256 LEDs of the 300 LEDs in the strip.)
Printed circuit board
a single row. Notice here that it would have been simpler Insulating varnish like Super Corona Dope™
to do a read of the D port pins 0-7 on the Teensy 3.1. In Analysis Chess Piece set from www.wholesale chess.com
one line of code, we would have read all eight Hall effect Neodymium disk magnets, 10 mm diameter by 3 mm thick,
sensors in one row. However, that would mean that we grade N50 (32)
Miscellaneous header pins, four-pin header jumper cable,
could not use pins 0 and 1 with our serial monitor. solid 22 gauge hookup wire, screws, nuts washers,
In most of my projects, I try to leave these two pins spacers, wooden frame, 1/4 inch Plexiglas
26 January 2017
Gravatt - Retro PIC SBC - Feb 17_Blank Rough NV.qxd 12/5/2016 11:00 PM Page 27

Vintage Computing
The Retro PIC Single-
Board Computer
By Dan Gravatt Post comments on this article and find any associated files and/or downloads at
www.nutsvolts.com/magazine/article/January2017_Retro-PIC-Single-Board-Computer.

Over the years, I have accumulated a


bunch of chips from before the era of
true PCs (Photo 1) when computers
with names like Altair, KIM-1, and
Cosmac ELF were popular. I’ve been
looking for a way to use them in new
projects, but until now I’ve held back
for a couple of reasons.
PHOTO 1 : CPUs,
irst, I’m not a very good programmer and I RAMs, EPROMs,

F don’t do assembly language; and second,


those computers stored their code in
EPROMs (programmable read-only
memory chips that were erased with ultraviolet
light through a clear window in their cases) and I didn’t
and support
chips — all
waiting to be
reused.

microcontroller, on the other hand, has these separate


have an EPROM programmer. After looking at some of the components merged on a single chip with limited
proposed schematics for Z80 based systems at amounts of memory and I/O, and usually no expansion
www.z80.info, I was inspired to design such a system buses. I’ve used microcontrollers for years and love their
(Photo 2) around a 40-pin PIC16F887 which I do know simplicity, but when programming them with high-level
how to program. I figured this languages it’s easy to forget
would put some of my historic what’s going on “under the
chips to work and be a great hood” between those various
learning tool for understanding components. Sometimes a better
how a microcomputer works. knowledge of the hardware-level
In general, a microcomputer processes can make you a better
is a small (relative to a mainframe programmer and debugger.
— the other type of computer in For this project, the PIC gets
use when this term was coined in treated like a true CPU with
the 1970s) self-contained PortC as a dedicated address bus
computer with separate CPU, and PortD as a dedicated data
RAM, ROM, I/O, and some sort bus (Figures 1a and 1b). The
of non-volatile storage medium, PortC address bus connects to
with the separate components static RAM and EPROM totaling
linked by address and data buses 64 kilobytes, and uses an eight-bit
that can be expanded to include latch to form the necessary 16
additional devices. A PHOTO 2 : The PIC SBC. address lines. The PortD data bus
January 2017 27
Gravatt - Retro PIC SBC - Feb 17_Blank Rough NV.qxd 12/5/2016 11:03 PM Page 28

Vintage Computing

Full size schematics are available


at the article link.

FIGURE 1B: Schematic of the memory and latch


FIGURE 1A: portions of the SBC.
Schematic
of the CPU bus for the RTC and nonvolatile storage EEPROM.
and I/O
portions of Of course, a computer needs a keyboard and a
the SBC. display, so there’s a PS/2 keyboard interface and an RS-
232 serial link to use an old laptop computer as a “dumb
terminal.” The block diagram in Figure 2 shows the
connects to the RAM and EPROM, as well as an eight-bit functional relations between all these parts. Let’s dive in
output latch and an alphanumeric LCD. Size constraints and see how to make these parts work together.
on the circuit board kept me from including more period-
appropriate peripheral chips such as the 8255 parallel I/O Keyboard
controller, the MC146818 real time clock (RTC), and
some sort of disk controller chip, so I had to compromise The PS/2 keyboard uses a synchronous serial interface
the “retro” nature of the project a bit by including an I2C to send 11-bit packets of data to the host computer, with
the keyboard generating the clock signal for the
interface (see References). PS/2 keyboard scan codes
are a random nightmare — there’s just no other way to
describe them. Take a look at the spreadsheet I created
(available at the article link) to help me figure out how
to translate them into ASCII. The keyboard sends data
both when you press a key (usually one or two packets)
and when you release it (usually two or three packets),
but most of that data is irrelevant for our purposes.
If that wasn’t complicated enough, paired keys like
shift, ctrl, alt, numbers, and enter send different codes
depending on which one you press! There is no formula
that can transform the scan code data into the
corresponding ASCII character, so I used the 256-byte
EEPROM in the PIC as a one-to-one translation matrix,
FIGURE 2: Block diagram of the SBC. where the scan code is the address of the byte
28 January 2017
Gravatt - Retro PIC SBC - Feb 17_Blank Rough NV.qxd 12/5/2016 11:00 PM Page 29

Vintage Computing

signal timings for the chip.


REFERENCES The read and write signals are generated with the
“Legacy Communication with the 32-bit Micro
Experimenter,” Nuts & Volts, October 2011 PIC’s PortE: a three-bit port that drives a 74HC138 three-
to-eight decoder chip. Until the memory chip receives a
Retro microcomputer designs using the Z80 read or write signal, its data bus connections are internally
www.z80.info disconnected or “tri-stated” so they do not interfere with
Retro microcomputer designs using the CDP1802 data transfers with other chips on the bus. When the
www.cosmacelf.com signal is received, the selected memory chip accepts the
data on the bus for a write, or places the data from the
Description of PS/2 keyboard protocols selected address on the bus for a read. I’ve placed a
www.burtonsys.com/ps2_chapweske.htm
“Data” LED on output 0 of the decoder which will flicker
62256 SRAM datasheet when data is being transferred; it can also be used to send
http://web.mit.edu/6.115/www/document/62256.pdf blink codes to the user.
27C256 EPROM datasheet
From the PIC’s perspective, the PortC address bus and
http://ecee.colorado.edu/~mcclurel/fnm27c256.pdf the PortE decoder bus are always outputs, but the PortD
data bus must rapidly switch between outputs and inputs
PCF8563 datasheet as necessary throughout the code. Look for lots of trisd =
www.nxp.com/documents/data_sheet/PCF8563.pdf
255 and trisd = 0 statements in the code in the data
PIC16F887 datasheet transfer subroutines. Also look for the address latch
ww1.microchip.com/downloads/en/DeviceDoc/41291D.pdf operation that presents the 16-bit address to the bus as
two separate bytes — similar to the way the old CDP1802
24LC512 datasheet
ww1.microchip.com/downloads/en/DeviceDoc/21754M.pdf microprocessor and some others addressed their memory.

containing the character. Latch and LCD


The code for keyboard input supports the core
functions (all characters, shift, backspace, enter, escape) A true CPU can only use its data bus pins to drive the
necessary for this project without taking up too much inputs of other logic chips because they are a “logic level”
code space, and without using interrupts. It works well interface that has almost no capacity to supply current.
with a 4 MHz clock speed as long as you are not a super- They cannot directly control an LED, serial port, or any
fast typist. See the comments in the code at the article other device in the “real world.” In addition, since the data
link for more on how it works. bus is usually busy talking to the memory, it cannot afford
to be tied up with those functions. A variety of interface
Memory chips usually share the data bus to provide the necessary
real world connections and free up the bus. Interface
CPU communication with external memory consists chips have their own read, write, and enable inputs, and
of an address bus to select the required byte, a data bus are generally accessed similarly to memory chips except
to either read or write that byte, a chip select signal to that they usually don’t use the address bus.
activate only the desired chip on the bus, and read and In this design, a 74HC574 octal latch acts as a simple
write signals to tell the memory chip whether to send or output-only interface chip on the data bus. To use it, the
receive data. The CPU starts by placing the address on the PIC places a byte on the data bus and uses the 74HC138
memory chip’s address inputs, and then places data on decoder to send a pulse to the latch’s clock pulse input.
the data bus (for a write) or sets its data bus pins to inputs The data is then available on the latch’s outputs and is no
to read data. The desired memory chip is activated with its longer just “data,” but can be used to control real world
individual chip select input, and then its read or write devices.
input is activated to complete the transfer. The alphanumeric LCD in the project also acts a lot
The order and timing of these steps is specified in the like a latch on the data bus. The HD44780 compatible
datasheet for each type of memory chip (see References). display controller has an eight-bit data interface, a
This project uses a 62256 32 kilobyte static RAM and a read/write input, an “RS” input which tells the controller
27C256 32 kilobyte EPROM. The EPROM can be hard to whether the data on the bus is text to be displayed or a
find as a new part, so use one from your collection of command to be executed (such as clearing the display),
vintage chips. Address bit A15 is used to handle the chip and an “E” input that latches the data into the controller.
select signal for the two memory devices through an The RS input can be shared with address line A7 to save a
inverter logic gate, so one or the other chip is always pin on the PIC since you will never being accessing the
selected. Address bits A0-A14 then select the byte within memory at the same time you are writing to the LCD. The
the selected chip. This means that sending the 16-bit 74HC138 decoder’s active-low output drives the LCD’s
address handles the chip select and byte address active-high E latch input through an inverter. The high-level
simultaneously, which is okay if you respect the overall LCD control commands available in various PIC
January 2017 29
Gravatt - Retro PIC SBC - Feb 17_Blank Rough NV.qxd 12/5/2016 11:00 PM Page 30

Vintage Computing

programming languages simply automate the process of by pauses to let the chip complete its write cycle, which is
presenting data bytes to the display controller and toggling on the order of 5-10 milliseconds — an eternity in CPU
the RS and E inputs to complete the data transfer. For this time. This is an example of how better understanding the
project, the R/W input of the controller is hard-wired to hardware improves your code. If you don’t allow for these
ground (write-only) on the LCD module itself. pauses between write cycles, the writes will fail!
The EEPROM is internally broken up into 128-byte
I2C “pages” and supports a block-write mode where a single
I2CWRITE instruction can save up to 128 bytes. This mode
The I2C bus is a true bus like the CPU’s address and is faster than writing a byte at a time since there is only
data buses, in that multiple devices share the same one 5-10 ms pause required per block. It also saves wear
connections to the CPU but can be accessed individually. and tear on the EEPROM, which is guaranteed for a large
In contrast to the separate parallel address and data buses but not infinite number of write cycles.
discussed above, I2C provides data, address, chip select, If you use this mode, you must keep track of the
and read/write control to its devices over a single EEPROM addresses you are writing to so that the block
synchronous serial connection. This greatly cuts down on write does not cross a page boundary and garble your
the physical connections needed for the bus. Note that data in the process. This does not affect read operations
much of the schematic in Figure 1a is taken up by the from the EEPROM, which can start and end anywhere.
wires for the CPU’s address and data buses. The tradeoff The PCF8563 RTC can be hard to find in an eight-pin
is that the I2C’s serial data streams transfer data more DIP package. I’ve specified a surface-mount part in the
slowly than the parallel-mode buses. Parts List because it is readily available. You can use a
For this project, we’re moving relatively modest commercially-available adapter to attach the SO-8 package
amounts of data on the I2C bus a few bytes at a time to to the circuit board, or fabricate a “spider” adapter from
and from the PCF8563 real time clock chip, and up to some leftover resistor leads. The DS1307 RTC is available
64K bytes for the 24LC512 EEPROM. The entire EEPROM in a DIP package and is mostly pin-compatible with the
contents can be read in a few seconds — not unlike the PCF8563, so you could substitute that with some
performance of an early eight inch floppy drive. Much of modifications to the code and circuit board.
the time required for a write to the EEPROM is taken up
ITEM PART # (DIGI-KEY) DESCRIPTION Stack
U1 PIC16F887-I/P-ND PIC microcontroller, 40-DIP
U2 1450-1182-5-ND 32 Kb static RAM, 28-DIP CPUs and
U3, U6 (2) 296-1598-5-ND 74HC574 octal latch, 20-DIP microcontrollers have a
U4 32 Kb EPROM, 28-DIP (see text) small array of registers
U5 296-1577-5-ND 74HC14 hex inverter, 14-DIP
U7 296-1575-5-ND 74HC138 decoder, 16-DIP that are used to store the
U8 24LC512-I/P-ND 64 Kb EEPROM, 8-DIP address of a program
U9 568-6650-1-ND PCF8563 real time clock, SOIC-8 instruction that jumps to
U10 LM34DZ/NOPB-ND LM34 temperature sensor, TO-92
(optional) another instruction
LCD NHD-0224BZ-FL-GBW-ND 2x24 character display location but needs to be
D1, D2 1N4148FSTR-ND Signal diode able to find its way back
D3 754-1720-ND Green LED, T-1
D4 516-1769-ND Amber LED, T-1
to where it started, such
D5 1N5399-E3/54GICT-ND Reverse protection diode as CALL or GOSUB. This
C1, C2 Optional, see PIC datasheet array is called a stack, and
C3 399-1418-ND 10 μF tantalum
C4-C7 399-4151-ND 0.1 μF ceramic
it is limited in size. The
C8, C9 Optional, see text PIC16F887 has an eight-
C10 Frequency trim cap; see PCF8563 datasheet level stack that can
R1 10KEBK-ND 10K 1/6 watt support eight nested
R2, R3, R6, R7, R12 4.7KEBK-ND 4.7K 1/6 watt
R4, R8, R9, R10 1.0KEBK-ND 1K 1/6 watt CALLs (i.e., a CALL within
R5 22KEBK-ND 22K 1/6 watt a CALL within ...).
R11 1.0MEBK-ND 1M 1/6 watt (optional) PICBasic PRO uses four of
SP1 445-2525-1-ND Piezoelectric beeper
X1 631-1081-ND 4 MHz crystal these levels for its own
X2 300-3007-ND 32 kHz crystal internal purposes, leaving
X3 Optional, see text four nested levels for use
J1-J6 S1011EC-40-ND 0.1” straight header
J7 CP-1560-ND PS/2 Mini-DIN-6
in your code.
I learned the hard
PARTS
S1 ED3048-5-ND 40-pin DIP socket
S2, S4 (2) ED3052-5-ND 28-pin DIP socket way that neither the PIC
LIST
SW1 450-1665-ND SPST momentary switch nor PICBasic PRO will
BT1 BS-7-ND Battery holder for CR2032
(none) S1111EC-40-ND 0.1” right-angle header for warn you if you write
memory jumpers code that creates a stack
30 January 2017
Gravatt - Retro PIC SBC - Feb 17_Blank Rough NV.qxd 12/5/2016 11:00 PM Page 31

Vintage Computing

overflow by trying to store too many addresses on the


stack. You can’t read the stack pointer to tell how
many levels have been used, so you have to keep
track manually while coding. Reading the fine print of
the PIC’s datasheet may be overwhelming, but it will
help your coding and debugging!

Putting It All Together


While it is theoretically possible to breadboard this
circuit (Photo 3), you’ll really want a circuit board. I’ve
built some flexibility into the hardware — particularly
with respect to the memory. The pinouts of the 62256
SRAM and 27C256 EPROM are not identical, but only
the functions of pins 1 and 27 differ. I added two two-
position jumpers on the back of the circuit board (not PHOTO 3:
shown on the schematic for clarity) to swap the Prototype SBC on
functions of these two pins (Write/Vpp and A14) and breadboards.
allow Socket 0 to hold a SRAM or circuit under PIC control (Figure 3)
an EPROM. If you have smaller applies the programming voltage to
capacity memory chips such as a the EPROM as needed and turns the
6264 8K SRAM or a 27C128 16K project into an EPROM burner.
EPROM, these can also be used with Check the programming voltage
some caveats. You’d think that the specifications for your particular
un-needed address pins for these EPROM and adjust the values of R2
chips would simply be “no-connect,” and R3 accordingly. Make sure to
but sometimes they are used as UV-erase your EPROMs first; this sets
additional chip select inputs. Check FIGURE 3: Voltage selector circuit all the bits to “1” and the burning
your datasheets carefully and either for EPROM programming. process turns some of them into
modify your code to set these inputs zeros. A better programmer than I
as necessary or break a trace or two on the circuit board could write a bootloader that would run PIC code stored
to set them in hardware. on the EPROM to expand the 8K code space in the
The schematic and PCB layout support a few other 16F887. The main reason that this project uses an eight-
hardware options, including a general-purpose crystal bit-at-a-time memory address scheme is to free up the
oscillator using a couple of leftover inverters; an external eight PortB pins on the PIC for general-purpose I/O. Use
crystal oscillator for the PIC for greater clock accuracy or them as another data bus to talk to some of your vintage
if you want to run faster than its 8 MHz internal clock interface chips on a separate circuit board, or take
limit; access to the clock and interrupt outputs of the RTC advantage of some of the special functions available on
chip; and a three-terminal analog temperature sensor. PortB like analog inputs or external interrupts.
There is also an unused output on the 74HC138 decoder The code I’ve written for this project uses a very
that can be used to access other data bus devices or drive simple command-line structure to select subroutines that
a piezo speaker. demonstrate the hardware functions described above.
Note that there are no pads for R11 on the circuit Among other things, it will check for the presence of
board as I just couldn’t find space for it, so you’ll have to SRAM or EPROM in Socket 0 and adjust the SRAM start
solder it across the pins of crystal X3 on the back of the address accordingly. I’ve also included a very bare-bones
board; the same goes for R12, the pull-up resistor for the file system to use the EEPROM as a tiny disk drive; its
open-collector CLKOUT pin of the RTC. structure is explained in a separate tab of the reference
The circuit board holes for the case mounting tabs of spreadsheet available online.
J7, the mini-DIN PS/2 keyboard jack are not full size as A 9600 baud serial link with a laptop running a
they are too close to the edge of the board. Use a cutoff terminal program displays the list of files on the “disk” and
wheel or hobby saw to cut notches in the edge of the supports data import to and export from the SBC. A
board to accommodate these tabs. command reference that explains how each subroutine
A potential application for this project is an EPROM works is also available online. There are plenty of
programmer or “burner.” One of the Socket 0 jumpers comments to explain the code and help you roll your own
isolates the programming voltage pin on the EPROM PIC based operating system. So, dust off those vintage
which is set at logic high for read operations, but typically chips, read their datasheets, and build a microcomputer to
needs around 13 volts for programming. A simple external call your own! NV
January 2017 31
Lindley - RSS News Reader - Jan 17_Blank Rough NV.qxd 12/5/2016 11:07 PM Page 32

ESP8266 RSS
News Reader
I admit it. I am a self-proclaimed news nut. I don't know, but this might actually
be an undiagnosed illness since I look at the news on the web constantly during
the day and then watch the news in the evenings on TV. There is always
something going on in our world (for better or worse) that I don't seem to want
to miss. So, when I was thinking about other applications for the amazing
ESP8266, I thought why don't I write an RSS reader so I can monitor the
headlines from many different news sources from around the world. Then, if
something catches my attention, I can open up my laptop and read the full story.

or those of you who aren’t familiar with RSS, In this article, I’m going to describe an RSS news

F according to Webopedia: “RSS is the acronym


used to describe the de facto standard for the
syndication of Web content. RSS is an XML
based format and while it can be used in different ways
for content distribution, its most widespread usage is in
reader application I built on the same hardware as my
previous two articles. Again, that’s the NodeMCU Amica
module, an Adafruit 1.8” TFT LCD display, a pushbutton
switch, USB cable, USB power supply, and some wire.
With this hardware, you can upload the NTP clock
distributing news headlines on the Web.” software and have an auto setting time and date clock;
An RSS XML document — also called a feed or upload the weather clock software, and get current and
channel — includes summarized headline text along with forecasted weather conditions for your location along with
metadata like publication date and author information. the NTP clock functionality; or the software I provide with
The RSS acronym itself has had numerous definitions this article to have the RSS news reader all without
over time. Originally, it meant RDF Site Summary; later, changing a single wire or component.
RSS was defined to mean Rich Site Summary. Currently, As supplied, the software for this news reader has
RSS is understood to mean Really Simple Syndication. hardcoded RSS feeds for NPR, CNN, AP, L.A. Times, BBC,
Regardless of the true definition, in this article I will use Reuters, and USAToday, and it is a simple matter to add
the term RSS to mean an Internet feed of headlines from your own feeds and/or delete or reorder any that I have
one or more news/information sources. If you have been supplied. Once the RSS reader is configured, it will
reading Nuts & Volts regularly, you probably have noticed connect to your local Wi-Fi network and then make a
that I have written quite a few articles about putting the request for headlines from NPR (which happens to be at
NodeMCU Amica module with an embedded ESP8266-12 the top of the feed list, but more on that later). It will
chip to work. Those articles include: continuously cycle through the display of headlines by
1. “Meet the ESP8266: A Tiny Wi-Fi Enabled Arduino horizontally scrolling them across the LCD. After all
Compatible Microcontroller” in the October 2015 issue. headlines have been displayed, a new request to NPR will
2. “Thinking of You” in the November 2015 issue.
3. “ESP8266 NTP Clock” in the June 2016 issue.
4. “ESP8266 Weather Clock” in the November 2016 issue.

All of these projects were developed within the


Arduino integrated development environment (IDE) using
the ESP8266 as a relatively high performance
microcontroller with a built-in Wi-Fi interface. That is to say
no other microcontroller was used to control the ESP8266
as a peripheral like in so many other ESP8266 projects I
see on the Internet. Hosting applications directly on the
ESP8266 itself both drives project costs down and
increases reliability at the same time as a result of fewer
parts and less software involved. FIGURE 1. Fritzing connection diagram/schematic.
32 January 2017
Lindley - RSS News Reader - Jan 17_Blank Rough NV.qxd 12/5/2016 11:07 PM Page 33

By Craig A. Lindley Post comments on this article and find any associated files and/or downloads at
www.nutsvolts.com/magazine/article/January2017_ESP8266-RSS-News-Reader.

be made and the process repeats. unzip it and copy/move the


If, however, you press and ESP8266RSSNewsReader directory
hold the feed advance from the zip file into your Arduino
pushbutton until the last headline directory. While the hardware is
has scrolled off of the screen, you about as simple as it gets, the
will advance to the next feed on software is somewhat complicated
the feed list and its headlines will and is made up of the files shown
then be displayed. When a in Table 2.
headline has an associated In addition to the files listed in
publication date, this will be Table 2, a modified version of the
displayed on the LCD as well. Adafruit_GFX library is required.
To summarize, the RSS news This library provides text and
reader will continuously display graphics functions for the LCD
headlines from the selected news display when connected to an
feed until the feed is changed ESP8266 device. Whereas the
using the feed advance stock library is available at
pushbutton or it is powered https://github.com/adafruit/
down. Since the news reader Adafruit-GFX-Library, the modified
makes a new request every time version of this library I used to
all of the headlines have been develop the RSS news reader is
displayed, the headlines you see FIGURE 2. RSS news reader breadboard. included in the zip file for this
will be as up-to-date as the news article. Remember, libraries must
source itself. be installed in the arduino/libraries directory on your
development computer and the Arduino IDE must be
Hardware restarted to recognize them.

As mentioned, the RSS news reader uses the same RSS News Reader
hardware as described in my previous ESP8266 articles. To
save you from going back and (re)reading previous
Software Operation
articles, the hardware information is repeated here starting Before you can use the RSS reader, you must supply
with the Parts List. Figure 1 shows a Fritzing connection login information for your Wi-Fi network. You do this by
diagram/schematic for the RSS news reader. Figure 2 opening up the main sketch/program file
shows the design wired up on a breadboard. The news ESP8266RSSNewsReader.ino and finding the following user
reader is powered via a USB cable and a USB power configuration section:
supply module, although it could be powered by plugging
it into your computer. The wire by wire connections are // ******************************************
// Start of user configuration items
shown in Table 1 because they might not be clear from // ******************************************
the Fritzing diagram.
// Set your WiFi login credentials
The GPIO designations are shown as that is how const char * WIFI_SSID = “xxxxxxxx”;
these digital I/O lines are referred to in the Arduino code. const char * WIFI_PASS = “xxxxxxxxxxx”;
The Adafruit LCD display also has a micro-SD memory
// ******************************************
card interface which can be used with the ESP8266, but it // End of user configuration items
was not needed for this project. // ******************************************

Software Parts List


Part Source
As mentioned, the software for the ESP8266 RSS
NodeMCU Amica R2 Module Electrodragon.com
news reader was developed using the Arduino IDE.
See my previous articles and/or the Resources 1.8” TFT SPI LCD Display (blacktab) Adafruit.com — Product ID: 358
section for how to set up the Arduino IDE on your Pushbutton Switch SPST RadioShack or anywhere else
computer for targeting ESP8266 type devices. Make
USB Cable — USB A to USB Micro B RadioShack or anywhere else
sure to select “NodeMCU 1.0 (ESP-12E Module)” as
the board type in the tools menu. USB Power Supply RadioShack or anywhere else
(capable of at least one amp at five volts)
The ESP8266 news reader software is available
for download at the article link. To use this software, Hook-up Wire and Breadboard RadioShack or anywhere else

January 2017 33
Lindley - RSS News Reader - Jan 17_Blank Rough NV.qxd 12/5/2016 11:07 PM Page 34

This information allows the ESP8266 to login to your This is the RSS feed list with the NPR feed as the first
Wi-Fi network as required to access the RSS feeds across entry. That is why the first feed displayed by default is
the Internet. The login screen shown in Figure 3 is displayedNPR. As you use the feed advance pushbutton, you move
on the LCD while the login process is occurring. It will be down the list one RSS feed at a time. When you
replaced with the RSS news reader screen shown in Figure increment past the last entry, you wrap around to the first
4 when the login process completes successfully. Check again. You can easily delete feeds from this list or
your Wi-Fi login credentials (WIFI_SSID and WIFI_PASS) if rearrange their order to suit your preferences. You can
the login screen doesn’t go away. You’ll also notice towards even add feeds to this list by Googling the news provider
the top of the sketch this array of character strings: you are interested in and looking for the URL they publish
for their RSS feed(s). Once you have that, insert it into the
// Array of feed URLs feeds list, recompile the code, and upload it to the
const char *rssFeedURLs [] = {
“www.npr.org/rss/rss.php?id=1001”, NodeMCU Amica module, and you will be all set.
“http://rss.cnn.com/rss/cnn_topstories.rss”, Most of the remaining code in the
“http://feeds.bbci.co.uk/news/rss.xml”,
“http://hosted.ap.org/lineups/SCIENCEHEADS- ESP8266RSSNewsReader.ino sketch file is concerned with
rss_2.0.xml?SITE=OHLIM&SECTION=HOME”, declaring instances of the LCD driver, the text scroller, and
“http://www.latimes.com/rss2.0.xml”, the RSS reader classes and initializing them. The loop()
“http://rss.cnn.com/rss/cnn_tech.rss”,
“http://feeds.reuters.com/reuters/topNews”, function in the sketch continually calls the read function of
“rssfeeds.usatoday.com/usatoday- the RSSReader class, passing the URL of the RSS feed to
NewsTopStories”,
display. The code for the RSSReader is the most complex
};
in this application. The complexity is a result of having to
request the headline information from a news
Table 1.
Adafruit 1.8” LCD Display News Feed Advance source and then to extract the information of
NodeMCU Amica Pin Connection Pushbutton SPST Switch interest from the XML returned from the source.
D1 (GPIO 5) SW1 For those not familiar with XML, it is a software
D3 (GPIO 0) LITE and hardware independent tool for storing and
D4 (GPIO 2) D/C transporting data in human readable format.
D5 SCK • XML stands for EXtensible Markup Language
D7 MOSI
• XML is a markup language much like HTML
D8 (GPIO 15) TFT_CS
• XML was designed to be self-descriptive
3V3 VCC
GND Gnd SW2 • XML is a W3C Recommendation

Table 2. More information on XML can be found in the links


File Description in the Resources section. Usually in an RSS news reader
Main program. Initializes the hardware application hosted on a PC, a full blown XML parser
and software, logs into the local Wi-Fi would be employed to extract the headlines and other
ESP8266RSSNewsReader.ino network, initializes the RSS reader
callbacks, and prepares the loop() pertinent data. Unfortunately, I couldn’t find an XML
function for accessing and retrieving parser that could fit in the memory available on the
the selected RSS feed.
ESP8266, so I had to use a different approach for data
LCD driver code specific to the Adafruit extraction. Without going into too much detail, the
ESP8266_ST7735.cpp 1.8” (blacktab) display utilizing the
hardware SPI interface of the ESP8266. portions of the RSS XML that I wanted to retrieve
resemble the following:
ESP8266_ST7735.h Header file for the LCD driver code.
Implementation of the RSSReader
class. The RSSReader has a lot of <title>This is some headline from a news feed</title>
functionality including implementing a <description>This optional component of the news
crude parser for extracting information
from RSS XML documents; has code story provides more detail than the title</description>
RSSReader.cpp for parsing URLs to extract the host <pubDate>Fri, 06 Nov 2015</pubDate>
and the path components; and the
code that requests the RSS documents
from news sources across the Internet. All of the components have the same format: a start
It also manages the feed advance
pushbutton. tag like <title>, followed by the actual content, followed
RSSReader.h Header file for the RSSReader code. by an end tag </title>. Whereas the title portion of a
news headline is required in the RSS XML, the description
Misc functions for formatting text and
TGFunctions.h graphical data for display on the LCD. and the pubDates are not. Note that this application
Class for horizontally scrolling text doesn’t currently use the description information from
TextScroller.cpp strings on the LCD display. the XML even though the code supports retrieving it.
TextScroller.h Header file for the TextScroller code. To extract data from the XML, I wrote a Finite State
Data for the Wi-Fi icon used on the
Machine (or FSM) that is fed every character returned
Icons.h login screen in XBM format. from the news source over the Internet. The FSM ignores
34 January 2017
Lindley - RSS News Reader - Jan 17_Blank Rough NV.qxd 12/5/2016 11:07 PM Page 35

all characters until it sees an opening


<. Then, it starts to listen for the tags
of interest, which in this case are: title,
description, and pubDate. If it finds
one of these, it starts collecting the
text starting after the > in the start tag
until it sees < which is the start of the
end tag. Once the text is collected, a
callback (more on callbacks shortly) is
made to the main program passing this text. After FIGURE 3. Wi-Fi login
the callback completes, the FSM goes back to screen. This screen will
listening for an opening < character and the process be displayed during
the Wi-Fi login process. FIGURE 4. RSS news reader
repeats. screen. The large font is the
The complete XML text is processed this way. scrolling news headline.
This is not as elegant or as easy of a solution to
parsing XML as using a real XML parser, but it gets // Then add some trailing spaces
the job done. The RSSReader class has three functions that strcat(buffer, “ “);
allow application code to register interest in the data // Scroll the composite text
extracted from the RSS XML. They are: textScroller.scrollText(SCROLL_Y, buffer);
}
void setTitleCallback(pt2Function titleCallback); // Callback called every time a pubDate tag is
void setDescCallback(pt2Function descCallback); // found in the RSS XML
void setPubDateCallback(pt2Function dateCallback); void pubDateCallback(char *dateStr) {

where the argument to these functions is a function drawCenteredText(DATE_Y, 1, dateStr,


pointer defined as follows: COLOR_RED, COLOR_BLACK);
}
// A function pointer for callback Later in the setup() part of the code, the RSSReader is
typedef void (*pt2Function)(char *);
made aware of these functions via the following:
A pt2Function is a pointer to a function that takes a
single argument which is a pointer to a char string and // Setup callbacks for title and pubDate tags
// in RSS XML
returns nothing or void. Because the code in the main reader.setTitleCallback(&titleCallback);
sketch is interested in both the title and pubDate reader.setPubDateCallback(&pubDateCallback);
information from the RSS XML, it defines the titleCallback
and the pubDateCallback functions as shown here: At runtime, the following sequence of events occur:
1. A request is made to a news source for its RSS
// Callback called every time a title tag is information.
// found in the RSS XML
void titleCallback(char *titleStr) { 2. The returned XML is parsed by the RSSReader
code, and when a title element is found, the titleCallback
char buffer[TITLE_BUFFER_SIZE];
function is called; when a pubDate element is found, the
// Make buffer empty pubDateCallback function is called.
buffer[0] = ‘\0’; 3. The titleCallback formats the title data and sends it
// First add a leading space char to make to the text scroller for horizontal scrolling across the LCD
// reading easier display.
strcpy(buffer, “ “);
4. The pubDateCallback simply displays the dateString
// Then add the title string passed in, centered on the LCD display.
strcat(buffer, titleStr); Using callbacks is a way to keep the code organized
and structured, and to prevent the code from becoming
Resources one big mess to maintain.
Information about the
Information about XML can NodeMCU Amica can be
be found at
www.w3.org/XML.
found at www.electro
dragon.com/product/node
Conclusion
mcu-lua-amica-r2-esp8266-
Information about wifi-board. By using a single circuit, you can have an auto setting
programming the ESP8266 clock, a weather clock, or an RSS news reader. If you are
in the Arduino environment Information about the a self-proclaimed news nut like myself, why don’t you
can be found at github Adafruit 1.8” TFT SPI LCD build one of these devices for your desk?
.com/esp8266/Arduino and display can be found at
in my four articles www.adafruit.com/ This way, you are never very far away from the latest
mentioned previously. products/358. headlines. NV
January 2017 35
Weston - PCB Rax review - Jan 17_Blank Rough NV.qxd 12/5/2016 11:12 PM Page 36

REVIEW

Bench Werx Offers a


Versatile PCB Holder
I was recently asked to review a product that readers may soon see
advertised in this magazine — the PCB Rax system from Bench Werx. A quick
look of the Bench Werx website (see www.benchwerx.com/pcb-rax) had me
intrigued, and I agreed to put the PCB (printed circuit board) Rax through its
paces and report back the results. Here’s what I found.

ench Werx describes the PCB Rax system as

B an easy-to-use, versatile circuit board holder


for board repair, prototyping, and assembly.
The basic PCB Rax consists of two side rails
with feet, connected by threaded rods that allow the rails
to clamp rectangular circuit boards between them, plus
four extension brackets that connect to the rails at
adjustable angles to hold smaller or different shaped
boards. Figure 1 shows these components assembled into
the PCB Rax system, ready to hold a circuit board for
assembly or rework.
To put the system through its paces, I assembled four FIGURE 1. The PCB Rax
circuit boards of varying size and complexity that I found system from Bench Werx.
lurking in my goody box. These included an Elenco SP-3B
Solder Practice Kit (partially completed by the grandkids), a current project of mine. These boards are mostly
an ancient Parallax S-2 Robot Badge kit, an old Pocket through-hole construction with a few surface-mount
Mini Computer kit from Propellerpowered, and one components, and they have varying component densities
Parallax EDU circuit overlay board that I used to build out and component proximity to board edges. They represent
most of the PCB assembly tasks that I encounter as a
hobbyist. I also placed a few components on an old
prototype board, then removed and replaced them to
simulate some board repair (Figure 2).
To cut right to the chase, I’ve been building things
electronic for a long time, and I was a bit skeptical that the
PCB Rax could add much value to the process I’ve
developed over the years. With my curiosity still intact, I
spent about eight hours over six different sessions
evaluating the system. I found it easy to learn and easy to
use, and I discovered that circuit board assembly and repair
went noticeably quicker and easier using the PCB Rax. I like
this tool, and I’m going to order one. Here’s why.
With 50 plus years of hobbyist soldering under my
belt, I’ve become something of a minimalist, now relying
on tape, clips, and trained fingers to get the most out of
my simple 15 watt iron. I no longer have a full-time
electronics bench or even a soldering station, and I long
FIGURE 2. Projects completed for this
evaluation. Note the different board sizes, ago traded in my big oscilloscope and signal generator for
shapes, and component densities. tiny PC-driven devices that hide in a desk drawer and see
36 January 2017
Weston - PCB Rax review - Jan 17_Blank Rough NV.qxd 12/5/2016 11:12 PM Page 37

Post comments on this article and find any associated files and/or downloads at
By Dane Weston www.nutsvolts.com/magazine/article/January2017_Bench-Werx-PCB-Rax.

FIGURE 4. The Solder Practice Kit in the


vertical position. This allows soldering
FIGURE 3. The Elenco Solder Practice Kit, with multiple components in one pass and offers
the PCB Rax in the horizontal position. This access to both sides of the board at once.
position was good for trace repair and (flipped
over) component insertion. So, I positioned the system to hold the board
vertically, tightening the tension knobs to make sure the
the light of day only occasionally. This minimalist approach PCB didn’t slip in the extension brackets. Now, I could
has been working okay for me for some time. So, could stuff several components at once, then swing the PCB Rax
the PCB Rax teach this old dog a new trick? It turns out it around and solder them all in the same pass. The little
could, and did. The first thing you notice when unpacking heatsink clamp was still required to secure components,
the PCB Rax is the care with which it was packed. While but now I was starting to see some benefits of the PCB
not as fancy, it brought to mind the pride Apple and Rax (Figure 4).
others display with their product packaging. The next Next, I tackled the Parallax S-2 Robot Badge kit, which
thing you notice is the heft and finish of the PCB Rax. It is is a roughly circular PCB 1-1/2” in diameter with only
aircraft grade aluminum, anodized with a nice blue finish three components. By now, I was getting comfortable with
with quality fittings — top drawer, just asking for a place PCB Rax adjustments, but I was still surprised how easy it
on your bench. So, could it make a difference in my was to secure the small round board (Figure 5). This board
hobbyist circuit board work? was through-plated with nice lands on either side, and I
Assembling the PCB Rax is straightforward and quick learned that I could tack some components from the
— just follow the excellent video instructions on the Bench component side (using gravity to hold them in place
Werx website. Once the system was assembled, I started instead of my heatsink clamp), then set the PCB Rax
with the Elenco SP-3B Solder Practice Kit, which is a 2-
1/2” x 4” rectangular board with generous component
spacing and areas to practice solder bridge avoidance and
trace repair. Placing the board in the PCB Rax horizontally,
I adjusted the extension backers to hold the board corners
and tightened the tension knobs on the rails.
There are a lot of possible adjustments (important to
the flexibility of the system) and it took me a few minutes
to get the hang of things. I soon had the Elenco PCB held
securely and was stuffing components and emulating
board repair (Figure 3).
At first, the system seemed only marginally better than
my tried-and-true method of placing a single component,
securing it with a small heatsink clamp, tacking one lead in
place, then soldering all the leads — with all work done from
the trace (underside) of the board. This required repeated
flipping of the PCB Rax for each component, which the
FIGURE 5. Assembly of the S-2 Robot Badge.
system supported nicely, but which didn’t seem to be any Note the heatsink clamp holding a component
real improvement over my old non-PCB Rax method. in place for soldering.
January 2017 37
Weston - PCB Rax review - Jan 17_Blank Rough NV.qxd 12/5/2016 11:12 PM Page 38

PCB work I do, and I thought this kit would provide a


“real” test of the PCB Rax. In addition, I had built several
of these kits before using my tried-and-true method, which
I thought should provide a good baseline for a “before
and after” comparison of the system.
I started with the 2” x 3” shield board in the vertical
position, and had no trouble soldering the discrete
components and IC sockets. Some components needed
my little heatsink clamp to steady them while soldering,
but most didn’t, and things went smoothly.
This kit had several connectors on the board edges,
and I had to jockey the extension brackets a few times to
make room for the connectors being installed. Again,
things went pretty smoothly, except for my over-
confidence-driven haste (hey, I’m starting to get the hang
of this!) that left a VGA connector slightly raised off the
FIGURE 6. The PCB Rax extension brackets offer
good positioning flexibility and easily held the board on one side (Figure 7).
small irregular-shaped Robot Badge PCB. The 1” x 1” daughterboard required some surface-
mount work, which meant the PCB Rax had to be in the
horizontal position. To my mild surprise, the system held
this tiny board securely, using only two of the extension
brackets. It took some shifting around to get my iron
positioned comfortably above the PCB Rax in the
horizontal position (the feet stick up a couple of inches on
each corner), but with my heatsink clamp holding things
down, I was able to complete the necessary joints. I did
have to remove the board, rotate it 90 degrees in the
extension brackets, and re-tighten to get clear access to
some of the joints. All in all, construction of this Pocket
Mini Computer kit using the PCB Rax seemed easier and
FIGURE 7. The completed PMC shield and quicker than the several I had built previously using my
daughterboard. The size, component density,
and component proximity to the board edges old method (Figure 8).
are typical of many kits available today. My final PCB assembly test was a homebrew project
built on a 1-1/2” x 2-1/4” Parallax EDU circuit overlay
board which is a protoboard that can be used to create
“shields” for the Amigo computer kit sold in the Nuts &
Volts webstore. Unlike the three previous “kit” boards —
where component x goes in position y — effective layout
of the components on the protoboard is a big part of the
build process.
I found that my new skills with the PCB Rax allowed
me to quickly solder the male shield headers in place with
the system set vertically. Then, I switched to the horizontal
FIGURE 8. My sloppy installation of a VGA orientation with the component side of the board up, and
connector. I should have adjusted the
extension brackets on the PCB Rax to give me dropped the various components into the protoboard,
more room. moving them around until I found a layout that I liked.
Gravity held everything in place, and the PCB Rax
vertically and solder the whole lot. I was beginning to get elevation above my workspace allowed long component
a feel for this new system (Figure 6). leads to stick out below the board with no ill effects.
Having made short work of the Robot Badge kit, I With the board still horizontal, I tacked down the
decided to attempt an old Pocket Mini Computer (PMC) components I could, working easily from above and using
kit which consisted of a 2” x 3” “shield” for the Parallax gravity as my helper. I then turned the system vertically
QuickStart Board, with a 1” x 1” daughterboard on top. and soldered all the connections on the trace side of the
These boards were mostly through-hole with some board, using my little heatsink clamp to hold components
surface-mount components, and component density was I couldn’t tack from above. For me, the whole process was
high with a number of headers and connectors at the surprisingly intuitive — I now had a good “feel” for this
board edges. These characteristics embody much of the new tool — and again my build seemed quicker and easier
38 January 2017
Weston - PCB Rax review - Jan 17_Blank Rough NV.qxd 12/5/2016 11:12 PM Page 39

than it would have been using my old process (Figure 9).


To complete my evaluation of the PCB Rax, I also
simulated some board repair and rework by stuffing some
components into an old prototype PCB (4” x 4”, from one
of my projects), then removing and replacing them using
the PCB Rax. The vertical positioning capability of the
PCB Rax allows easy access to both sides of a board at
the same time, which is very helpful for component
removal — much easier than trying to hold your iron,
needlenose pliers, and the board with just your two hands,
no matter how skilled you are. If you do any amount of
PCB repair, this feature alone should make PCB Rax a
valuable addition to your workbench.
I also tried out a few interesting add-on components FIGURE 9. Arranging components on the EDU
that will soon be available from Bench Werx for the circuit overlay board. Once I had a layout I
system, including a center rail, alligator clips for the liked, I tacked things down as shown, then
shifted the PCB Rax to the vertical position and
extension brackets, and some neat “third hand” articulated soldered everything on the trace side of the
arms that fasten to the side rails. Depending on your board.
needs, you may find that these significantly extend the
capabilities of the system, and you should check them out me, circuit board work seems noticeably easier and
if you’re considering PCB Rax. quicker using PCB Rax, enough so that I’m going to add
Bottom line: The PCB Rax system from Bench Werx one to my current “minimalist” tool suite.
can securely hold almost any shape circuit board in either If you do much circuit board assembly or protoboard
the horizontal or vertical position for project assembly or work or if you just enjoy having the right quality tool for
board repair. It is a high quality tool that should last for the job at hand, I suggest you take a close look at the PCB
years, and I found it easy to learn and intuitive to use. For Rax. NV

The
The E
Easiest
asiest W
Way
ay tto
o Design Custom
Front
Front Panels
Panels & Enclosures

You design it We machine it


to your specifications using and ship to you a
our FREE CAD software, professionally finished product,
Front Panel Designer no minimum quantity required
Speakers Project Accessories
 Cost effective prototypes and production
runs with no setup charges
 P
 owder-coated and anodized finishes in
various colors
  elect from aluminum, acrylic or provide
S
your own material
Components Tools and Tech Aids  Standard lead time in 5 days or express
$ $ manufacturing in 3 or 1 days
Save 10 on 100 order at
parts-express.com!
Promo code: NVJ7T
*Offer expires 3/31/17

parts-express.com
1-800-338-0531 FrontPanelExpress.com

January 2017 39
Ward - MyRIO - Part 2 - Jan 17_Blank Rough NV.qxd 12/5/2016 11:24 PM Page 40

Computer Control
and Interfacing with
the NI MyRIO
By David Ward

In the first article in this series last month, the


reader learned how to build, compile, and deploy
a very simple LabVIEW VI (virtual instrument) and
run it on the National Instruments’ (NI) MyRIO
unit, controlling it through a USB cable connected
to a host PC running LabVIEW 2015. In this
second article, we will take that first simple VI and
build and deploy it as an embedded program
which will not require a host PC to be connected
to the MyRIO after it has been deployed.
refers to VIs that
NI are “embedded”
into the MyRIO as “real
time” VIs. Each time the
MyRIO unit is powered
up or reset, the VI will
automatically run. The
second task covered by
this article will be to use
an Apple iPad to
interact with and FIGURE 1.
control that simple VI FIGURE 2.
through a Wi-Fi wireless
connection on an iPad FIGURE 3. Figure 1. From the window shown in Figure 2, in the
using NI’s Data category column, select Source Files. Next, in the
Dashboard. Project Files column, click on your VI (which was
To make a real time called demo_1.vi), then click on the blue right-facing
or embedded VI, you arrow to send that VI name into the Start-up VIs
will need to open up column on the right. Click on the Build button at the
the project that was bottom of the window. You will now see the window
demonstrated in the first article. Next, you will need to shown in Figure 3.
open up the Project View window. Left-click on the Build Click on the Done button. You will now be back to
Specifications, then right-click and from the pull-down the Project View window. All of the other windows and
menus, select New > Real-Time Application as shown in choices in Figure 2 should work fine in their default
40 January 2017
Ward - MyRIO - Part 2 - Jan 17_Blank Rough NV.qxd 12/5/2016 11:24 PM Page 41

Post comments on this article and find any associated


Part 2: Building and Deploying an files and/or downloads at
www.nutsvolts.com/magazine/article/January2017_
Embedded VI, and Controlling the NI Computer-Control-with-NI-MyRIO-Wireless-VI.
MyRIO Wirelessly with an Apple iPad.
settings and should
not need to be
changed.
Left-click on My
Real-Time Application,
right-click, and from
the pull-down menu FIGURE 6.
select Run as Startup
as in Figure 4. You
should now see the
Deployment Progress FIGURE 4.
window shown in FIGURE 7.
Figure 5; click on the
Close button. You FIGURE 8.
should now see the
window in Figure 6
asking you if it is OK to reboot
the MyRIO unit. Click on Yes.
If you set up a password on
the MyRIO unit, you will be FIGURE 5. FIGURE 9.
prompted for the username and
password; refer to Figure 7. The
default username is “admin” and
during the original setup
procedure it will require you to
enter a password. The password
that was set up in this particular
unit is “nimyrio.” The MyRIO unit should now reboot and
your VI will start running. Each time the unit is powered
up, that VI will run since it is stored in non-
volatile memory in the MyRIO unit. You will
also see the window in Figure 8; click on Do
Nothing. It’s probably a good idea to build
your real time VIs so that pressing the
BUTTON0 on the bottom of the MyRIO unit
will stop the real time program execution. This
makes it easier to communicate with the unit
when you want to change programs or wish to
stop a VI’s execution for any other reason.
Since BUTTON0 is being used for something
else in this VI, it can’t be done at this time. FIGURE 11. FIGURE 10.
When you look at the Project View
window, you should see that you can still run
your original VI (demo_1.vi) by double-clicking
on it to open up the front panel and block diagram, and pull-down menu select Unset as Startup as shown in
then clicking on the Run arrow icon as was done before Figure 10. Click again and select Deploy as shown in
the real time demonstration. As it deploys, you will see a Figure 11. You will be prompted to make sure it is okay to
window telling you there is already a VI running on the do this in another window.
MyRIO unit; see Figure 9. Click on OK. Running your Next, we will demonstrate how to control this VI
original VI this way does not erase or stop the real time wirelessly using an iPad. Three things need to occur
version of the VI from running every time the unit is before this can be done. First, the MyRIO unit will need to
powered up or reset. have the Wi-Fi set up as a router. Second, the project will
To stop the real time version from running on power- need to be set up to “publish” or send/receive two
up, click on Build Specifications, right-click, and from the variables through the Wi-Fi connection. These variables
January 2017 41
Ward - MyRIO - Part 2 - Jan 17_Blank Rough NV.qxd 12/5/2016 11:24 PM Page 42

FIGURE 13.
FIGURE 12.

There are
two usernames
and two
passwords
FIGURE 16. configured on
the MyRIO
used in these
articles. The
username and
password to
FIGURE 14. access the
MyRIO itself to view files, reboot,
etc., is “admin” and “nimyrio.” The
username and password to access
will then need to be added to the block the Wi-Fi connection is “NIMYRIO”
diagram. and “nilabview.” The address that
The LED variable status or data (true or should appear on the iPad needs to
false) will be sent out from the MyRIO Wi-Fi to FIGURE 15. be 172.16.0.1 and be named
the iPad and turn an LED indicator on the iPad NIMYRIO. Be sure to click on the
on and off. A control on the iPad (acting as a Save button before exiting. When
switch) will send its data (true or false) from the MyRIO Wi-Fi is working, there is
the iPad back to the MyRIO to control LED0. Third, NI an orange or red LED located just above LED0 that will be
Data Dashboard will need to be installed and a Data on. There is also a Wi-Fi button on the bottom of the
Dashboard built to interact with the VI through the MyRIO unit next to BUTTON0 that can be pressed to turn
MyRIO wireless router. the Wi-Fi off and on. However, if the Wi-Fi LED is not on,
If you have not set up the MyRIO Wi-Fi yet, it will be the Wi-Fi connection will not work.
demonstrated here. Setting up this Wi-Fi can be done To set up your project so that it can transmit and
several ways, but the way shown here will be through the receive wireless data, open up the Project View window.
USB cable connected to the host PC. On the PC, open Click on NI-myRIO..., right-click, and from the pull-down
Windows Explorer and type in address 172.22.11.2; this is menus select New > Web Service as shown in Figures 14
the default address the MyRIO unit uses for the USB and 15. Now, click on NI-myRIO..., right-click, and from
connection. You should see the System Configuration the pull-down menu select New > Variable as shown in
window shown in Figure 12. Select the fourth icon down: Figure 16. For the next step, refer to Figure 17.
Network Configuration. Figure 13 shows how this From the Shared Variable Properties window, you can
particular MyRIO Wi-Fi was configured: Wireless Mode > rename the variable (renamed as LED), then click on
Create wireless network; Country > United States; SSID > Variable Type > Network-Published, Data Type > Boolean,
NIMYRIO; Security > WPA2 Personal; WPA Passphrase > then click on OK. In the Project View tree, you will now
nimyrio; and finally Configure IPv4 Address > DHCP Only. see an untitled library with your LED variable under it;
42 January 2017
Ward - MyRIO - Part 2 - Jan 17_Blank Rough NV.qxd 12/5/2016 11:24 PM Page 43

FIGURE 19.

FIGURE 17.

FIGURE 18.
refer to Figure 18. To add more variables to your
project, click on Untitled Library, right-click, and
from the pull-down menu, select New > Variable
and name another variable as before; in this
case, button and Data Type > Boolean; see
Figure 19. Now with both the Project View
window and the Block Diagram window placed
next to each other, drag the two variables (LED
and button) one at a time from the Project View
tree over into the while loop of the block
diagram as shown in Figure 20. The green data
arrow on the button variable is on its right side;
this will work as it will be a control coming from
the Wi-Fi. However, the arrow on the LED FIGURE 20.
variable needs to be on its
left side so that it can
transmit its status through
the Wi-Fi.
To make this change,
select the LED icon, right-
click, and from the pull-down
menu, select Properties.
From its Properties window,
change the Access Type
from Read to Write. Refer to FIGURE 22.
Figure 21. Now, wire these
two variables into the block FIGURE 21.
diagram as shown in Figure
22, adding another “Or” gate as shown. This means that data through its Wi-Fi. The last step in this process is to get
either the pushbutton on the front panel of the VI, the the iPad ready to interact with the MyRIO Wi-Fi. First,
BUTTON0 on the MyRIO unit, or the control on the iPad download and install NI Data Dashboard onto your iPad
can control LED0, and that the LED indicator will be on from the Apple ITunes store; it should be free. When it is
the Data Dashboard of the iPad. installed, you should see the Dashboard icon as shown in
Be sure to click on File > Save All on either the front Figure 23. Open Settings as in Figure 24. You should be
panel or the block
diagram after you make
all of these changes so
you don’t lose them. It
is also wise to click on
the File > Save All (this
project) from the
Project View window FIGURE 23.
from time to time.
Now, the VI can be run
on the MyRIO unit. It FIGURE
24.
should start publishing
January 2017 43
Ward - MyRIO - Part 2 - Jan 17_Blank Rough NV.qxd 12/5/2016 11:25 PM Page 44

FIGURE 26.

FIGURE 25.

FIGURE 27.

FIGURE 29.

FIGURE 28.

FIGURE 30.

it (Figure 26). If your iPad Wi-Fi status shows you are


connected to the MyRIO, you can close the Settings
able to see your MyRIO as one of the possible Wi-Fi window. Open the Data Dashboard; you should see
Networks. Make sure the MyRIO is on and running your several tutorials available as in Figure 27. To start a new
VI with the newly configured variables; see Figure 25. dashboard, touch the “+” in the upper right corner (Figure
If your MyRIO has a password, you will need to enter 28). You should now have a blank dashboard.
44 January 2017
Ward - MyRIO - Part 2 - Jan 17_Blank Rough NV.qxd 12/5/2016 11:25 PM Page 45

FIGURE 31.
FIGURE 32.

FIGURE 34.

FIGURE 33.
FIGURE 35.

FIGURE 36.

in Figure 32. Select the correct address for the


NImyRIO; in this case, 172.16.0.1. If the connection
is successful, you should see your library name from
FIGURE 37. your Project View window displayed; select it
(Figure 33). Sometimes the libraries may not appear
unless you touch the Refresh icon on the lower right
of the window (the blue circle/arrow).
Select Palette > Indicators, and drag an LED down After selecting the appropriate library, you should see
onto your dashboard as in Figure 29. Select Palette > your two variables displayed as in Figure 34. If they are
Controls, and drag a switch down onto your dashboard as not showing, touch the Refresh icon. Select the LED
shown in Figure 30. Now, click on the little box located variable; the block below the LED should change from
below the LED and it will open up the window shown in gray to green if all of this was successful; see Figure 35.
Figure 31. This shows that there are shared variables as Repeat the same steps for the switch to assign it to the
well as demo variables. button variable. Now you can touch the “RUN” icon —
The demo variables can be used to make dashboards the arrow at the top of the dashboard to run the
if you are not connected to a suitable NI wireless dashboard; see Figure 36. You will probably see yellow
connection. The shared variables are the ones we need. warning triangles or spinning star shaped images until the
After selecting shared variables, you will see the window connections actually take place (Figure 37). They can also
January 2017 45
Ward - MyRIO - Part 2 - Jan 17_Blank Rough NV.qxd 12/5/2016 11:25 PM Page 46

MyRIO unit will be blinking if things are working correctly.


To stop your dashboard, touch the “STOP SIGN” icon in
FIGURE 38. the upper right corner.
Hopefully, you were able to get everything to work
together. Running the MyRIO with a real time VI and
using Wi-Fi published variables makes it so you can run
and control your MyRIO wirelessly from your iPad without
a host PC present. The Data Dashboard is also available
for Android devices, however, I have only used an iPad
and am not aware of any differences between the two
platforms (there are sure to be a few).
If you spend some time exploring your Data
Dashboard tutorials, you can learn how to change the
background colors, etc., to make your dashboard look
more interesting than the very simple one demonstrated
here. Once successful Wi-Fi connections exist between
the MyRIO and the iPad, time can be spent improving the
appear if the MyRIO is not running or if the iPad changes look of the dashboard. Figure 38 shows the Data
network connections for some reason. Dashboard for the final temperature control system that
Now as you run your VI, you should see your will be covered in the final article in this series.
dashboard LED light up whenever: BUTTON0 on the Next time, I will demonstrate how to translate the low
MyRIO is pressed; the pushbutton on the front panel is voltage/low current digital I/O signals from the MyRIO
clicked on; or when the switch from your dashboard is ports into higher voltage and higher current real world AC
touched. You should notice that the Wi-Fi LED on the and DC loads. NV

46 January 2017
McPhalen - Spin Zone - Jan 17_Spin Zone - Aug 15.qxd 12/5/2016 11:31 PM Page 48

THE SPIN ZONE ■ BY JON MCPHALEN


ADVENTURES IN PROPELLER PROGRAMMING

Making Menus
Today, I have Willie Nelson stuck in my head — well, one of his songs, anyway, because I
am, in fact, on the road again. As I bask in the solitude of a quiet condominium, my
colleagues and their families are enjoying the day at Disney World. We're in a bit of a
celebratory mood because we've just come off a very big trade show and it was a
success. My client introduced a new product that uses a custom board designed by EFX-
TEK, and coded by yours truly. What my client's customers enjoyed about the new
controller is the simplified menus. They're easier to navigate, more consistent, and just
make better sense (FTR, I did not design nor code the previous product!). Menus are
important — in restaurants and in consumer devices — and we should never take them
for granted.
This month, I’m going to explore some of the code I

J
ust over 20 years ago, I created the concept for an
irrigation controller that would be developed into the used in my customer’s laser tag product, though we’re not
Toro ECx. The requirements for the product were a going to build a working laser tag weapon, nor a sprinkler
challenge: It had to be price competitive, and it had to be timer for that matter — but we are going to enter data for
available for sale all over the world. As a product designer, what would be useful in a small irrigation control
user interface is always something that I put a lot of application. Just as my client limited me to a 2x8 LCD with
energy into; that paid off this week with the laser tag three buttons (well, two buttons and a trigger; see Figure
controller, just as it did 20 years ago at Toro. I am very 1), we’re going to stick with that to see if we can make it
happy that the ECx (with tech upgrades, of course) is still work. It would be easier to work with four buttons, or
available for sale in my local hardware store. I put a lot of even six as I have on another project (a road sign
effort into that product, and it helped me realize a life-long controller), but the real world doesn’t always bend to our
goal of earning a United States patent (in fact, I earned desires and wishes. Another singer/song writer that I quite
two from it). It also allowed me to contribute to an enjoy once said, “You can’t always get what you want, but
employer that treated me very well. When I hand a new if you try, sometimes you get what you need.”
design to a customer, I am intensely focused on their I like to start with a map before coding any menu
initial reaction. A vice president at Toro was first to try the based projects; this is particularly helpful when working
ECx; he looked at me and said, “It’s too good!” (Not what with a client. On the laser tag project, for example, my
I was expecting.). On the show floor a few days ago, a client made a fairly serious structural change when he was
nice lady who runs a lot of laser tag facilities in Canada able to see the entire system laid out on a page, and this
kissed me on the cheek for how I had cleaned up the change was greatly appreciated by his customers. Figure 2
menus and operations versus the previous product. Again: shows the layout of our bare-bones sprinkler timer data
User interface matters, so it behooves us to do it well. entry menus. Note the color coding; the colors indicate

■ FIGURE 2. Menu map.

■ FIGURE 1. Laser tag HMI.


48 January 2017
McPhalen - Spin Zone - Jan 17_Spin Zone - Aug 15.qxd 12/5/2016 11:31 PM Page 49

Post comments on this article and find any associated files and/or downloads at
www.nutsvolts.com/magazine/article/January2017_SpinZone_Making-Menus-User-Interface.

entry elements that will use the same code or an identical In the sprinkler timer demo, the edit_settings()
coding strategy (i.e., copy, paste, modify as needed). The method is called when the green button is pressed. This
overall map also serves as a check-list for the methods that changes pgmstate to edit mode and gets us to the top
have to be developed. level menu. The program will stay in this menu until EXIT
Author’s Note: I found a freeware font that matches Setup is selected and the green button is pressed. The real
standard character LCDs so I used it in my maps. This work takes place in the select_from_list2() method:
allowed my customer to see exactly what his menus would
look like before I ever started coding. Small details like this pub select_from_list2(idx, lo, hi, p_list) {
} | last
can make a big difference in a project.
The next step in my process was to code some helper idx := 0 #> idx <# hi
routines that would work with my standard LCD object. repeat
For example, the top row of the map is the top level of last := -1
the menu. The arrows indicate buttons on the tagger: repeat
if (idx <> last)
black for up and forward, red for down and reverse; green display_2x8(p_list + (idx * 17))
(the trigger) is to enter or accept. last := idx
The top level menu is a simple list of screens. I lay out if (get_input(@idx, lo, hi))
the screens in a DAT section like this: clear_buttons(BTN_CLR)
return idx
dat else
time.pause(BTN_SPD)
s_MainMenu byte “SET W-Days “, 0
byte “SET W-Starts”, 0 At the top, we start by fixing idx (current index into
byte “SET Sta Run “, 0
byte “SET Clock “, 0 list) to the range defined by lo and hi. Defining the range
byte “EXIT Setup “, 0 allows us to use a small portion of a longer list. On first
entry or any time the red or black buttons are pressed, the
For each 2x8 display, I define a single 16-character screen is updated. Buttons are handled by the get_input()
string. Those strings are displayed with this method: method:
pub display_2x8(p_str) pub get_input(p_value, lo, hi) | btns

lcd.home repeat
lcd.substr(p_str, 8) btns := scan_buttons(BTN_MS)
lcd.line(1) until (btns <> %000)
lcd.substr(p_str+8, 8) case btns
M_FWD :
This routine expects a pointer to a string, and this if (++long[p_value] > hi)
string should be 16 characters long to cover both lines of long[p_value] := lo
the 2x8 display. Since we’re going to be overwriting the return 0
display, we don’t need to clear it — clearing the LCD takes M_REV :
more time than simply moving the cursor to the home if (—long[p_value] < lo)
long[p_value] := hi
position, anyway. The substr() method puts the first eight return 0
characters of the string on the first line of the display.
Next, we move to the bottom line and print the second M_SET :
return
eight characters from the string:
This method uses scan_button() to wait for user input.
pub edit_settings | idx Note that it requires a pointer to a [long] value to be
idx := 0 modified, as well as the low and high limits for that value.
If the black button is pressed, the value is incremented,
repeat
if (pgmstate <> PS_EDIT) rolling over to the low limit if the high limit is exceeded.
return Likewise, if the red button is pressed, the value is
decremented, rolling under to the high limit if we drop
idx := select_from_list2(idx, 0, 4,
@s_MainMenu) below the low limit. If black or red is pressed, zero is
case idx returned to indicate that we’re not done editing. If the
0 : set_watering_days
1 : set_irrigation_starts green Set/Enter button is pressed, one is returned as a flag
2 : set_station_run_times to terminate editing this value.
3 : set_clock The scan_button() method handles basic debouncing
4 : pgmstate := PS_RUN and manipulates the button pins so that we can share the
January 2017 49
McPhalen - Spin Zone - Jan 17_Spin Zone - Aug 15.qxd 12/5/2016 11:31 PM Page 50

first option is to set the day-of-week. This is very simple


■ FIGURE 3.
Laser tag HMI with a couple more support methods:
schematic.
pub set_day(now)

display_screen(true, @s_Today, false)

now.byte[3] := select_from_list1 {
} (now.byte[3], 0, 6, 1,
@s_Sun, 4)

return now

At the top, we use display_screen() to set up the LCD:


pub display_screen(clr, p_str0, p_str1)

if (clr)
clear_display(true)

if (p_str0 > 0)
line_out(0, p_str0)
LCD buss. This is not a new or original concept; my friend,
if (p_str1 > 0)
Scott Edwards showed us how to do it many years ago in line_out(1, p_str1)
Nuts & Volts. Almost every one of my LCD projects uses
the buss pins for buttons. Figure 3 shows the schematic This method gets the most use in my menu systems.
for the laser tag HMI which I am using in the sprinkler The first parameter determines whether the LCD will be
timer demo; you can easily modify this for your own cleared or not. Again, if we’re using two strings and both
projects, and even add a fourth button to DB7 if you need are eight characters, there is no need to clear the LCD.
it. The LCD is configured as write-only (W/R line is tied to The next two parameters are pointers to the strings to be
ground), so we don’t have to put series resistors in the displayed: the first on the top line; the second on the
buss. The 10K voltage dividers attached to the buttons bottom line. If we want to display a string on a particular
and LCD buss ensure that the button input voltage to the line, we pass the address of that string. If a line is to be left
Propeller is at a safe level: blank (i.e., after clearing) or unmodified, then we pass 0
(false). In set_day(), the call to display_screen() changes
pub scan_buttons(ms) | btns, t the top line to “Today is” and clears the bottom line. This
dira[BTN_F..BTN_S] := %000 sets up the screen for the work which is handled by
btns := ina[BTN_F..BTN_S] select_from_list().
if (btns) This behaves like select_from_list2(), but only
t := cnt modifies one line of the display. In this case, it will be the
repeat ms bottom line which will display the abbreviated name of
waitcnt(t += MS_001)
btns &= ina[BTN_F..BTN_S] the week. Those names come from a list which begins
return btns with the DAT element called s_Sun. Note that we’re using
@ to pass the address of s_Sun.
This method is simplified by using the LCD buss pins Author’s Note: I have made a small style change in my
which are connected to the Propeller in a contiguous own programs, vis-à-vis strings. When they’re pre-defined in
group (a requirement of the LCD object). The pins are a DAT section, I preface them with “s_” and use mixed-
made inputs and then checked to see if any are pressed. If case naming. This is consistent with my use of the “p_”
one or more inputs are active, the method drops into a prefix for pointer (address) variables, as we always have to
loop for the debounce period (ms), and then re-scans the pass the address of a string to a method. The laser tag
pins before returning a clean input. project has dozens of strings, and this style change made
On the other side of this, the output routine for the them far more manageable.
LCD object must ensure that the buss pins are set to The parameter passed to set_day() is actually a long
outputs before any write. That is already in place. that contains all four RTC elements: day, hours, minutes,
I know what you’re thinking: “That’s a lot of layers for and seconds. As you can see, we’re only modifying byte 3
a simple menu!” You’re right, it is, but you’ll also notice of this value as that’s what holds the current day (0..6).
that each of the routines is atomic which will allow us to Since we’ve jumped into setting/editing the clock,
employ them elsewhere. In the laser tag project and in our let’s back up one level. In the menu map, you see four
simple sprinkler timer demo, we have more than screen elements under SET Clock, and routines for those
selections. For example, when we select Edit Clock, the elements are called with this method:
50 January 2017
McPhalen - Spin Zone - Jan 17_Spin Zone - Aug 15.qxd 12/5/2016 11:31 PM Page 51

pub set_clock pub show_clock(tregs)

rtc := set_day(rtc) lcd_dec2(tregs.byte[2])


rtc := set_hours(rtc) lcd.out(“:”)
rtc := set_minutes(rtc) lcd_dec2(tregs.byte[1])
rtc := set_seconds(rtc) lcd.out(“:”)
lcd_dec2(tregs.byte[0])
This is one of those simple bits of code that is easy to
take for granted — but we shouldn’t. Stating the obvious, There’s nothing to this. We pull the hours, minutes,
this method allows us to control the flow of data into the and seconds bytes from tregs and display them as two-
system. Here’s a similar method from the laser tag program: digit (with leading zero) values. We will use this method
later to display the current time of day.
pub edit_weapon_menu The edit_value() method gets a lot of use in my menu
edit_ir_power systems, and by now should be very easy to understand:
edit_ir_range
edit_sounds pub edit_value(value, lo, hi, col, line,
width) | last
if (edit_mag_size > 0)
edit_magazines value := lo #> value <# hi
edit_reload last := !value
if (edit_fire_select == BURST) repeat
edit_burst if (value <> last)
lcd.crsr_xy(col, line)
edit_damage lcd_dec(value, width)
edit_cyclic last := value
edit_muzzle_flash
if (get_input(@value, lo, hi) > 0)
As you can see, there are if structures embedded into clear_buttons(BTN_CLR)
return value
the list; these allow me to control what the user sees else
based on other selections. For example, if the magazine time.pause(BTN_SPD)
size is not set to “Unlimited” (a special feature for players
with physical limitations who may not be able to handle This method lets us modify a value between lo and hi,
the reload function), then the next element to be set is the and we’re able to control placement and field width as
number of magazines. If the magazine is set to unlimited well. This allows us to neatly set an individual time
rounds, there is no need to set the number of magazines element while the others are displayed.
in the tagger. As we get further into the menus, things get easier.
In another case, if the Fire Select mode is set to Watering days are defined as off or on, and we can set
BURST, then the operator can edit the maximum number the entire week with just one method:
of rounds that can be fired in a burst. For full- or semi-
automatic modes, the number of burst rounds is not used; pub set_watering_days | d, check
hence, we don’t have to bother with it while editing. I repeat d from 0 to 6
know these things are elementary, but I will continue to clear_display(true)
lcd.str(@s_Run)
maintain that they can make a very big difference in how lcd.str(@@DayName[d])
a customer perceives a product.
The color coding of the menu map suggests that check := (Water_Days >> d) & 1
check := select_from_list1{
setting the time elements will use similar code, so let’s } (check, 0, 1, 1, @s_No, 4)
have a look at just one of those elements: if (check == 1)
Water_Days |= 1 << d
pub set_hours(now) else
Water_Days &= !(1 << d)
display_screen(true, @s_Hours, false)
lcd.line(1) ee.wr_byte(@Water_Days, Water_Days)
show_clock(now)

now.byte[2] := edit_value{ The active watering days for the program are stored as
} (now.byte[2], 0, 23, 0, 1,
2) a byte called Water_Days that is embedded in a DAT
section. Each bit is identified by day name using an array
return now of strings and an array of string addresses which is why
This is starting to look familiar, right? It should. After we’re using the @@ operator to display a day name. Each
setting up the initial display, we display now as a clock bit is extracted into check which is then edited using
using the show_clock() method: select_from_list1(). In this case, the choices are “No” (0)
January 2017 51
McPhalen - Spin Zone - Jan 17_Spin Zone - Aug 15.qxd 12/5/2016 11:32 PM Page 52

and “Yes” (1). The edited choice is put back into


idx := Start_Times[n]
Water_Days. After all the days have been set, the value of
Water_Days is written to the EEPROM so that it’s available repeat
after a program reset or power-up. lcd.line(1)
if (idx => NO_START)
Finally, we get to those special cases where we need lcd.str(@s_Off)
to do more than edit a value or pick something from a list. lcd.out(“ “)
lcd.out(“ “)
A moment ago, I spoke about the magazine size in the else
laser tag weapon having an “Unlimited” setting. In this stime := idx * 15
case, zero is used to define unlimited, but putting “0” in lcd_dec2(stime / 60)
lcd.out(“:”)
the display would be quite confusing. Likewise, in the lcd_dec2(stime // 60)
sprinkler timer demo, we may not want to use all of the
available start time slots for a given watering day; instead if (get_input(@idx, 0, 96))
clear_buttons(BTN_CLR)
of showing a time, a disabled start slot would show “OFF.” quit
What this means is that in advanced menu systems, else
time.pause(BTN_SPD)
we will have specialty methods. Still, they’re not hard to
code given the other support methods that we’ve created. Start_Times[n] := idx
Let’s have a look at the code that edits the start times for ee.wr_byte(@Start_Times[n], idx)
an active watering day: The program supports up to four irrigation starts on
the active watering days; these are stored in a table called
pub set_irrigation_starts | n, idx, stime Start_Times that is in a DAT section. As with the other
repeat n from 0 to 3 elements, using a DAT section lets us pre-define values like
constants, except that they can be modified at run time.
clear_display(true)
A repeat loop controls which start time (0..3) is being
lcd.str(@s_Start) edited, and updates the LCD accordingly. Inside that loop,
lcd_dec1(n+1)

www.embeddedARM.com
Single Board Computer
TS-7680
Low Power Industrial SBC
454 MHz ARM CPU
WiFi & Bluetooth Enabled
4GB eMMC Flash Storage
-40°C /+85°C Temp
e Range

Computer-on-Module
TS-4900
High Per fo
ormance
Freescale i.MX6 ARM CPU
WiFi & Bluetooth Enabled
Quad Core Option

(480) 837-5200
52 January 2017
McPhalen - Spin Zone - Jan 17_Spin Zone - Aug 15.qxd 12/6/2016 12:30 AM Page 53

Jon "JonnyMac" McPhalen


jon@jonmcphalen.com
Parallax, Inc.
www.parallax.com programs, I like to apply George Lucas’ thought on
movies: They’re never done, they’re simply abandoned.
we will display the starting time. For the purposes of this This example is small, but within it we’ve built the tools to
program, all values are stored as bytes. These means that create a much more complex system. The laser tag
we have to use a bit of compression because we cannot project, for example, has nearly 60 elements (x4 user-
store 1440 (minutes in a day) into a byte. For stand-alone selected weapon types) that can be set by the field
sprinkler timers, watering start times do not require a lot operator; this requires about 2000 lines of Spin code to
of resolution, so the time is expressed in 15 minute accomplish — and that’s with the common code elements
increments (we could use 10, but I decided 15 was fine). to handle the variety of menus in that system, and not
Here’s where we get special: At the top of the loop — counting attached child objects.
where the LCD is updated — we check to see if the start Big project or small, take your time when it comes to
time index is 96; when this is the case, we will display the user interface, and design a system that is sensible and
“OFF.” Otherwise, we will calculate and show the starting easy to use. Apple built its entire brand on user interface.
time formatted as HH:MM. The bottom of the loop is Final story: About five years ago, I designed a camera
similar to other editors, using get_input() to modify the pan/tilt controller that uses an LCD and six-button
start time index value in the allowable range. interface. One of the testers was on location in a cave
When the green Set/Enter button is pressed, the index when rocks fell and damaged the LCD. Because my client
for the start time is saved to the Start_Times element and and I had spent a lot of time designing the flow of the
copied to the EEPROM. As you scan through the example interface, the person using the controller was able to
code, you’ll see that the sprinkler run times are handled in remember the sequence of button presses and finish the
a similar fashion. shoot! To me, that was a big success.
Okay. That was a bit of work, wasn’t it? Yes, in fact it
was — and some will continue to wonder why I use so Happy New Year, friends! Until next time, keep
many layers in a simple program. When it comes to Spinning and winning with the Propeller! NV

(716) 630-703
0

CHASS
IS

TRANS
FORME
RS

ENCLO
SURES

January 2017 53
THE DESIGN CYCLE n BY FRED EADY

A Look at the nRF52832’s


SPI Peripheral

W orking with the nRF52832 makes me want to throw away my stock


of mundane microcontrollers. The ARM based nRF52832 blinks LEDs,
speaks SPI, UART, and I2C just like any other microcontroller. It even
does things without its CPU that some microcontrollers can’t do with
the assistance of their CPU. So, in this installment of the Design Cycle, we will
continue our exploration of the nRF52832’s peripherals.

The nRF52832 Serial Peripheral


The SPI GPIO pin definitions are located in
Interface the sdk_config.h file. The resultant definitions were
Commonly known as SPI, the nRF52832’s Serial actually a result of the selection of the SPI GPIO ty
Peripheral Interface is capable of operating in Master or pins in the Configuration Wizard. You can see this in H
Slave mode. SPI was developed by Motorola in the 1980s Screenshot 1.
and is still used widely today. Most every microcontroller Now that we have decided where to put the SPI t
out there has an SPI portal. portal, we must spawn an instance of the portal. This {
SPI is a clocked synchronous protocol that utilizes is done within the confines of the main function:
Master/Slave relationships. Basically, the Master controls
everything. The Master selects a Slave device by dropping //SPI Instance Index = 0
the SS (Slave Select) signal to a logically low level. The #define SPI_INSTANCE 0
Slave device becomes active and waits for a clock signal, //SPI Instance = spi0
which is provided by the Master device. With each clock static const nrf_drv_spi_t spi0 = NRF_DRV_SPI_
edge transition, the Master sends a bit of data to the Slave INSTANCE(SPI_INSTANCE);
device on the MOSI (Master Out Slave In) line. The Slave //SPI Instance Complete flag
uses the other clock edge to pass a bit of data back to the static volatile bool spi0_xfer_done;
Master on the MISO (Master In Slave Out) line. The data
transfer ends when the Master forces the SS signal logically }
high.
The nRF52832 allows us to assign any peripheral
function to any pin. So, let’s start assigning SPI signals at sp
the first available GPIO pin. As you can see in Photo 1, we m
have chosen to include a 32.768 kHz crystal to drive the th
low power clock. In that we have installed the 32.768 kHz c
external crystal, our first available GPIO pin is P0.02. We
will use a Saleae Logic to capture the SPI data exchange. /
The Saleae defaults the signal order to MOSI, MISO, SCK
(Clock), and SS (Enable). With that, here is how we define
the SPI GPIO to the nRF52832:
#
#define SPI_MOSI_PIN 2 {
#define SPI_MISO_PIN 3 n PHOTO 1. Every GPIO pin pulled out to a header is
#define SPI_SCK_PIN 4 ready to do our bidding. We have the ability to assign
#define SPI_SS_PIN 5 any peripheral function to any of the nRF52832’s
available GPIO pins.
56 January 2017

Eady - Design Cycle - Jan 17.indd 56 12/5/2016 8:16:49 PM


ADVANCED TECHNIQUES FOR DESIGN ENGINEERS
Post comments on this article and find any associated files and/or downloads at
www.nutsvolts.com/magazine/article/January2017_DesignCycle.

h
l n SCREENSHOT 1. The Configuration Wizard allows us
to easily change the nRF52832 peripheral configuration.
A scripting language allows us to create our own custom n SCREENSHOT 2. As you can see, the contents of the
sdk_config.h entries, which can be accessed via the sdk_config.h file can be altered by our selections within
Configuration Wizard. the Configuration Wizard.
Recall that we have the ability to right-click on .use_easy_dma = CONCAT_3(SPI, id, _USE_EASY_ \
types and be directed to their original definitions. DMA) \
Here is what the nrf_drv_spi_t structure looks like: }

typedef struct The .p_registers statement is pretty straightforward.


{ The other definitions within the macro are just as easy to
void * p_registers; understand if you do the concatenation:
///< Pointer to the structure with SPI/SPIM
///< peripheral instance registers. .irq = SPI0_IRQ
IRQn_Type irq; .drv_inst_idx = SPI0_INSTANCE_INDEX
///< SPI/SPIM peripheral instance IRQ number. .use_easy_dma = SPI0_USE_EASY_DMA
uint8_t drv_inst_idx;
///< Driver instance index. If we keep right-clicking, we will find within the nrf52.h
bool use_easy_dma; file that SPI0_IRQ = 3. There is a definition to be found for
///< True if the peripheral with EasyDMA (SPIM) SPI0_INSTANCE_INDEX within the nrf_drv_spi.h file:
///< shall be used.
} nrf_drv_spi_t; #define SPI0_INSTANCE_INDEX 0

Note that we used the nrf_drv_spi_t type to create the The state of SPI0_USE_EASY_DMA is determined by
spi0 structure. We populated the new structure using the a setting within the Configuration Wizard. I’ve captured
macro NRF_DRV_SPI_INSTANCE(SPI_INSTANCE). Using the negative point of definition for DMA operation in
the magic of right-clicking again, we can reveal the macro’s Screenshot 2.
contents: At this point, we have defined the SPI portal GPIO
pins and the spi0 instance. The SPI portal is being built to
/** transfer data. So, we will need to allocate some storage to
* @brief Macro for creating an SPI master driver house the data that will be exchanged over our new SPI
* instance. portal. For this, we need not conjure up any nRF52832-
*/ specific code. Just plain old C will work here:
#define NRF_DRV_SPI_INSTANCE(id) \
{ \ #define txdata “NutsVolts”
.p_registers = NRF_DRV_SPI_PERIPHERAL(id), \ static uint8_t m_tx_buf[] = txdata;
.irq = CONCAT_3(SPI, id, _IRQ), \ //extra byte in rx_buf for NULL character
.drv_inst_idx = CONCAT_3(SPI, id, _INSTANCE_ \ static uint8_t m_rx_buf[sizeof(txdata) + 1];
INDEX), \ //number of bytes to transfer = m_length
January 2017 57

Eady - Design Cycle - Jan 17.indd 57 12/5/2016 8:16:53 PM


ADVANCED TECHNIQUES FOR DESIGN ENGINEERS

static const uint8_t m_length = sizeof(m_tx_buf); ///< (optional). s


Okay. Everything is in place ... almost. If you’ve been /**< Set to @ref NRF_DRV_SPI_PIN_NOT_USED d
following along, you realize that we have been working * if this signal is not needed. */ w
with tasks and events. Our SPI instance will generate an uint8_t miso_pin; ///< MISO pin number c
event when the SPI exchange has completed. So, we’ll ///< (optional).
need an SPI event handler. Our SPI event handler is very /**< Set to @ref NRF_DRV_SPI_PIN_NOT_USED
simple. Its only purpose in life is to change the state of the * if this signal is not needed. */
Boolean variable spi0_xfer_done: uint8_t ss_pin; ///< Slave Select pin
///< number (optional).
void spi0_event_handler(nrf_drv_spi_evt_t const /**< Set to @ref NRF_DRV_SPI_PIN_NOT_USED
* p_event) * if this signal is not needed. The
{ * driver supports only active low for
spi0_xfer_done = true; * this signal.
} * If the signal should be active high,
* it must be controlled externally. */
Now everything is in place. The next steps involve uint8_t irq_priority; ///< Interrupt priority.
initializing the SPI portal. To do this, we will pass the uint8_t orc; ///< Over-run character. th
structure information we have created to yet another /**< This character is used when all c
structure called spi0_config: bytes from the TX buffer are sent, st
but the transfer continues due to c
nrf_drv_spi_config_t spi0_config = NRF_DRV_SPI_ RX. */ a
DEFAULT_CONFIG; nrf_drv_spi_frequency_t frequency; ///< SPI h
///< frequency.
Our spi0_config structure is based on the nrf_drv_spi_ nrf_drv_spi_mode_t mode; ///< SPI mode. th
config_t type: nrf_drv_spi_bit_order_t bit_order; ///< SPI bit d
///< order. re
/** } nrf_drv_spi_config_t; tr
* @brief SPI master driver instance configuration
* structure. We have previously used macros to populate
*/ structures. One would expect we can continue that
typedef struct tradition here. You are correct. We can:
{
uint8_t sck_pin; ///< SCK pin number. /**
uint8_t mosi_pin; ///< MOSI pin number * @brief SPI master instance default
* configuration.
*/
#define NRF_DRV_SPI_DEFAULT_CONFIG \
{
\
.sck_pin = NRF_DRV_SPI_PIN_NOT_USED, \
.mosi_pin = NRF_DRV_SPI_PIN_NOT_USED, \
.miso_pin = NRF_DRV_SPI_PIN_NOT_USED, \
.ss_pin = NRF_DRV_SPI_PIN_NOT_USED,  \
N
.irq_priority = SPI_DEFAULT_CONFIG_IRQ_ \
PRIORITY, \ p
.orc = 0xFF, \ p
.frequency = NRF_DRV_SPI_FREQ_4M, \ a
.mode = NRF_DRV_SPI_MODE_0, \ si
.bit_order = NRF_DRV_SPI_BIT_ORDER_MSB_ \ P
FIRST, \ S
n PHOTO 2. The relocation of the SPI portal is purely } d
logistical. The double row of pins allows us to insert our
Saleae Logic into the SPI signal path. Unfortunately, we can’t use most of the default w
58 January 2017

Eady - Design Cycle - Jan 17.indd 58 12/5/2016 8:17:07 PM


settings found within the macro. After all, we have
D defined an SPI portal and the GPIO pins that go
with it. We have the power to override the default
configuration values that the macro defines:

D nrf_drv_spi_config_t spi0_config = NRF_DRV_SPI_


DEFAULT_CONFIG;
spi0_config.ss_pin = SPI_SS_PIN;
spi0_config.miso_pin = SPI_MISO_PIN;
D spi0_config.mosi_pin = SPI_MOSI_PIN;
spi0_config.sck_pin = SPI_SCK_PIN;
spi0_config.frequency = NRF_DRV_SPI_FREQ_125K;
APP_ERROR_CHECK(nrf_drv_spi_init(&spi0, &spi0_
, config, spi0_event_handler));
/
The SPI configuration overrides are obvious to
the most casual observer. At this point, we have a n FIGURE 1. With our help, the MPLAB Code
complete set of SPI structures. We have the instance Configurator assigned these SPI Slave portal pins. There
structure (spi0) and the configuration structure (spi0_ is also a dataRdy pin which we will use to signal the SPI
config). The SPI initialization function also requires Master.
a reference to the spi0 event handler, which we also
have. Curiosity board you see in Photo 2. The Curiosity
. The SPI data storage spaces are allocated and development board’s PIC layout is detailed in Figure 1.
. the data to transfer (NutsVolts) has been previously Our goal is to transfer a byte of data from the SPI Slave to
t defined. Since we are not expecting any particular the SPI Master. The transfer will be triggered by a signal
response from an SPI Slave device, we can pull the from the SPI Slave on the dataRdy pin. An SPI Slave device
trigger on an SPI exchange at will: normally supplies stored data (EEPROM) and sensor data
on demand to the SPI Master.
//Clear rx buffer and reset transfer done The SPI Slave transfers data just like the SPI Master.
//flag However, the SPI Slave relies on the SPI Master’s
memset(m_rx_buf, 0, m_length); clock signal to spin the bits out of its buffer. Within the
spi0_xfer_done = false; perspective of a PIC microcontroller, that bit buffer is
SSPBUF. In our application design, the SPI Slave drives the
APP_ERROR_CHECK(nrf_drv_spi_transfer(&spi0, m_ dataRdy signal logically low when it has placed valid data
tx_buf, m_length, m_rx_buf, m_length)); in its SSPBUF. The nRF52832 SPI Master sees the dataRdy
line go logically low and begins a data exchange. The data
while (!spi0_xfer_done) that was loaded into the SPI Slave’s SSPBUF is clocked out
{ to the SPI Master.
__WFE(); At the same time, whatever is in the SPI Master’s
\ } SSPBUF is clocked over to the SPI Slave. In our case, we
\ don’t care about the SPI Slave’s clocked in data from the
\ SPI Master. However, if we did care, we could retrieve
\
Now for Something Totally Different the incoming SPI Master byte and use it. Here’s what our
\ Not really. However, we are going to change the MPLAB Code Configurator-generated Curiosity SPI Slave
\ positon of our SPI Master portal. Moving the SPI Master driver code looks like:
\ portal to pins P0.25 (MOSI), P0.26 (MISO), P0.27 (SCK),
\ and P0.28 (SS) makes it a bit easier to monitor the SPI uint8_t SPI_Exchange8bit(uint8_t data)
\ signal activity. This becomes obvious when you look at {
\ Photo 2. We can now plug our Saleae Logic into the uint8_t dummyRead = SSPBUF;
\ SPI signal path between the nRF52832 and Curiosity //Clears buffer full flag
development board. // Clear the Write Collision flag, to allow
We are going to let the MPLAB Code Configurator // writing
write our SPI Slave code, which we will run on the SSP1CON1bits.WCOL = 0;
January 2017 59

Eady - Design Cycle - Jan 17.indd 59 12/5/2016 8:17:07 PM


SSPBUF = data; The dataRdy line (P0.29) on the nRF52832 SPI Master is
while(SSP1STATbits.BF == SPI_RX_IN_PROGRESS) is configured as an input. We are not doing anything fancy c
{ and simply poll the incoming dataRdy signal looking for a
} logical low: N
return (SSPBUF); d
} static uint8_t m_tx_buf[4] = a
{0x31,0x32,0x33,0x34}; c
The SPI Master driver code is very similar. The SPI //extra byte in rx_buf for NULL character S
Master starts to clock when data is loaded into SSPBUF. static uint8_t m_rx_buf[4]; w
The completion of the SPI exchange is signaled by a full //number of bytes to transfer = m_length
SSPBUF. The same SSPBUF full logic is valid on the SPI static const uint8_t m_length = 1;
Master side of the connection.
W
This is a snippet of our SPI Slave application code nrf_gpio_cfg_input(29,NRF_GPIO_PIN_NOPULL);
which resides within the main function: while (1) th
{
uint8_t rxBuf[4]; //Clear rx buffer and reset transfer done flag
uint8_t txBuf[4] = {0x41,0x42,0x43,0x44}; memset(m_rx_buf, 0, m_length);
uint8_t pktLen = 4; spi0_xfer_done = false;
uint8_t dataFromMaster; if(nrf_gpio_pin_read(29) == 0)
{
dataRdy_SetHigh(); nrf_delay_ms(100);
i=0; APP_ERROR_CHECK(nrf_drv_spi_transfer(&spi0,
while (1) m_tx_buf, m_length, m_rx_buf, m_length));
{ while (!spi0_xfer_done)
dataRdy_SetLow(); {
dataFromMaster = SPI_Exchange8bit(txBuf[i]); __WFE();
if(++i == 4) }
{ while(nrf_gpio_pin_read(29) == 0);
i = 0; LEDS_INVERT(BSP_LED_0_MASK);
} nrf_delay_ms(200);
dataRdy_SetHigh(); }
} }
n
S
The SPI Slave drives the dataRdy signal logically just When a logical low is sensed on the dataRdy
before it places data from txBuf into the SSPBUF. The pin, the SPI Master begins the exchange. When
Curiosity development board’s PIC then waits until the SPI the SPI exchange is complete, the SPI Master polls
exchange is complete before returning the dataRdy signal the dataRdy line looking for the SPI Slave to drive it
to a logical high state. logically high. Just for fun, we flip the blue LED which
0
D
S
D
R
a
I

0
1
F
d
a
a

P
n SCREENSHOT 3. Our nRF52832 Master device is at work. Every SPI signal you see in this capture was generated by U
the nRF52832. Since there is no Slave device attached, the MISO line is seen as a logical high for the duration of the
data exchange.
60 January 2017

Eady - Design Cycle - Jan 17.indd 60 12/5/2016 8:17:09 PM


ADVANCED TECHNIQUES FOR DESIGN ENGINEERS

is attached to the nRF52832, to visually signal a nRF52832. In the meantime, check out the Nordic
completed data exchange. Semiconductor website, build up an nRF52832 jig,
The SPI operations can be seen in Screenshot 4. and write some Bluetooth Low Energy code of your
Note the SPI Master always clocks out an ASCII 1. It own. NV
doesn’t matter in this case what the SPI Master sends
as we’re only interested in the SPI Master supplying a
clock to retrieve the SPI Slave data. As you can see in Raytac MDBT40 BLE Module
Screenshot 4, the SPI Slave sends one byte of its txBuf Raytac
with each data exchange cycle. www.raytac.com

We Ain’t Done Yet nRF52832


Nordic Semiconductor
There is much more we can glean from www.nordicsemi.com
the Raytac BLE module that houses a Nordic

n SCREENSHOT 4. Each cycle of data exchange transfers two bytes: one from the SPI Master (ASCII 1) and one from the
SPI Slave (txBuf[i]).

Your Single Source of Electronic Equipment, Tools, and Components

01DM820B 01DMMY64 01DMM9803R Sweep Function Generator


Digital Multimeter Digital Multimeter Bench DMM 3MHz, 6 Waveform Functions, Int/Ext Counter,
Super Economy 32 Ranges True RMS lin/log sweep
DMM - Volts, current, Including temperature, Auto and manual Model FG-30 $135
Resistance, Transistor capacitance, frequency range, RS232C (no display)
and Diode Test. and diode/transistor standard interface. Model FG-32
$7.50 $139.95 $195
Includes Leads testing
$29.95 Runs on DC or AC (5 digit display)

01DS1102E 01SDS1052DL DC Power Supplies


100MHz Rigol Oscilloscope Siglent 50MHz DSO Model HY3003
Variable Output, 0-30VDC,
Features: 1 million points of
deep memory, FFT, record
500MSa/s Sampling
32K Memory 0-3Amp. $95
and replay, roll mode, alternate trigger mode, and 6 Digit Frequency Counter Model HY3003-3
USB Interface Two 0-30VDC, 0-3Amp Variable
adjustable trigger sensitivity
$399 7” Color TFT-LCD Screen $279 Outputs plus 5V 3A fixed. $195

Parallax Board of Education Full Kit BOE Full Kit $98.90 0603ZD98
48W Soldering Station
USB version with Stamp and USB Cable. Parallax 7.5V Power Supply $8.95 Temp. Controlled
$15.25
310oF~840oF

1 (800) 972-2225 | http://www.elexp.com | contact@elexp.com


January 2017 61

Eady - Design Cycle - Jan 17.indd 61 12/5/2016 8:17:10 PM


TECHFORUM READER - TO - READER

>>> QUESTIONS and tolerances of components? For practical use of a small ultra capacitor p
example, if my power source is 12 is to maintain a CMOS memory while th
Uno-Known Device volts, is an electrolytic capacitor with the set is unplugged.
I’ve used the Arduino IDE with a 24V rating “better” than one with a Chip Veres
a genuine Arduino Uno board 16V rating? What do good designers Miami, FL
for experiments for a few months use as a margin?
without trouble. Recently, I wanted to #1174 Enrico Gutiérrez [#9163 - September 2016] to
permanently put an Uno in a desktop Panama City, FL Cassette to MP3 ja
project, so I purchased some budget I have a box of cassette audio st
Arduino Uno compatible boards. The >>> ANSWERS tapes that I want to convert to MP3 V
budget boards seem fine, but the [#9162 - September 2016] format. What’s the simplest way to o
Arduino IDE doesn’t recognize any of What’s The Deal With Ultra Caps? do it? I have a Windows 10 PC and a A
them. When connected, the boards I am looking to experiment with Nakamichi CR-2A cassette deck. p
show up as an “Unknown Device.” “ultra capacitors” as a replacement
I am using Windows 7 32-bit. Does for AA batteries. Is this possible to #1 There is a very good little box (i
anyone have any pointers on how to do and, if so, what kind of capacitors made just for transferring LPs and a
make this board work? would be a good place to start? CDs to MP3 or wave format. It’s e
#1171 Michael Allison made by DAK and costs $69.90. a
Camden, NJ #1 The short answer is NO. The See the link: www.dak.com/ Fo
main function of ultra caps is for reviews/2021story.cfm. so
Trainsformer Needed TEMPORARY backup of memory The box accepts stereo input th
I found a bargain at a local thrift type devices (i.e., clocks in DVD from any source (including a A
store and now have a 1959 Marklin players) during brief (i.e., less than a microphone), provides for balance si
HO Scale train, cars, and track. The day) power outages. They are NOT and loudness adjustment, digitizes Fo
set didn’t come with a transformer, so suitable nor designed to replace it according to the resolution you si
I thought it would be a fun project to batteries simply because, as they are want, and prepares a file for a CD. to
build from scratch. Does anyone have electrolytic capacitors, they need You can name the flie and see the w
a schematic or suggestion for a DIY recharging when their stored energy audio as it is played. This is especially lik
train transformer they can share? is depleted. Also, they’re not really useful in that you can ensure that a
#1172 Alfred Thompson designed for current loads greater the signal is not being clipped. One
Kingsport,TN than a couple hundred microamps. can then run the file(s) through a
This subject has come up a few times hiss and click reduction program,
Turn Signal Signal in the past couple of years and I which is especially good as it is based [#
I have a newly restored 1971 believe N&V had an article comparing on an algorithm rather than just F
Honda CB350 motorcycle that I ultra caps to batteries (primary and clipping spikes. Thus, it works on low
ride for fun on the weekends. One rechargeable). amplitude as well as high amplitude sw
problem is forgetting to turn off the Ken Simmons signals. co
turn indicators. I have found a kit that Auburn, MI The latest software also has a a
“beeps” every time the indicator lights feature which will automatically take p
up, but it's very annoying as I sit at a #2 This is only practical when the out the large gap one may have
light. I would like a circuit that would current draw is very low. A coulomb between sides of tapes or LPs, leaving
alert me only if the turn indicator is one amp-second. By definition, a only, say three seconds. I have found u
stays on for more than two minutes. one-Farad capacitor charged to five the whole process very satisfactory
Schematic would be welcome! volts can deliver five coulombs. A though time-consuming, as one in
#1173 Leland Collins single AA battery can deliver at least must — of course — pay a certain n
Gulfport, MS 1,350 coulombs. This is because the amount of attention to whether the —
material of the battery is consumed tape or LP is finished when doing the d
How Much Tolerance Is Enough? when it is delivering current. The conversion. The ideal thing is to have c
When designing circuits, is there capacitor isn’t consumed; it’s just a two screens on your computer so you n
a rule of thumb for picking voltages tank for electricity. About the only can keep your eye on the conversion
62 January 2017

Tech Forum - Jan 17.indd 62 12/5/2016 11:51:12 PM


>>>YOUR ELECTRONICS QUESTIONS ANSWERED HERE BY N&V READERS

Send all questions and answers by email to forum@nutsvolts.com


or via the online form at www.nutsvolts.com/tech-forum

r process while doing other work on solution is readily available from them out. Today, there are power
e the other screen. Harbor Freight Tools. Item 43060 MOSFETS but they aren’t very fast. So
John Drake is a “Router Speed Control” and the existing MOSFETS tend to fall in
es Ann Arbor, MI works great with inductive AC or DC two families: Fast but fragile, or strong
L motors up to 15 amps (120 VAC). but slow. Kind of like people.
#2 Quite easy to do. You need I have several to vary the speed Chip Veres
to get a cable to go from the RCA of many tools, not just my router. Miami, FL
jacks on your cassette deck to a Costing about $15 a piece, I use this
stereo mini plug to go into your PC. controller with my five-speed wood [#10162 - October 2016]
Very common, but if you can’t find drill press (when drilling soft metals Fish Caller Circuit
one, then Amazon has them. Dynex that require slower speeds); with I found a partially assembled kit
A20420 and many others. For your Harbor Freight’s largest “hurricane” labeled “Fish Caller.” Does anyone
purposes, practically anything will do. fan (which also has a HI/MED/LOW/ have a schematic for one that I could
Then, download Audacity, which OFF switch); and other AC powered use to finish it? Also, what’s the theory
(in my humble opinion) is the best fixed speed tools. behind how it works ... or does it?
audio editing program out there — Equipped with a 15 amp
especially since it is free. Go to www. 3AG type fuse and a three-prong #1 Seriously, you can find all the
audacityteam.org for the details. receptacle, this lightweight controller circuits you want by Googling “Fish
For MP3 export, you’ll also need is hard to beat and much safer to use. Caller Circuit” and looking at the
something called LAME, available on BGoodWill KD2FZU images. Less than seriously, it emits
the Audacity site. Play your tapes into Rahway, NJ Fishy Language for “Neener, neener,
Audacity, then export them either as neener! You can’t catch me!”
single songs per file or entire sides. #2 Danger Danger! The typical Chip Veres
For that matter, you can capture both lamp dimmer is not compatible with Miami, FL
sides of the tape and use Audacity the typical cheap fan motor. There
to remove the dead areas that occur are good articles on the Web as to #2 I built one years ago. It was
while changing sides. Or, if you only why. Look up shaded pole speed designed to produce a high frequency
y like a couple of the songs, just copy control and see why. That said, I find noise that supposedly attracted fish.
and paste what you want. that box fan motors tend to be okay Maybe my fish were hard of hearing
Jerry McCarty with better (triac based) motor speed but it never worked in my field trials.
via email controllers, such as sold by Harbor I have never seen them promoted in
Freight and on eBay. On a shaded any fishing supply catalogs either.
d [#10161 - October 2016] pole motor of a typical cheap fan, M. Herman
Fan Conversion overheating the motor is possible. LaQuinta, CA
My desk fan has a three-position Jim Lacenski
switch: HI/OFF/LOW. I would like to Bellevue, WA #3 Theory: It makes a ticking
convert the fan to variable speed. Will sound that sounds like a dying fish
a simple lamp dimmer work for this [#9164 - September 2016] which attracts other fish.
purpose? Transistor Training You might try https://www.
I’m retired and re-learning electronickits.com/electronic-fish-
g #1 Please do not even think of electronics. I am confused about the caller-plan. On the other hand, if all
using a simple lamp dimmer for this! differences between MOSFET and it does is tick, you now know what
Lamp dimmers are for “regular” transistors. Is there a rule of the circuit is supposed to do and you
incandescent (filament) bulbs only — thumb as to when/where/why you might be able to complete it with just
not inductive motor (AC or DC) loads would use one over the other? that much information. The above link
— and will likely cause a fire! A lamp sells plans to build such a thing. There
e dimmer connected to a ceiling fan Traditionally, MOSFETS were used are others selling kits as well. I simply
caused such a fire, nearly burning my for small-signal amplifiers and mixers, did a web search to find the above.
u neighbor’s house down! Don’t do it. particularly at high frequencies. High Phil Karras
The easiest, cheapest, and safest currents or voltages would easily burn Mt Airy, MD
January 2017 63

Tech Forum - Jan 17.indd 63 12/5/2016 11:51:55 PM


Reader Feedback - Jan 17_Dev Perspectives - ReadFeed Feb15.qxd 12/5/2016 10:26 PM Page 64

READER FEEDBACK
Continued from page 7

meets or exceeds 60% of the investment I will have to incur, Defining Electronics
I will order from the OEM and take my chances on selling the
rest. I will keep you posted as to the status of this offer. Electronics: The study of the electrical properties of and
Robert Reed the use of electronic devices.
Electronic devices include resistors, capacitors, inductors,
Anode + Cathode = ? diodes, transistors, integrated circuits, antennas, waveguides,
electronic tubes, batteries, etc.
I would like to point out an error on the picture of an Electronics includes laying out circuit boards — signal
LED. The schematic symbol polarity is reversed. The device crosstalk, current limit for a given width of trace, impedance
matching, skew of parallel signals, etc.
should be: cathode + and anode -. If the device is hooked up A person experienced in electronics will know how to
as pictured, it will destruct. You might want to print a assemble a circuit and how to solder the connections.
correction in the magazine. Programming DSPs, FPGAs, CPLDs, SoCs,
Mike Jobe microcontrollers, computers, etc., is just that — programming.
Marion, IL Programmers do not need to know which end of a soldering
iron to grab. (There has been talk over the years that BSEE
graduates don’t know that either.)
Thanks for having a look at the article. The LED drawings I like the mix of articles and the mix within articles in
on page 24 of the October 2016 issue appear to be correct. Nuts & Volts Magazine. This includes programming articles
Have a look at "LED" on Google Images. An LED must be about microcontrollers that react to and affect real world
biased in the forward direction in order to emit light. Thus, + devices. I would not change anything — not the articles nor
to the anode and - to the cathode. This terminology of the name.
cathode and anode is from the days of vacuum tubes: In a If you were to change the magazine’s name to Keyboards
and Microcontrollers, please consider that this new name
vacuum tube, electrons flow from cathode to anode, so the would make the magazine sound like a purely programming
current direction (defined as the flow of positive charges) is magazine and you would probably not get any new readers
from anode to cathode. that are interested in electronics.
That said, if you were to connect a low impedance We need Nuts & Volts!!! I know of no other magazine
voltage source — say a battery — of sufficient voltage to the that fills the bill for me. I like to read the mid-level articles in
LED in the polarity pictured, the LED would indeed destruct N&V and the ideas I get from N&V. I like to find out about
after a brief flash. So, a current-limiting resistor is needed, the new devices used in your articles and mentioned in your
New Products department such as the DS1820 temperature
which is the purpose of R3, R4, and R16 in the circuit. sensor, the S.USV Pi, and the EXasPiB.
I did notice one small glitch: the upper-right paragraph on My background?
page 26 refers to Figure 7; the reference should be to Figure - Took the Cleveland Institute of Electronics first phone
10. course.
Randy Keenan - Got my first phone FCC license 48 years ago. (Yup. I’m
almost older than dirt.)
- Was trained in television electronics — receivers and
broadcast equipment — in the Army (MOS 26T).
- Graduated from the Univ of MN with a BA in Industrial

CLASSIFIEDS Education, Electronics.


- Worked as a technician and logic designer.
- Most of my employment has been as a computer
programmer — IBM mainframe and PC, have programmed in
ROBOTICS LIGHTING more than 25 languages.
- Taught myself PIC16F, PIC18F, and PIC10F
  programming.
- Have programmed and designed the electronics for
several microcontroller projects using the PIC18F4685,
PIC18F2455, PIC16F767, and PIC10F200.
- Since retirement, I volunteer as the studio engineer for
a 50 KW AM station.

PIC programming is so fun because there are no


HARDWARE problems from an RTOS or other operating system — there IS
NO operating system. I’m programming right down at the
WANTED hardware level!
Keep up the good work at N&V and please don’t change
DEC and VME anything.
Equipment WANTED! Mark Peterson
Digital Equipment Corp
and Thanks for the comments, definitions, and a glimpse of
Motorola VME Systems your impressive background. I don't think we have plans of
changing the name any time soon.
and Parts Bryan Bergeron
Buy - Sell - Trade

  CALL KEYWAYS 937-847-2300
or email buyer@keyways.com

64 January 2017

Вам также может понравиться