RasPi 03
RasPi 03
BUILD
3
CODE
Get hands-on with your Raspberry Pi
16 Problems solved
14
PRACTICAL
GUIDES
Plus
Upgrade
your robot
with sensors
WorldMags.net
Welcome
There’s one sure thing in life – if
something can go wrong, it will
Get inspired
go wrong at some point. With Discover the RasPi
this in mind we’ve put together community’s best projects
a Fix Your Pi feature for this third issue of
RasPi magazine, where we tackle the most Expert advice
common hardware and software problems Got a question? Get in touch
you will encounter with your Raspberry Pi. We and we’ll give you a hand
also take the robot tutorial from issue two to
a whole new level – adding in microswitches
and sensors to give your creation a set of
Easy-to-follow
senses that will bring it to life. With 87 pages guides
in this issue we have got lots more Raspberry Learn to make and code
Pi inspiration for you too – check out the gadgets with Raspberry Pi
Bioscope film player, tweet wildlife pictures
and make the most of your memory with
Python. Enjoy your issue and have fun!
Deputy Editor
WorldMags.net
WorldMags.net
Bioscope
A film player from the 19th Century, updated
What is a GertDuino?
Essential accessories for making some amazing projects
Talking Pi
Your questions answered and your opinions shared
WorldMags.net
WorldMags.net
Fix Your Pi
Troubleshooting – Hardware
A list of common Raspberry Pi hardware problems
and what to do when they occur
“If the picture
We’ve all been there. We’ve come back to
from your
something, and for whatever reason, the
thing we’re trying to do just won’t work! We’ve
Pi is noisy
plugged everything back in where we thought it came (e.g. screen is
from, but there’s nothing. So, what do we do when it shaking) it’s
comes to this? Usually there are a few different solutions probably a dirty
to any one problem – but sometimes there’s only one connection”
way, and finding that one key to victory might not be all
that easy.
WorldMags.net
Maybe you’ve come back to your Pi after several
WorldMags.net“These are
months of it being sat in a drawer. You plug it in and boot
common
it up and… X, Y or Z has happened!
What can we try when it just seems that everything problems for
has completely fallen over and nothing will work? any Raspberry
Well, hopefully your problem will be listed as one Pi user to come
here. These are common problems for any Raspberry across at one
Pi user to come across at one point or another while point or another
using their device. Have a look through and if you’re
while using their
experiencing one of these issues, we’ve got a solution on
hand for you. device”
Some of these things you’ll want to slap yourself in
the face for not thinking of – but that’s all part of the joy
of computers, right? The simplest of things can put you to
the test for the longest of times, just ready for that eureka
moment when it all finally comes together.
WorldMags.net
Problem 2: I can’t
see my USB hard WorldMags.net
drive
Solution: This is also
another really common one
and is generally caused
by using a non-powered
portable USB hard drive in
a non-powered USB hub.
The easiest way to fix this
is to power one side or the
other. If using a portable,
USB-powered hard drive, you should really use a Above Is your hard
powered USB hub. drive in an unreadable
format?
If you definitely have power, the hard drive could be in
an unreadable format. Try using FAT32.
WorldMags.net
WorldMags.net“Make sure
the HDMI or
composite
cable is
connected
properly and
Problem 4: The HDMI image from the Pi free from dust”
has noise
Solution: If the picture from your Pi is noisy (.e.g screen
is shaking, dots or green lines moving around) then it’s
probably a dirty connection. Make sure the HDMI or
composite cable is connected properly and free from dust
and other contaminants. If you still have a problem, try
another HDMI cable.
You can also try adding the following to your SD card’s
config.txt:
config_hdmi_boost=4
WorldMags.net
Problem 6: Ethernet stops
working with some USBWorldMags.net
devices
Solution: The first thing that you
should do in this situation is check
your power supply is working! It has
been known for some power supplies
to provide an inadequate source of
power. First, try changing out your cable
(it may just be a poor-quality cable).
Also, try the failing device in a powered
USB hub – rather than plugging it directly into the
Raspberry Pi.
WorldMags.net
WorldMags.net
Problem 8: Red power LED is on, nothing Above The red power
LED is at the top-right
on display of this picture, fourth
Solution: First, check the power cable is properly seated. from the right edge of
the board
Check that your SD card has a valid image on it. Can
you still read the SD card in the PC that the image was
created on?
If you can, try booting your Raspberry Pi with just the
power supply connected. Watch whether the ‘OK’ light
flashes. If it does, add the cables back in one by one.
WorldMags.net
WorldMags.net
Troubleshooting – Software
A list of common Raspberry Pi software problems and what
to do when they occur
Software can be just as much of a pain “Sometimes
as hardware. The problem with software, the only way
however, is that different configuration options to go is from
can lead to a really bad, frustrating time. Hardware we
the ground up.
have attached can affect the configuration of our system
and lead to further issues – sometimes the only way to go
You have got to
is from the ground up. You have got to think logically about think logically
these things. about these
Some problems will seem to have little to no correlation things”
with their answers, but those scratch-your-head moments
soon go when you realise that actually the thing is working
and doing exactly what you wanted it to again. There’s a lot
you can do from the command line to help with any of this
stuff, but things aren’t always as clear as they seem.
Thankfully there are a lot of helpful tools to start making
a dent in the most common problems. In these pages we
feature a list of the most common software problems with
their solutions.
If the worst comes to the worst then you can always
rebuild it. Due to the Pi’s nature, doing this is a simple
reflash of a single image, rather than painstaking hours
of driver and software reinstalls like some other operating
systems out there.
As always, be sure to keep frequent backups of your
most precious data, though.
WorldMags.net
Problem 9: I’m getting
WorldMags.net
a kernel panic on every
boot
Solution: If you’re seeing kernel
panic messages each time you
start your Raspberry Pi, the first
thing to try is booting it without
any USB devices in – and adding
them one by one afterwards.
If you’re still getting the
messages, it’s likely that your flash
of the SD card was unsuccessful.
Reflash the card and try again. Make sure you use admin “The first thing
privileges to do it! to try is booting
it without any
Problem 10: My Pi’s Ethernet connection is USB devices
working at 10Mbit, not 100Mbit
Solution: This may or may not be inaccurate. On the
in – and
earlier Pi revision boards, the 100Mbit LED was mislabelled adding them
– it was actually a 10Mbit socket. On newer revision one by one
boards, however, it was correctly labelled on the newer afterwards”
boards that actually have a 100Mbit socket.
You can check your link speed with
cat /sys/class/net/eth0/speed
WorldMags.net
WorldMags.net“The default
user/password
combination is
pi/raspberry”
Problem 11: I cannot SSH to my
Raspberry Pi
Solution: If you’re receiving a connection time-out error
when you try to SSH to your Pi from another machine, it
probably means that SSH access to it is disabled. You need
to open up the raspi-config tool, then use the option ‘ssh’ to
enable SSH. You should now be able to connect to your Pi.
The default user/password combination is pi/raspberry.
WorldMags.net
Problem 13: The
visible desktop WorldMags.net
goes off the
screen
Solution: You
probably want to turn
overscan off. Use the
raspi-config tool to
disable overscan.
If you now see
a big black border
round the edges of
your screen, you can
usually use your TV’s settings to zoom in.
“If you now
If not, try setting the overscan manually in the config.
txt using the properties overscan_left, overscan_right,
see a big black
overscan_top and overscan_bottom. border round
the edges of
Problem 14: I don’t know the root password your screen,
Solution: This is probably because the root account in you can usually
many newer Linux distributions is disabled by default – use your TV’s
and as such doesn’t have a password. You can enable
settings to
a password by entering the following command in the
terminal: zoom in”
sudo passwd root
Exercise caution when doing this, however, since
meddling with root accounts can be dangerous.
WorldMags.net
Problem 15: I can’t install new
software with apt-getWorldMags.net
Solution: If you’re seeing the error
‘Package xx is unavailable’ then you
probably need to update the Apt tool first.
Seeing this error means that your software
list is out of date.
Start by running this command:
sudo apt-get update
Let it update its list of packages (you’ll
need a network connection) – then do: “The Pi’s
sudo apt-get upgrade.
composite
When this completes, try installing your package
over again. output defaults
to NTSC
Problem 16: Composite output is only (American).
black and white Some PAL
Solution: The Pi’s composite output defaults to NTSC (European) TVs
(American). Some PAL (European) TVs may either now
may either
show an image, or display it in black and white. To solve
this, change the config.txt on the SD card to add/modify:
now show
sdtv_mode =x and image,
Where x is: 0 – NTSC; 1 – Japanese NTSC or display it
2 – PAL; 3 – Brazilian PAL in black and
white”
WorldMags.net
WorldMags.net
Upgrade your
Raspberry Pi
robot
Now your robot’s moving, it’s time
to get it sensing and interacting
with the world around it
“Using analogue
sensors, we can
build a robot
that is capable
of following or
avoiding light”
WorldMags.net
WorldMags.net
Installing microswitches
Give your robot the sense of touch and train it to react
when it bumps into something
Caution
In the previous issue of RasPi, we constructed While we’ve carefully
our base robot. Now that we’ve got a robot that constructed this
can move any way we want it to, let’s move on feature with safety in
to the simplest form of interaction: touch. It may not be as mind, accidents can
sophisticated as we experience as humans, but giving happen. Imagine
our robot its first sense will help it to navigate its own path,
Publishing cannot be
giving it a very basic form of intelligence.
held responsible for
Adding a sense of touch can be handled in quite a
damage caused to
few different ways, but the quickest and easiest method
is by adding some ‘antennae’ to your robot in the form Raspberry Pis and
of microswitches. Given their name, they aren’t so much associated hardware
micro but they do have long arms that protrude, making by following this feature.
them perfect for mounting on the front of your robot. If your
switch hasn’t got a lever or it isn’t long enough, you can
always try adding or extending it using a piece of dowel
or a drinking straw.
Adding multiple switches gives our robot a greater
sense of its surroundings and allows a very simple bit of
code to control how it should operate. As it will be mostly
moving forward, we will only need to add switches to the
front. So let’s begin by creating the circuit and testing it. THE PROJECT
ESSENTIALS
Breadboard
Jumper wires
“The motor driver we will use is called an 2x 10K resistors
2x CPC microswitches
L293D, otherwise known as an H-Bridge”
WorldMags.net
NO/NC Additional switches
WorldMags.netYou can easily add
Most switches are labelled
with NO and NC; which more switches, not just
stands for Normally Open bumpers, by following the
and Normally Closed. circuit and connecting it to
Open simply means no a free pin
current can pass through
WorldMags.net
WorldMags.net
Testing your microswitches
Now the switches are wired up, let’s get them working
WorldMags.net
The Code WorldMags.net
TESTING THE MICROSWITCHES
while True:
inputleft = GPIO.input(18)
inputright = GPIO.input(15)
if inputleft:
print “Left pressed”
if inputright:
print “Right pressed”
sleep(0.1)
WorldMags.net
WorldMags.net
Completing the
‘bumping’ robot
It’s time to add the switches to the robot and find some
walls to test it with
We’ll mount the switches to the front of the
robot, fixing it down with double-sided tape or
Blu-tack so the levers can stick out enough to
be pressed when it touches an object. Re-using the motor
function code we created before, we can easily add the
microswitch support. So this time if an object presses the
left microswitch, we tell the motors to switch into reverse
for a second then stop. Hopefully this is long enough to
move the robot away from the object so we can now
turn just the left-hand motor on for 2 seconds before
continuing on its new path. This is a big step – we’re
implementing AI and making the robot smart.
Variations can be made to refine our robot, such as
creating a reverse for the right-hand motor and having it
spin on the spot to create a new path to continue on.
WorldMags.net
WorldMags.net Above left Placing the
microswitches takes a
little trial and error
“Mount the
switches to the
front of the
robot, fixing
it down with
double-sided
tape or Blu-tack
so the levers
can stick out”
WorldMags.net
03 Log in with SSH WorldMags.net“When you
start the script,
As our robot will be starting to run around freely, it is
a good idea to provide the Raspberry Pi with its own the motors will
battery. Using Wi-Fi, we can remotely connect using start turning
SSH to emulate the Pi’s terminal. forward.
Pressing a
04 Create and save your work
As before with the motors, we shall create our script
switch should
using nano. Let’s do this by typing then reverse
nano bumpers.py the motors and
Saving different scripts allows the testing of individual spin one motor
parts. We can also use them as a reference for before going
creating bigger scripts. forward again”
05 Test it in situ
Copying the example script into bumpers.py,
followed by Ctrl+X with a Y to save, we can test it out
and make any hardware modifications. With the script
running, press a microswitch and see what happens!
WorldMags.net
The Code WorldMags.net
BUMPING ROBOT
WorldMags.net
The Code WorldMags.net
BUMPING ROBOT
GPIO.output(10,GPIO.HIGH) Digital
Motor1.ChangeDutyCycle(speed) switches
Motor2.ChangeDutyCycle(speed) A switch is a
perfect digital
def left(speed): signal, as it can
GPIO.output(24,GPIO.HIGH) only be one of two
GPIO.output(23,GPIO.LOW) states: on or off.
Motor1.ChangeDutyCycle(speed)
def right(speed):
GPIO.output(9,GPIO.HIGH)
GPIO.output(10,GPIO.LOW)
Motor2.ChangeDutyCycle(speed)
def stop():
Motor1.ChangeDutyCycle(0)
Motor2.ChangeDutyCycle(0)
while True:
inputleft = GPIO.input(18)
inputright = GPIO.input(15)
if inputleft:
print “Left pressed”
backward(100)
sleep(1)
stop()
“Creating a
left(75)
sleep(2)
while True: loop
elif inputright: will create an
print “Right pressed” infinite loop, as
backward(100) the condition is
sleep(1)
always true”
WorldMags.net
The Code WorldMags.net
BUMPING ROBOT
stop()
right(75)
sleep(2)
else:
forward(75)
sleep(0.1)
WorldMags.net
WorldMags.net
Line-following sensors
Give your robot a track to follow using masking
tape or inked paper
THE PROJECT
ESSENTIALS
“Add some line sensors to the underside so we Breadboard
Jumper cables
are able to control it by using some masking 2x 2N3904 transistors
tape on a dark floor (or some dark tape on a 2x 1K resistors
2x Line detector sensors
light floor)”
WorldMags.net
Lower the current WorldMags.net Safety first
The transistors only need a small
Thanks to the transistor,
amount of current to actually work; we have a much safer
a resistor helps to smooth out the voltage going back into
sensors’ output the GPIO pins when
using 5-volt electronics
WorldMags.net
WorldMags.net
Testing the line sensors
Now you’ve given your robot eyes, let’s try them out
“This Python
With the line sensors wired up and the script is very
Raspberry Pi switched on, we can now test
similar to the
them. This Python script is very similar to the
microswitch test code because we are just reading the microswitch
GPIO pin’s status, checking if it is high (a 1 or on) or if it is test code
low (0 or off). because we
As some sensors work differently to others, we need are just reading
help to understand the output. Displaying the current the GPIO pin’s
sensor data on the screen allows us to work out how the
status”
sensor responds on black and white surfaces and plan
the code accordingly.
WorldMags.net
WorldMags.net
WorldMags.net
The Code WorldMags.net
TESTING THE LINE SENSORS
if Sensor1 == GPIO.HIGH:
print “Sensor 1 is on White”
else:
print “Sensor 1 is on Black”
if Sensor2 == GPIO.HIGH:
print “Sensor 2 is on White”
else:
print “Sensor 2 is on Black”
print “------”
sleep(1)
GPIO.cleanup()
WorldMags.net
WorldMags.net
Finalise your
line-following bot
It can see! Now put its new eyes to good use…
WorldMags.net
WorldMags.net
WorldMags.net
WorldMags.net
04 Power up and log on
Connect the batteries for the motors and add power
to the Raspberry Pi. Now log in using SSH on your
computer so we are able to create our motor-
controlled line sensor code.
WorldMags.net
The Code WorldMags.net
BUMPING ROBOT
def forward(speed):
GPIO.output(24,GPIO.HIGH)
GPIO.output(23,GPIO.LOW)
GPIO.output(9,GPIO.HIGH)
GPIO.output(10,GPIO.LOW)
Motor1.ChangeDutyCycle(speed)
Motor2.ChangeDutyCycle(speed)
def backward(speed):
GPIO.output(24,GPIO.LOW)
GPIO.output(23,GPIO.HIGH)
GPIO.output(9,GPIO.LOW)
WorldMags.net
The Code WorldMags.net
BUMPING ROBOT
def stop():
Motor1.ChangeDutyCycle(0)
Motor2.ChangeDutyCycle(0)
while True:
sensor1 = GPIO.input(7)
sensor2 = GPIO.input(8)
if sensor1 == GPIO.LOW:
print “Sensor 1 is on white”
stop()
else:
left(60)
if sensor2 == GPIO.LOW:
print “Sensor 2 is on white”
stop()
else:
right(60)
sleep(0.05)
WorldMags.net
WorldMags.net
Ultrasonic sensing
Now that the robot can touch, and it can see beneath its
wheels, what about a new type of sight?
THE PROJECT
Let’s start making things a little more complicated ESSENTIALS
Dagu pan & tilt kit
by adding an ultrasonic sensor and placing it Jumper cables
onto a pan-and-tilt mounting. Ultrasonic sensors Seeed Studio ultrasonic
are used in different ways to judge distance by emitting an sensor
2x 2K2 resistors
ultrasonic pulse and counting how long it takes to bounce 1x 10K resistor
off an object then back to the receiver. Cars that come with
reverse parking sensors work in the same way to give an
audible tone depending on how far away an object is.
Using an ultrasonic sensor on your robot will give it a
chance to take action as it approaches an object such as a
wall, with enough time to evaluate and choose a new path.
Ultrasonic sensors come in two varieties, based on
the number of pins. Both types work in a very similar way.
Since we would like to use the same Python code for both,
we would wire the 4-pin sensor to act like a 3-pin ultrasonic
sensor. However, we will focus on the affordable 3-pin model
from Dawn Robotics.
As we only require one GPIO pin, we will first need to set
it as an output and send a 10ms pulse to trigger the sensor
to start and begin counting. Next we switch to an input to
wait for the pin to go high, at which point we stop timing
and calculate how long that took. The last thing needed is to
convert the time in sound into a measurement we can read,
in this case centimetres.
WorldMags.net
Voltage divider WorldMags.netWe’re using a 3-pin 3-Pin sensor
As again we are dealing with 5-volt
sensors, we need to lower the voltage sensor which has a
to 3.3 volts to make it safer for use with combined Echo/Trig
the Raspberry Pi pin. The functions
perform the same as
on the 4-pin
WorldMags.net
WorldMags.net
Add a pan-and-tilt kit
Wouldn’t it be great to take readings from different angles?
Here’s how…
WorldMags.net
WorldMags.net
Installing your pan & tilt
It’s a fiddly job, but well worth the trouble
WorldMags.net
WorldMags.netWhat are
Lastly, run it – remember, every time you reboot or switch
on your Pi, you will just need to type this line: servos?
sudo ./servod If the robot doesn’t
The pre-compiled kernel is already configured to use act like it should,
pins 4 and 22 as servos, so let’s hook everything up. or the servo goes
The servos will need to be powered separately as they the wrong way, just
are at heart just motors with a little bit of circuitry. swap the servo data
The code we have (listed just after this section) will
pins around. Double-
combine the wheel motors, servos and ultrasonic. The end
check your code and
result will involve the robot moving forward until it senses an
give it another try.
object less than 30cm away, stop, then turn the pan-and-
tilt left, check the distance, then turn the ultrasonic on the
pan-and-tilt right and pick whichever direction has a further
distance until the next object.
WorldMags.net
WorldMags.net“The
04 Create your script screen
should fill
Now we can create the test script. Swipe to the next
page to see the full code listing and then start typing with distance
it in – there’s a fair bit, but it’s a great way to get your data so we
code-writing muscle memory working! can see what
is happening
05 And she’s off…
When you set off the script, the screen should fill with
and check on
distance data so we can see what is happening and the direction it
check on the direction it decides to take. It may pose decides to take”
a challenge if it gets stuck in a corner - see if you can
debug it.
06 Debugging problems
If the robot doesn’t act like it should, or the servo goes Below Test each
the wrong way, just swap the servo data pins around. function to ensure all
motors and servos
Double-check your code and give it another try. work as planned
WorldMags.net
The Code WorldMags.net
THE COMPLETE ULTRASONIC CODE
Echo = 17
Pan = 22
Tilt = 4
def forward(speed):
GPIO.output(24,GPIO.HIGH)
GPIO.output(23,GPIO.LOW)
GPIO.output(9,GPIO.HIGH)
GPIO.output(10,GPIO.LOW)
Motor1.ChangeDutyCycle(speed)
Motor2.ChangeDutyCycle(speed)
def backward(speed):
GPIO.output(24,GPIO.LOW)
WorldMags.net
The Code WorldMags.net
THE COMPLETE ULTRASONIC CODE
GPIO.output(23,GPIO.HIGH) “Next we
GPIO.output(9,GPIO.LOW) switch to an
GPIO.output(10,GPIO.HIGH)
input to wait for
Motor1.ChangeDutyCycle(speed)
Motor2.ChangeDutyCycle(speed) the pin to go
high, at which
def left(speed): point we stop
GPIO.output(24,GPIO.HIGH) timing and
GPIO.output(23,GPIO.LOW)
calculate how
Motor1.ChangeDutyCycle(speed)
long that took”
def right(speed):
GPIO.output(9,GPIO.HIGH)
GPIO.output(10,GPIO.LOW)
Motor2.ChangeDutyCycle(speed)
def stop():
Motor1.ChangeDutyCycle(0)
Motor2.ChangeDutyCycle(0)
def get_range():
GPIO.setup(Echo,GPIO.OUT)
GPIO.output(Echo, 0)
sleep(0.1)
GPIO.output(Echo,1)
sleep(0.00001)
GPIO.output(Echo,0)
GPIO.setup(Echo,GPIO.IN)
while GPIO.input(Echo) == 0:
pass
start = time()
WorldMags.net
The Code WorldMags.net
THE COMPLETE ULTRASONIC CODE
WorldMags.net
The Code WorldMags.net
THE COMPLETE ULTRASONIC CODE
WorldMags.net
WorldMags.net
Use analogue sensors
Open your robot up to a new world of input
THE PROJECT
As we’ve already shown using microswitches ESSENTIALS
and ultrasonic sensors, the Raspberry Pi is 1x MCP3008
very capable of taking inputs and performing 2x Light-dependent
resistors (LDRs)
actions based on the outside world. Inputs also come 2x 10K resistors
in a variety of different types. Most common are digital Jumper wires
sensors such as buttons and switches, but there are
also analogue sensors which can be used to read
temperatures or brightness. These sensors give their data
in the form of a voltage.
The Raspberry Pi is unable to read an analogue
signal natively, so a little help is required and this
comes in the form of a microchip called an MCP3008.
This chip is commonly referred to as an ADC (analogue-
to-digital converter). It can communicate with the
Raspberry Pi via serial and is capable of reading eight
analogue inputs at once and giving their voltage in the
form of a number: 0 will correspond to the lowest, while
1023 is the maximum voltage.
Using analogue, we can build a robot that is capable
of following (or avoiding) bright light – perfect if you wish to
have a plant pot follow the sun during the day.
Pull-down resistors
The sensors To give a stable reading,
MCP3008 The light-dependent we have to give it a basic
The heart of the resistors (LDRs) change reference point for the
analogue-to-digital their voltage based on the voltage, so a pull-down
conversion amount of light they receive resistor is required
WorldMags.net
WorldMags.net
WorldMags.net
WorldMags.net“From
Before we can interface with the MCP3008, we need
left to
enable the serial drivers and install a Python library called
right on the chip
spidev, so let’s do this before anything else.
Open up a terminal, or connect to your Raspberry Pi, the channels
and then type in the following commands: start at 0 and
sudo nano /etc/modprobe.d/raspi-blacklist. go all the way
conf to 7”
And add a # to the start of each line in the file, then…
sudo apt-get install python-pip python-dev
sudo pip install spidev
sudo reboot
WorldMags.net
The Code WorldMags.net
TESTING THE ANALOGUE-TO-DIGITAL CONVERTER
while True:
print “Chan 0: “ + str(get_value(0))
print “Chan 1: “ + str(get_value(1))
time.sleep(0.3)
WorldMags.net
WorldMags.net
Sensing light with the
Raspberry Pi
With everything connected up, let’s go chase some light
WorldMags.net
WorldMags.net
03 Double-check everything
As we have a lot of power types – we are using
3V3 for the MCP3008, 5V to the L293D and also the
batteries – it is best to check they are all correctly
wired up. Once it looks good, add some power and
log into the Pi.
WorldMags.net
04 Create the scriptWorldMags.net
Once everything is connected, we shall use nano to
write our Python script: type
nano analog.py
…to create the file. Copy the code. Exit nano with
Ctrl+X and then Y and Enter to save the file. It should
be second nature by now!
06 Something is wrong
If you’re sure it’s working properly, it could be that
a tweak to the value may be needed. Run the test
script again to get a suitable number to replace the
600 currently used. Remember – testing at different
times of day may require you to change some of
your variables.
WorldMags.net
The Code WorldMags.net
THE COMPLETE ANALOGUE CODE
def forward(speed):
GPIO.output(27,GPIO.HIGH)
GPIO.output(17,GPIO.LOW)
GPIO.output(9,GPIO.HIGH)
GPIO.output(10,GPIO.LOW)
Motor1.ChangeDutyCycle(speed)
Motor2.ChangeDutyCycle(speed)
def backward(speed):
GPIO.output(27,GPIO.LOW)
GPIO.output(17,GPIO.HIGH)
GPIO.output(9,GPIO.LOW)
WorldMags.net
The Code WorldMags.net
THE COMPLETE ANALOGUE CODE
GPIO.output(10,GPIO.HIGH) MCP3008/
Motor1.ChangeDutyCycle(speed) MCP3004
Motor2.ChangeDutyCycle(speed) A smaller ADC chip
called the MCP3004
def left(speed):
is also available, it
GPIO.output(27,GPIO.HIGH)
GPIO.output(17,GPIO.LOW) only has 4 analogue
Motor1.ChangeDutyCycle(speed) channels as
opposed to 8 with
def right(speed): the MCP3008.
GPIO.output(9,GPIO.HIGH)
GPIO.output(10,GPIO.LOW)
Motor2.ChangeDutyCycle(speed)
def stop():
Motor1.ChangeDutyCycle(0)
Motor2.ChangeDutyCycle(0)
def get_value(channel):
if ((channel > 7) or (channel < 0)):
return -1
r = spi.xfer2([1,(8+channel)<<4,0])
while True:
ldr_left = get_value(0)
ldr_right = get_value(1)
WorldMags.net
The Code WorldMags.net
THE COMPLETE ANALOGUE CODE
“As each
if ldr_left > 600: lighting situation
print “Turn right”
will be slightly
right(100)
elif ldr_right > 600: different,
print “Turn left” perform the
left(100) test script to
else: get an idea of
forward(75)
the values that
time.sleep(0.25) will be expected
from the LDRs”
WorldMags.net
WorldMags.net
What next?
So you’ve finished building our project robot and you’re
wondering what’s next…
There are loads of choices, which is one of the “With a bigger
attractive things about robotics, and really you’re platform, you
only limited by your time and imagination. You could also
could choose to expand your robot’s hardware, add an arm to
adding more sensors as your knowledge and confidence
your robot so
improves, so that your robot can learn more about the world.
Gas, light and sound… for practically any stimulus you can it doesn’t just
imagine, there’s the corresponding sensor that you can add sense the world
to your robot. With a bigger platform, you could also add an – it can also pick
arm to your robot so it doesn’t just sense the world – it can up bits of the
also pick up bits of the world and move them around. Here world”
are a couple of ideas you could try…
WorldMags.net
WorldMags.net
“The Raspberry
Facial recognition
With the simple addition of the Raspberry Pi’s camera Pi comes with
module and OpenCV software, face detection and an audio output.
recognition is possible. You could do this by replacing the So combining
ultrasonic from the pan-and-tilt mount with the camera; this with a
this will then allow the camera to move about and follow travel speaker
your movements.
will unlock a
Learning to talk new world of
The Raspberry Pi comes with an audio output. So communication”
combining this with a travel speaker will unlock a new
world of communication for your robot. Using a Python-
friendly speech module like eSpeak, you can teach your
robot to talk, sing or simply report readings for debugging
WorldMags.net
WorldMags.net
Spatial analysis
Using the ultrasonic sensor with the pan-and-tilt kit
on your robot, you can effectively measure every wall “Adding speech
and every object in a room – a popular specialism in recognition
computer science. So by taking a series of measurements with a USB
in different directions, controlled by the servos in the pan- microphone, or
and-tilt mount, it is possible to make a map. With another similar, can take
sprinkling of code and gadgetry, you could teach your bot
it to a whole
to navigate your house. PID is an excellent field that can
certainly help with this.
new level”
WorldMags.net
Swarming WorldMags.net“Using just
a little more
Swarming is an interesting branch of computer science.
Using just a little more code than we already have, we code than we
can create behaviour similar to that of a swarm of bees, already have,
or ants. A swarm of robots could discover an area quickly, we can create
or be used to scientifically model traffic-calming measures. behaviour
You could even create your own synchronised routines, or similar to that
build a robot football team.
of a swarm of
Robot arm bees, or ants”
Everyone would love a robotic helper, perfect for
performing tasks around the house. Unfortunately we
aren’t there yet, but we can come close. By mounting a
small gripper arm to the front of the robot, it can fetch
lightweight items. With the help of the Pi camera module,
or an RGB colour sensor, you could colour-sort LEGO bricks
or entertain a pet.
Maze solving
Path finding and maze solving are other exciting branches
of computer science you can attempt with your RasPi
robot. Competitions are held around the world to be
the fastest to solve a maze, using lines on the floor or
ultrasonic sensors. All you need is a mechanism to recall
past movements and a scientific approach to the robot’s
attitude to maze solving.
WorldMags.net
WorldMags.net
Bioscope
A hand-cranked film player from the 19th Century,
updated for the modern era. How and why was
the Bioscope created?
WorldMags.net
Where did the idea for the Bioscope initially
WorldMags.net
come from?
Jon Stam: I was on vacation in Italy. I went to
a flea market and I came across an old Mupi, which was
the name of the toy company that produced this 8mm
movie viewer. In the States, most people know it as a
Fisher Price toy that already existed, but I actually never
ever saw it before in my life. I knew the View-Master but Simon de Bakker
never this movie viewer. I was watching an animated has a background
movie, thinking how it was amazing to see this, and then in interactive
wondered about putting your own content on the device. design and has
What if your own home movies could be played in this been working
way, where you can actually stop at the most beautiful for ten years at
part and speed up through the more boring parts. As the V2 Institute in
soon as I came back, I went to Simon’s and we agreed Rotterdam, at the
to do it, thinking it would be even more exciting than the V2 Lab.
View-Master.
WorldMags.net
realised if we teamed up then we could start working on If you like
WorldMags.net
more ambitious projects. One of the side-
projects resulting
What influenced your decision to use the Raspberry Pi from the Bioscope
in the project? is the Raspberry Pi
SdB: When we started the project, the Pi wasn’t out Power Shield, an
yet. It was just before it really came out, so it had been extremely portable
announced at that point. I actually had two on pre-order and rechargeable
and we were just waiting for them to come in. We had the power supply for
idea for the Bioscope and we applied for residency at the the Raspberry Pi.
V2 Institute where I was working at that time. And we got
accepted to do this project, where it was made during the Further reading
summer sessions. We were looking for some hardware To learn more
to actually build it – most of the boards are pretty square. about the Bioscope
The Raspberry Pi ended up just fitting exactly in the case and the Power
we wanted. And it had a composite output, which we also Shield, visit
needed. In the end, we started the project two weeks www.simbits.nl
before it was supposed to be delivered. Good timing!
WorldMags.net
WorldMags.net
WorldMags.net
larger quantities. However, the way that we’re producing
WorldMags.net
it now ends up with it being a rather expensive device.
We’re still actually curious and open to the different
possibilities, and we’ve been talking to some people that
actually want to commercialise it. We’re not 100 per cent
sure exactly where that’s going or not.
“We do have
a few projects
lined up for the
near future, and
right now we’re
working on
some new
stuff too”
WorldMags.net
WorldMags.net
What is a GertDuino?
A Raspberry Pi accessory with an odd
name, it’s essential for making some
amazing projects
WorldMags.net
Q The GertDuino is an accessory. That’s a bit of a What
WorldMags.net
vague term. Can you be a little more specific? makes up
A The GertDuino is basically another circuit board that you GertDuino?
can attach to the Raspberry Pi, extending its functionality The individual
beyond the original chips and ports and such. components that a
GertDuino replaces:
WorldMags.net
has specific inputs and outputs that are specifically What
WorldMags.net
programmable for the task at hand. It’s a lot more cost- makes up
and space-efficient than an entire computer system GertDuino?
built up to do it, as it manages to do all the operations
on a single chip. The type of microcontroller used in the
GertDuino has a lot of physical circuits, which means that
people do not need to build the physical board up around
the microcontroller.
Gertboard
In some ways a very
Q That sounds pretty neat. What’s the deal with it basic version of
being Arduino then? the GertDuino, the
Gertboard is one of
A Well, as we said, it’s open source. Open hardware. the first add-ons that
The specs are there for everyone to use, so it’s easily allowed the Raspberry
Pi to do some physical
implemented into the GertDuino with no licensing fee. computing. The
Arduino is also extremely popular as microcontrollers GertDuino board
manages to take this
go, making it easier for people to pick it up if they’ve got to another level.
experience with it.
WorldMags.net
you have all of the software, but you still don’t have an
actual printer. WorldMags.net“Itchiphasonaitspecial
called
Q I’ll take your word for it. How does the GertDuino an ATmega 48,
connect to the Raspberry Pi? which offers
A Like the Gertboard and most other major add-ons, infrared signal
it’s connected via the GPIO ports. These are the major support, a
expansion ports for the Raspberry Pi, and it allows the Pi very precise
to properly speak with the Arduino chip. This allows you to
real-time clock
actually then program the Pi, which will then program the
Arduino to do the work you want it to do. as well as a
form of spare
Q Can you not connect a normal Arduino up to a battery”
Raspberry Pi then?
A Actually, you can. People have been using the
Raspberry Pi to help power Arduino boards since it first
came out.
WorldMags.net
programming it, and it will work on its own thanks to the
ATmega 48’s battery.WorldMags.net“Arduino
powers a lot
Q So it sounds pretty nifty, but what can I use it to do? of physical
A Arduino powers a lot of physical hobby projects. Garage hobby projects.
door openers, robots, home breweries and even some Garage door
of the Makerbots. The GertDuino is capable of all of the openers,
functions that similar Arduinos can perform. Gert van robots, home
Loo himself has suggested that you can use it to time the
breweries and
opening of a chicken coop in the morning, or as a remote
for opening and closing curtains. even some of
the Makerbots”
Q Just for hobby projects? What about full commercial
projects?
A While Arduino boards are fantastic for rapid-prototyping
and tinkering with low financial risk, when your product
is complete it is usually a lot cheaper to start making
custom chips. For everyone else, though, it’s the most cost-
effective for both prototypes and final products.
Below The GertDuino
is designed to sit on
Q All right then, I think it’s time to get one. My Rube top of the Raspberry
Pi, so you’ll be able to
Goldberg alarm clock needs upgrading. Where do I fit both into a case if
get one of boards? you want to
A You can buy a board from
element14, which coincidentally
is one of the four major
distributors of Raspberry Pis.
The manual for the board
is also available there,
along with some basic
guides on how to use it,
and more useful information
on the board itself.
WorldMags.net
WorldMags.net
WorldMags.net
WorldMags.net“We
to let us automagically capture images of birds (and other
don’t want
wildlife) before tweeting to a Twitter account of our choice
to send millions
whenever activity occurs.
of accidental
01 Configure the infrared sensor tweets to
Twitter, so
we should do
some pretty
extensive
testing”
WorldMags.net
WorldMags.net
testing.py script. Copy it onto your Pi and run it with
your PIR connected. You’ll probably find that it’s over-
“You’ll find two
tiny adjustable
sensitive for your needs by default. You’ll find two tiny screws on the
adjustable screws on the PIR. Gently adjust them to PIR. Gently
the left to lower the sensitivity and test thoroughly until
adjust them to
you get the desired result.
the left to lower
03 Set up the project the sensitivity”
With the camera connected as per our previous
camera project, we need to tie the camera, motion
sensor and Twitter code together to make a tangible
project that can be left to do its job. We’ll walk through
the script, but it’s worth looking around our project by
cloning it from GitHub. In the terminal type:
git clone https://github.com/linuxusermag/
tweety-pi.git
Enter the project with cd tweety-pi to take a look
around. It’s been set up as a full (if a little basic)
project with a readme, licence and even a folder for
our pictures to sit in.
WorldMags.net
05 Simple chain WorldMags.net“After we call
our GPIO event
The entire chain of main functions that make up the
meat of the project are laid out in trigger order and detect line, we
all initiated from that initial callback function. Once create a simple
motion is detected the take_picture function is infinite loop
called. As soon as the image has been saved to the
/pics folder we call the update_twitter function.
to ensure the
Here, we’re loading our previously saved image and script keeps
using the Twitter API’s update_with_media method running”
to allow us to tweet our picture to the outside world.
We can set our status from within this line, but instead
of repeating the same phrase we use the random
module’s choice method to pick from a list of three
we’d assigned to the variable tweet_text earlier in
the script.
WorldMags.net
The Code WorldMags.net
THE TWEETING MOTION SENSOR
WorldMags.net
The Code WorldMags.net
THE TWEETING MOTION SENSOR
def take_picture(resolution):
global pics_taken
camera.resolution = resolution
# Capture a sequence of frames
camera.capture(os.path.join(
‘pics’, ‘image_’ + str(pics_taken) + ‘.jpg’))
pics_taken += 1
print “Picture taken! Tweeting it...”””
update_twitter()
def update_twitter():
api.update_with_media(os.path.join(
‘pics’, ‘image_’ + str(pics_taken -1) + ‘.jpg’),
status = random.choice(tweet_text))
print “Status updated!”
#We don’t want to tweet more than once per minute!
time.sleep(60)
WorldMags.net
WorldMags.net
Raspberry Pi:
not unlimited
Memory is a limited resource on the Raspberry Pi.
What can you do to make the most of it in Python?
WorldMags.net
The first thing to realise is that everything in Python is an
WorldMags.net“Since
object, of one type or another. You can find out the type
everything is
of an object with the command type(). If you were to
create a list of integers with the command a=[1,2,3], an object, what
running the command type(a) would return that list. But are variables?
it goes even further than that. What happens if you run Variables are
the command type(1)? Does the integer 1 have a type? simply labels,
In this case, you will get the result ‘integer’. This makes pointing to the
sense. But it goes even further. The integer 1 is actually
objects that
an object. Integer objects have a function named bit_
length(), which gives the number of digits needed they represent”
to represent this integer in binary. If you have num1=1,
you can find the bit length with num1.bit_length().
But the interesting thing is that, since the integer 1 is an
object, you can also execute (1).bit_length(). This is
very different behaviour from most other programming
languages you’ll encounter.
Since everything is an object, what are variables?
Variables are simply labels, pointing to the objects that
they represent. This means that you can have more than
one variable pointing to a particular object. If we take
the list we defined above, we can create a new label
pointing to it with the line b=a. Now both variables, a
and b, point to the same object. You can prove this to
yourself by adding something to the end of b. If you run
b.append(4), typing in a will give you the list [1, 2, 3,
4]. This is good to know. You can create new references
to objects without accidentally creating extra copies and
using up memory unnecessarily. But this also means that
if you actually wanted to make a copy, you need to do it
explicitly. For lists, you can do this with slices.
Slicing lists
Slices are used to get a subset of the contents of a list
and return them in a new list. The format is [start:end],
WorldMags.net
where ‘start’ is the beginning index of the slice and ‘end’
WorldMags.net“One of the
is the finishing index of the slice. If you leave out ‘start’,
modules that
then the implied index is 0, and if you leave out ‘end’, the
implied index is the length of your initial list. Knowing is included
this, you can get a copy of a with b = a[:]. Now if you with Python is
alter b, you will not be affecting a. But, if it is so easy sys. Once you
to generate references to objects, how can you keep import it, you
track of how many there are? One of the modules that have a set of
is included with Python is sys. Once you import it, you
functions that
have a set of functions that allow you to interact with and
query the system that the Python engine is running on. allow you to
The specific one that will help us here is getrefcount(). interact with
If we run sys.getrefcount(a), we should see a result and query the
of 2 – one for the variable a, and one for Python’s system”
reference to the object that a points to. If you were to add
another reference with the command c=a, re-running
getrefcount() would give a result of 3. It is interesting
to run sys.getrefcount(1). You will likely see several
hundred, or even several thousand, references to the
object 1. Yet more evidence that even raw integers are
actually objects.
Memory matters
The other thing that is concerning to Raspberry Pi users is
how much memory is being used by all of these objects.
Since we already have the sys module imported, we can
use that to check this out. Another function available is
sys.getsizeof(). This function will return the number
of bytes being used by the object in question. On your
advisor’s system, the size of an integer is 8 bytes. You
can check this with sys.getsizeof(1). With most basic
object types, getsizeof will give you the total amount
of memory used. So, for example, if you have an empty
list with a=[], sys.getsizeof(a) gives an answer of
72. Adding an entry with b=[1] gives a size of 80. A
WorldMags.net
list with two elements takes up 88 bytes. So, the basic
WorldMags.net“Whenever you
size of a list with all of the required metadata is 72
have the ability
bytes, and each additional integer adds 8 bytes to the
size. Unfortunately, getsizeof doesn’t work as well if to reference
the object in question is compound. If you have a list an object with
of strings rather than integers, this becomes evident more than
very quickly. Executing sys.getsizeof(‘a’) gives 38 one label, you
bytes. But, if we stick this string in a list first and then need to keep
run getsizeof, it seems to only take 8 bytes. Obviously,
track of those
what getsizeof is measuring is actually the size of the
variable pointing to the string. To get the complete size of references”
the list, you will need to loop through all of the elements
and get the size of each individually.
The other measure of RAM is how much is being
used by the Python interpreter as a whole. You can get
this by importing the resource module. In the sample
code, you will find a function that uses this module to get
the total amount of RAM being used. Unfortunately, this
method gives you the maximum amount used up to this
point, so you can’t see what happens if you try to clean
up your memory usage. In order to do this, you will need
to use a different module, such as guppy.
WorldMags.net
are being tracked by the garbage collector, you can
WorldMags.net
use the function gc.get_count(). Normally, garbage
collection is handled automatically by an algorithm that
is meant to maximise memory usage with minimal
impact on runtime. But, if you want to force a garbage
collection, you can do so with the function gc.collect().
The number of objects cleaned up is returned. You can
set the threshold levels used by the garbage collector
Below With projects
with the function gc.set_threshold(). You can always like a Pi-powered
check what objects are about to be cleaned up with the buggy, the memory
freed up by garbage
variable gc.garbage. With the gc module, you get a lot collector can make all
more control over your system than in most languages. the difference
WorldMags.net
The Code WorldMags.net
MANAGING MEMORY
def memory_usage():
rusage_denom = 1024.
mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / rusage_denom
return mem
WorldMags.net
The Code WorldMags.net
MANAGING MEMORY
memory_usage()
list1 = range(10000)
memory_usage()
list2 = range(1000000)
memory_usage()
# Do we use up more RAM if we make another reference?
list3 = list2
memory_usage()
import gc
# How much garbage?
gc.garbage
# Go ahead and cleanup
gc.collect()
Short memory
The RasPi’s size and
price point dictates
that it doesn’t have a
lot of memory. How
frugal are you with
your code?
WorldMags.net
WorldMags.net
WorldMags.net
I heard there’s a WorldMags.net
Yes, the new Epiphany-based
new browser for
the Raspberry browser for the Raspberry Pi is
Keep up with the
Pi, how do I go an excellent piece of software latest Raspberry Pi
that is much faster than the news by following
about getting it? @LinuxUserMag on
current offering included with Twitter. Search for the
Alistair via
the Raspberry Pi. The latest hashtag #RasPiMag
Facebook
version of Raspbian contains
the browser, so if you’re setting
up or doing a fresh install you will already
have the brand new browser. Otherwise,
you can install Epiphany in the browser by
updating the software and performing a
AverageManvsPi:
distribution upgrade by using the following #RasPiMag pic.
three commands in the terminal: twitter.com/
dUMaecOpHA
$ sudo apt-get update
$ sudo apt-get dist-upgrade
$ sudo apt-get install epiphany-browser
WorldMags.net
I like the idea WorldMags.net
Yes you certainly can. There are
of the Kano
computer a couple of things that make
system but I up the Kano system and that’s
the hardware and software.
already have a
The hardware is cool but the
Raspberry Pi.
operating system is what really
Can I make one?
makes it useful; luckily that’s free
John Hogan via theuberchad:
for everyone to use and you can
email Almost ready to
grab it straight from the Kano have the scorpion bot
website, kano.me. controlled by its
#RaspberryPi brain.
Write it to an SD card like any other #raspimag pic.twitter.
image, get PDFs for how to use it and you’re com/cqtwafgpxM
on your way.
Am I stuck
to only using You can use Wi-Fi on the
an ethernet Raspberry Pi like just about any
cable on my other PC or Laptop, although
artekw: Wireless
you’ll need to buy a USB Wi-Fi
Raspberry Pi Home Automation
dongle to do this. It’s easier on Base station with
to go on the RaspberryPi & Arduino
the Model B+ as there are more #RasPiMag pic.twitter.
internet?
USB ports, but on the original com/hSm90i5KZr
Dan Chan via
Raspberry Pi’s you may need to
Facebook
get a powered USB hub if you
want to have mouse, keyboard
and wifi connected at once.
Not every wireless dongle works
though. A full list of tried and tested dongles
can be found online here: http://elinux.org/ CodyErekson: Meet
@RoboPaulLives,
RPi_USB_Wi-Fi_Adapters my #raspberrypi
powered robotic psychic
octopus. :) pic.twitter.
com/KxDaxZ9OIl
WorldMags.net
WorldMags.net
Next issue
Get inspired Expert advice Easy-to-follow guides
Supercharge your
Raspberry Pi
Plus Wireless access point, networking peripherals and more
E • FRE
SU
Available
ER
VERY IS
newsagents &
DE
ED supermarkets
OWNLOA today
ON SALE NOW:
» IBM and Linux » Why you need Python 3 » 4 Great competitions
THE LATEST NEWS ESSENTIAL GUIDES DEFINITIVE REVIEWS INDUSTRY INSIGHT EXPERT OPINION
facebook.com/LinuxUserUK twitter.com/LinuxUserMag
WorldMags.net