Tag Archives: raspberry pi

Sensors and Relays, Raspberry Pi, and Python

6 Jan

My school has a Computer Programming/Raspberry Pi club that my dad and I host.  Each time, we teach a lesson about the Pi, Python, Scratch, code.org, binary/hex, etc. and then students break into groups to learn about a topic of their choice.  Some choose to go deeper into Scratch, others work on Raspberry Pi projects, and others use websites like codeacademy or EdX to go learn a different programming language.  We spent a couple of classes talking about what the different languages are used for.  For example, we said that HTML and CSS are good for making websites, Python is good for making MineCraft hacks on the Raspberry Pi, and Javascript is good for making web apps.

We’ve also had several guest speakers who are experts in computer programming come to our school and speak.  For example, we had a Google intern, we went and visited Google, and we had a programmer from JennaSys Engineering speak to us.  We asked each one what programming language they would recommend that we start with.  The Google Intern said “Python or Java,” the Google engineer said “Anything but Python, it’s too far from the hardware,” and the JennaSys engineer said, “Python.”  So, we decided that our lessons would focus on Python.

Below is the script that I wrote for our most recent lesson.  For this lesson, we used a GrovePi to take input from a light sensor and send output to a relay.  The circuit spins a motor if the light level gets too low.  So, this could be used to open and close your window blinds as the sun rises and sets, but that’s not very realistic.  In reality, there are many, many devices that use this exact same structure.  For example, your thermostat turns on the heater if the temperature gets too low and the AC if the temperature gets too high.  Some cars turn on the headlights when it gets too dark.  Your refrigerator compressor kicks in if the fridge gets too warm.  Some cars have windshield wipers that turn on when they detect moisture.  Grocery store doors open when they detect a person nearby.  An alarm goes off when a door is opened.  What these systems all have in common is that there is a sensor that triggers a relay to do something.  There are hundreds of other examples of this, too (3D printer micro switch, printer jam detection, phone overheat protection, laptop turns off when the lid closes, etc.) so we decided to look at an example of code that can make this happen.

I have to put a picture of the code because my spacing in the program gets messed up on WordPress for some reason:


A “relay” is a switch that you can turn on and off with code.  The click that you hear when you turn on a device with a remote control is the relay switching on.  They have one side that is “Normally Open” and you can use code to close it (turn it on) and another side that is “Normally Closed” and you can use code to open it (turn it off).  It gets confusing because generally, when you send a value of “1” to an output, you are turning it on.  But if that device is plugged into the “Normally Closed” side of the relay, then it’s already on and you turn it off by sending the value of “1.”

So, although the circuit that we had that day was only slightly cool, the applications to other areas are powerful.  This project also demonstrates why a Google engineer told us that Python isn’t the best language to learn.  The libraries make it so easy.  If you were writing code for a car’s computer, you wouldn’t be able to take the shortcut by importing the GrovePi library.


Raspberry Pi Starter Kit: http://amzn.to/13UtN2F  $69.95

GrovePi board and sensors: http://amzn.to/1tEdgad  $75.00

DC Motor: http://amzn.to/1tKqzvg  $5.00

Variety of batteries, clips, and wires

My GrovePi Adventure

19 Nov

Here we go again . . . another story of following the instructions for a project exactly and failing miserably.  A while back, I got a GrovePi and a bunch of sensors.  It would be perfect for adding inputs to the Raspberry Pi since it has temperature, pressure, flame, light, sound, knock, distance, and more sensors.  So, first, I decided to try the joystick.  I went to the website for GrovePi and found instructions there (dexterindustries.com or seedstudio.com).  Wait . . . what?  The kit didn’t come with any cables.  Huh?  The one in the picture has a white plastic connector with four pins.  Mine has no connector and 5 pins!  What’s going on here?

I found out that the sensors that I bought on Amazon are not GrovePi sensors at all.  They are compatible . . . sort of, but they are not the GrovePi sensors.  They came with some connector wires (that don’t fit) and a ribbon cable (which is pretty useless).  The little instruction book only has a picture of each sensor and no instructions whatsoever.  There is an instruction manual online, but it sounds like it was written in another language and translated by a 4-year old.  Here are a couple of quotes:

“13 comes with digital interfaces of the LED, the shock sensor access number 3 interface, when a sense of shock sensor”

“The reason why we feel that infrared is really a wonderful thing, it is because we are invisible, intangible, but Okay, we do not need that, too, can control it and make it serve us, in fact, we are more magical, Is not?”

“The amount of points we can hand to block receiver module, see also the normal communication between them do? The following is the receive window Ah, looked at the window, and we all know it. . .”

I don’t mean to make fun of anyone and their English ability, but these sentences are so confusing that I cannot figure any of them out.  And it’s only written for Arduino (yuck!), not Raspberry Pi.

The reason for all of this is that I purchased a kit on Amazon called the SunFounder 37 modules Raspberry Pi Sensor Kit.  This kit is no longer available, but there are still Arduino kits like this one.  You can still get the old kit at Amazon.de, but I wouldn’t recommend it.

Bottom line is that the GrovePi is a great product.  It has solved all of the issues that I blogged about before with using analog sensors on the Raspberry Pi (here).  The GrovePi library has all of the code for accessing the analog ports on the GrovePi with simple code.  But I would highly recommend buying actual GrovePi sensors (like this one), not SunFounder sensors.  Support for GrovePi sensors on the Raspberry Pi is pretty good, but the software comes with sample code that can easily be modified to use most of the sensors and there are a few cool projects on their website (here).  (Note: This kit no longer says on the advertisement that it works with GrovePi and it comes with an instruction book.  I don’t have the book, so I cannot tell you if it’s good or not.)

I’ll blog later about how I used the code for the analog temperature sensor to make the SunFounder analog sensor work and then modified that code to make the Photo Resistor Sensor work with very few changes.  I’ve added some error handling that people on a forum told me about, so the program doesn’t crash anymore.  My ultimate goal is that some of the students at my school are planting an experimental citrus grove and we want to use moisture sensors to automatically trigger an irrigation system.  So, it would have about 40 moisture sensors and a couple of relays to trigger water pumps connected to a tank of reclaimed water.  We might also get a water flow meter to measure how much water we’ve used and track whether the system is working.

Raspberry Pi Kickstarter

8 Apr

Today, my school launched a kickstarter campaign to purchase Raspberry Pi kits for our computer science club to learn programming.  Please help us in the following ways:


1) Contribute to the campaign here: http://tinyurl.com/WCAComputerScience


2) Share the link with all of your friends on Facebook, Twitter, etc.



P.S. That’s my voice in the kickstarter video!

Servo Motor with Raspberry Pi and PWM

10 Feb

After my dad and I got an LED to dim using Pulse Width Modulation on my Raspberry Pi, we decided to try to spin a servo motor.  We had a bunch of old servo motors on my robotics team at school so I used one of those, but I didn’t have any information on the pulses that they use.  It was a HiTec HS-485SB.  So, we started off following this YouTube video to modify the code from the LED to operate the servo.  Of course . . . it didn’t work.

There were a couple of reasons why it didn’t work.  First, the video didn’t really talk about how to hook up the servo to the RPi.  Second, every servo is a little different.  The colors of my wires were even different than the colors of his wires.  Third, I didn’t know what pulse widths to use with my servo.  The only thing that I could find is that it used from 0.9 to 2.1 ms so I assumed that means that 0.9 is CCW, 1.5 is center, and 2.1 is CW similar to the video, but not exactly the same.

So, we hooked up the red wire to the 5 volt pin, the black wire to ground, and the yellow wire to pin 21.  I typed in the code from the video and changed all of the pin 7 to pin 21.  I changed all of the pulse widths to match my servo.  I ran the program and bzzz . . . I got a tiny little buzz out of the servo and the whole raspberry pi froze up.  My dad said that he read that you can destroy a RPi by hooking up a servo the wrong way, so we decided to hook the red and black wires up to four AA batteries instead.  So, with much anticipation (and cutting, stripping wires, and soldering batteries), I ran the program again . . . bzzzz, a little buzz and the program stopped.

I figured that it must be the pulse widths, so I played around with the numbers and couldn’t get anything else to work after many, many tries.  Same thing over and over.  It would rotate about 45 degrees counter-clockwise and stop (at least it doesn’t freeze up anymore).

So, I started doing research.  I came across this blog where a noob, like myself, was trying to learn how to spin a servo.  People suggested using something called servoblaster (too complicated for me) and lots of other things that I’d already tried.  But then something jumped out at me that I hadn’t tried yet.  It said that you have to connect the negative side of the batteries to the ground on the Raspberry Pi.  I connected that one wire and bzzz, bzzz, bzzzzzzzzzzz, bzzz, bzzz, bzzzzzzzzz, it WORKED!

Here’s the exact code that came from the video link above:


import RPi.GPIO as GPIO

import time



p = GPIO.PWM(21,50)        #sets pin 21 to PWM and sends 50 signals per second

p.start(7.5)          #starts by sending a pulse at 7.5% to center the servo

try:                      # I still don’t know what this does

    while True:       #starts an infinite loop

        p.ChangeDutyCycle(4.5)    #sends a 4.5% pulse to turn the servo CCW

        time.sleep(0.5)                   #continues for a half a second

        p.ChangeDutyCycle(10.5)    #sends a 10.5% pulse to turn the servo CW

        time.sleep(0.5)                   #continues for a half a second

        p.ChangeDutyCycle(7.5)    #sends a 7.5% pulse to center the servo again

        time.sleep(0.5)                   #continues for a half a second

except KeyboardInterrupt:


    GPIO.cleanup()                 #supposed to stop when a key is pressed, doesn’t work


The percents work because at the beginning, we set it to send 50 pulses per second.  So, 7.5% of 1/50 of a second is .0015 seconds or 1.5 milliseconds.  That’s the pulse that it needs to center the servo as I explained in the beginning.

See the video below of my servo working!  It doesn’t seem to be spinning the full 180 degrees, so I need to play with the numbers some more.  Maybe I’m not giving it enough time to move all the way.

My dad zoomed in real close on the servo because he didn’t want you to see how bad the soldering was on the batteries.  He’s terrible at soldering!  But don’t tell him I said that.

PWM Dimming of an LED with Raspberry Pi

3 Feb

This is Krystal’s dad guest posting again.  Krystal wanted to control some servo motors with her Raspberry Pi because she’s on a robotics team that uses the Lego NXT brick as the controller and it easily controls servos.  She wanted to see how easy it is on the Raspberry Pi.  I wouldn’t call it an easy task, but we accomplished the first step in several hours one night.  I am a complete novice to Raspberry Pi, Linux, PWM, python, and object-oriented programming in general, but I do know a thing or two about electronics and breadboards.

First thing, we read that Occidentalis is the way to go for using Pulse Width Modulation (PWM) to control servos directly from the Raspberry Pi without any controller boards connected.  So, as Krystal described in this other blog post on how to install Linux on a memory card, we used Win32DiskImager to install the Occidentalis image onto a 4 Gb memory card.  It went smoothly as soon as we remembered that we need to run Win32DiskImager as the Administrator on the computer (Right-click and “Run as Administrator”).

We popped in the memory card and started it up.  We went through the raspi-config and did the typical settings to use the whole memory card and such.  We noticed that there were no settings for overclocking in this version of Linux so we planned for tasks to take longer than we were used to with her jazzed up version of Wheezy that we usually use.

To start, we typed sudo apt-get update, but it didn’t work since we hadn’t configured the wifi yet.  So, we looked up the instructions for how to do that on Occidentalis.  We removed the wifi dongle, typed “sudo nano /etc/network/interfaces” and added our SSID and password and saved (CTRL^X, Y, Enter).  We shutdown the Pi (sudo shutdown now), put the wifi dongle back in, and turned the Pi back on.  We’ll skip a few trial and errors that occurred here and just skip to the part where it worked.  When we typed ifconfig, our IP address showed up.  This was actually the easiest time we’ve had connecting to wifi.  You can read about her other adventures with wifi in a past blog post.

So, we did the update and started watching a video about using PWM (but not on the RPi because there’s still no simple method to watch YouTube videos on the Pi).  We figured that we’d start by dimming an LED before running servo motors.  So, we went to http://youtu.be/uUn0KWwwkq8 and tried to reproduce his results.  Of course, you know what comes next if you’ve been following this blog at all . . . it didn’t work.

We kept getting the message that there was no module named RPi.GPIO.  So, we researched how to install RPi.GPIO and tried it time after time after time and kept getting the same error message.  So, we reinstalled and updated Python then installed Python3.  Still didn’t work.  Updated Python3, still didn’t work.  Typed startx to open Midori and research some more and found where we could download the RPi.GPIO module, unzip it, and install it from the graphical interface.

Didn’t work.  Kept getting an unexpected end of file error when extracting.  So, we tried installing Gzip to extract the files.  Couldn’t get that to work.  Finally, instead of doing a Save As and then extracting, we chose “Open” after clicking the download button and it worked.  (Download the module here: https://pypi.python.org/pypi/RPi.GPIO)  Then, we just typed “sudo python3 setup.py install” (as we read on the raspberrypi.org website) (and we admit that we failed several more times before coming to this solution) and it seemed to install.  But, it still didn’t work.  Turns out that one of the things that we’d tried in order to fix it earlier was the case of the letters in RPi.GPIO.  We’d changed it to rpi.gpio.  Once we changed it back, it worked (almost, we had to connect it to the right pin on the GPIO and that took several tries.  Why aren’t Pin 7 and GPIO7 the same thing?????).

Here’s the code that we used (Krystal was in bed by now and hasn’t seen this working as I’m writing this.)


import RPi.GPIO as GPIO        #This line alone caused 90 minutes of frustration

import time


GPIO.setup(21, GPIO.OUT) #set pin 21 to output

p = GPIO.PWM(21,50)        #set the PWM on pin 21 to 50%

p.start(0) #I don’t remember what this does but trust me, you need it.


while True:

for i in range (100):


time.sleep(0.02)         #These last three lines are going to loop and increase the power from 1% to 100% gradually

for i in range(100):


time.sleep(0.02)         #These three lines loop and decrease the power from 100%-1% gradually

except KeyboardInterrupt:

pass                   #This is supposed to stop the program if a key is hit, but it doesn’t work for us.  Only ctrl^c works




It works!  We have an LED that goes from dark to bright to dark again gradually over and over.  The only difference between our program and the one in the video referenced above is that we used pin 21 for our LED and he used pin 7.

So, I started playing with the numbers.  I found that the duty cycle is not allowed to go over 100.  By changing the time.sleep value, I can change how fast the dimming and brightening cycle is.  Changing it to 0.01 gives a nice, steady pulse.  We could change the i in range to 50 if we didn’t want the LED to go to full brightness.

See the un-amazing video here:

Next step is to control a servo motor instead of an LED.  It should be a very similar process.  After that, we’ll try and take over the world, dun dun duh.


Raspberry Pi, power supply, keyboard, mouse, USB hub, etc.

Occidentalis distro of Linux

RPi.GPIO module

LEDs, breadboard, wires, resistors

Wifi dongle or other direct internet connection

Infinite patience (no URL for that one)

I Beat it!!!

4 Dec

I beat it!!!  “What did she beat?” you may be asking yourself.  Remember when I blogged about the “Awesome Text Adventure Game” in the Pi Store called “The Abandoned Farmhouse Adventure” here?  I completed the game!  I saved my grandson!  OK, I don’t have a grandson, but that’s the point of the game, to save your imaginary grandson Matthew.

After long, difficult hours of exploring the woods, the house, and the farm, I was on the brink of giving up.  I couldn’t figure out how to kill the rats in the tunnel before they killed me.  I also died of thirst several times before I found a source of water.  So, I decided to stop picking things up and just explore and draw a map of all of the moves that I made.  The map helped sooooo much as I learned more and more about the strategy and had to start over again and again (don’t tell my mom that it was way past my bedtime).  I would highly recommend that you draw a map too (or scroll down and see the one that I made).  Once I knew where everything is, I started to figure out which items I needed to pick up and which items I’d just leave alone.  Every time I got a little farther, it would help me figure out which items are important.  Then I could use the map to easily go back and get them or start over and get back to this spot quickly.

When I finally saved Matthew, I literally screamed with joy!  Then, I went back and saved him a couple of more times while I wrote down step-by-step directions for how I did it.  I don’t want to ruin the adventure for you, so if you scroll down a little bit, I’ll give you some hints and the map that I used.  Or, if you get really frustrated, scroll down even farther to get the step-by-step directions.

Have a great adventure!!!


You’re going to need a weapon, something to pick up water, a way to open the door, a food source and a way to get the boy out of the tree.

You don’t need the flashlight.

There’s no need to go in the garage.

You don’t have to kill the rats, I tried for hours.

You can only hold a few things, so after you use something, drop it so you can pick up something else.

To go a direction, you don’ have to type “go north,” you can just type “n” and it does the same thing.  You can type n, e, s, w, u, d for go north, east, south, west, up, or down.

If you don’t know what a cistern is, look it up.



Step-by-Step Walkthrough

Spoiler Alert!!!!!!!!!!!

Take key

Go North

Take bottle

go north

go north

go up

take pitchfork






take candybar

use candybar

drop candybar





take toy car









use bottle


use key






use pitchfork

use toy car

That’s it!  You saved the boy!

Minecraft Adventure Part 2- The Reinstallation

22 Nov

Today was tough, more long clock-ticking hours of trying to download minecraft on my raspberry pi. I am very determined to get minecraft on the pi, because I know I can, I know that it’s possible, I’ve done it before (see my blog here).  But then, it fell apart.  It stopped working.  I downloaded it again, installed it, played it for a few seconds, and it would crash the whole Pi.  When I would restart the Pi, Minecraft wasn’t even there!  So, I downloaded it again.  And it crashed again.  And it disappeared again.  And so the cycle continued for hours.  I had a feeling that I could just re-image the memory card and start over, but I HATE doing that.  It takes hours of typing in Linux commands.  So, I put my Raspberry Pi away for a couple of months and moved on to other things.

But, when I was in Washington D.C. (read about that adventure here),  Eben Upton told me that there is a new version of raspbian, and that it should fix all of the problems that I had explained to him and that he read about on my blog.  So, I decided that tonight is the night, I’ll reimage, reinstall, and play.  Good thing I blog about my Raspberry Pi adventures because I had to go through all of my old posts to remember how to image, how to connect to wifi, how to upgrade, how to update, and how to install Minecraft.  All of the problems that I had the first time in my blog, I had again.  It took 30 minutes to connect to wifi.  Minecraft didn’t work the first 6 times I downloaded it.  For me, adafruit’s instructions worked better using the wget command.  The pi.minecraft.net instructions had me download the file and try to extract it.  Extracting never worked until I used wget instead of going to the download site in Midori.  Here’s the site that I now recommend: http://learn.adafruit.com/running-minecraft-on-a-raspberry-pi/download-the-software.

But much worse than all of that . . . Minecraft just crashed on me.  But, I rebooted and I’m running it again.  I’ll let you know how it goes.  So far, so good.  Ahhhhhhhhhhh!  It froze again . . . I’m going to break this keyboard in half.  Wait . . . it just came back kinda.  But there’s an error message that says, “DBus error org.gtk.Private.RemoteVolumeMonitor.NotFound: The given volume was not found”  I don’t know if these two are related at all, but I’m going to try to click OK and see what happens.

OK, when I read that message, I moved Minecraft to Desktop 2 and it disappeared again.  So, I ran it again.  This time, I tried to see if I could join a game running on my iPod.  That didn’t work.  So, I just started a regular game.  I’ve been playing now for about 10 minutes and it has frozen a couple of times but not permanently.  One time, the “w” key seemed to be stuck and I had to restart the game.  But it is letting me build and saving my progress.  It’s taking up most of the processing power on the little meter in the corner, so that might be why it keeps freezing.  I only overclocked it to the lowest level.  But I don’t know if overclocking makes it worse because it’s going faster and will fill up the processing meter.  Or if it will make it better because it’s going fast and the processing meter will never reach the top.  I guess I have to do some experiments.

I’ve now been playing for about 20 minutes without a crash!  Yes!  I just wish that there were creepers.  So, I think it’s stable now but it took me 3 hours to get to this point.