Electronica
Electronica
Hitec continues to expand our innovative D-Series servo line with the latest introduction of our Premium trio, the D930SW,
D954SW and D955TW. Powered by our 32-bit MCU (Microcontroller Unit) and 12-bit ADC (Analog to Digital Converter)
industrial science, this high-resolution, ultra-durable gear group delivers exactly what you need and have come to expect
from Hitec. Our D930SW is the perfect upgrade from the HS-8330SH; the D954SW replaces the HS-7954SH while the
D955TW is the advanced version of the HS-7955TG. Servo Engineering ReimagIned!!!
Hitec RCD USA, Inc. | 12115 Paine Street | Poway, CA 92064 | (858) 748-6948 | www.hitecrcd.com |
s
etail
ore d ibing,
Subscription Information
Fo r m r
ubsc n
on s our ad o
Nuts & Volts — PO Box 15277
se e 64.
North Hollywood, CA 91615-9218
Pag e Call 877-525-2539 or go to www.nutsvolts.com
Subscribe • Gift • Renewal • Change of Info
Devices
Departments
Here’s a quick beginner-friendly tutorial that shows you
Columns
how to interface and read data with this popular serial
protocol.
■ By Derek Hildreth
05 DEVELOPING 60 NV WEBSTORE
08 Q&A
PERSPECTIVES 62 TECH FORUM
What’s in Your Grab-and-Go? 65 CLASSIFIEDS
06 READER FEEDBACK 65 ELECTRO-NET
17 NEW PRODUCTS 65 AD INDEX
Workbench
Topics discussed this month:
• A Simple Current Source
• A Block Heater Power Indicator
4 July 2017
Bergeron - Developing Perspectives - Jul 17_Dev Perspectives - ReadFeed Feb15.qxd 5/30/2017 6:16 AM Page 5
Published Monthly By
T & L Publications, Inc.
430 Princeland Ct.
Corona, CA 92879-1300
(951) 371-8497
FAX (951) 371-3052
DEVELOPING
PERSPECTIVES
by
Bryan
Bergeron,
Editor
READER FEEDBACK
computers to monitoring and data been running Linux on my Dell Inspiron
Reader Response to breaches. 1545 laptop for over eight years. It is
Bryan Bergeron’s If you would like to fix your system, on the third keyboard; I forget how
June 2017 Editorial you will need to dump the OS and many batteries I have gone through. I
on “Real Electronics” reinstall everything from the ground up. am also on at least my fourth hard
The problem is probably not a drive. It came with MS Vista — which I
hardware issue. More than likely you never even booted.
The idea of computerizing
have viruses, spyware, and trojan I see little or no value in the
everything is all about squeezing more
horses. "Internet of Things." I have a few old
money out of the consumer. Washing
Another big drag on system Tek analog oscilloscopes which are
machines and stoves used to last 30
resources is Norton and other so-called definitely not Internet ready, but I can
years.
multi-use utility packages. Norton will fix them when they break. I do not
Now, the computerized versions
slow a system that can run Win7 at a need my microwave or toaster
last one to five years. Planned
decent speed by as much as 20%. Also, connected to the Internet.
obsolescence has reached new heights.
it only protects against infections that it The toaster pops when the toast is
Publicly traded corporations are
has definitions for. You see, the ready and the microwave beeps. They
required by law to be greedy.
infection is already on your system and do not need a web page. Imagine a
I have been a ham radio operator
your network before Norton can even hacker messing with your Internet
for about 50 years. I have radios from
do its job. Oops! Not good! connected toilet — or shower.
the 1950s and 1960s that still work
The best protection is with a wired I have a McIntosh amp (solid-state)
fine. My new computerized radio will
router/firewall. Wireless systems are which I have fixed three times in the 30
not last that long!
inherently insecure as the bad guys can years I have owned it. I also have a
Nowadays, most people are
sit outdoors with a laptop and steal Mac MX115 tuner preamp that is
carrying a tracking device with them
your data. Even if it is encrypted, they halfway through a recap.
(smartphone), screens have TV cameras
still have a copy of it and now they can I am much more a "fixer" than a
watching the viewers, politicians say
take it and use a much more powerful "maker." I enjoy fixing these old things
things that are the opposite of the
machine to break the encryption. and getting them working. It clears my
truth. George Orwell knew what he
I am an electronics hobbyist, head after a day of writing software.
was talking about in "1984." The
retired master automobile technician, Mike McGinn KD2CNU
Internet has its uses, but I don't want to
computer technician, and a somewhat
depend on it for everything. It will fail
competent programmer. I have seen a Hey Mike, I hear you. I enjoy
occasionally.
lot of changes in electronics and cars playing with the latest tech available,
Doug Reid
over the last six decades. I like being but at home use old reliable devices.
able to fix things without having to find My Mac amp is tube type. No Internet
Thanks Doug! I agree with most of
a technician to do it for me. connection to my refrigerator or
your points.
I am also an electronics and disposal. I too enjoy fixing things. That
Bryan Bergeron
computer scrounger. I really enjoy Nuts said, I have an elderly parent who lives
& Volts and drop everything else to alone and it would be great to verify his
My primary computer for years
read it when it shows up in my toaster was used in the morning, etc.
was a XP 32-bit machine running on
mailbox. I just wish that I had For me, however, give me the retro
hardware that I built. I do not buy pre-
subscribed to it sooner. God bless! tech.
made systems. I don't like the software
Richard R. Pope Bryan Bergeron
packages and I especially don't like
Reedsburg, WI
having only a recovery disc instead of
I feel your pain! I tried Ubuntu
the complete OS disc.
Thanks for sharing your experiences, (10.10) when I was gifted an old
I have built a dual processor MB
Richard. I'm right there with you on the Thinkpad. It loaded and ran fine.
with Intel Xeon E-2603 v3 six core
subscription services. I keep an old When I bought a new HP 15, the
CPUs running at 2.1 GHz. I have 32
machine on my desk with out-of-date first thing I did was to format over
GBs of RAM and I am running Win8.1
Photoshop and similar programs that I Windows 10 and install Ubuntu
64-bit Pro. I finally hit a wall with XP
own on disc. 14.04LTS. I think I spent $15 for a copy
and I needed Win8.1, but it won't run
Bryan Bergeron of Ubuntu Magazine just to get the
on my XP hardware.
distribution CD.
This will probably be my last MS
There are ways around the I installed Wine for the couple of
OS. I will not use OSes nor software
subscription software model. For office times I wanted to run a Windows only
that depends on a subscription service
software, there is Open Office and package.
and/or the Internet. These requirements
Libre Office. There is also Linux. I have James Lynes KE4MIQ
also open up your network and
6 July 2017
Reader Feedback - Jul 17_Layout 1 5/30/2017 6:18 AM Page 7
Thanks for reaching out with your but it is a disturbing trend. make a habit of storing my iTunes library
story. Yeah, I guess it's inescapable for Had this been the unofficial policy as local MP3 files, and backing those
those of us working with tech. back in the early days of computers, up.
Bryan Bergeron garage-based companies like Apple and I know that eventually the Apple
Microsoft would never have come to cloud will blow away with the other
I could not agree with you more. I fruition. Imagine if Motorola had stated clouds, or cost a fortune to access.
have been saying the same thing for that when you bought a 6805, you Bryan Bergeron
decades, but it goes so much deeper. could only use it in certain pre-
My first experience with the prescribed circuits.
"subscription" model was the failed I don't know about society as a
Would you like to receive Nuts & Volts’
Circuit City video disc, DIVX. You whole, but for me, I will stick with my
purchased the physical media at a physical LPs and CDs for music. I'll stick weekly content newsletter? You have
greatly reduced cost versus traditional with physical media (including my three ways to sign up:
DVD discs, and then each time you beloved LaserDiscs and Selectavision
wanted to watch the movie, you had to discs) for movies. I'll stick to open • Visit us on Facebook and click on “Join My
pay a "rental" fee. source programs and data I can modify
My first impression was, what to my hearts’ content — all stored and List.”
happens when this goes bust? You're running on my own hardware. • Using your cell phone, send
essentially stuck with a coaster. Sure As an independent thinker, I will
enough, my prediction came true do whatever I want with hardware that
“NVNEWSLETTER” as a text message to
shortly thereafter. I purchased with cold hard cash. 22828.
Now, despite that failed Derek Tombrello KM4JAG
• Visit the Nuts & Volts FAQs to sign up at
experiment, "cloud" based services
encompass almost every aspect of life. Thanks for sharing your thoughts. I nutsvolts.com/faqs
VUDU and its kin have taken up where
DIVX died; iTunes stores your music
library; TinkerCAD and other online
programs are gaining acceptance as the
norm; even your data is stored in the
cloud in many cases.
Every bit of this is doomed to
obsolescence by design. At least in the
case of DIVX, Circuit City could have
released a patch before going under
that would have unlocked the discs to
give buyers the multimedia for which
they paid. When companies like VUDU
go under, you've lost not only the
money you've put out on these
nonexistent ones and zeros, but you've
also lost the data.
Even worse than that, though, is
the public-accepted model of buying
hardware and being told by the
manufacturer what you can and cannot
do with it. The Nintendo 3DS leaps to
mind as but one example. I understand
the desire to hinder piracy, but piracy is
not the only reason to "root" hardware.
It would be like buying a PC and
Microsoft telling you that you cannot
install Linux on it. If you do, they will
disable your hardware. I can't
understand why the public in general
has collectively agreed to give so much
power over their lives to corporations,
July 2017 7
Q&A
n WITH KRISTEN A. McINTYRE
In this column, Kristen answers questions about all aspects of electronics, including computer
hardware, software, circuits, electronic theory, troubleshooting, and anything else of interest to
the hobbyist. Feel free to participate with your questions, comments, or suggestions. Send all
questions and comments to: Q&A@nutsvolts.com.
We start with the simple current source
• A Simple Current Source that you’ve probably seen me use before in this
column. It’s based on a bipolar transistor (see
Figure 1). To understand how it basically works,
• A Block Heater Power Indicator we will make some simplifying assumptions.
These assumptions are not entirely true, but
• Arduinos and LEDs — Redux allow us to look at the effects which are
dominant as the circuit tries to supply current.
For this discussion, we will assume that: a)
A Simple Current Source the base current is negligible; b) Vbe is always 0.6V; c) the
Q
I am doing some experiments and need a transistor can be modeled from collector to emitter as a
constant current source as a reference. Most current source itself; and d) that β — the current gain — is
of the designs I have seen appear overly quite high.
complicated to me, and the off-the-shelf units With these assumptions in place, you’ll notice that
are too expensive. Is there a simple constant current source the base is held at a particular voltage with respect to the
circuit design you can recommend? I need something in power supply common point using a zener diode, D1.
the range of 0-12V and 1-100 mA. In this case, it’s a 5V diode. With assumption b) above,
Terry Keith we can see that the emitter will be at 4.4V. Next, we use
Los Angeles, CA assumption a) to say that the emitter current is about the
same as the collector current. That means we can calculate
A
Building a functional current source is actually the emitter current by simply doing a V = IR calculation,
quite simple. The major considerations are how using 4.4V for V; R is the emitter resistor, R1 in the
much voltage and power needs to be supplied, schematic.
and how stable it needs to be — particularly With the values shown, the emitter current is 100 mA.
thermally. Let’s take a crack at this first without much Using assumptions c) and d) tells us that the collector will
consideration for stability. We’ll assume that we are going work to make its current be 100 mA also, if that’s possible.
to control the current with a simple resistor that could With that, we have a roughly 100 mA current source.
also be a potentiometer. Regulating the current under What are the limitations, though? First, you may notice
computer control with an Arduino or some other single that the lowest voltage at which the collector can be and
board computer is quite doable, but adds an extra level of still function as a current source is somewhere a bit above
complication. 4.4V. Below that value, junctions in the transistor might
become forward biased
that we don’t usually use
that way. Current might
begin to flow in ways that
break our assumptions,
and thus the current won’t
be what we expect.
Under some
circumstances, the
transistor will go into
saturation, keeping it from
responding quickly to
changes that might make
it behave as a current
source again. How can
we fix this to match the
0-12V range?
n FIGURE 1. Simple NPN current source. n FIGURE 2. “Upside down” PNP current source. There are a
8 July 2017
A Block Heater
Power Indicator
Q
I am a diesel
head who
drives a 2002
F250. I noticed
that when I plug in the
engine block heater, there
is no indicator light to
tell me that the cord is
actually attached to 120
VAC. Do you have a circuit
n FIGURE 3. JFET current source. for rigging up some kind of
indicator safely?
couple of different solutions. One n FIGURE 4. Thermally stabilized NPN current source. Mark Newsom
would be to lower this circuit below Franklin, TN
the 0V point (where the triangular ground symbol is). That
A
would work fine, but might be inconvenient. The other This should be a rather straightforward task, I’m
would be to turn the circuit upside down using a PNP thinking. There are a number of LED indicator
transistor, and raise the supply voltage to compensate for lights that you can buy that already have the
the 4.4V lost by the base voltage (see Figure 2). proper current-limiting resistors. This puts
Another thing we might do is reduce the voltage of everything in one package and keeps you from having to
the zener diode. This last technique has the drawback insulate everything quite so carefully with those small LED
of reducing thermal stability. Bipolar transistors have the leads and a resistor. A search on the Internet for “120V
characteristic that Vbe drops considerably with increases in LED” shows me many different lights of different colors
device temperature. FETs can also be used in a similar way that range around $3 to $5. You can just get a small panel
with fewer components (see Figure 3) using their property mount LED indicator. I would not recommend routing the
of voltage control at the gate, but FET Vgs thresholds are AC mains far from the heater since that might become a
also affected by temperature. hazard if there was ever a problem with the insulation.
Thermal compensation can best be done by using The LED indicator will likely flicker a bit from it only
another transistor (Q2, Figure 4) to put in some negative lighting on half of the 60 Hz sine wave, but that should be
feedback. This negative feedback will try to keep the fine for most people. I personally have a high flicker fusion
current constant based on Q2’s Vbe. This requires that rate, so I tend to notice that. Anyway, carefully solder the
Q2 be thermally isolated from Q1. There is an additional LED indicator into the heater and mount it as you please,
benefit that the required voltage to
get Q1 to act as a current source is
reduced (it will work down to a little
above 2 x Vbe).
Note that you can easily invert
this to use PNP transistors. It doesn’t,
however, compensate for all thermal
variations — particularly ambient ones.
The best way to compensate for almost
all of the thermal variations — short
of matched devices — is to use large
amounts of negative feedback by
employing an op-amp with a precision
voltage reference (Figure 5). I have
used this technique on precision
measuring equipment I’ve designed.
The op-amp power supplies should
be between the 0V and 18V points. n FIGURE 5. Op-amp based current source with stabilized voltage source.
July 2017 9
Q
I once came across a minimal component also try to measure the current. With the thermometer, I’ll
design with an ATtiny and LED without a resistor see if the part or the LED heats up beyond a reasonable
and had the same question as Mike in the temperature for the devices in question. Here we go.
February column: Wouldn’t this burn up the I wrote a couple of lines of Arduino code to make
microcomputer? I don’t think 20 mA is a current-limited pin 6 an output and high, and began the experiment by
output; it’s the safe maximum current without converting letting the Arduino board’s temperature stabilize in that
the driver transistors into fuses. The datasheet does have configuration. I took a reading of the Atmel device’s
the answer in the Pin Driver Strength graph showing output temperature with the infrared thermometer. I then
source/sink voltage vs. current (the graph stops at 20 mA, downloaded the code and measured the voltage on pin
i.e., is not a knee). 6 with no load. The starting values were 86˚F and 4.98V.
Carl Hage Those are the nominal values.
Next, I stuck the LED anode into the pin 6 header.
A
I have actually received a couple of responses I used a clip lead to connect the cathode to my digital
like this. My assertion was that the outputs ammeter, and the LED came on nice and bright blue.
are current limited and well protected. Who Measuring the current, it was 44 mA. That’s not bad for
knows, I might be wrong. There’s nothing like this device. I then reconfigured the meter to measure
an experiment to try to answer such a question. I have a the voltage with the LED in-circuit, and it was 3.46V.
bunch of LEDs in my parts box and an Arduino that I’m That’s about what I expected. It seemed to be working as
willing to sacrifice to the cause! I also have an infrared predicted. Refer to Figure 6 for a picture of the test setup
TS-4900
Computer on Module
Choose your own adventure. WiFi and Bluetooth Enabled
1 GHz i.MX6 Computer Module
Now Supporting Ubuntu Core
Now Supporting:
www.embeddedARM.com
10 July 2017
July 2017 11
K
en Gracey, the CEO of Parallax, has been my friend
for 20 years, and like me, he loves to teach people thing, now I can drag and drop programming blocks that
how to create with Parallax microcontrollers. Over generate standard code (Propeller compatible C).
the past year, I have seen a huge renewal in Ken’s love of BlocklyProp differs from more traditional programming
the Propeller — not that it has ever waned, mind you. With tools in that it is web-based and runs through a browser.
the implementation of a new programming tool, Ken On our end, we run a small client app which allows the
seems to be on a non-stop tear around the country BlocklyProp server to provide compiled code that is
teaching students and their teachers the joys of Propeller downloaded into a Propeller board. This does, of course,
programming. His joy is infectious, and that — I believe — require a live connection to the Internet to run
is the key to inspiring others. BlocklyProp.
The tool I speak of is called BlocklyProp: a visual Being web-based, there is a bit of a process to get up
programming environment based on Google’s Blockly and running, but don’t worry! It’s quite painless. First,
which, in turn, is loosely based on MIT’s Scratch point your browser to:
programming language.
There are several implementations of Blockly for a http://blockly.parallax.com/blockly
variety of platforms. For example, MIT App Inventor 2 is
used to create Android applications. This was my first Click on the Register Now! link and provide the
exposure to Blockly programming, and I have used it to necessary details: screen name, email, and password. A
create several small mobile apps that communicate via confirmation email will be sent to you. You’ll click on a
Bluetooth with various Propeller boards. link in that email to confirm your registration.
Some will logically wonder why an experienced At this point, you can go to the BlocklyProp home
programmer would embrace a system clearly intended for page and log in with your email address and password.
beginners. I can give you a couple reasons. First, it’s a Once logged in, you’ll need to download and install the
proven programming tool, and as I love to help others get BlocklyProp client. There is a link at the bottom of the
started in microcontrollers, this may be the nudge that page for this. Download the installer that is appropriate for
pushes a newcomer over the edge into writing their own your computer: Mac, Windows 32-bit, or Windows 64-bit.
programs. Most newcomers find Blockly inviting, and the After running the client installer, it’s a good idea to restart
colorful drag-and-drop blocks help them succeed with your computer to ensure the latest FTDI drivers are
simple projects very quickly as they work through to more running.
complex tasks. I allowed the installer to create a desktop shortcut for
Here’s another reason: Being a visual programming the client. Double-clicking brings up the client window as
environment, Blockly engages different areas of the brain. shown in Figure 1. Click Connect to start the client, then
I frequently step away from my computer to draw click Open Browser; this second step will open your
12 July 2017
McPhalen - Spin Zone - Jul 17_Spin Zone - Aug 15.qxd 5/30/2017 6:19 AM Page 13
To post comments on this article and find any associated files and/or downloads, go to
www.nutsvolts.com/magazine/issue/2017/07.
you to read the preceding paragraphs than it would to for practical delays where a milliseconds timer would be
build a simple program like this from start to finish. That’s more convenient.
the point: BlocklyProp allows us to build a program If you’re a regular reader, you know that I’m not a big
through an intuitive process and does us the big favor of fan of the Arduino, but I do use it from time to time to
handling pesky syntax details like curly braces and help my friends. One of its saving graces (for me) is the
semicolons (something I always forget about when millis() function that gives us the number of milliseconds
programming in C). since reset. Using millis(), we are able to create programs
In listening to Ken talk about BlocklyProp, this is about that appear to multi-task.
the extent of instruction that most students need. After Here’s how we can use it (this is pseudo-code):
that, they are allowed to roam free in the system to
xtimer = millis
accomplish personal or assigned tasks. You should do that ytimer = millis
too (after finishing my column, of course).
Explore the menus. If you’re new, some items may not repeat forever
if (millis – xtimer) >= XTIME
make sense right away, so ignore them until later. If you’re xtimer += XTIME
an experienced programmer, this is the time to get a feel do_x_process
for the various menus and the elements they contain. if (millis – ytimer) >= YTIME
For those that want to take a look under the hood, ytimer += YTIME
click on the Code button in the upper right-hand part of do_y_process
the screen. Here’s what we get:
This simple framework adds a lot of power to
/* SERIAL_TERMINAL USED */ applications, allowing us to do more work in a core (the
// ——— Libraries and Definitions ———
#include “simpletools.h” Arduino only has one) while not wasting time with
pause().
// ——— Main Program ———
int main() The first step is to synthesize a milliseconds timer in
{ the Propeller. We will create a function that manages the
while (1) timer; this function will contain an infinite loop that will be
{
print((“Nuts & Volts”)); launched into its own cog. From the Functions menu,
print(“\r”); drag a function block onto the work space and name it
high(26);
pause(500); “background.” From the Variables menu, drag a variable
low(26); block onto the canvas and change its name to “ms1Tix.”
pause(500); This value will be the number of system clock ticks in one
}
}
millisecond, which is to say the clock frequency divided
by 1000. Can we have a variable assignment that is an
In the beginning, we don’t need to look at the expression in BlocklyProp? We can.
generated C code. Down the line, however, BlocklyProp Open the Operators\Numbers menu, drag a math
will likely become a bridge to programming with operator (topmost) block onto the canvas, and connect it
traditional tools. For my part, I copied the code produced to the ms1Tix block. Now, set the operator to division. In
by BlocklyProp into SimpleIDE, made modifications, and the System menu, locate the system block and drag this
ran it. into the first parameter space of the math operator block.
The blinker project that we just created could, in fact, The system block defaults to “counter.” Change this to
run on any microcontroller that has a Blockly “clock frequency.” Complete the expression by dragging a
environment. The ability to use multiple cores is what sets number value block from the Values menu into the
the Propeller apart from the rest, and even in a beginner- second parameter space of the math operator block, and
friendly system like Blockly, we can create sophisticated then change the value to 1000.
multi-core programs. By now, you have the hang of using BlocklyProp, so
The output of the next LED blinker program will I’m going to point you to Figure 4 as a guide to
match the first, but will use a framework that allows us to completing the background function.
do other work while waiting for the time to change the Here’s what’s going on in the background function: A
state of the LED. The lesson here is that pause() is the variable called ms1Tix is initialized to the number of
devil and should be avoided when possible. system clock ticks in one millisecond. Next, a variable
Okay, then. How do we create a delay without using called sysMillis (our timer) is initialized to zero. The final
pause()? A simple way is to track the time between two variable, sysT0, is initialized to the current value of the
points. system timer. This variable allows us to run the repeat
As you may know, the Propeller has a system counter loop at exactly 1,000 Hz.
that runs at the system clock speed; in BlocklyProp, this Inside the repeat loop, we add the value of ms1Tix to
defaults to 80 MHz. This is great for short delays, but not sysT0 to create a new target for the Pause until block.
14 July 2017
McPhalen - Spin Zone - Jul 17_Spin Zone - Aug 15.qxd 5/30/2017 6:20 AM Page 15
■ FIGURE 4. Background
function.
T IN G
U V P R IN
F E R IN G
NOW OF
T PA N E L
FRON N E RI T
I G
D E S – WE MACHINE
GN IT
YOU DESI re s
lo s u
ls & E n c
C u s to m Pane
c tu ri n g
a n u fa
tM
■ FIGURE 5. Modified w a re
A D S o ft
LED blinker. tF re e C
h ip p in g e n ts
tF re e S e q u ir e m
im u m O rd e r R
tN o M in
5 Days
tB u il t in
www.frontpanelexpress.com
Parallax, Inc.
www.parallax.com
Propeller boards, chips, and programming tools
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.
em
e Controlled
310oF~840oF $15.25
■ HARDWARE
range as BR/EDR or
BPA LOW ENERGY classic Bluetooth.
BLUETOOTH The Bluetooth low
PROTOCOL energy specification
allows new lower power
ANALYZER wireless devices to
BUILD IT YOURSELF
I hope you enjoyed “Spinning” into near space last month, where we introduced a
flight controller that you can use in your own near space ballooning projects. This
month, we’ll introduce the program and highlight a few of its key features. The
program has evolved over the past five years to keep up with changes in the flight
controller and to accommodate new sensors. Although it works as-is for the specific
flights we completed in the past, you should review and modify the program to meet
your own needs.
18 July 2017
Levergood - Spinning into near space Part 2 - Jul 17_Blank Project NV.qxd 5/30/2017 6:23 AM Page 19
To post comments on this article and find any associated files and/or
downloads, go to www.nutsvolts.com/magazine/issue/2017/07.
Overview of the Code ALTCUT = 175 ' cut initiated above the
' altitude (m) if mission
' time > ALTTIME(s)
ALTTIME = 60
Programming was done using the free Propeller Tool
programming software and Spin — the native language for DESC_EN = TRUE ' TRUE allows autonomous
the Propeller. We also relied on several library “objects” ' cut based on a continuous
' descent, false disables
from the Parallax Object Exchange. DESC_ALT = 10_000 ' altitude above which
For Mac users, you can run Propeller Tool under Boot ' descent cut is enabled
Camp™ or Parallels™. Or, download PropellerIDE from the ' (m)
DESC_REQ = 10 ' number of descent
Parallax website. At this time, it is beta. ' measurements needed to
The program has undergone many revisions since first ' initiqate a cut
written. You can download the current version and all the BURN_TIME = 30 ' elapsed mission time(s)to
needed objects in a zip file from the article link. You may ' burn cutter after cut
use if freely if the MIT license and credits to original ' initiated
authors are kept with the programs. WRITE_PERIOD = 2 ' # time interval between
' writes to SD card and PST
Mission Options RECO_EN = TRUE ' TRUE enables recovery
The program starts with a long list of constants that ' beeper, FALSE disables
are used to configure each mission: RECO_BEEP_TRIG = 12_000
' mission time (s) at which
' to start recovery beeps
CON 'Mission Options RECO_BEEP_PER = 15
' Mission box definition in seconds ' time period (in # of
' test Launch Site, Exit 10 Warner ' loops) between recovery
NORTH = 158_400 '44 deg ' beeps
SOUTH = 154_800 '43 deg
EAST = 255_960 '71.1 degrees VREF = 2500 ' reference voltage for ADC
WEST = 259_200 '72 deg ' (mV)
BASE_ALT = 50 'base altitude in meters,
'for pressure altimeter
'calibration Features can be enabled or disabled by assigning
certain constants a value of TRUE or FALSE, as detailed in
PST_EN = TRUE ' TRUE loads Parallax
' serial terminal; FALSE the comments. Other constants are assigned important
' does not numeric values specific to the mission. For example, the
ADC_EN = TRUE ' TRUE loads the ADC driver constants NORTH, SOUTH, EAST, and WEST define what
' at startup, FALSE does
' not we call the “mission box:” the boundaries within which
CTR_EN = TRUE ' TRUE enables the counter the balloon and payload are allowed to drift. You can scan
' at startup using CTRA, the comments to find the meaning of the others.
' FALSE does not
ALT_EN = TRUE ' TRUE loads the Parallax
' 29124 altimeter at GPS and Position
' startup, FALSE does not
Code in the main loop compares the current GPS
LEDSTROBE_EN = FALSE position to the mission box. If “out of bounds,” the global
' true starts the FAA variable outbox is TRUE:
' required strobe light
' driver. FALSE does not.
T_ON = 100 ' strobe on time (ms) 'assess GPS status-------------------------------
T_OFF = 1500 ' gate off time (ms) nsats := gps.n_satellites
if (gps.hasgps == FALSE or nsats < 4 )
MTIME_EN = FALSE ' TRUE allows autonomous ' test for valid gps signal
' cut based on mission High(LEDSatFXQ)
' time,FALSE disables ' turn on FXQ warning indicator LED
MCUT_TIME = 10 ' elapsed mission time(s) else
' when cut is initiated ' there are 4 or more satellites locked on
low(LEDSatFXQ)
MBOX_EN = FALSE ' TRUE allows autonomous ' turn off FXQ warning indicator LED
' cut based on mission box, latsecs := gps.n_lats+(gps.n_latm*60)
' FALSE disables +(gps.n_latd*3600)
BOX_DELAY = 60 ' elapsedtime (s) outside ' compute latitude in seconds
' the mission box before lonsecs := gps.n_lons+(gps.n_lonm*60)
' cutting +(gps.n_lond*3600)
' compute longitude in seconds
ALTCUT_EN = FALSE ' TRUE allows autonomous outBox := lonsecs > WEST or lonsecs <
' cut based on altitude, EAST or latsecs > NORTH or latsecs <
' FALSE disables SOUTH
July 2017 19
Levergood - Spinning into near space Part 2 - Jul 17_Blank Project NV.qxd 5/30/2017 6:23 AM Page 20
' check if outside mission box variable ttock that toggles every second, like a ticking
if outBox == TRUE
high(LEDMissionBox) clock:
' turn on alarm LED
else PRI softrtc | t0, i
low(LEDMissionBox) '' Software RTC
' not out of the box , turn off warning LED '' -- runs in standard "clock" mode
'' Jon "JonnyMac" McPhalen (aka Jon Williams)
'' Copyright (c) 2010 Jon McPhalen
The code that actually initiates a cut is contained in ''revised by ral, 2016.
the PUB Linecutter method. The balloon can be
t0 := cnt
autonomously cut free from the payload if the flight drifts repeat
beyond the mission box boundaries, the mission box if (Clock[REG_RST] < 0) ' reset flag?
MBOX_EN is TRUE, and signals from at least four GPS longfill(@Clock, 0, 6) ' yes, clear
' everything
satellites have been acquired. This is provided as an waitcnt(t0 += MS_001) ' wait 1ms
example. The method includes additional criteria for
cutting the payload free; for example, when descent is if (++Clock[REG_MS] == 1_000) ' one second?
Clock[REG_MS]~ ' clear ms
detected and at a certain time or altitude. ttock := 1
To prevent premature cutting, the payload must be if (++Clock[REG_SC] == 60)
' inc secs, check for 60
outside of the mission box for more than BOX_DELAY Clock[REG_SC]~
seconds before cutting: ' clear secs
if (++Clock[REG_MN] == 60)
'check for mission box state and evaluate cut -- ' inc mins, check for 60
elseif nsats >3 and MBOX_EN == TRUE Clock[REG_MN]~
if outBox == TRUE ' mission is outside ' clear mins
' of mission box if (++Clock[REG_HR] == 24)
if outTime == 0 ' if the out of box ' in hrs, check for 24
' clock is zero... Clock[REG_HR]~
outTime := missionTime ' clear hours
' set the initial out of box clock to the if (Clock[REG_DY] < posx)
' current mission time ' days below max?
else ++Clock[REG_DY]
dtime := missionTime - outTime ' increment
' time difference clock is current seconds minus else
' initial seconds ' else
if dtime > BOX_DELAY Clock[REG_DY]~
' cut if out of mission box for however many ' clear
' seconds
High(LineCut)
' turn on pin driving transistor/relay The clock is zeroed when the Flight Enable tab is
High(Beep) pulled by calling the resetClk method. Next, the main loop
' sound warning piezo
cutActive := TRUE starts and mission time is calculated using hour, minute,
' cut is on so set cut flag and seconds values accumulated by the softrtc method.
cutTime := missionTime
' define time cut turned on Notice that the missionTime unit is seconds — a
cause := 10 convenient scale for keeping track of time that avoids the
need for floating point values in units of minutes or hours.
if outBox == FALSE
'reset out of box clock The statement low(LEDSD) turns off the SD warning
dTime := 0 indicator LED if the SD card is successfully mounted:
outTime := 0
repeat until ina[FlightEnable] == 1
'hold until jumper pulled
Timing resetClk
Of course, it is important to keep track of time when
logging data. Because our total elapsed time will be a '------------------------------------------------
matter of a few days rather than weeks or months, a 'main loop
handy software clock by Jon McPhalen meets our needs '------------------------------------------------
repeat
(see N&V July 2010). The clock runs independently and ' used for testing
uninterrupted in its own processor (known as a “cog”). ' outa[RLY1]:=!ina[IN1]
' outa[RLY2]:=!ina[IN2]
The method is launched with this bit of code: ' toggle(Driver)
'start the software clock ---------------------- missionTime := (CLOCK[REG_HR]*3600)+(CLOCK
cognew(softrtc, @RTCStack) [REG_MN]*60)+ CLOCK[REG_SC]
pause(50) ' calculate mission time in seconds
The method itself is shown next. It includes a global ' assess SD card status ------------------------
20 July 2017
Levergood - Spinning into near space Part 2 - Jul 17_Blank Project NV.qxd 5/30/2017 6:23 AM Page 21
if (sdRecording == FALSE) into every Propeller chip (see Resources sidebar). They
'flight tab pulled, not yet recording SD card
OpenNewFile each work independently, so there are no worries about
'open new sd card file. OpenNewFile method missing a pulse while the processor is busy doing other
toggles value of sdRecording
if(sdRecording == TRUE) things.
' a 1 means card successfully mounted The code that reads the pulses is simple. First, the
low(LEDSD) counter is configured and started in a method named
'turn off warning LED
ctrInit. The counter the pulse count is totaled in is a
register that is accessed within the main loop, as shown in
The state of the ttock variable controls the frequency the code block above.
of the main program loop shown next. Execution in the This block of code also computes the average counts
loop is paused when ttock = 0, and continues when it is per minute for each interval before it writes to the SD
toggled to 1 by the softrtc method. This results in a one card, then zeros the register. The global variable total
second period for the main loop. Writes to the SD card maintains the pulse count total for the entire mission. This
occur at the time interval specified in the constants has worked very well, helping us detect the altitude at
section. This arrangement allows reading and responding which maximum cosmic radiation occurs (Pfotzer
to sensors every second, but reduces the amount of data maximum) on several missions:
written to the SD card to a manageable amount:
' pulse counter
' regulate write to SD card and PST------------- if (CTR_EN == TRUE)
if (missionTime => lastWrite + WRITE_PERIOD) ' check if Geiger counter or scintillator is
' write to SD card and PST at interval = ' used
WRITE_PERIOD cpm:=phsa*60/WRITE_PERIOD
lastWrite := missionTime ' compute mean cpm for the write period
' re-initialize lastWrite to current missionTime total:=total+phsa
if (sdRecording == TRUE) ' totalize the counts
' call write to SD card method if write function phsa := 0
' enabled ' zero the ctra
WriteSD (missionTime, meters, nsats,
cpm) SD Card Data and Serial Terminal Display Formats
if (PST_EN == TRUE)
PrintPST (burntime,meters, nsats, cpm) Two Spin methods are responsible for data output:
PUB WriteSD writes data to the SD card; PUB PrintPST
prints to the serial terminal. You will probably need to
Analog-to-Digital Conversion modify the code in both methods depending on what
The ADC is enabled using ADC_EN in the constants sensors you use. We included a lot of example code in
section. The following code reads the four ADC channels these sections for your reference.
and calculates the digital equivalent of the analog sensor
voltages: Future Modifications
After flying Version 1 and Version 2 many times, we
' get ADC data---------------------------------- are very pleased with the performance of the board. The
if ADC_EN == TRUE
' is ADC enabled? upgrades that led to Version 3 need flight time before we
repeat adcCh from 0 to 3 consider it “certified.”
adu [adcCh] := adc.read(adcCh,1)
' read analog to digital units After our PCB file was submitted for manufacturing,
mvolts[adcCh] := adu*vref/4096 we realized that it would be useful to allow quick
' convert to millivolts using 12 bit resolution selection of either onboard or external LEDs. A simple
' and reference voltage
pause(10) solution is a jumper that ties either group of cathodes to
ground. We added this feature to the design files.
The next step, of course, is to convert the voltage to The only planned upgrade to the code is to add the
the desired physical quantity such as, for example, BCD routine. Code to read the digital inputs and control
temperature or light intensity. How to do this depends on the two small relays and high current driver are not
the calibration equation for your specific sensor. We often included in the downloadable program. You can easily
leave the millivolt units in the SD card data file, and have add necessary code to the existing structure as the need
the students import the *.csv file into a spreadsheet arises.
program for further calculation and analysis.
Use of the Controller
Counter Starting up the controller in the field is simple if your
As described above, J8 is a handy way to connect sensors and software have already tested on the bench.
with devices that generate a pulse output. Counting pulses Start by inserting a micro-SD card into the card socket. We
is easily done using one of the 16 counter modules built have used a 2 GB SD card from Parallax many tens of
July 2017 21
Levergood - Spinning into near space Part 2 - Jul 17_Blank Project NV.qxd 5/31/2017 10:45 AM Page 22
times and they always work well. the controller is acquiring contact with GPS satellites. It
Next, power-up the board and watch the four will go off after four or more satellites are acquired. It
indicator LEDs. All will be on for a second test, with a may blink on and off several times if you are in an area
double chirp from the piezo buzzer. They will all be off. with a limited sky view.
The green heartbeat LED (labelled HB) should begin The red MBX LED will initially be on. After the
pulsing with a two second period, indicating the program satellites are acquired, it will stay on if you are outside the
is running. The red SD LED will come on briefly, then mission box, or go off if inside.
quickly go off if the SD card is mounted successfully. The red LED next to the big cutter relay should be
The red FXQ LED will be on for a minute or so while off. If it is on, watch out! There is a problem. That means
the real contact is closed and power
is being sent to the nichrome cutter.
FREE
If so, there will also be an audible
warning from the piezo buzzer.
Be sure to delete all of the files
on the SD card before each flight. A
new file is created — to a maximum
PCB Layout Software & of 99 — every time you boot-up the
PCB Schematic Software controller. This can happen quickly if
you do a lot of pre-flight testing. The
controller will freeze when the file
limit is reached.
The serial terminal is a
convenient way to evaluate pre-flight
sensor and program performance.
Simply start the Parallax Serial
Terminal quickly after the controller
is started. Sensor data and program
function information will be
displayed.
Final Thoughts
The original goal for the 2013
mission was to capture an image of
3 PCBs 3 PCBs 3 PCBs the aurora borealis from 100,000
$
41 $
61 $
81
feet. Although that was not
+ shipping + shipping + shipping successful, the project was successful
in many other ways. We all learned a
2-layer 2-layer 4-layer lot, and for several students the
MiniBoard MiniBoardPro MiniBoardPro project motivated changes in college
(Shipped in 1 business day) (Shipped in 2 business days) (Shipped in 3 business days) and career plans.
I would enjoy hearing from you if
you decide to build and launch one
of these. Please send your thoughts
1 DOWNLOAD our free CAD software to me at rlevergood@london
Now Offering derry.org. NV
2 DESIGN your 2 or 4-layer PCB
BUILD IT YOURSELF
BRAIN
www.nutsvolts.com/magazine/issue/2017/07.
HACKING?
Operating an armed military
drone half way around the
world is not only a complex
task, but allows for no margin
for error. Lives are quite literally
on the line. The training of
drone operators is necessarily
in depth and intense. Faced
with the problem of training
personnel quickly enough,
DARPA (Defense Advanced
Research Projects Agency)
decided to try an absolutely
extraordinary approach ...
S
eizing on recent exciting research in surprised if we take a couple quick detours to project
neurostimulation using transcranial direct current completion.
stimulation (tDCS), DARPA scientists attached salt
water electrodes to the temple and left shoulder of drone A Quick Look at the
operator trainees. After passing very small direct currents
of a few milliamps through the electrodes, scientists were Schematic
“shocked” to find that new pilots attained the skills All that is required for a working device is that we
needed to pilot the drones in half the time normally produce a regulated current of between .5 and 2 mA
required. through a pair of salt water electrodes attached to the
The results were so striking that extensive double skin.
blind testing followed using “sham” currents and control Because skin resistance can vary enormously from
groups, only to find the same results. person to person (I’ve measured resistance between the
Though the idea of using small DC voltages for brain electrodes of anywhere from 1.5K to 5K with different
stimulation is more than 100 years old, the immense people), a minimum voltage of approximately nine volts is
publicity from the well controlled DARPA experiment and needed (2 mA at 9 volts = 4.5K skin resistance).
the simplicity of the design has led to a great deal of both Voltage ranges on commercial units run all the way
professional and amateur interest.
I was first introduced to the ITEM DESCRIPTION
idea by a friend who had been R1 330 ohm
treated for major depression using R2 470 ohm
just such a tDCS machine. His R3 75 ohm
R4 50 ohm
observation was that though he R5 37 ohm
did not feel as if his problems had C1-C2 10 mfd electrolytic
gone away, he said it was “as if a D1-D2 1N4148 (Any general-purpose will do)
net that had been dragging him LED Any 1.8-2.2 VDC
down had been removed after the IC1 ICL7660SCPA voltage converter
IC2 LM334 voltage regulator
treatment,” allowing him to get on S1 Three-position switch
his feet again and deal with his life
PARTS
ST1 Two-pole terminal block
positively.
Many studies show
encouraging results for decreasing
Misc: USB cable
26 Ga stranded hookup wire LIST
1.5" stainless steel fender washers
anxiety, addiction, lessening
Kitchen sponge
depression, and even increasing
concentration. Case: RadioShack 270-1801 (large)
The actual circuitry needed to Or, if ambitious: Hammond 1551GBK (small)
24 July 2017
Noon - Brain hacking - Jul 17FINAL_Blank Project NV.qxd 6/7/2017 11:14 AM Page 25
!
■ FIGURE 2.
"# $
% & $
!'$$ ()$*($
#
$
%
&
'
"
(
from nine volts to 18 volts and more. Important Note: Never power any tDCS unit from a
In what is strictly my personal opinion, anything below device that connects — even indirectly — to line current
six volts seems to produce no effect, and above 12 volts under any circumstances.
can occasionally lead to skin irritation (if used with smaller
electrodes). The basic schematic is shown in Figure 2 and uses a
For our schematic, I wanted to power this device simple 7660 voltage converter (configured as a voltage
directly from a cell phone for convenience, or even with doubler with the diode and cap multiplier). The output of
an inexpensive rechargeable cell. So, I thought it would be the converter is coupled to an LM334 voltage regulator.
particularly useful to get power from a USB port Three switched positions allow selection of
connection. Figure 1 shows a USB cable and suitable approximately .5, 1.5, and 2 mA settings.
case. In this configuration, the 7660 will boost the five volt
■ FIGURE 3.
July 2017 25
Noon - Brain hacking - Jul 17FINAL_Blank Project NV.qxd 5/30/2017 6:26 AM Page 26
■ FIGURE 7.
Making Your
Electrodes
■ FIGURE 5.
■ FIGURE 6. Method 1
■ FIGURE 8.
Method 3
■ FIGURE 9.
As a quick alternative, you can make a
disposable electrode by just using the wire glue to
attach the wires and “any old” washer directly to the
July 2017 27
Noon - Brain hacking - Jul 17FINAL_Blank Project NV.qxd 5/30/2017 6:26 AM Page 28
■ FIGURE 12.
■ FIGURE 11.
are among the best researched placements, but many I strongly recommend researching tDCS devices
more options are available with a quick Internet search. before experimenting if this topic has caught your
Typical times for sessions are between 20 and 30 interest. Many of the stories are wildly interesting and
minutes, and can be repeated in 48 hours. Electrodes can entertaining.
be held in place on the head very easily with a couple of Does it really affect your brain? Or, is this yet another
women’s hair bands. example of the latest fad in placebos?
I base my evaluation of “is it working” I certainly have an opinion, but I’ll leave it to you to
(voltage/electrode position, etc.) on a tiny flash of light form your own. NV
(called a phosphene) that is often witnessed just as the
device is disconnected. This is a flash of light that is seen
only in your mind.
Wrap Up
It’s always a pleasure for me to delve into “strange
science,” and I hope it has been for you as well! I tend to
be a very skeptical person by nature, but do feel after
experimenting with this device, it has been a fascinating
and worthwhile project and experience.
I’ve been interested in electric therapies since Dr.
Robert Becker’s book, The Body Electric caught my
attention just out of high school many years ago. The
topic of “electrotherapy” makes for many nights of good
reading.
July 2017 29
Lindley - ESP8266 World Clock - Jul 17_Blank Project NV.qxd 5/30/2017 6:28 AM Page 30
BUILD IT YOURSELF
By Craig A. Lindley
Build an ESP8266
WORLD CLOCK
What do most movie scenes of the stock market trading floor and most high-end
international hotels have in common? They both have world clocks that allow people
to see the time and date in remote locations of the world.
W
orld clocks are important to business as they Enabled, Arduino Compatible Microcontroller” in the
allow companies and/or individuals to have an October 2015 issue.
idea of the time of day and date where their 2. “Thinking of You” article in the November 2015 issue.
customers reside. There is nothing more embarrassing 3. “ESP8266 NTP Clock” article in the June 2016 issue.
than calling an international client in the middle of the 4. “ESP8266 Weather Clock” article in the November
night because you figured the time difference incorrectly. 2016 issue.
World clocks can even be important to families that have 5. “ESP8266 RSS News Reader” article in the January
members distributed across the US or the world so they 2017 issue.
know when would be a good time to make contact.
In order for world clocks to be useful, they must be The hardware used in articles 3, 4, and 5 is exactly the
accurate; they must show the time and date correctly for same, so there is just one hardware setup (be it a
each location; and they must take worldwide Daylight breadboard or a printed circuit board [PCB]). With
Saving Time into account. different software, you can have an NTP clock, an NTP
To assure the accuracy of this world clock design, I clock and weather station combination, or an RSS news
have opted to use the Network Time Protocol (or NTP) as reader.
the provider of time information. NTP can provide time Now, with this article, the exact same hardware can
accurate to within a second to devices over the Internet, function as a world clock as well.
which is good enough for our application here. The world clock design presented here has some
Basing a digital clock design on NTP requires access rather interesting attributes, including:
to the Internet which can be expensive to implement, but
allows for a very simple clock design for a couple of • It uses NTP, so it sets itself automatically whenever
reasons. it is powered up. There is no need for switches or buttons
First, no battery backup circuitry is required to for setting the time or date. In fact, there are no switches
maintain the time setting. If clock power is lost, the or buttons at all in this design.
connection to the Internet will automatically be re- • It uses a time zone library that automatically deals
established once power is restored, and the clock will with Daylight Saving Time (DST) worldwide, so there is no
automatically set itself to the correct time. need to reset the clock when the time changes or to click
Second, no controls for manually setting the time and a button to enter/exit DST.
date are typically necessary because the
time and date are set automatically. Hardware Parts List
The ESP8266 family of devices makes Part Source
inexpensive access to the Internet possible,
NodeMCU LUA Amica R2 Module Electrodragon.com
so it is a natural to use in digital and world
clock applications. Readers of Nuts & Volts Adafruit.com - Product ID: 358 or
1.8” TFT SPI LCD Display SainSmart.com 1.8 ST7735R TFT LCD
may remember my previous articles using Module with MicroSDSKU:20-011-920
these amazing devices: USB Cable - USB A to USB Micro B RadioShack or similar
USB Power Supply Capable of at
1. “Meet the ESP8266: A Tiny, Wi-Fi RadioShack or similar
least 1A @ 5V
30 July 2017
Lindley - ESP8266 World Clock - Jul 17_Blank Project NV.qxd 5/30/2017 6:28 AM Page 31
To post comments on this article and find any associated files and/or downloads,
go to www.nutsvolts.com/magazine/issue/2017/07.
Table 1. Resources
NodeMCU Amica Pin Adafruit 1.8” Display Connections Information about NTP can be found all over the
D4 D/C Internet. See www.ntp.org for detailed information.
D5 SCK
Information about time zones can be found at
D7 MOSI https://en.wikipedia.org/wiki/List_of_UTC_time_offsets.
D8 TFT_CS
Information about programming the ESP8266 in the
3V3 RESET
Arduino environment can be found at
3V3 LITE github.com/esp8266/Arduino and also in my articles
3V3 3V3 previously mentioned.
GND Gnd Information about the NodeMCU Amica can be found
at www.electrodragon.com/product/nodemcu-lua-
Table 2. amica-r2-esp8266-wifi-board.
File Description Information about the Adafruit 1.8” TFT SPI LCD display
can be found at www.adafruit.com/products/358.
Main program which initializes the
hardware for operation and runs a Information about the SainSmart display can be found
ESP8266WorldClock.ino finite state machine that insures at www.sainsmart.com/sainsmart-1-8-spi-lcd-module-
the Wi-Fi connection to the Internet with-microsd-led-backlight-for-arduino-mega-atmel-
is continually maintained. atmega.html.
Code for formatting and displaying
time and date information on the The ST7735 display driver library can be found at
LCD, and a finite state machine https://github.com/sumotoy/TFT_ST7735.
that controls the order that time
zones are displayed in; which time The Time library can be found at
zone is currently being displayed; https://github.com/PaulStoffregen/Time.
and how long each time zone is
DisplayFSM displayed. The Timezone library can be found at
https://github.com/JChristensen/Timezone.
Time Change Rules (described
shortly) for each time zone are also unzip the file and copy/move the ESP8266WorldClock
defined in this file, and the
conversion of NTP’s UTC time to directory into your computer’s Arduino directory. The
local time,zone time is perform zip file also contains the versions of the libraries I used
here as well. during program development.
Functions for sending UDP packets It is important to use these versions as newer or
NTP.h to NTP servers on the Internet and older versions may not function correctly. The library zip
retrieving the returned UTC time. files should be unzipped as well, and then moved into
TextGraphicsFunctions.h Misc. functions for formatting text your Arduino/Libraries directory for use. Remember the
data for display on the LCD. Arduino IDE — if running — must be restarted to
A subclass of the Timezone class recognize new libraries after you install them.
TimezoneExt.h that contains the Time Change Whereas the hardware for this world clock borders
Rules in addition to a name on the trivial, the software/firmware for the clock is a bit
assigned to the time zone.
more involved and complex. The files which make up
the program are described in Table 2. In addition
Table 3. to the files listed in Table 2, the Arduino libraries
Library Source shown in Table 3 are also required.
TFT_ST7735 https://github.com/sumotoy/TFT_ST7735
Time https://github.com/PaulStoffregen/Time
User Configuration
Timezone https://github.com/JChristensen/Timezone
of the World Clock
Software
sidebar for how to set up the Arduino IDE on your The world clock’s software must be configured before
computer for targeting ESP8266 type devices. Make sure the clock will operate correctly. All user configuration
to select “NodeMCU 1.0 (ESP-12E Module)” as the board items are found in the file ESP8266WorldClock.ino. Please
type in the Tools menu. locate the following text in that file:
The ESP8266 world clock software is available at the
article link; the file is called // ******************************************
Lindley_ESP8266WorldClock.zip. To use this software, // Begin user configurable items
32 July 2017
Lindley - ESP8266 World Clock - Jul 17_Blank Project NV.qxd 5/30/2017 6:28 AM Page 33
■ FIGURE 3. Initial Wi-Fi connection display. ■ FIGURE 4. Typical world clock time zone
display page.
// ****************************************** Fi network. If this screen doesn’t change to a time zone
// Set your WiFi login credentials display similar to Figure 4, it means there were problems
#define WIFI_SSID “XXXXXX” logging on to the Wi-Fi network. If this is the case, go
#define WIFI_PASS “YYYYYY” back and verify that the WIFI_SSID and WIFI_PASS entries
in the code are correct and that the Wi-Fi network is
#define USE_12_HOUR_FORMAT true working.
#define PAGE_DISPLAY_TIME_SECS 20 The Wi-Fi login display will be replaced by the first
#define PAGE_DISPLAY_TIME_MS time zone display page once a Wi-Fi connection is
(PAGE_DISPLAY_TIME_SECS * 1000) established. The clock should run as long as power is
applied and it will sync its time to an NTP time server
// ****************************************** every five minutes, making the clock very accurate. Each
// End user configurable items time zone page will be displayed for the configured time
// ****************************************** interval in a round robin fashion. By default, this means
the time and date will be displayed in the following order:
First and most importantly, you must modify the code Sydney, Frankfurt, London, New York, Houston, Denver,
with the SSID and password of your Wi-Fi network. Phoenix, and Los Angeles.
Otherwise, the clock won’t be able to access the Internet, The clock will continue to run as long as power is
and by extension, the NTP servers that provide the time. applied. If the Internet connection is dropped, the clock
Next, you must decide if your clock will operate in 12 or will maintain the time itself. If Wi-Fi goes down but the
24 hour format. Set USE_12_HOUR_FORMAT to true to clock remains powered, the clock will continually try to re-
run your clock in the 12 hour format or it will establish Internet connectivity and will re-sync with NTP as
automatically operate in the 24 hour time format. soon as possible. If power is lost to both the clock and the
Finally, you can configure how long each time zone Wi-Fi network, when power is restored, the clock will
page is displayed. By default, the time is 20 seconds, but reboot, wait for the network to come back up, and will
you can make this longer or shorter depending on your then reconnect automatically.
preference.
The code can be compiled and uploaded to the Time Zones, Time Zones,
NodeMCU device once the configuration data is set and
all of the required libraries have been installed in the Time Zones
Arduino environment. Wrapping my head around worldwide time zones was
the most difficult part of writing this code. Think about it.
World Clock Operation It’s a somewhat easy task to calculate offsets from the
time in your location to any time zone in the world, but
The clock should start immediately once the software what happens when the time zone you are interested in
is compiled and uploaded. Figure 3 shows the clock’s changes to or from DST (or whatever it may be called in a
display while a connection is being made to the local Wi- particular location). To compound the problem, there is
July 2017 33
Lindley - ESP8266 World Clock - Jul 17_Blank Project NV.qxd 5/30/2017 6:28 AM Page 34
no world standard that I am aware of that says the time TimeChangeRule usMDT = {“MDT”, Second, Sun, Mar,
changes from standard to DST and back have to occur on 2, -360};
the same date and time in all locations. TimeChangeRule usMST = {“MST”, First, Sun, Nov,
Luckily, the time zone library used in this application 2, -420};
(written by J. Christensen) has this kind of smarts built in. It TimezoneExt usMT(“Denver”, usMDT, usMST);
is our responsibility, however, to define Time Change Rules
for each time zone that explain to this library the rules for The first rule, usMDT, is for when DST starts in my
each location. location. It says the time change occurs the second
To define the appropriate Time Change Rules for each Sunday of March at 2 am, and that during DST we are
time zone requires gathering the following information: offset a negative 360 minutes or -6 hours from UTC time.
the day of the week the time change occurs; which week The second rule, usMST, is for standard time that starts the
of the month the change occurs in; at what hour the first Sunday of November again at 2 am. During standard
change occurs; and the offset in minutes of the time zone time, we are -7 hours from UTC time. Note: There is no
from Universal Coordinated Time (or UTC) when the mention of the day of the month that time changes as that
change occurs. is different every year.
Two rules are required for each time zone: one for the These two Time Change Rules are then combined into
change to DST and another for the change back to a TimezoneExt object called usMT that is given the name
standard time. Since I live in Colorado, I’ll use the Time “Denver” which will be displayed for the Mountain time
Change Rules for the Mountain time zone as an example. zone on the LCD. Using these rules, the UTC time
The following code fragment was extracted from the file returned from NTP is converted to local time for the time
DisplayFSM.h: zone, so that is what gets displayed on the world clock.
Arizona is unique in that they don’t use DST in their
// US Mountain Time Zone (Denver, Colorado state (they may have the right idea). Arizona is on
// Springs, Salt Lake City) standard Mountain time the whole year. To accommodate
34 July 2017
Lindley - ESP8266 World Clock - Jul 17_Blank Project NV.qxd 5/30/2017 6:28 AM Page 35
this, the TimezoneExt object specifies usMST for both of zones of your choice. The world clock code should
their Time Change Rules as shown below: automatically adapt to any changes you make to the
timeZones array. If you have a large distributed family, for
// Arizona is US Mountain Time Zone but does not example, you might want to have your world clock display
// use DST the time and date where each family member lives.
TimezoneExt usAZ(“Phoenix”, usMST, usMST); You’ll want to check the time and date for any time
zones you add. This can easily be done by Googling,
After all the Time Change Rules and the TimezoneExt “time in XXXX” where XXXX is the name of a city in the
objects are defined in the file DisplayFSM.h, the time zone you added.
TimezoneExt objects are placed into an array called
timeZones: Conclusion
// All of the timezones we want to display The world clock presented here is one of the simplest
// time for projects one could build, plus it can be done for around
TimezoneExt timeZones [] = { $22. Two components connected with six wires is all it
ausET, CE, UK, usET, usCT, usMT, usAZ, usPT takes.
}; Plug your world clock into your computer, update the
user configuration info, compile the code, and upload it to
The world clock code walks through this array your world clock. You should be good to go. Now you
sequentially, and displays the time and date information can feel like you are living in a high-end international hotel
calculated for each time zone. as you have access to times and dates all over the world.
Because you have access to the software, you could As always, have fun! NV
change the order of the time zones displayed, remove
time zones you are not interested in, or add new time
HIGH-PERFORMANCE
HIGH-PERFORMANCE
8-CHANNEL O
OSCILLOSCOPE
SCILLOSCOPE
The
The PicoScope
input
PicoScope 4824
4824 is a llow-cost,
input applications.
applications. With
ow-cost, po
portable
rtable solution
With 8 high-resolution
solution for
high-resolution analog
for multi-
analog channels
multi-
channels you
you
12-bit 20 MHz
resolution
can ea
easily
sily an
analyze
alyze aaudio,
udio, ultr
ultrasound,
asound, vib
vibration,
ration, po
power
wer and bandwidth
timin
timingg o
off co
complex
mplex ssystems.
ystems.
T
The
he PicoScope
PicoScope 4824
4824 hashas the
the power
power and functionality
functionality to
to d
deliver
eliver
accurate
accurate results.
results. It also
also ffeatures
ea
e tures d
deep
eep memory
memory to to analyze
analyze
multiple
multiple serial
serial buses
buses susuch
ch as
as UART,
UARRT, I2C, SPI,
SPI, CAN,
CAN, CAN
CAN FD
LIN
and LI Npplus
lus control
control and driver
driver signals.
signals.
Also
Also ffeatures:
ea
e tures:
• H igh-performance ar
High-performance bitrary w
arbitrary aveform ggenerator
waveform enerator
• A dvanced digital
Advanced digital tr iggers
triggers
8
• SSerial
erial b us decoding
bus decoding
• Su perSpeed USB
SuperSpeed USB 3.13.1 Gen interface
Gen 1 interface
• Windows,
Windows, Mac Mac and Linux
Linux software
software
256 MS
channels buffer memory
For
For m
more
ore inf
information
formation pplease
lease visit www
www.picotech.com/us108
.picotech.com/us108
Em
Email:
ail: sal
sales@picotech.com.
es@picotech.com. Er
Errors
rors and omissions
omissions excepted.
excepted. Please
Please contact
contact P
Pico
ico T
Technology
ec
e hnology for
for the
the latest
latest p
prices
rices be
before
fore o
ordering.
rdering.
July 2017 35
Hildreth - Working with I2C Device - Jul 17_Blank Rough NV.qxd 5/30/2017 6:31 AM Page 36
Working
with I C
2
Sensor
Devices
By Derek Hildreth
Technologic Systems
Let’s take a look at what is required to read sensor data from an I2C
interface (a.k.a., I2C, IIC, TwoWire, TWI). In particular, we’ll be reading
data from the NXP MPL3115A2 altimeter/barometer/temperature
sensor. The principles found here can also be applied generically, even
to your ambifacient lunar wane shaft positioning sensor of your
turboencabulator.
connect it to something
with an I2C interface to
read the data. Most any
SBC or even
microcontroller could
do the job, but we’re
going to reach for our
handy Technologic
Systems’ TS-7970 high
performance industrial
SBC with Wi-Fi and
Bluetooth, since we
have an IoT-like end
goal in mind.
The MPL3115A2 breakout board requires no more
than 3.3 VDC and a connection to SDA (I2C Data) and
SCL (I2C Clock). There are two interrupt pins that can be (https://github.com/ControlEverything Community) that
used for things like events and triggers, but we’re not has working example code for Python, C, Java, and more.
going to use those in this article. All of this is brought out Take a look for yourself at the ControlEverything
on the header designated as HD3 on our TS-7970 (see Community/MPL3115A2 github repository.
section HD3 of the TS-7970 manual available at
https://wiki.embeddedarm.com/wiki/TS-7970). Pro Tip: If you are interested in using Python, you’ll
When we’re all hooked up and powered on, the I2C need to install python-smbus first
interface is brought out to the Linux device file /dev/i2c-1 (https://pypi.python.org).
(see section TWI of the TS-7970 manual). This number
might change depending on your system, so be sure to Once we have a basic understanding of how to
run i2cdetect -l to get a list of I2C interfaces on your board. program for I2C from looking at examples and
documentation, we need to dive into the specifics of our
Note: We’re making a couple assumptions at this sensor using the MPL3115A2 datasheet.
point. One is that you already know how to boot and Luckily, NXP also provided a really nice application
connect to your board. If you’re following along with a TS- note — Data Manipulation and Basic Settings of the
7970, you may want to take a look at the Getting Started MPL3115A2 Command Line Interface Driver Code — which
Guide (available at the same link as the manual). Another helps further our understanding of how to interface with
assumption we’re making is that you’re running Linux and this sensor. In section 11 (Quick Start Setup), you’ll find a
have i2c-tools installed. flowchart showing necessary steps to read altimeter data.
Programming the I2C Client Pro Tip: Since we don’t plan on using the events to
trigger an interrupt pin, you should be able to skip the
Official documentation for programming an I2C client step of enabling data flags in PT_DATA_CFG.
in C can be found in the Linux Kernel in /i2c/dev-interface.
(You can find documentation
mentioned in this article at
www.embeddedarm.com.)
We don’t have to be stuck
using C though. You can reach for
C++, Python, Java, or others. For
this article, we’re going to work
with C for learning purposes, and
because we know C is uber fast
where hardware is involved.
July 2017 37
Hildreth - Working with I2C Device - Jul 17_Blank Rough NV.qxd 5/30/2017 7:18 AM Page 38
On our TS-7970, we know that /dev/i2c-0 is used root@ts-imx6:~# i2cget -y 1 0x60 0x0C
0xc4
internally to connect the FPGA (field-programmable gate
array) with the RTC (real time clock) as mentioned in the
manual, so that leaves us with /dev/i2c-1. We can then use Perfect! For now, let’s conclude our little sanity check.
that information to detect chips connected to /dev/i2c-1 If you’re looking for some homework, you could manually
by running i2cdetect -y 1, like so: step through the flowchart using i2c-tools to see what the
raw data looks like.
root@ts-imx6:~# i2cdetect -y 1 We’re going to move onto the C program.
38 July 2017
Hildreth - Working with I2C Device - Jul 17_Blank Rough NV.qxd 5/30/2017 6:31 AM Page 39
The C Program
We’re going to make things easy on ourselves and use
the ControlEverythingCommunity/MPL3115A2 example
code as our base. This uses the same principles as taught
in the official Linux I2C documentation and is well
commented. Let’s take a look:
#include <stdio.h>
#include <stdlib.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <fcntl.h>
void main()
{
// Create I2C bus
int file;
char *bus = "/dev/i2c-1";
if((file = open(bus, O_RDWR)) < 0)
{
printf("Failed to open the
bus. \n");
exit(1);
}
// Get I2C device, TSL2561 I2C address
// is 0x60(96)
ioctl(file, I2C_SLAVE, 0x60);
40 July 2017
The new starting point for robotics
Building
My love affair with microcontrollers and
microprocessors began back in 1988 when I was
working toward a technical degree at CEFET-PR
Your Own
(a four year Brazilian secondary/technical school
and university located in Curitiba). I began by
learning the basics while exploring the classic
Microcontroller
Zilog Z-80 (Figure 1a).
F
ast forward through a career of programming that
included authoring some books on microcontroller
programming (see Resources), starting a small
design house (ScTec), and finishing a post-
graduation program at CEFET-SC (another Brazilian
university located in Florianopolis). This was in 2008, when
I had more contact with programmable logic and VHDL
and my curiosity was peaked. Years later in 2016, I found a FIGURE 1A.The Zilog Z-80A (courtesy of Wikimedia Commons).
very affordable FPGA (Field-Programmable Gate Array) kit
and decided to give it a chance, and started learning more
about FPGA technology.
What would be better than designing a softcore to
learn more about VHDL (VHSIC hardware description
language), FPGAs, and microprocessor cores themselves?
I ended up choosing a modern Z-80 relative: the Zilog
Z8 Encore! (a.k.a., eZ8; Figure 1b). It’s an eight-bit
microcontroller core with a simple -- yet powerful --
instruction set and a very nice on-chip debugger. With its
lightweight IDE (integrated development environment) and
free ANSI C compiler, it is an excellent project to learn
(and also teach) about embedded systems.
Before diving into the depths of the core operation,
VHDL, and FPGAs, let’s take a glance on the Zilog Z8 FIGURE 1B. Zilog eZ8.
Encore! features.
Zilog Z8 Encore!
The eZ8 is an eight-bit microcontroller family based on
Zilog’s successful Z8 family and on the great Z-80 heritage.
It features a Harvard CISC machine with up to 4,096 bytes
of RAM (file register and special function registers area), up
to 64 KB of program memory (usually Flash memory), and
up to 64 KB of data memory (RAM). The eZ8 core also
includes a vectored interrupt controller with programmable
priority and an on-chip debugger which communicates
with the host computer using asynchronous serial
communication. These microcontrollers are packed with a
very nice peripheral set, ranging from versatile 16-bit timers
to motor control timers, from multiple UARTs (IrDA ready) FIGURE 1C. FPz8 on an FPGA.
42 July 2017
A L L
E L E C T RON I C S
www.allelectronics.com Order Toll Free 1-800-826-5432
PROJECT BOX, 3M SAFETY GLASSES WITH
4" X 3" X 1.6" LED LIGHTS
Black ABS plastic Adjustable, ultra-
project enclosure. bright LED lights
Interlocking lid secured integrated into stylish
with self-tapping screws. safety glasses providing
Interior slots for pc boards. illumination right where you need it.
$ 00
Includes hardware.
3
each
CAT# SG-11 $
10 for $2.75 ea. 11 95 6 for
CAT# MB-173 each $11.50 ea.
Bundle of 8 three
foot lengths of 2 for $ 100 2-CONDUCTOR LOCKING
assorted colors. CONNECTORS W/ LEADS
100 for 40¢ each Pins on 2.5mm
centers. Black
CAT# HW-24
July 2017 49
Here It Comes
Guy Clark’s classic song about an
express train could be about the upcoming
solar eclipse — just change the third line to
“Screamin’ through America” and the title to
“August — 2017!” I hope you have Monday,
August 21st circled on your calendars in
bright red ink. A total solar eclipse will be
seen on that day by millions of people from
Portland, OR to Charleston, SC. Many more
millions will see a partial eclipse. The US
couldn’t have a better opportunity.
While totality — in which the entire
solar disc is blocked by the Moon — will
be viewable at any point along the path for
about two minutes, some portion of the
Sun will be covered by the Moon across
the US (including Alaska and Hawaii),
Canada, Central America, the Caribbean,
and some of northern South America. The
orthographic map from NASA in Figure 1
shows how much of the Sun will be covered
and the approximate time. If you are one of
the lucky ones, the path of totality shown by
the blue line will be close enough for you to
see the fully-covered solar disc.
50 July 2017
frequency bands
Eclipse Information available to it than
If you want more information on August’s eclipse, here are some good sites: any other service.
• NASA — Complete information on the eclipse With the new 630
(eclipse.gsfc.nasa.gov/solar.html) meter band (476
• Space — How to View the Eclipse Safely kHz) and the 2,200
(www.space.com/33797-total-solar-eclipse-2017-guide.html) meter band (136
• Astronomy Magazine — 25 Eclipse Tips kHz), hams will
(cs.astronomy.com/asy/b/astronomy/archive/2014/08/05/25-facts-you-should-know- have access to
about-the-august-21-2017-total-solar-eclipse.aspx) frequencies from
• NOAA Space Weather Prediction Center — Lots of real time information about radio conditions well below the AM
(www.swpc.noaa.gov/communities/radio-communications) broadcast band to,
well, light.
observed is the effect an eclipse has on radio propagation. Time of day is pretty easy to control. Assuming
As the May and July 2016 columns explained, someone is “out there” to make a contact, you can try
ultraviolet (UV) light from the Sun creates the ionosphere any band at any time. Having been at this radio business
by giving enough energy to electrons for them to escape since 1906, hams like to think we understand propagation
from the outer shells of atoms of gas; mostly oxygen and pretty well. However, there is always something new
nitrogen. coming up. Either better equipment or protocols or science
These free electrons and the positively-charged ions enables us to “try something different,” and there is usually
left behind can act like charges in a wire that respond something new to be discovered around every bend in the
to a voltage. That means the ionosphere is a very weak ionospheric road.
conductor that can affect the electromagnetic radio waves The eclipse is particularly interesting this way. It is one
passing through it. The main effect is bending or refracting thing for night to slowly fall as the Sun sinks below the
the waves in a way that returns them to the surface of the horizon; it’s quite another for a complete day-night-day
Earth. The effect is that of a reflecting surface high above cycle to occur in three hours or less! (Totality will only last
the Earth — the ionosphere starts at about 30 miles up and for a couple of minutes at most, but the partial phases will
extends to around 200-250 miles. last up to three hours depending on how close you are to
Not every wave gets the same treatment, however. the path of totality.) This means the solar UV will have a
The higher the wave’s frequency, the less it is bent. Above sudden well-defined disruption as suggested by Figure 2.
some frequency, the wave can’t be bent enough to
return and so is lost to outer space. At the other end
of the spectrum, the ionosphere becomes lossier
and lossier, eventually soaking up all of the signal so
that none of it returns to the Earth below a certain
frequency. Between these two limits, the waves are
bent, channeled, guided, and otherwise pushed
around.
More UV during the daylight hours raises the
level of ionization. This allows the ionosphere to
bend higher frequency signals more, supporting
long-distance “skip” of 2,500 miles or more above
10 MHz. Below 10 MHz, more UV means more
absorption by the ionosphere’s lower layers. The n FIGURE 2. A sketch of how solar UV irradition of the
signals never make it through to those long-distance ionosphere will change during the eclipse. (Graphs are not to
bending layers. At night, the situation reverses. scale.) The dashed gray line shows the regular diurnal (daily)
The outcome of all this wave bending is which variation in UV exposure.
signals we can receive depends on a variety of
factors: signal frequency, season, solar and geomagnetic We know from past experience that a total eclipse
activity, and time of day are the most significant. The of the Sun does have a big impact on ionospheric radio
easiest things we can control and vary to see what happens propagation. The eclipse duration will be long enough
to our signals are time of day and frequency. for those separated electrons and ions to find each other
Hams have a lot of frequency choices. In fact, next again — a process called recombination — and we’ll have
to the military, amateur radio has a bigger variety of nighttime propagation.
July 2017 51
experiments. listening to the effects of the eclipse. You can do any of the
The early “Listening Tests” were coordinated by the following experiments while watching the eclipse without
Naval Research Lab (the DARPA of its day). Today’s SEQP leaving your backyard:
is being coordinated by HamSCI (hamsci.org): an informal
team of faculty, graduate, and undergraduate researchers 1. Absorption on the AM Broadcast Band
at a variety of academic institutions. HamSCI stands for Remember how solar UV causes the ionosphere to
Ham Radio Science Citizen Investigation. Its mission is to absorb low frequency signals during the day but reflect
coordinate and promote a variety of scientific projects them at night? That is exactly what happens to AM
involving ham radio. broadcast signals, and it’s the reason you can receive
The initial focus was on the eclipse — what could hams distant AM stations after sunset that you can’t hear at all
do to promote the science associated with it? Once the through the day. Your experiment will be to see if you can
SEQP had been devised, it became apparent that there receive distant stations during the eclipse and for how long.
were many other opportunities. A number of organizations Start by determining the direction towards the
were all working on their own projects, too. So, the idea path of totality from your location: NE, SW, or maybe
of a platform to connect all these people and projects was you are in the path, so E-W. Determine the frequencies
born. Check out the various projects on the website. You’ll of clear-channel AM stations in that direction. If you
be impressed. live in, say, Texas, you might listen for KOA-Denver,
KMOX-St Louis, WLS-Chicago, WHO-Des Moines, and
How Can You Participate? WCCO-Minneapolis. (There is a list of these stations at
en.wikipedia.org/wiki/Clear-channel_station.)
Assuming you’re not (yet) a ham, what can you do to Before the eclipse begins, listen for these stations at
observe the eclipse from the standpoint of radio? First, you night on a good quality radio — preferably with a piece
might check with local ham clubs and see if any of them or of wire attached to the antenna terminal. Find a few you
their members are planning to operate during the eclipse can hear well and write down their frequencies. These are
— either as part of the SEQP or in some other way. You your beacons. During the eclipse, tune from one station
would probably be welcome as an observer. What a great to another and note whether you can hear them and how
way to get a look at ham radio in a new and interesting strong they are at different times. What you’re looking for
way! are stations that approach their nighttime signal during the
If you are not licensed, you can still have a great time eclipse and then fade again as it passes.
July 2017 53
Put on a PiFace
The Raspberry Pi is a very popular computing platform. Its claims to fame are
inexpensive hardware and open source programming. Browse the Internet and you will
find that many have purchased a Pi with the thoughts of easily applying Python to the
hardware. As you claw through the thousands of hits, you’ll find a bunch of those
potential Pi users crying in their beer. Seems there’s a learning curve that goes along
with Python coding that’s coupled with little gotchas that come with the Raspberry Pi
itself. I’ve suffered with the Pi gotchas, but I didn’t lose any hair learning Python. In this
installment of the Design Cycle, we will use a free RAD (Rapid Application Development)
tool called B4J to twiddle the I/O pins of a PiFace that is hosted by a Raspberry Pi.
Preparing the Pi
You should use the RaspPi website
(www.raspberrypi.org) as a reference to avoid
frustration when working with the Pi.
Documentation for the PiFace is at best weak.
However, dig hard and you will find what you need.
You will discover that the PiFace is a very simple
device.
We will be running the latest version of
Raspbian on our RaspPi. Everything we need to
interface to the B4J program and PiFace is already
included in the Raspbian kernel. SSH is disabled by
default in Raspbian, so be sure to create an empty
file called ssh on the Pi’s bootable micro SD card.
The PiFace you see in Photo 1 is based on the ■ PHOTO 1. The PiFace is an I/O expansion board that falls under
Microchip MCP23S17 16-bit I/O expander. The the control of a Raspberry Pi’s SPI portal. Standard PiFace
features include an octet of LEDs sitting on high current outputs
RaspPi interfaces to the PiFace via the MCP23S17’s and a quad of pushbutton switches positioned on an octet of
SPI portal. I/O instructions from the Pi’s SPI portal digital inputs.
are processed by the MCP23S17, which drives a
ULN2803A Darlington transistor array.
The ULN2803 is designed to drive inductive loads.
To that end, the PiFace is equipped with a pair of relays
that are driven by the ULN2803A. The MCP23S17 pins
out to eight digital inputs and eight digital outputs. The
ULN2803A buffers the MCP23S17’s output pins, and
drives an octet of onboard LEDs in addition to the pair
of onboard relays. There is also a quad of pushbutton
switches tied to the MCP23S17’s input pins.
If you consult the Raspberry Pi website, you will
find that the Pi’s SPI portal is disabled by default. So,
our first task will be to enable it. We do this by editing
the /boot/config.txt file. As you can see in Screenshot 1,
we enable the RaspPi’s SPI portal by simply removing
the comment character standing in front of
dtparam=spi=on. ■ SCREENSHOT 1. I find it funny that the Raspberry Pi fathers
To a programmer, B4J is very much like Visual Basic listed the SPI and I2C portals as “optional.”
July 2017 55
Eady - Design Cycle - Jul 17_Design Cycle - Sep 15.qxd 5/30/2017 6:33 AM Page 56
To post comments on this article and find any associated files and/or downloads,
go to www.nutsvolts.com/magazine/issue/2017/07.
Sub Process_Globals
End Sub
application)
#Region Project Attributes
Let’s declare a private PiFace object: #CommandLineArgs:
#MergeLibraries: True
‘Non-UI application (console / server #End Region
application)
#Region Project Attributes Sub Process_Globals
#CommandLineArgs: Private pf As PiFace
#MergeLibraries: True Private Timer1 As Timer
#End Region End Sub
Sub Process_Globals Sub AppStart (Args() As String)
Private pf As PiFace pf.Initialize(0x40,0)
End Sub Timer1.Initialize(“Timer1”,1000)
Timer1.Enabled = True
Sub AppStart (Args() As String) End Sub
End Sub
Sub Timer1_Tick
‘Return true to allow the default exceptions End Sub
handler to handle the uncaught exception.
‘Return true to allow the default exceptions
Sub Application_Error (Error As Exception, handler to handle the uncaught exception.
StackTrace As String) As Boolean Sub Application_Error (Error As Exception,
Return True StackTrace As String) As Boolean
End Sub Return True
End Sub
This code template will compile and can be executed.
However, nothing will happen and the process will end. As you can see in the B4J code, we declared a Timer1
We still need to do some things in the AppStart object in the Process_Globals subroutine. We then
subroutine. Like the Process_Globals subroutine, the initialized and enabled our Timer1 object in the AppStart
AppStart subroutine is called only once at the beginning subroutine. This code will behave exactly like the
of the process. unmodified code we previously laid down. It will compile,
The purpose of the AppStart subroutine is to initialize execute, and do nothing that we can see.
our desired variables and objects. We know that our Let’s do something proactive and blink the PiFace’s
MCP23S17 must be initially configured via the SPI portal, LED2:
so we’ll add some MCP23S17/PiFace startup code in our ‘Non-UI application (console / server
AppStart subroutine: application)
#Region Project Attributes
‘Non-UI application (console / server #CommandLineArgs:
application) #MergeLibraries: True
#Region Project Attributes #End Region
#CommandLineArgs:
#MergeLibraries: True Sub Process_Globals
#End Region Private pf As PiFace
Private Timer1 As Timer
Sub Process_Globals End Sub
Private pf As PiFace
End Sub Sub AppStart (Args() As String)
pf.Initialize(0x40,0)
Sub AppStart (Args() As String) Timer1.Initialize(“Timer1”,1000)
pf.Initialize(0x40,0) Timer1.Enabled = True
End Sub StartMessageLoop
End Sub
‘Return true to allow the default exceptions
handler to handle the uncaught exception. Sub Timer1_Tick
Sub Application_Error (Error As Exception, pf.GetLED(2).State =
StackTrace As String) As Boolean Not(pf.GetLED(2).State)
Return True End Sub
End Subj
‘Return true to allow the default exceptions
handler to handle the uncaught exception.
Our new PiFace code will also compile, execute, and Sub Application_Error (Error As Exception,
stop. We must assume that the MCP23S17 got the StackTrace As String) As Boolean
message. To know for sure, we need to beef up our Return True
End Sub
application and force some kind of visual indication that
things are indeed working as designed. Let’s begin by Since this is a non-UI application, we must call
adding a one second timer and an associated tick handler StartMessageLoop to force the thread to take charge of the
subroutine: message queue. This effectively allows the program to
keep running. Our Timer1 will trigger a tick event every
‘Non-UI application (console / server second. So, we’ll code a subroutine to handle the tick
July 2017 57
Eady - Design Cycle - Jul 17_Design Cycle - Sep 15.qxd 5/30/2017 6:52 AM Page 58
event. In our case, we’ll toggle the PiFace’s LED2 every Next
StartMessageLoop
second. End Sub
Now that we’ve conquered the PiFace LED interface,
let’s turn our attention to the pushbuttons. To read the Sub Timer1_Tick
pf.GetLED(2).State =
state of the PiFace’s pushbuttons, we must code in some Not(pf.GetLED(2).State)
button handlers called event listeners. End Sub
Event listeners are nothing more than subroutines that Sub Pushbutton0_StateChange(State As Boolean)
handle the change in button state. For this to work, we Select State
must declare each of the PiFace’s pushbuttons as a B4J Case True
pf.GetLED(3).State = True
Switch object. Doing this adds the Switch object’s events Case False
and members to each pushbutton. For instance, after the pf.GetLED(3).State = False
declaration, each pushbutton is associated with an event End Select
End Sub
called StateChange which returns the Boolean state of the
pushbutton (true or false). The state of the pushbutton Sub Pushbutton1_StateChange(State As Boolean)
Select State
(true or false) is also defined within the Switch object as a Case True
member. pf.GetLED(4).State = True
Another Switch object member is called AddListener, Case False
pf.GetLED(4).State = False
which adds an event listener. Here is what our pushbutton End Select
event listener initialization code looks like: End Sub
58 July 2017
Eady - Design Cycle - Jul 17_Design Cycle - Sep 15.qxd 5/30/2017 6:36 AM Page 59
Or, we could control the PiFace relays in a more ‘Non-UI application (console / server
politically correct manner: application)
#Region Project Attributes
Sub Pushbutton0_StateChange(State As Boolean) #CommandLineArgs:
Select State #MergeLibraries: True
Case True #End Region
pf.GetRelay(0).State = True
Case False Sub Process_Globals
pf.GetRelay(0).State = Private piController As GpioController
False Private piPinOut As GpioPinDigitalOutput
End Select Private piPinIn As GpioPinDigitalInput
End Sub Private Timer1 As Timer
End Sub
Sub Pushbutton1_StateChange(State As Boolean)
Select State Sub AppStart (Args() As String)
Case True piController.Initialize
pf.GetRelay(1).State = True piPinOut.Initialize(27,True)
Case False piPinIn.Initialize(“pInput”,25)
pf.GetRelay(1).State = Timer1.Initialize(“Timer1”,1000)
False Timer1.Enabled = False
End Select StartMessageLoop
End Sub End Sub
Sub Timer1_Tick
piPinOut.Blink(500)
Twiddling the Pi I/O End Sub
End Sub
StartMessageLoop
Guess What?
Sub Timer1_Tick Now that you have been exposed to the ways of B4J,
piPinOut.Blink(500)
End Sub you can also program using B4A (Basic for Android), B4R
(Basic for Arduino), and B4i (Basic for iOS). You’ll have to
‘Return true to allow the default exceptions purchase B4A and B4i, but you can download B4J and
handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, B4R for free.
StackTrace As String) As Boolean Once you’ve actually
Return True programmed using one of PiFace
End Sub
the B4x products, you’ll www.amazon.com
By declaring piPinOut as a GpioPinDigitalOutput wonder why you never
object, we can blink and pulse the Pi’s GPIO pin 27 with thought to put it into your
simple commands. Design Cycle before. NV B4J
The code for reading the Raspberry Pi’s digital inputs
is very similar to the code we wrote to read the PiFace Anywhere Software
inputs: www.b4x.com
July 2017 59
NV Webstore - Jul 17 working_NV Webstore June 2016 working.qxd 5/30/2017 6:40 AM Page 60
60 July 2017
NV Webstore - Jul 17 working_NV Webstore June 2016 working.qxd 5/30/2017 6:40 AM Page 61
July 2017 61
TECHFORUM READER - TO - READER
add a knob to it. The transformer is not so stable because the voltage knowing what voltage in and voltage
the most expensive component and drops as the charge is depleted. If out you have, it’s hard to say, but
can be sourced from other suppliers if you have a full time battery charger the LM317 will scrub off the excess
you need to reduce costs. Hope this attached, the stability problem goes voltage as heat. However, there are
helps! away. The zener diode has a rather boost/buck converters available
Schematic: www.eleccircuit. high impedance; up to 100 ohms for not much money (I bought four
com/the-variable-high-voltage-power- for those under six volts and lowest little boards based on the LM2587
supply-0-300v at 6.8 volts. If you have a 6.8 volt for about $7.50 each off eBay, for
Parts List: www.digikey.com/ zener running at 20 mA with an instance) that will conserve the
short/327wpp impedance of 25 ohms and the load current (minimal heat, minimal waste,
Doug Foreman varies 10 mA, then the voltage will minimal extra battery usage) and keep
Warren, MI vary: delta V = Ro * delta I = 25 * .01 the voltage even more accurate.
= 0.25V. The LM317, on the other For perfect usage, team one of
#2 You want to be extremely hand, has an output impedance in those up with a zener secondary
cautious experimenting with high the order of .05 ohms and you can regulator, so that you have a
voltages as they are lethal and can be set the voltage as accurate as you minimum of wasted current through
fatal. Rather than trying to construct need using the schematic in Figure 5 the resistor feeding the zener and
a high voltage supply — which could of the datasheet. The voltage should your circuit; that way, you have both
be dangerous — you might consider stay within 1% over time, but you can worlds working for you.
a variable transformer such as the reset it periodically if you want. You Ralph Phillips
Volteq #1KVA_110V/250V (www. should have a minimum load of 10 Shreveport, LA
volteq.com) which costs about $70. mA on the LM317 for good stability.
This transformer plugs into a Don’t run at max current if you want #4 The LM317 appears to be about
standard 120 VAC outlet and provides good reliability. 5% in accuracy (you also need to
an adjustable output from 0 to 250 Russell Kincaid add the error from the resistors used
VAC; it also provides isolation from Milford, NH for the adjustment, but you could
the AC power grid. If you want DC get some 0.1% resistors to manage
voltage, you can construct a simple #2 Three-terminal voltage that). A quick look on Digi-Key shows
bridge rectifier circuit. However, there regulators such as the LM317 are plenty of 1% zeners, so that path may
are many more interesting projects very accurate, and are suitable for offer more accuracy.
that use 5-12 volts. I suggest you most applications. You might want to If your load is fairly constant, your
pursue some of them instead. consider a fixed voltage output, low zener circuit can be tuned so the
Bob Stewart drop-out type, three-terminal regulator zener will just barely turn on with the
Mancos, CO such as the 78L00 series, made by expected load. If the load goes down,
several different manufacturers. The the zener will eat power to keep you
[#3172 - March 2017] low drop-out minimizes power loss — regulated. There are some other parts
Reliable Voltage Source for example, you can obtain five volts out there that offer better accuracy.
I am designing a battery powered out from six volts in (4x AA batteries). Check out the LT1460: 0.125% (but
circuit that requires a very reliable However, the purpose of any voltage only ensures 20 mA output).
voltage source. I was considering using regulator is to create a stable fixed Kevin Cutts
a zener diode in series with a resistor output from a variable input. Thus, the Lake Zurich, IL
across the power source and then regulator must dissipate power, and
tapping it at the diode/resistor for the you must observe the power rating of [#5172 - May 2017]
power point, but it seems this would the regulator or it will overheat and FCC Search
be very wasteful for the battery. Would self-destruct. Has anyone had any success
I be better off with a linear regulator Bob Stewart using the FCC ID search feature? I’ve
like an LM317 and if so, would it Mancos, CO searched about 15 ID numbers and
create as accurate a voltage? have yet to get any useful info!
#3 The LM317 would create a
#1 Are you looking for stability or more accurate voltage; however, that So, let’s say you are motoring
reliability? The battery is reliable but may not be the best way to go. Not about the countryside one fine day
July 2017 63
and you spot an interesting tower tower height in meters (307 meters station of interest and type it in there.
structure. Look around the entrance or a little over 1,000 feet). By the Example: WLW and hit the Submit
area and you should see a sign with way, you can also get here by going Station Search button. A new window
the FCC Tower Identification Number to www.fccinfo.com where the good opens with the results, which are fairly
on it. Let’s use number 1027514 as folks at Cavell, Mertz, and Associates skimpy at this point. However, on the
an example. Go onto www.fcc.gov have an easy-to-use database front- far right of the Results is a link labeled
and: end and a nifty Google Earth plug-in Click for Details. Another Results
1. Click the Licensing and that will give you the callsign for a window opens with more links to
Databases tab. You’ll be presented station associated with a broadcast more information. Now, we can get
with a list of about 25 databases listed tower. Note: broadcast, not cell, two- into the good stuff.
by their acronyms. Some of them are way, or other utility tower. On the Bureaus & Offices/Media
intuitive. Others, not so much. 5. On the ASR Results page, click home page, select Electronic Filing
2. In this case, click on ASR (for on the Registration Number. A new and Databases along the left side. The
Antenna Structure Registration). window opens, chock full of good new page that opens offers another
Partway down the page, you’ll information. list of choices — one of which is AM
find Search with a choice of either Another way to go about this Query, among others. Hit that one
Registrations or Applications. is on the FCC home page; click on and a new query search opens. On
3. Click on Registrations and a ‘browse by Bureaus & Offices,’ then the first line, enter WLW. Further
new window opens. In the upper on the Media sub-tab. The Media down, just above the Results buttons,
left corner is a field you enter the home page will appear. Now, along you choose how much information
registration number. While you’re the left side you will be presented you want. Choose the AM Query
here, you can check out the other with a list of choices. You want CDBS (detailed output + CDBS Links) menu
possible searches such as lat/lon, by Search. You’ll then be presented item and hit either the Results To
state, etc. with another list of choices which This Page/Tab or the Results To Next
4. Enter the registration number should be fairly self-explanatory. Page/Tab buttons, depending on your
and hit Submit. Note that this takes a As an example, choose the first preference. You’ll get everything you
whole lot longer to describe than to selection which is Search for Station ever wanted and more. If you’ve got
actually do. A new window opens, Information (as of the date I’m doing the time, you can easily spend hours
with the results — typically one line, this). The new window is a whole looking up all kinds of arcane things.
but a fact-filled line. We now know bunch of search fields, but to keep it Jerry McCarty
the FCC File Number, the owner (in simple the first line is Call Sign. In that Jackson, MI
this case, WLAJ-TV), lat/lon, city, and field, enter the call letters. Pick your
64 July 2017
ELECTRONET
www.nutsvolts.com and click Electro-Net USB
For the ElectroNet online, go to Add USB to your next project--
It's easier than you might think!
USB-FIFO USB-UART USB/Microcontroller Boards
RFID Readers Design/Manufacturing Services Available
Absolutely NO driver software development required!
CLASSIFIEDS www.dlpdesign.com
LIGHTING HARDWARE
WANTED
DEC and VME LED Lighting for Everything
Equipment WANTED!
Digital Equipment Corp
and
Motorola VME Systems
and Parts
Buy - Sell - Trade
ADvertiser INDEX
■L O O K F O R ■S E A R C H F O R ■F I N D Find your favorite advertisers here! Accutrace ..............................67
(408)748-9600
ITAR I SO 9001:2008 UL Approved