0% found this document useful (0 votes)
28 views25 pages

Full Circle Magazine 'Programming in Python' Series. Volume 11.

Full Circle Magazine 'Programming in Python' series. Volume 11.

Uploaded by

lukyanov
Copyright
© Attribution ShareAlike (BY-SA)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views25 pages

Full Circle Magazine 'Programming in Python' Series. Volume 11.

Full Circle Magazine 'Programming in Python' series. Volume 11.

Uploaded by

lukyanov
Copyright
© Attribution ShareAlike (BY-SA)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Full Circle

THE INDEPENDENT MAGAZINE FOR THE UBUNTU LINUX COMMUNITY

PROGRAMMING SERIES SPECIAL EDITION

PYTHON
In the Real World
Volume Eleven
Parts 60 - 66
Full Circle Magazine is neither ailiated, with nor endorsed by, Canonical Ltd.
H OW-TO
Written by Greg D. Walters P yt h o n I n T h e R E AL W o rl d
W elcome fellow pythoners. As
the kids here in the central
parts of the U.S. say, “What’s
Linux on an SD card. Its output
goes to your TV set via HDMI. It
also has an Ethernet connection
like LEDs, sensors, push buttons,
etc. Many people have made home
automation systems, multiple
poorly health-wise, so I’m saving
my strength for the next article.
Until then, grab some electronics
Shakin’ Bacon?” I’m not exactly for Internet access. processor systems (by linking 40 or and get ready for fun!
sure what that’s supposed to so Pi computers together to
mean, but I assume it’s a good You can find out more at the emulate a supercomputer),
thing. official site weather stations, even drones. So
https://www.raspberrypi.org. If you can imagine that the
You might notice the new you want to follow along with the possibilities are endless. That’s
header. I decided that I’ve taught projects, you will need a Pi, SD why I decided to start with it for
you all the basics of Python that I card, Keyboard, Mouse, a 5volt DC this series of articles.
can for “general” programming, so power supply like the ones on
now we are going to delve into modern cell phones, and access to After a while, we will begin to
using Python to talk to other types an HDMI monitor or TV. Eventually, work with the Arduino, which
of computers and controllers, like you should also consider getting a according to the official website
the Raspberry Pi and the Arduino breadboard and some connecting (https://www.arduino.cc): “Arduino
micro controller. We’ll look at wires for when we start to is an open-source electronics
things like temperature sensors, interface to the outside world. You platform basedon easy-to-use
controlling motors, flashing LEDs can find any number of places that hardware andsoftware. It's
and more. sell the Pi on the Internet. Here in intendedfor anyone making
the U.S., we can get them for interactive projects”.
This issue we will be focusing around $35.
on what we’ll need to do this and Once again, this is an exciting
focus on a few of the projects we One other thing about the Pi is device to work with. In this part of
will be looking at in the future. that it provides access to a series the series, we will look at talking to
Next issue, we will start the first of pins that support GPIO (General the Arduino, first in its native
project. Purpose Input/Output). Basically, scripting language, and then in Greg Walters is owner of RainyDay
this means that you can write Python and eventually interfacing Solutions, LLC, a consulting company
in Aurora, Colorado, and has been
One of the things we will talk programs that will send signals to the Pi with the Arduino. programming since 1 972. He enjoys
about next time will be the the output pins and read the cooking, hiking, music, and spending
Raspberry Pi. The Pi is a credit-card signals from the input pins. This I know this month’s article is time with his family. His website is
sized computer that natively runs can be used to interface to things fairly short, but I’ve been doing www.thedesignatedgeek.net.

full circle magazine #1 02 13 contents ^


H OW-TO
Written by Greg D. Walters P yt h o n I n T h e R E AL W o rl d
W elcome back to the new
direction of my Python
series. In case you missed last
articles, we will be interfacing with
sensors and the Arduino micro-
controller.
In February 201 5, both of those
models were superseded by the
RPi 2 Model B. It shares a good
various kits and add-on modules
like cameras, servo controllers,
motor controllers and so on. At
month, I am changing the direction deal with the RPi 1 B+, but has a this point, the add-ons won’t be
of this 5 year series from teaching
programming in Python to what is
A BRIEF HISTORY OF THE RPI 900 MHZ Quad-core ARM Cortex- needed, but we might use some in
the future, so if it is something
A7 CPI and 1 GB Ram.
called Physical Computing using Much of this information comes that you are interested in use your
Python. When you see the phrase from the official Raspberry Pi You can find various models of own judgment. As to the kits, here
'Physical Computing', think of website the RPi at any number of web are some things you should
buttons, LEDs, motors, sensors (http://www.raspberypi.org) and retailers. My humble suggestion is consider before you invest in the
(temperature, humidity, motion my memory of buying my first RPi. to get the RPi 2 Model B if you can “ultimate kits”. In the next few
sensors, barometric sensors, etc.) When the Raspberry Pi first came afford the difference in the price articles, we will need :
and more. The reason I decided to out, there were two models – between the P1 Model B (it
do this was that after 5 years, I Model A+ and Model B+. The shouldn’t be that much of a delta). • A Raspberry Pi computer.
thought I had shown pretty much decision tree was fairly easy since Any of the code that we create in • A power supply. For the P1
everything that you needed for the two different versions fit a the next few articles should easily versions, a 5 VDC 1 -1 .2 amp cell
“normal” computing, so let’s focus “simple or full feature” mindset, as work with any version of the RPi. phone charger with a micro USB
on what I consider the future of you can see in the gross details connection (normal for many smart
small computer programming and presented below (They are now While you are searching the phones today) will work well. For
microcontrollers. called RPi 1 Models)… web for your RPi, you will see the P2 version, I strongly suggest
that you get a power supply that
This month, I will be going over has an output of 5 VDC 2.5 amp
selecting a Raspberry Pi (yes there power supply with a micro USB
are more) that will fit your goals, connector.
installing an operating system • A USB Keyboard and Mouse.
onto the SD card and starting the While many places offer very small
RPi for the first time with the new keyboard/mouse combos, for
OS. programming work and “normal”
computer use, you will want a full
Next month, we will start size version of both. You can move
learning to respond to switches to the small wireless versions later
and control LEDs. In future on if you decide to use the RPi for
full circle magazine #1 03 12 contents ^
HOWTO - PYTHON
other uses like a multimedia centre has replaced it with a 3.5mm jack at SparkFun, their item is called the • Download the OS image.
or expanded home automation. that combines audio and video in “Pi Wedge”. Unless you want to • Unpack the image file from the
Normally when I work with the Pi, I one. You would need a 3.5 mm to assemble your own (read this as archive file. Put it somewhere it's
use a VNC server on the Pi and a 3 RCA connectors to connect to an soldering tiny parts), you will want easy to get to.
VNC client on my linux machine, so older TV. to get the Preassembled version. • Installing OS to the SD Card.
I don't have to have multiple • Speakers or headphones (unless This one costs about $1 0.00 U.S.. I • Getting the RPi hooked up.
keyboards and mice on the top of the monitor or device you are believe that they have retired • First boot of the RPi with the new
my desk. using supports HDMI audio). (discontinued) the version for the OS.
• A 4-8 GB SD Card that is Class 1 0. RPi 1 A and 1 B. You CAN elect not
Versions P1 A and B used SD cards. While this is the “minimum” to get the interface board and So, let’s get the OS image. Go
P1 Model B+ and above have requirement list for this article, for ribbon cable and use female (Pi to the downloads page on the
switched over to a Micro-SD card our first project you SHOULD have side) to male (breadboard side) official Raspberry Pi website
only support. Keep this in mind the following items available… jumpers. These will work, (https://www.raspberrypi.org/dow
when buying a specific version. Of however, in some of the things we nloads). You will be presented
course you can use a bigger card. • Breadboard – The breadboard do later on, if you get the jumper multiple versions of various images
Officially they say that testing has will be needed to start working on the wrong pin of the Pi, it could that you can download, including 2
been done with 32 GB cards and with add on discrete components lead to damage to your Pi. versions of Ubuntu (The GUI
don’t see many issues with most of like LEDs, resistors, switches, etc. • Various Resistors, LEDs and Mini version is Ubuntu Mate), Windows
the larger cards. Please Be careful without having to do any pushbutton switches. I will give 1 0 IOT and more. If you have an
when buying SD cards, since they soldering. you a list before we need them to older model (original models A or
are not all created equal. Just • GPIO interface board (header) give you plenty of time to obtain B), neither of the Ubuntu images
because a cheap card is marked and Ribbon cable. This will them. You can get these at many or the Windows image will run on
“Class 1 0” doesn’t actually mean connect the GPIO pins from the places. these models. You need the
that it is going to work like a more RPi to the breadboard. Check out • One other thing you might ARMV7 processor and the extra
expensive card. http://sparkfun.com or consider is a case, but only if you memory to be able to use these
• Some sort of Internet connection, http://www.Adafruit.com for this have the breakout boards and images.
either USB Dongle or Ethernet item. The item you will want to ribbon cables. This will protect
cable. look at from Adafruit is called “Pi your Pi from your handling of it. The two we are interested in
• A HDMI monitor/television for T-Cobbler Plus”. Note that this for this project, are the NOOBS
output and HDMI cable. If HDMI is particular item will NOT work with S ETUP OF YOUR RP I and the RASPBIAN images. I will
not available, the P1 A and B the RPi V1 A or B. It will only work be using the RASPBIAN Wheezy
versions provide a RCA Composite with the later versions. It is Now comes what must be for image dated 05-05-201 5 for our
Video out and 3.5mm Audio Out currently about $8.00 U.S.. If you me, the most tedious part of the first few projects, but if you want
connector. The P1 B+ version and are using a model A or B, you project… the setup. The steps we to have the option of booting into
later have done away with the RCA should get “Pi T-Cobbler” which is will perform are: other OS images on the same card,
Composite Video connector and about $7.00 U.S. If you are looking
full circle magazine #1 03 13 contents ^
HOWTO - PYTHON
feel free to download the NOOBS for you to remember. named my machine Slartibartfast.
image. Just remember, if you have
more than one OS on the card, you
have less space available to the
I NSTALLING THE OS I MAGE
TO THE SD CARD
Slartibartfast ~ # df -h
Filesystem Size Used Avail Use% Mounted on
RASPBIAN image and you will run /dev/sda1 451G 336G 93G 79% /
into an issue that I always used to, none 4.0K 0 4.0K 0% /sys/fs/cgroup
not enough space for all the things If you are using an early version udev 3.9G 4.0K 3.9G 1% /dev
you want to try. Assuming that of the Pi, you will be using a tmpfs
none
796M
5.0M
1.5M 794M
0 5.0M
1% /run
0% /run/lock
you are doing your work on a Linux standard sized SD card. If you are none 3.9G 124M 3.8G 4% /run/shm
machine, you can see the official using a later version you will be none 100M 32K 100M 1% /run/user
installation instructions at using a Micro-SD card. To save me /dev/sdd1
EXT
2.8T 2.5T 314G 89% /media/greg/TOSHIBA

https://www.raspberrypi.org/docu having to type the distinction /dev/sdb1 1.8T 1.5T 294G 84% /media/greg/extramedia
mentation/installation/installing- every time, I will use “SD” in the /dev/sdc1 917G 681G 190G 79% /media/greg/MoreMedia2
images/linux.md . If you are using documentation. One more thing Slartibartfast ~ #

a Windows machine or a Mac, before we start. I STRONGLY


follow the links there. I’m going to SUGGEST that you do not use a Notice that I have 4 drives (sda1 , sdb1 , sdc1 and sdd1 ). I hope that when
assume a Linux machine and will device connected to an external I plug in the SD card, it will come up as /dev/sde1 . This will be important
give you the instructions here. USB hub for the imaging of the SD to know because if we get the wrong /dev/ device, we will corrupt it!
card. I know the specs say you can, Now plug your SD card into the computer and run “df-h” again. My
Before we get started, you but I've never had very good luck system responds as:
might be asking why, if there is a doing this.
newer/better version available, am Slartibartfast - # df-h
I using the older version. I’ve had OK, here we go. Before Filesystem Size Used Avail Use% Mounted on
some trouble with the ‘J essie’ inserting the SD card into your /dev/sda1 451G 336G 93G 79% /
release and am more comfortable Linux box, open a terminal and do: none
udev
4.0K 0 4.0K
3.9G 4.0K 3.9G
0% /sys/fs/cgroup
1% /dev
with the ‘Wheezy’ release at this sudo -i
tmpfs 796M 1.5M 794M 1% /run
time. I doubt that this was an issue none
none
5.0M 0 5.0M
3.9G 124M 3.8G
0% /run/lock
4% /run/shm
with the release, probably just a Most of the commands don't none 100M 36K 100M 1% /run/user
bad download, but I just wanted to actually need the sudo level
/dev/sdd1 2.8T 2.5T 314G 89% /media/greg/TOSHIBA
let you know. For the purpose of permissions, but it won't hurt and
EXT
/dev/sdb1 1.8T 1.5T 294G 84% /media/greg/extramedia
the next few articles, use ‘Wheezy’ neither you or I have to remember /dev/sdc1 917G 681G 190G 79% /media/greg/MoreMedia2
and feel free to play with other when they do. Now run “df -h” to
/dev/sde1
/dev/sde2
56M 20M
30G 3.0G
37M 36% /media/greg/boot
25G 11% /media/greg/13d368bf-
versions. see what devices are currently 6dbf-4751-8ba1-88bed06bef77
Slartibartfast - #
mounted in the system. My system
Unpack the archive and have it responds as shown below. Yes, I've
be sent to a folder that will be easy
full circle magazine #1 03 14 contents ^
HOWTO - PYTHON
Thank goodness! However Slartibartfast Raspbian # dcfldd bs=4M if=2015-05-05-raspbian-wheezy.img of=/dev/sde
/dev/sde1 has two partitions. This 768 blocks (3072Mb) written.
will be important in the next step. 781+1 records in
If you are me, please write down 781+1 records out
Slartibartfast Raspbian #
the drive information so you don't
make a mistake. Now you will want
to unmount the SD card drive. We are about to write the Slartibartfast Raspbian # dd bs=4M if=/dev/sde of=wheezy-
Raspbian image to the SD card. 2015-11-07.imgsafe
Slartibartfast ~ # umount There are two ways to do this. 7609+1 records in
/dev/sde2 First is to use the “dd” command 7609+1 records out
31914983424 bytes (32 GB) copied, 1675.51 s, 19.0 MB/s
Slartibartfast ~ # umount
AS SUDO, which I'm sure will be Slartibartfast Raspbian # truncate --reference 2015-05-05-
/dev/sde1 the first thing that comes to raspbian-wheezy.img wheezy-2015-11-07.imgsafe
everyone's mind. However, Slartibartfast Raspbian # diff -s wheezy-2015-11-07.imgsafe
2015-05-05-raspbian-wheezy.img
Slartibartfast ~ # df -h
remember when we use “dd”, we Files wheezy-2015-11-07.imgsafe and 2015-05-05-raspbian-
don't get any information coming wheezy.img are identical
Notice that I started yet back to tell us what is going on and
another “df -h” just to verify that if it takes 5 minutes or longer to have unpacked the image you are want to verify the write so that
the device is unmounted. write the image, we won't see going to use. you can be sure that this matches
anything that entire time in the the image. We will make an image
If you have ever used this SD way of progress. While there are I show (below) an “ls” command of the SD card we just did and
card for anything before, you will other methods I'm going to here. I do this so I can remember write it to a temporary image file
want to remove the partitions suggest that instead, you can use the name of the file that I'm just back to the hard drive. Since your
before proceeding further. Some the “dcfldd” command (shown top about to work with, and I have the SD card will likely be bigger than
people might argue that this is not right). Once it gets started (whichexact spelling. the one they used to create the
necessary, but why not? It only could take a minute or so) it will distribution image, we will need to
takes a few seconds and it keeps give a progress report about how On my machine, the process truncate our copy to match the
us from having problems. Use much has been written. Pick your took about 1 0 minutes total. size of the original and finally use
“gparted” to remove all the “weapon” of choice. I'm going to diff to verify that both images are
partitions. show “dcfldd”. Now, as SUDO, This next step (above) is totally the same. Remember this could
please change to where ever you optional, but if you are like me, you take a rather long time if you have
a card larger than about 8Gb. I'm
Slartibartfast Raspbian # ls -al
total 7424016 using a 32Gb card and it looks like
drwxr-xr-x 2 greg greg 4096 Oct 31 12:02 . it's going to take probably 30+
drwxr-xr-x 3 greg greg 4096
-rw-r--r-- 1 greg greg 3276800000
Oct 23 20:11
May 7 2015
..
2015-05-05-raspbian-wheezy.img
minutes to copy the image to the
-rw-r--r-- 1 greg greg 4325376000 Sep 24 16:14 2015-09-24-raspbian-jessie.img drive.
Slartibartfast Raspbian #

full circle magazine #1 03 15 contents ^


HOWTO - PYTHON
As you can see, the images are Plug in the Ethernet cable into this once. keyboard layout I wish to use. It
the same, so if there is anything the Ethernet port or Wireless asks a lot of questions, so I would
wrong from here until we log in, dongle into the USB Port. You will see a screen with 9 select “Generic”, “US”, “US”,
it's not our fault. This process options on it. We will work with “Default”, ”No Compose Key” and
could be a useful process as you go Switch on your monitor or TV numbers 1 ,3 and 4. “No” to Xserver Termination key.
along and want to make a backup and get it set to the proper mode • Option #1 - Asks about
image of your Pi's “drive”, just in (HDMI or Composite). expanding the file-system. You Finally I'm ready to set it up, so I
case something happens. really want to do this so you can select “Finish” and “yes”. Your Pi
Plug in the video cable (HDMI get the most space you can. It will should reboot and you should see
Finally, we want to run the sync or Composite). take effect at the next reboot. the normal desktop. Now we want
command which will make sure • Option #3 - Enable boot to to update the system to the latest,
that anything remains Put the SD card (or Micro-SD Desktop/Scratch. You should go add a couple of applications that
uncommitted in the write cache is card) into place. It doesn't matter ahead and set this to Desktop we'll need right away and then let
flushed and that is ok to unmount if you are using a full size SD card Login as User 'Pi' at the Graphical it reboot once again.
the SD card. or a Micro-SD, you will insert it Desktop.
with the label facing down, not up • Option #4 – This sets various Open a terminal off the top
Now we can move on to some towards the bottom of the Pi. And things that we take for granted by menu bar and do:
more “exciting” things. Powering whatever you do, DO NOT remove our automated setup systems.
on the Pi. the SD card while the RPi is They include Locale, Timezone and sudo apt-get update
powered on. Keyboard Layouts. sudo apt-get dist-upgrade
G ETTING READY TO POWER At this point, we are ready to
• First select Locale. Since this
computer comes from the UK, its
UP YOUR RP I plug in the power, so take a deep default is to select things that
Now we want to install
TightVNCServer. While this is an
breath and cross your body parts. someone living there would need. optional step, I find it much more
Notice how I worded the Plug it in. I, on the other hand, need to constructive to use the Remote
heading for this portion of the change some settings. I have to window on my Linux desktop than
instructions. There are certain If it worked, then we'll move on. let the window scroll down to be forced to have 2 monitors,
things you should do before you If not, please retry the instructions EN_US.UTF-8 UTF-8 and select it. keyboards and mice. It always gets
apply power to your RPi. There are above. Follow the prompts and you'll be me confused about what/where I
possibilities you can damage your fine. am.
RPi if you don't do the steps in Once you get Pi booted into a • Next I need to set my time-
order. distribution for the first time, you zone. Since I live in Colorado, USA, I sudo apt-get install
will presented with the raspi- would select America under the tightvncserver
Plug in the Keyboard and config application. We are going Geographic area, and Denver for
Mouse into the USB port/ports. to want to tweak some of the the Time Zone. Once that's set up, it will ask
settings. We only really need to do • Finally I have to select the you to create a password, so no
full circle magazine #1 03 16 contents ^
HOWTO - PYTHON
one can just jump into your screen. Move over to your normal surprised by the power of this tiny
Make it easy for you to remember. computer and load VNCViewer device.
software on it. Once that's all
The very next thing we want to done, you will probably want to So until next month, the last
do is set the tightvncserver to spend a moment or two by thought I will leave you with is
automatically startup on boot. rebooting the computer and something we hear here in the U.S. The Ubuntu Podcast covers all
That way we don't have to have a making sure that the VNC really all the time... the latest news and issues facing
mouse or a keyboard. did start up and connect. If Ubuntu Linux users and Free
everything works, you are done. “But wait … there's more!!!!!!!” Software fans in general. The
• Change to the home directory if show appeals to the newest user
you aren't already there. You will need (as I said earlier) a and the oldest coder. Our
$ cd /home/pi few things for next month. Some discussions cover the
• Next, change to the .config male to male jumpers, female to development of Ubuntu but
directory. female jumpers, the breadboard, aren’t overly technical. We are
$ cd .config
• Now we will make a new interface and cable and a handful lucky enough to have some
directory here called 'autostart'. of things from the electronics great guests on the show, telling
$ mkdir autostart store… us first hand about the latest
• Change to the autostart directory exciting developments they are
we just created. • Some small LEDs. Try to get working on, in a way that we can
$ cd autostart around 1 0 of each Red, Green, all understand! We also talk
• Now create a new configuration Yellow and Clear. about the Ubuntu community
file. $ nano tightvnc.desktop • Some small ¼ watt resistors. 220 and what it gets up to.
And enter the following lines: ohm, 4.7K ohm, 1 0K ohm, and
[Desktop Entry]
Type=Application
some other “normal” hobbyist The show is presented by
Name=TightVNC resistors. About 1 0 each will do members of the UK’s Ubuntu
Exec=vncserver :1 you and the salesperson at the Linux community. Because it is
StartupNotify=false
local shop should be able to get covered by the Ubuntu Code of
• Save the file (^O) and exit (^X). you what you need. Conduct it is suitable for all.
• A couple of small switches (spst)
Almost done now. The last that will fit on the breadboard. The show is broadcast live every
thing we will need to do is install (usually comes with 4 pins). Greg Walters is owner of RainyDay fortnight on a Tuesday evening
the IDE we will be using for our Solutions, LLC, a consulting company
in Aurora, Colorado, and has been (British time) and is available for
code development, which is Geany. Really that's about all you will programming since 1 972. He enjoys download the following day.
need for the next article. In the cooking, hiking, music, and spending
sudo apt-get install geany time with his family. His website is podcast.ubuntu-uk.org
meantime, enjoy playing with Linux www.thedesignatedgeek.net.
on the Pi. I think you will be
full circle magazine #1 03 17 contents ^
H OW-TO
Written by Greg D. Walters P ro g ra m m i n g I n P y t h o n P t . 6 2
B y the time you read this, it will
probably be old news that
there is a new Raspberry Pi that
(http://fritzing.org/home/). Not
only can you keep copies of our
projects locally, you also can have
on some of the electronic
components we will be using this
one. In the case of the LED
projects, we will be using resistors
time, Resistors, LEDs and Switches. so that they will reduce the
was released on November 26, some fun designing your own amount of electricity flowing
201 5. It's called the Raspberry Pi
Zero and the price is an
circuits. RESISTORS through the LED (and the GPIO
pin), to keep it from burning out.
unbelievable $5 U.S. or 4! . I
haven't had a chance to find any
A Q UICK D ISCUSSION O F A resistor is a device that
For a more detailed discussion
actual dimensions, but they say it O UR COMPONENTS 'resists' the flow of electricity to a
given extent. This will allow us to of resistors, please see:
is about the size of a stick of gum. limit the amount of electricity that https://learn.sparkfun.com/tutorial
So if you've been holding off One more thing before we get s/resistors.
started, which is a quick discussion flows through a circuit or part of
getting your new Pi due to cost,
now you don't have an excuse. We
will discuss the Pi Zero in future
LED S
articles.
Now back to my Physical
Programming series. This time we
are going to start actually
controlling things. Hopefully, you
have been able to procure some
LEDs, resistors, switches, jumpers
and a breadboard.
As we go through the series, I LEDs are Light Emitting Diodes
will be using a free design tool and are the “standard”
called Fritzing to provide a visual replacements for bulbs in just
representation of what the project about everything. With a little care
wiring should look like. in design, they will last almost
forever. An LED has two
You might want to get yourself leads/wires called Anode and
a copy from their website Cathode. The Anode is the positive
full circle magazine #1 04 11 contents ^
HOWTO - PYTHON
side and the Cathode is the
negative side. O UR FIRST PROJECT...
If you have a new LED directly Now let's get started with our
out of the package, you will notice first construction project. It's a
that one of the leads is longer than very simple electronics version of
the other. That is the Anode or the “hello world”. We will connect a
positive side. If both leads on a switch to one of the GPIO pins and
new device are the same length (or monitor it to catch the press of the
if you are recycling parts from an button.
old circuit board), look for the flat
edge. That will always show the Shown right is the actual
Cathode or negative lead. schematic that we will be working
with.
SWITCHES So we have a switch that is
connected between ground pin
The switch I chose to use for and GPIO pin 1 7 which is physical
this project is one that easily pin 1 1 . We also have an LED
mounts in the breadboard or on a connected with its cathode to
circuit board. It is simply square GPIO pin 1 8 (physical pin 1 2) and
with a small round momentary its anode connected to a resistor
button on the top. It also has 4 that connects to the 3.3volt pin on
pins. The trick is to know which the Pi. It is at this point that you
two pins of the four will be the need to make a decision. Will you
ones we need. You could take an reference the pins by their position
ohm-meter and run across all the on the board, or the GPIO
combinations of pins until you find numbers. We'll get back to that in
the set that works, or you could a minute. In the meantime, here's
just look at the layout of the pins the wiring diagram…
that connect it to the breadboard.
The two pins to be used have the You can see on the breadboard
leads that grip into the board the three components...the switch,
pointing at each other. You only the LED and the resistor. The first
need one set of pins, so just pick pin on the RPi is the one on the top
the set you wish. right. That pin provides the 3.3
full circle magazine #1 04 12 contents ^
HOWTO - PYTHON
volts DC that we need to power If you have been keeping up so
our project. The pin below it is far, you will notice that I am giving
import RPi.GPIO as GPIO
counted as pin #2. Pin #6 is a both the physical pin number as # If you are using the BCM GPIO pin numbers...
ground pin. Note that both of well as the BCM GPIO pin number. #LedPin = 18
those pins have wire connectors The “BCM” stands for Broadcom,
#BtnPin = 17
# Otherwise the physical board numbers...
that go to the long horizontal and, in our code, we will have to LedPin = 12
buses on the breadboard. Some tell the RPi.GPIO library if we are
BtnPin = 11
breadboards have a “+” and “-” on using board numbering or BCM
the power bus to help you numbering. This is the decision I to be very nice, but it gives you references, and it defines the
remember which bus is which. I was referring to earlier. In our only the BCM numbers on the pins. Output pin to drive the LED and
also have a long jumper from the code, we will have to be consistent Our next bit of code (shown the pin that the signal from the
positive 3.3 volt bus at the top of with one numbering scheme or the below) will be a function called button will be coming in on. Also
the breadboard down to the bus other. In the code we are about to “setup”, where we set up the notice that we define the pin for
on the bottom. It really doesn't look at, I provide both, and you can information for the library to use. the button to have a pull-up
matter which bus on the comment out whichever one you resistor. This means that the
breadboard you use for your don't want to use. My personal Notice that the first line is signal-line will be at 3.3 volts and
power, as long as you are preference is to use the BCM GPIO commented out since I will be when the button is pressed it is
consistent. numbers, but for this project, I will using the board numbering in this pulled down to ground.
stick with the physical board pin example, but it's there to show you
There is a short jumper going numbers. Now let's get into the how to make the call. Our next function (following
from the top ground bus to one code. page, top right) is called loop, and,
side of the switch and the other Lines 3 and 4 show how to as the name suggests, we simply
side of the switch connects to As always, I will break the code define what the pins will be, either do a loop, checking the button
physical pin 1 1 on the RPi (or GPIO into parts and discuss each one. input or output, and if we use the input pin to see if it has been
pin 1 7). As for the LED, the First (top right) we have to import internal pull up resistors built-in on pulled low. If it has, then we turn
Cathode is connected to the the RPi.GPIO library, and we will the RPi or not. So basically this the LED on, otherwise we set the
physical pin 1 2 on the RPi (GPIO alias it to the name “GPIO” to make portion of the code says to use LedPin to high. That might sound
1 8) and the Anode is connected to things easier to type. Next, we physical board pin numbers as counter-intuitive, but remember
the resistor, which in turn is define two variables; LedPin and
connected to the lower 3.3 volt BtnPin to the pin numbering def setup():
bus. Also notice that the wiring is scheme we wish to use. Here, I've
#GPIO.setmode(GPIO.BCM)
GPIO.setmode(GPIO.BOARD)
colour coded. Red will ALWAYS (in decided to use the Physical pin GPIO.setup(LedPin, GPIO.OUT)
my diagrams) be a positive voltage, numbering, since you probably GPIO.setup(BtnPin, GPIO.IN,pull_up_down=GPIO.PUD_UP)
Black is for ground. Any other don't have a breakout wedge yet.
colors will mean interconnections I've found the one from SparkFun
for data.
full circle magazine #1 04 13 contents ^
HOWTO - PYTHON
we have the Anode connected to
the 3.3 volt bus through the def loop():
while True:
resistor. This means to turn the if GPIO.input(BtnPin) == GPIO.LOW:
LED on, we have to pull the print('...LED On')
Cathode down to ground (0 volts) else:
GPIO.output(LedPin,GPIO.LOW)
level to allow the LED to turn on. print('...LED Off') The Ubuntu Podcast covers all
GPIO.output(LedPin,GPIO.HIGH) the latest news and issues facing
The destroy function (shown Ubuntu Linux users and Free
below) basically cleans up the our loop routine reads the level or authors to have room for their Software fans in general. The
states of the pins so we don't get status of the button pin and once articles. Keep everything close at show appeals to the newest user
any errors the next time we need the voltage goes low, it says hand, because we will be using the and the oldest coder. Our
to use them. “oh...the button input is low, so I same hardware setup next time. discussions cover the
need to turn on the LED”. development of Ubuntu but
Finally, we use the “main loop” Enjoy playing for now and I will aren’t overly technical. We are
(shown bottom) to call the One other thing to notice is see you next month. lucky enough to have some
routines in the proper order and to that our first and second routines great guests on the show, telling
allow us an easy way to break out are named “setup” and “loop”. It is us first hand about the latest
of the loop by pressing the Ctrl-C a good thing to keep this format, exciting developments they are
key sequence. because when we get to the working on, in a way that we can
Arduino programming, these two all understand! We also talk
So, load the program into your routines are required. about the Ubuntu community
RPi and run it. You will notice the and what it gets up to.
text “...LED Off” keeps repeating We are going to stop here for
on the screen until you press the this month. I want the other The show is presented by
button. That is due to the fact that members of the UK’s Ubuntu
Linux community. Because it is
def destroy(): covered by the Ubuntu Code of
GPIO.output(LedPin,GPIO.HIGH)
GPIO.cleanup() Conduct it is suitable for all.
The show is broadcast live every
Greg Walters is owner of RainyDay fortnight on a Tuesday evening
if __name__ == '__main__': Solutions, LLC, a consulting company
setup() in Aurora, Colorado, and has been (British time) and is available for
try: programming since 1 972. He enjoys download the following day.
loop()
except KeyboardInterrupt:
cooking, hiking, music, and spending
destroy() time with his family. His website is podcast.ubuntu-uk.org
www.thedesignatedgeek.net.

full circle magazine #1 04 14 contents ^


H OW-TO
Written by Greg D. Walters P yth on I n Th e Rea l World Pt . 63
W elcome back to our Real
World programming series.
Last time, we programmed the RPi
questions, I suggest you look at
last month’s article which should
answer any of your concerns.
LED, and the orange wire controls
the red LED, since the red wire is
already being used.
connected to GPIO 1 7 (Physical pin
1 1 ), yellow LED cathode is
connected to GPIO 23 (Physical pin
to turn on and off an LED when a 1 6), and the green LED cathode is
button was pressed. Very simple, First, let’s look at the schematic You should also know that the connected to GPIO 22 (Physical pin
but this got us started. This month, and the breadboard (below right). pins being used should work on a 1 5). The Anodes of all three LEDs
we will do another simple project, RPi v1 a/b, RPi v1 b+ and RPi v2b. are connected to one side of 220
a traffic light simulator using 3 Notice that the wire colours Ohm resistors and the other sides
LEDs, one Red, one Yellow and one correspond to its ‘job’, with the The red LED cathode is are connected to a common 3.3
Green. For the most part, the code exception of the orange wire. The
is very similar to what we used last red wires supply 3.3 volts. The
month, so you shouldn’t have any green wire controls the green LED,
problems. If you have any the yellow wire controls the yellow

full circle magazine #1 05 12 contents ^


HOWTO - PYTHON
VDC. We don’t need the ground def setup():
voltage for this particular project. GPIO.setmode(GPIO.BCM) # Numbers GPIOs by physical location

Since I’ve driven only in the U.S. GPIO.setup(RedLedPin, GPIO.OUT)


GPIO.setup(YellowLedPin, GPIO.OUT)
# Set the 3 LedPins mode as output
I’ve based the simulation on our GPIO.setup(GreenLedPin, GPIO.OUT)
traffic patterns. Long red light (1 0
seconds), green light is usually GPIO.output(RedLedPin, GPIO.HIGH)
GPIO.output(YellowLedPin, GPIO.HIGH)
# Turn off LEDs
shorter than the red light time (8 GPIO.output(GreenLedPin, GPIO.HIGH)
seconds), and the yellow light is
fairly short (2 seconds). These physical pin numbers, be sure to
values are currently hard coded in change the GPIO.setmode() line in
def LEDLoop():
print "Green On..."
The LEDLoop routine is very
the time.sleep() function calls. Feel the next routine (top right). simple:
free to change them as you see fit. GPIO.output(GreenLedPin,0) • We print on the console “<color>
time.sleep(8) On…”,#
As I mentioned above, the • Turn the LED on by setting the
Now let’s start working through GPIO.setmode needs to be GPIO.output(GreenLedPin,1)
the code. print "Green Off..." output value to 0 or low,
changed from ‘GPIO.BCM’ to print "Yellow On..."
• Sleep for a designated period,
#!/usr/bin/env python
‘GPIO.BOARD’ if you want to use GPIO.output(YellowLedPin,0) • Set the output value of the pin
the physical pin numbers instead time.sleep(2) back to 1 or high,
# Traffic Light Simulator of the BCM numbers in our • Then print that the LED is now
# Written by G. D. Walters definitions. The next three lines GPIO.output(YellowLedPin,1)
print "Yellow Off..." off.
#-------------------------- set the LED pins as output pins, print"Red On..."
and then turn all three LEDs off to GPIO.output(RedLedPin, 0)
This is then duplicated for the
import RPi.GPIO as GPIO
import os start the program by setting the time.sleep(10)
GPIO.output(RedLedPin,1) Yellow and Red LEDs. The loop()
import time output value to HIGH. print "Red Off..." routine simply forces the
import datetime

#-------------------------- def destroy():


GPIO.output(RedLedPin, GPIO.HIGH) # led off
RedLedPin = 17 GPIO.output(YellowLedPin, GPIO.HIGH) # led off
YellowLedPin = 23 GPIO.output(GreenLedPin, GPIO.HIGH) # led off
GreenLedPin = 22 GPIO.cleanup() # Release resource

if __name__ == '__main__': # Program start from here


The first 9 lines are our setup()
standard import statements and a try:
few comment lines. The next three loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy()
lines define the BCM pin numbers will be executed.
for our LED pins. If you wish to use destroy()

full circle magazine #1 05 13 contents ^


HOWTO - PYTHON
LEDLoop() routine to be called
over and over until the user hits
<CTRL> C on the RPi keyboard.
THE O FFICIAL FULL CIRCLE APP FOR U BUNTU TOUCH
def loop():
while True:
LEDLoop()
B rian Douglass has created a
fantastic app for Ubuntu Touch
devices that will allow you to view
current issues, and back issues, and
The destroy routine and the to download and view them on your
main loop are the same as last Ubuntu Touch phone/tablet.
month. We simply set all the LED
pins to high, turning them off, and
then call GPIO.cleanup().
I NSTALL
Either search for 'full circle' in the
I’m not sure that we could make Ubuntu Touch store and click
a much simpler program to do install, or view the URL below on
what we need to do. your device and click install to be
taken to the store page.
If you want, you could duplicate
the 3 LEDS and make an https://uappexplorer.com/app/
intersection simulation before fullcircle.bhdouglass
next time.
Next time, we’ll have something
that is a bit more challenging. Until
then, happy programming.

Greg Walters is owner of RainyDay


Solutions, LLC, a consulting company
in Aurora, Colorado, and has been
programming since 1 972. He enjoys
cooking, hiking, music, and spending
time with his family. His website is
www.thedesignatedgeek.net.

full circle magazine #1 05 14 contents ^


H OW-TO
Written by Greg D. Walters P yth on I n Th e Rea l World - Pt 64
W elcome back to the crazy
world of Python
Programming in the real world.
output. The RPi, unlike the
Arduino, cannot do analog I/O. So
we are limited to turning a GPIO
Before we get started, I need to pin (and in this case, a LED) either
make a confession. Last time I on or off. This time we will be using
goofed. The images in part 63 are that knowledge to do something
wrong. The LEDs are backwards pretty interesting.
from what they should be. Brian
Kelly noted this and was brave So get your Pi and your
enough to point out the old man’s breadboard and we’ll start
errors. Thank you Brian. If you working.
follow the text, you should be
good to go. THE WIRING
Secondly, I have to apologize You will need a Raspberry Pi, a
for not making it last month breadboard, two LEDs - one Red
(FCM#1 06). I’m having more and one White, two 220 Ohm
medical issues that are keeping me resistors and 3 jumper wires.
from sitting for too long. Hopefully
this will be taken care of soon. I’ve used the original Pi for this
wiring image example. If you have
Enough of that. Now for this a Pi B+ or 2B (or even the brand
month’s offering. new 3), the pins at this point are
exactly the same.
THE M YSTERY LED
Just to avoid confusion (on my
In the last two articles, we side), the Cathodes (Negative side)
learned how to turn on and off of the LEDS are connected to the
LEDs programmatically. That was resistors going to ground, and the
simple enough. This is digital Anodes (Positive side) are
output as opposed to analog connected through the jumper
wires to the Pi pins. The positive
full circle magazine #1 07 15 contents ^
HOWTO - PYTHON
side of the LED is usually marked
by the longer lead and the import RPi.GPIO as GPIO
from time import sleep
negative side is the one that has GPIO.setmode(GPIO.BCM)
the flat spot on the base of the GPIO.setup(25,GPIO.OUT)
LED. GPIO.setup(24,GPIO.OUT)
white = GPIO.PWM(25,100)
red = GPIO.PWM(24,100)
THE CODE white.start(0) # start white led on 0 percent duty cycle (off)
red.start(100) # red fully on (100%)
pause_time = 0.05
I won’t explain the code just print("Program Starting...Press CTRL+C to exit")
try:
yet. Just put into the editor as it is. while True:
We will discuss it in a bit. for i in range(0,101): #101 because it stops when it finishes 100
white.ChangeDutyCycle(i)
red.ChangeDutyCycle(100-i)
Once you have the code sleep(pause_time)
entered correctly, then run it and for i in range(100,-1,-1):
white.ChangeDutyCycle(i)
see what happens. red.ChangeDutyCycle(100-i)
sleep(pause_time)
THE REVEAL except KeyboardInterrupt:
white.stop()
red.stop()
If you have been paying GPIO.cleanup()
attention over all these years, you
probably have figured out what are bending them to our benefit. a 1 . Just like we have assumed... You can see that the signal is on
the code is doing. If you can’t The pictures below, taken from my either Off or On. for about 80% of the time and off
figure it out, don’t feel bad. We’ll oscilloscope connected to the for about 20%, which would be a
jump into the explanation. project, should help explain a bit This time we vary the amount 80% duty cycle. By doing this
clearer. We will be concerned with of time that the GPIO signal is high quickly, the LED reacts by dimming
Instead of the LEDs being only one LED at this point. and low. If we do it slowly, the LED
either on or off, they pulse on and would simply flash on and off in
off. Since I said earlier, we can only If we send out a Low to the response to the voltage. In the
send out (or read) a On/Off GPIO pin to the LED it's zero volts. case of this version, we are
voltage (or 1 /0, or High/Low), so The LED is getting nothing on the switching it on and off very quickly
how can this be? Anode, so it is off. In the last two and at the same time, changing the
articles, when we turned the LED amount of time it is on compared
We are using a trick called PWM on by sending the Anode of the to off, which is called the duty
or Pulse Width Modulation. We are LED a High So we have in the first cycle.
still living with the rules, but we instance a zero, and in the second
full circle magazine #1 07 16 contents ^
HOWTO - PYTHON
a bit from the 1 00% on all the try:
time. As the program does its loop, while True:
it changes the duty cycle and for i in range(0,101): # 101 because it stops when it finishes 100
makes the high longer or shorter white.ChangeDutyCycle(i)
red.ChangeDutyCycle(100-i)
depending on what part of the sleep(pause_time)
loop it is. for i in range(100,-1,-1):
white.ChangeDutyCycle(i)
red.ChangeDutyCycle(100-i)
sleep(pause_time)
except KeyboardInterrupt:
white.stop()
red.stop()
GPIO.cleanup()

GPIO.setmode(GPIO.BCM) print("Program happens, we fall out of the TRY


GPIO.setup(25,GPIO.OUT) Starting...Press CTRL+C to
exit") side so we can do our clean up
GPIO.setup(24,GPIO.OUT)
white = GPIO.PWM(25,100) code.
red = GPIO.PWM(24,100) We set the pause_time variable
to 0.05 seconds. This makes it fast So now you know that we can
In the picture above, we have a In these five lines, we set the enough to (hopefully) not allow for bend the rules to our use.
duty cycle of about 5%. In this case GPIO mode to BCM, and set the a flicker.
the LED is turned on for such a GPIO pins 24 (physical pin 9) and Next time, we will start to
short time, that it is extremely dim 25 (physical pin 1 1 ) to be output In the next block of code, we do examine a different GPIO library.
and for all intents and purposes it pins. We have done this before. our loops. The first loop is to make Until then, have fun.
is off. Now we set the values for the the white LED get “brighter” and
PWM to 1 00% duty cycle. the red LED to get “dimmer”. The
Now, let’s start taking apart the second is to reverse the process.
code. white.start(0) # start white
Just using the first loop as an
led on 0 percent duty cycle
import RPi.GPIO as GPIO
(off) example, we use a FOR LOOP to
from time import sleep set the value of i and then we set
red.start(100) # red fully on
(100%) the duty cycle for the white LED to Alan holds a PhD in Information and
the Knowledge Society. He teaches
As always, we start with our i and that of the red LED to 1 00-i. computer science at Escola
imports. We import the GPIO We next turn the Red LED on Andorrana de Batxillerat (high-
library, and this time, we import (1 00%) and the white LED to 0 Notice that we have wrapped school). He has previously given
the sleep function from the time volts. this with a TRY...EXCEPT set. This GNU/Linux courses at the University
of Andorra and taught GNU/Linux
library. You will understand the allows us to continue to run until syadmin at the OU of Catalunya.
reason for that shortly. pause_time = 0.05 the user enters CTRL+C. When that
full circle magazine #1 07 17 contents ^
H OW-TO
Written by Greg D. Walters P yth on I n Th e Rea l World - Pt 65
W elcome back. This month
will be a hodgepodge of
information. The main reason is
• Male to Male jumpers (Arduino to
Breadboard) about 8”
• Male to Male jumpers
currently the Echo / Alexa is
available only in the US and many
people in the UK and other
https://github.com/lennysh/AlexaP
i. To be honest, I tried this, but
could not get it to run. I will tell
that there are some important (Breadboard to Breadboard) small countries have been waiting, not you that I did not spend nearly as
advances in tech and you will need to medium so patiently, for it. This gives them much time on this project as I did
time to get some parts for the • Toy/Hobby motor 6 VDC a chance to enjoy the technology. on the Java version, due to many
next few articles. • L293D or SN75441 0 Motor doctor visits this past week. I
Control Chip There are at least two projects intend to spend more time on it to
In the near future, we will be • 4 AA Battery Holder and currently working on getting Echo try to get it working.
adding the Arduino into our Batteries. on the Pi. The first uses Java. You
toolbox. I suggest starting off with can find the code and instructions If you decide to try either
the UNO or a UNO clone which can This will pretty much get you at https://github.com/amzn/alexa- projects, PLEASE use a blank SD
be purchased for less than $30 US going for the next few months. Of avs-raspberry-pi. I have done this card and not one that has
(£22). We will also need some course, you could get more and project on both a Pi Version 1 B and something you want to keep. Load
sensors to really get going. While explore on your own. Most the new Pi 3B. It worked well on the Raspbian or NOOBS OS from
these are optional and you can just everything on the list is less than both. Many people have problems scratch. That way, if something
read the article, building these $1 0 US. If you shop the internet getting this to work, but I did it in goes wrong, you can just reload
projects are more than half the diligently, you can get very good about 4 hours (with small breaks the OS and start fresh.
fun. So, with that said, here is a list prices on everything really and interruptions), and it worked
of parts… inexpensively. We’ll leave this for the first time. The best advice I can There are some things you need
• One Wire Digital Temperature now, but for next time, you will give you is take your time, plan on to know before you attempt to do
Sensor - DS1 8B20 need the DS1 8B20 temperature a long weekend, and follow the this project. All of the information
• DHT1 1 Basic sensor and a 4.7K resistor as well instructions to the letter. The only below pertains to the java version,
Temperature/Humidity Sensor as a breadboard and jumpers if you problem that I had was that npm but some can be considered to
• 1 6x2 LCD Display don’t already have one. and nvm needed to be installed, apply to both projects…
• 4.7K and 1 0K ¼ Watt resistors (3 and, at that time, these installation • You need to have a USB
or 4 of each) Recently, there has been a instructions were not included. I microphone. Headphone based
• Large Breadboard (60+ x 1 0 with great stir on the Internet about the believe this issue has been microphones have issues. I’m using
power rails) Amazon Echo / Alexa device corrected. a Logitech webcam with built in
• 1 0K Potentiometer (2 or 3) software being ported to run on microphone and it works well.
• Male to Female jumpers (Pi to the Raspberry Pi. The biggest The second project uses Python • You will also need a set of
Breadboard) about 8” reason for the excitement is that and is located at speakers or headphones attached
full circle magazine #1 08 15 contents ^
HOWTO - PYTHON
to the audio out jack. Many people patient. The device was a sleeper smaller than 1 6 Gig. month, but next month, we will
have had lots of issues with for a while and just recently took • As soon as you boot into the new turn our RPi into a thermometer.
bluetooth audio devices. off well. Amazon, I’m sure, is operating system for the first time, The neat thing about using the
• You must push a button to get working on support for other run a ‘sudo raspi-config’. Be sure to DS1 8B20 sensor is that you have
the Echo / Alexa to listen for your countries right now. enlarge the file system to take in more of them on a single line. This
command. It doesn’t currently • When you start the app, you have the entire card. Be sure to turn way, you could use one in the living
listen for the “wake” word. (more to run two processes. The second SSH on. You will need to reboot room, one outside, etc. We’ll use
below). one will create a GUI box which has here. Next you should then do a these sensors later on with the
• Some of the features that the a long URL string that you must ‘sudo apt-get update’ and then a Arduino and be able to use the
actual Echo / Alexa have don’t copy and paste into a web browser. ‘sudo apt-get dist-upgrade’ so you arduino as a remote device so we
currently work. Once that gets to Amazon are at the latest software don’t have to try to run a long
• Things like location, weather, properly, then you must click the revisions. cable and change the resistance to
traffic, work correctly only in the [OK] button on the screen. You will • There are some steps that a point that it won’t work.
USA. In any other country, you will be presented with a screen that require you to enter certain data.
get information for Seattle, has a [Start Listening] button and Make notes of what you entered, Until next month, enjoy
Washington, USA some multimedia buttons. To either by a screen shot, into your checking out the Alexa project,
• The only supported language “wake” Alexa up, you click the smartphone, or (HORRORS!!!!!!) on and, if you try it / them, hope you
currently is English. According to ‘start listening’ button and, after paper. It will make things easier. have success.
what I was able to find out from you hear the “ding”, speak your • If you have any problems, check
my research is that, once the question or command. When the issues section. More than likely
device is being sold in a given finished, you can click that button someone has already had the same
country, they will add support for again to have it stop listening and problem and there might be a fix.
that country's “official” language. I process your command, or you can • Print the web page with the
understand that in the UK, the let it timeout (about 5 seconds) instructions and work off the print.
official language is English, and then it will start processing. Many This way, you can check off those
that in the USA, there is no people are working on headless steps you have already completed.
“official” language and that operation (no monitor) and a Especially helpful if you get
Spanish is a largely spoken physical button connected to a interrupted.
language, but is not supported on GPIO pin, and some are actually • You can find more information,
the device as yet. There are many working on the “wake” word and change certain settings, at
Greg Walters is owner of RainyDay
flame threads on the web – if you option. You can find more alexa.amazon.com. I understand Solutions, LLC, a consulting company
wish to voice your ire at the fact information in the issues section. that some people who are not in in Aurora, Colorado, and has been
that your language of choice is not • You should (read MUST) use a the USA have problems with this programming since 1 972. He enjoys
supported or that the Echo / Alexa decent quality SD card. My site. cooking, hiking, music, and spending
is not available there. All I can suggestion is to get nothing less time with his family. His website is
www.thedesignatedgeek.net.
suggest is that you should be than a Class 1 0 card that is no I think that’s enough for this
full circle magazine #1 08 16 contents ^
H OW-TO
Written by Greg D. Walters P yth on I n Th e Rea l World - Pt 65
L ast month, I suggested you get
a number of parts and if you
were able to get them, I hope that
that seemingly could not be done
without a ton of training. Secondly,
is to show that the newer
are using now will go unused after
a single project. For example, once
we have a grasp of some of the
accuracy (32⁰ to 1 22⁰ F, ±3.6⁰F) and
a humidity range from 20-90%RH
±5%. You can see that it’s not the
it didn’t cost you too much. If you technology, like the Raspberry Pi Arduino basics (which WILL involve most accurate sensor on the
haven’t gotten them, then follow and the Arduino, is not beyond the learning a small amount of ‘C’ like market; there is a DHT22 that is
along as best you can, and if there ken of the “general joe” out there, programming (sorry about that)), more accurate and has a wider
is a particular project you want to but that anyone can do things that we’ll be writing programs in range (-40⁰ to 80⁰ C temp range)
try, then get those components have real world applications (hence Python on the RPi (or your local but about twice as expensive.
that are needed. I’m trying to do the title of our series). That having
computer) to control the Arduino.
this on as little cash outlay for been said, making LEDs blink is The sensors we have learned about It’s a bit of a funny looking
either you or me as possible. only the same kind of project for in our RPi experiments will be re- thing. A blue rectangular plastic
Frequently, you can recycle many the hardware world as the “Hello used when we learn about the box with holes in it and something
of the items from older electronic World” program is in the Arduino, and many will be shiny inside it. It might come just
items; many can be found at a local programming realm. You have to incorporated into some larger as a single sensor with 4 pins, or
thrift store for pence on a pound. take small steps before you move projects. Very shortly, we will be already on a mini-circuit board with
(Hopefully I got that one right. We to the big race. Believe me, we willusing DC Motors, Solenoids and 3 or 4 pins. Either way, they are
say pennies on a dollar here, so at be doing some amazing things with Stepper Motors in some really basically the same. For now, we’ll
least give me an “F” for effort… all those little parts, whatsits andbasic projects, but we’ll use them use the discrete component (the
ok?) thingamabobs. in larger projects, including one without the circuit board) for
building a Computer Controlled the sake of the discussion, and I’ll
As I was laying last week, This month, we will be using the (RPi) Laser Engraver using a Laser address the differences as we go
waiting for some surgery, I was DHT1 1 Basic Temperature/ Diode recovered from an old DVD along.
thinking that if someone were to Humidity Sensor with our Burner.
come up to me and ask directly Raspberry Pi. Next month, we will Whenever you want to work
why I’m doing this, what my be doing the same sort of thing Enough about the future. Let’s with a new sensor, you should get
answer would be. Before the using the Dallas DS1 8B20 start with this month's project. a spec sheet (data sheet). A simple
wonderful chemicals they pumped temperature sensor, and if there is web search should turn up a
into my body to make the process time and/or space, we’ll also talk The DHT1 1 is the least number of results. Try to get
less horrible, I realized that the about the 1 6x2 LCD display. In a expensive sibling of a series of something directly from the
REAL reason is multi-part. First, is few months, we’ll switch from the temperature and humidity sensor manufacturer if at all possible. For
to create excitement in “non- Raspberry Pi to using the Arduino. sets. The DHT1 1 has a temperature the DHT1 1 , a good place to get
programmers” when doing things Don’t worry, none of the things we range from 0⁰ to 50⁰ C with ±2⁰ C one of the various data sheets
full circle magazine #1 09 18 contents ^
HOWTO - PYTHON
available is supply (at the sensor) as a pull-up. “raw” DHT1 1 sensor WITHOUT a a 5K resistor works pretty well. If,
http://www.micropik.com/PDF/dht One last thing (I’m going to stop breakout board. If you have a however, you are going to use 5
1 1 .pdf. While this isn’t directly here, but there’s much more): Pin 1 sensor with a breakout board, see VDC as shown in the diagram, use a
from the manufacturer, it is from a is positive voltage, Pin 2 is the data my discussion below the diagram. 1 0K resistor.
company that sells it, and has pin, and Pin 4 is the ground pin.
“translated” the manufacturer’s This gives us pretty much Notice that I said earlier that a You can see that it’s fairly
data into a 9-page PDF file. everything we need to know to 5K resistor was needed as a pull- simple, just three wires and a
safely connect this to our RPi. up. If you are going to use 3.3 VDC resistor. For our simple project,
You might already be asking, Below is the wiring diagram for a as a power source (RPi pin 1 ), then don’t try to make the wiring the
why do I need this? There’s a bunch entire 20 meters though.
of information that, unless you
have a PhD in Physics or If you have a DHT1 1 on a
something, you’ll never need. Well, breakout board, you will likely have
that is true, but there is a lot of only 3 output pins on it. I have two
information that IS relevant and sensors from different vendors,
can potentially keep you from and (go figure) both have a
blowing up either the sensor, the different pinout. One is laid out
controller, or your work bench. In [Data] [Positive Voltage] [Ground]
this case, we find that the DC and is marked “S -”. The other is
operating voltage is between 3 to [Ground] [Data] [Positive Voltage]
5 volts and it pulls about 0.5mA and is marked as such. Hopefully,
during “normal” conditions yours has some sort of pinout
(section 6). We also find that this is definition printed on it. If not, you
a rather slow device and that we can use a multimeter to trace the
should not try to pull data more ground pin and voltage pin directly
than once per second. Basically from the sensor to the breakout
we’ll keep it around once every pin. You can usually guess that if
five seconds in our testing there are three output pins on the
program, which is way more than breakout board and you know
we’ll need in reality. Another thing: ground and positive voltage, then
if the cable that sends the data the other SHOULD be the data pin.
from the sensor to the
microcontroller (our RPi) is less Now our program code.
than 20 meters, we should have
about a 5K ohm resistor between For the sake of getting things
the data line and the local power up and running quickly, we will be
full circle magazine #1 09 19 contents ^
HOWTO - PYTHON
using some code provided by the
kind people at Adafruit.com – they #!/usr/bin/python
# simpletest.py
provide the library for working #----------------------------------------------------
with the DHT1 1 . (They found that # Original code information copyright below.
trying to run straight Python code # Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
for the library causes some timing # Permission is hereby granted, free of charge, to any person obtaining a copy
issues, so the library is actually # of this software and associated documentation files (the "Software"), to deal
written in ‘C’.) There are a number # in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
of steps involved, so follow the # copies of the Software, and to permit persons to whom the Software is
instructions carefully. I’ve # furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
paraphrased them so if something # copies or substantial portions of the Software.
doesn’t work, you can also find the # Code modifications by G.D. Walters for Full Circle Magazine
instructions at the Adafruit import Adafruit_DHT
from time import sleep
website at #----------------------------------------------------
https://learn.adafruit.com/dht- # Sensor should be set to Adafruit_DHT.DHT11,
humidity-sensing-on-raspberry-pi- # Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
#sensor = Adafruit_DHT.DHT22
with-gdocs-logging/software- #----------------------------------------------------
install-updated . Once everything sensor = Adafruit_DHT.DHT11
is done, you can run my modified #----------------------------------------------------
Python example presented at the
end of the instructions. package is already installed. The two import statements and relating Celsius to “real”
the assignment of the variable temperatures, so I convert it so
In your "/home/pi" directory, Next, install the library by ‘sensor’ to the class code. that I can understand it. If you
run the following commands: running: want Celsius, just comment out the
pin = 4
sleep(3)
conversion line.
git clone sudo python setup.py install
https://github.com/adafruit/A
Here we define that the sensor Now (next page, bottom right)
dafruit_Python_DHT.git
Once all that is done, you can we check to see if we got realistic
move on to our sample code. is connected to GPIO pin 4 and
cd Adafruit_Python_DHT
then we wait 3 seconds for things values for both humidity and
to settle and be ready to work. temperature, then we display
sudo apt-get update
Above is my modified sample them and sleep for 5 seconds.
sudo apt-get install build- code “borrowed” from the Adafruit
essential python-dev python- sample code. We use a simple loop (next
openssl page, top right) to grab the values I must admit, when I run the
program with one sensor, it gives
Ignore any errors that state a All of the above can basically be for humidity and temp over and some rather wacky results for the
boiled down to three lines of code. over. I never got the knack of first two or three minutes, then
full circle magazine #1 09 20 contents ^
HOWTO - PYTHON
#----------------------------------------------------
# Here we loop over and over getting and displaying the
data.
# Use <Ctrl><C> to break out.
#----------------------------------------------------
while 1: The Ubuntu Podcast covers all
# Try to grab a sensor reading. Use the read_retry
method which will retry up the latest news and issues facing
# to 15 times to get a sensor reading (waiting 2 Ubuntu Linux users and Free
seconds between each retry). Software fans in general. The
humidity, temperature = show appeals to the newest user
Adafruit_DHT.read_retry(sensor, pin) and the oldest coder. Our
# Comment out the next line to display Celsius
discussions cover the
temperature = temperature * 9/5.0 + 32 development of Ubuntu but
aren’t overly technical. We are
lucky enough to have some
settles down to values that I can great guests on the show, telling
trust. The other sensor seems to us first hand about the latest
“lock in” faster, so I’m just writing exciting developments they are
it off to something in the first working on, in a way that we can
sensor. all understand! We also talk
about the Ubuntu community
Well, that’s it for this month. and what it gets up to.
Remember, we’ll be using the
Dallas temp sensor next time, so The show is presented by
be ready. members of the UK’s Ubuntu
Linux community. Because it is
Have a good time and I’ll see covered by the Ubuntu Code of
you next month. Conduct it is suitable for all.
The show is broadcast live every
Greg Walters is owner of RainyDay fortnight on a Tuesday evening
Solutions, LLC, a consulting company
in Aurora, Colorado, and has been (British time) and is available for
programming since 1 972. He enjoys download the following day.
cooking, hiking, music, and spending
time with his family. His website is podcast.ubuntu-uk.org
www.thedesignatedgeek.net.

full circle magazine #1 09 21 contents ^


Full Circle Team

HOW TO CON TRI BUTE Edit or - Ronnie Tucker


[email protected]
Please note: Webmast er - Lucas West ermann
FULL CIRCLE NEEDS YOU! Special editions are
A magazine isn't a magazine wit hout art icles and Full Circle is no compiled from originals [email protected]
except ion. We need your opinions, deskt ops, st ories, how-t o's, and may not work with
reviews, and anyt hing else you want t o t ell your f ellow *bunt u users. Special Editions - Jonathan Hoskin
current versions.
Send your art icles t o: art icles@f ullcirclemagazine.org Edit ing & Proof reading
We are always looking f or new art icles t o include in Full Circle. For help and advice Mike Kennedy, Gord Campbell, Robert
please see t he Of f icial Full Circle St yle Guide: ht t p:/ / url.f ullcirclemagazine.org/ 75d471 Orsino, Josh Hert el, Bert Jerred, Jim
Dyer and Emily Gonyer
Send your comment s or Linux experiences t o: let t ers@f ullcirclemagazine.org
Hardware/ sof t ware reviews should be sent t o: reviews@f ullcirclemagazine.org Our t hanks go to Canonical, t he many
Quest ions f or Q&A should go t o: quest ions@f ullcirclemagazine.org t ranslat ion t eams around t he world
Deskt op screens should be emailed t o: misc@f ullcirclemagazine.org
and Thorst en Wilms for t he FCM logo.
... or you can visit our sit e via: f ullcirclemagazine.org

Get t ing Full Circle Magazine:


For t he Full Circle Weekly News: EPUB Format - Most edit ions have a link t o t he epub f ile
on t hat issues download page. If you have any problems
You can keep up t o dat e wit h t he Weekly News using t he RSS
wit h t he epub f ile, email: mobile@f ullcirclemagazine.org
f eed: ht t p:/ / f ullcirclemagazine.org/ f eed/ podcast

Or, if your out and about , you can get t he Weekly News via Issuu - You can read Full Circle online via Issuu:
St it cher Radio (Android/ iOS/ web): ht t p:/ / issuu.com/ f ullcirclemagazine. Please share and rat e
ht t p:/ / www.st it cher.com/ s?f id=85347&ref id=st pr FCM as it helps t o spread t he word about FCM and Ubunt u.

and via TuneIn at : ht t p:/ / t unein.com/ radio/ Full-Circle-Weekly-


Magzst er - You can also read Full Circle online via
News-p855064/
Magzst er: ht t p:/ / www.magzt er.com/ publishers/ Full-Circle.
Please share and rat e FCM as it helps t o spread t he word
about FCM and Ubunt u Linux.

29 cont ent s ^

You might also like