Skip navigation

STEM Academy

3 Posts authored by: mconners Top Member

Another simple real world measurement that can be performed with the Raspberry Pi B+ is to make measurements of the physical world around you. As several have shown before, you can get digital sensors to determine temperature, humidity, distance, motion, and a host of other things. But sometimes you may not have a digital sensor, or your budget doesn't allow for it. The lack of an Analog to Digital converter  built into the Raspberry Pi would seem to be a hindrance, but that is not entirely true. You can use a few inexpensive discrete components and approximate analog values by combining an analog sensor, like a photocell, or an analog temperature sensor, or any other sensor that changes resistance based on external stimuli, with a capacitor of fixed value. This creates an RC circuit. Where R means resistor and C means capacitor. According to wikipedia (and probably every electronics textbook in the world) :


"The simplest RC circuit is a capacitor and a resistor in series. When a circuit consists of only a charged capacitor and a resistor, the capacitor will discharge its stored energy through the resistor. The voltage across the capacitor, which is time dependent, can be found by using Kirchoff's current law, where the current charging the capacitor must equal the current through the resistor."


What does all that mean to us? The key in the above is that the voltage across the capacitor is time dependent. That means we can measure it. There is a threshold in digital circuits where a signal is recognized as a High (logic 1) or a Low (logic 0). We often dismiss this by saying "A high is 3.3v or 5v and a Low is 0v." This is not necessarily true, what about the voltages in between. Sure, 0 volts is a LOW, but what about 0.5 volts? It's not a HIGH. So until it reaches a certain voltage logically we will treat it as a logic 0, once it exceeds the threshold, the device will register the level as a HIGH and we will treat it as a logic 1. This threshold on the Raspberry Pi seems to be around 1.4 volts. Back to the fact that we can measure this time, since the current charging the capacitor must equal the current through the resistor, and our resistor value is changing due to external stimulus, the time to charge and discharge the capacitor will also change, and that is what we will measure.


In this example we will use a photocell and a capacitor together in series. A photocell is simply a device that changes resistance based on ambient light. The brighter the light, the lower the resistance, the dimmer the light, the higher the resistance. Very simple.


The way we will take advantage of all of the above information is:


1) We will start by driving our sensing pin on the B+ to low, this will give us a known starting point of 0 volts

2) We will change the sensing pin to an input

3) We will count in a loop until the capacitor charges to a level recognized as a logic level 1 on the input pin (approximately 1.4 volts)

4) We will print the value and do it again


What we expect to see is that as the amount of light is decreased, the time it take to charge the capacitor will be longer, so the counted output from our loop will be higher, if we increase the brightness of the light, the resistance will decrease, causing the capacitor to charge more quickly, giving us a lower number from our count. This is sensitive enough to be done by simply waving your hand over the photocell, or you can place a finger over the sensor to simulate total darkness. Bear in mind, this is not an exact measurement, but it is good enough to tell if there is a light on in a room, or if the sun is up, but that is the extent of it. If we were to use an analog temperature sensor instead of a photocell we would probably need to calibrate the outputs to known good values.


On to the code and the circuit, first things first, you need the python GPIO libraries, these can be installed as follows:


sudo apt-get update
sudo apt-get install python-dev
sudo apt-get install python-rpi.gpio


If you are not sure whether those things are installed just run them, it will either download the latest version or tell you that you have the latest version already installed. It may prompt you to answer 'Y' to confirm the installations.


Next you can wire up the circuit. Make sure the Raspberry Pi is off and no power is applied. Even with simple circuits you can make mistakes, so double check your connections. The components needed are:

1) A breadboard

2) A 1 uF Capacitor

3) A photocell

4) The B+

5) Some jumper wires.


We are only going to use 3 pins from the B+, Pin 1 3.3 volts, Pin 6 Ground, and Pin 11 one of the GPIO pins.

Follow the diagram below to make your connections:




I straddled the capacitor from the light blue rail on the left side to the first pin on row 10 of the breadboard, if using an electrolytic capacitor like I did (looks like a small soda can with legs) make sure that the - side (will be clearly marked) is inserted into the ground row (- bus) and not in row 10. I then took my photocell and straddled the channel down the middle of the board on row 10. I connected a jumper from the red row on the right side of the board (+ bus) to row 10 on the right side of the channel down the middle of the board. I connected a green jumper from a hole on row 10 on the left side of the channel in between the capacitor and the photocell and connected that to pin 11 of the Rasberry Pi. I then connected pin 1 of the B+ to the +bus on the right side of the board and Pin 6 of the B+ to the -bus on the left side of the board.


That's it!!! Easy peazy, George and Wheezy.


Now on to the code:


import time
import RPi.GPIO as GPIO


def RCtime (RCpin):
        reading = 0
        GPIO.setup(RCpin, GPIO.OUT)
        GPIO.output(RCpin, GPIO.LOW)

        GPIO.setup(RCpin, GPIO.IN)
        while (GPIO.input(RCpin) == GPIO.LOW):
                reading += 1
        return reading

while True:                                     
        print RCtime(11)


The code above was shamelessly lifted from adafruit. I made a few small modifications, but the basic code came from there.


I've included it as an attachment, so you can download it.


Once the code has been downloaded to your B+, open a command window and go to the directory where the file is stored and type:


chmod 755


This will change the permissions on the file to allow it to be executed. This is only necessary one time, after you download it. To run the program, from the directory where the program was downloaded type:


sudo ./


The sudo is necessary because you need to be super user to access the GPIO pins, and the ./ just tells the shell that the file is in the current directory.


you should expect to see an ouput as follows:




You can stop the execution of the program by typing Ctrl-C (hitting the Ctrl key and the c key at the same time) this will generate a keyboard interrupt to stop the program.


The above output was generated in a room lit by sunlight with the blinds partially drawn. The highest values were read when I cupped my hand over the sensor. Play around with it, run it in a dark room, then turn the lights on, see how the values change.


Below is a picture of the actual setup. Looks a lot like the fritzing diagram :-)




Now I have to give credit where credit is due. I didn't invent this technique. I discovered it in an adafruit tutorial. Being one to never believe anything I read, I had to prove it to myself and write a blog on it giving it my own spin.


This is a very interesting method of measuring analog values with the Raspberry Pi that I would have never thought of, but it uses basic electronic principles and works pretty well for rough measurement, with a little more work and some calibration with other more precise measurement tools you could probably convert the time values read to fairly consistent values that equate to the real world. BTW, although I used a B+ for this, any of the Raspberry Pi family would probably work just as well.


I hope you have enjoyed it.



Posted by mconners Top Member Dec 22, 2014

OK, I dug deep into my parts bin and found another Parallax part. The Passive Infrared Motion Sensor, or PIR sensor. This is another very simple device that you can connect up to your B+ (or any other Raspberry Pi devices).


The theory behind the PIR sensor is that is is a pyroelectric device, this means that it can detect small changes in the radiant heat of objects in the sensors vicinity, when this occurs the output of the sensor will flip from low to high, which is something that you can detect.


The device is fitted with a Fresnel lens that focuses the infrared signals onto the sensing element.


The version of the device that I have is Parallax Part #555-28027, this device, once again, is safe to connect directly to the Raspberry Pi as it only outputs 3.3v. This is very important when selecting sensors for the Raspberry Pi as signals greater than 3.3 volts can damage the Pi.


So the first thing to do is to ensure that you have the python gpio libraries installed, this can be done as follows:


You just need to run the following commands at the command line


sudo apt-get update
sudo apt-get install python-dev
sudo apt-get install python-rpi.gpio


If you are not sure whether those things are installed just run them, it will either download the latest version or tell you that you have the latest version already installed. It may prompt you to answer 'Y' to confirm the installations.


Next, shutdown your pi and power it off.


Connect the + pin on the PIR sensor to the Raspberry Pi pin 2, the - Pin to the Raspberry Pi pin 6, and the Out pin to the Raspberry Pi Pin 11 (the pins are numbered in an alternating fashion, with pin 1 being closest to the red power LED, odd numbered pins are in one row, even numbers are in the next row).


Thats it!!! Just 3 pins!!!


Once the devices are connected you can power up the Raspberry Pi and dowload the attached code,, and perform the following command in the directory where you downloaded


chmod 755


This should only be necessary right after you download the file, it sets the permissions of the file to allow it to be executed.


To run the file simply type the following in the same command window:


sudo ./


The sudo command is necessary to execute the command as the super user ensuring you have adequate permissions to access the GPIO pins. The ./ in the command simply indicates to the command window that the program is in the current directory.


The code is listed below:


import time
import RPi.GPIO as GPIO

# Use board based pin numbering

pirPin = 11

# setup pirPin as input
GPIO.setup(pirPin, GPIO.IN)        

while True:
    if GPIO.input(pirPin):
        print("ACK!!! Someone's here!!!")


As you can see, it is very simple code, all it will do is print the message "ACK!!! Someone's here!!!" whenever the sensor determines someone is in the room. You can point the device towards the door and call someone into the room, when they appear in the sensors range the message will be printed to the screen.


What can you do with your new found knowledge? Well I have seen PIR sensors employed as power saving devices on vending machines. The external lights are turned off until the sensor determines someone is close enough to the vending machine to purchase something, then the front panel will light up telling you it is time to purchase a Coke.


In addition it could be used to signal when someone enters a room, or to control a nightlight when it senses someone is in the hallway, There are many uses for a Passive Infrared Motion Sensor.




Ping))) Me!!!

Posted by mconners Top Member Dec 21, 2014

Hi everyone. This post is going to be a little different than some of the others. In fact it is different than what I had originally intended to blog about. I was going to do a post using temp sensors, but I see that several others have chosen that topic, so I thought I would write a couple of posts about simple projects that allow the Raspberry Pi to measure some other things around them.


I looked through my toolkit and discovered I had one of the sensors that I had purchased several years ago when i first got interested in the Arduino world. I thought it would make an interesting project for the Raspberry Pi B+, although this project would work just as well on the standard B, and probably the Model A as well.


The sensor I discovered was the Ping))) Ultrasonic Sensor manufactured by Parallax. According to the documentation:


"The Parallax PING))) ultrasonic distance sensor provides precise, non-contact distance measurements

from about 2 cm (0.8 inches) to 3 meters (3.3 yards). It is very easy to connect to microcontrollers such

as the BASIC Stamp®, SX or Propeller chip, requiring only one I/O pin.


The PING))) sensor works by transmitting an ultrasonic (well above human hearing range) burst and

providing an output pulse that corresponds to the time required for the burst echo to return to the

sensor. By measuring the echo pulse width, the distance to target can easily be calculated. "


The Ping (as I will refer to it from this point forward) is a very simple device. It requires only 3 wires to connect it to the Pi. One is +5V which can be grabbed directly from pin 2 of the Raspberry Pi, one is Ground, which is provided on pin 4, and the third is pin 11, one of the available GPIO pins. A Fritzing diagram is provided for reference.






That's it!!! That is all that is required to connect this circuit!!!


According to the Ping documentation, it is perfectly safe to connect to a 3.3v device such as the Raspberry Pi. This is something very important to check because providing an input over 3.3v to any of the pins on the Raspberry Pi can cause damage to the device. Also, all electrical connections should be made when the Raspberry Pi is off and there is no power applied. Even a circuit as simple as this can be miswired so double check all connections.


OK, now we have the device connected. What does it do? How do I use it? I'll answer those questions below:



What does it do?

As described the Ping is an Ultrasonic Distance measuring device. The theory is that when the device is signaled to start, an audio signal (above the range of human hearing) is emitted from one of the "speakers" on the device, that signal is expected to bounce off of a solid object and return to the Ping as a reflected sound wave, a pulse that corresponds to the return time of the reflected signal is sent back to the signalling device. Dividing that value by 2 (because it had to travel to the object and back, you only need 1/2 of the distance) and then multiplying that object by the speed of sound in centimeters (34000cm/s) will give you the approximate distance from the Ping sensor to the object. You can demonstrate this to yourself while running the example code and moving the sensor around or placing your hand at different distances from the sensor.


How do I use it?


I've included some sample code that sends the start signal, captures the return pulse, measures the duration of the pulse, then prints out the distance in both cm and inches:


import time
import RPi.GPIO as GPIO

# Use board based pin numbering

def ReadDistance(pin):
   GPIO.setup(pin, GPIO.OUT)
   GPIO.output(pin, 0)


   #send trigger signal
   GPIO.output(pin, 1)


   GPIO.output(pin, 0)

   GPIO.setup(pin, GPIO.IN)

   while GPIO.input(pin)==0:

   while GPIO.input(pin)==1:
   # Distance is defined as time/2 (there and back) * speed of sound 34000 cm/s 
   return distance

while True:
   distance = ReadDistance(11)
   print "Distance to object is ",distance," cm or ",distance*.3937, " inches"


I've included the above code as an attachment that you can download and run locally. You will need to ensure that the proper python libraries have been installed.

You just need to run the following commands at the command line


sudo apt-get update
sudo apt-get install python-dev
sudo apt-get install python-rpi.gpio


If you are not sure whether those things are installed just run them, it will either download the latest version or tell you that you have the latest version already installed. It may prompt you to answer 'Y' to confirm the installations.

Once the board is wired up, and you have downloaded the attached, you can open a command shell, go to the directory where you saved and type:


chmod 755

that will change the permissions on the file to executable. (only necessary right after downloading)

and then type


sudo ./


That will execute the program. It is necessary to type sudo to execute the program as the super user so you will have access to the gpio pins, and the ./ simply indicates that the file is in the current path.

When it executes, you can expect the following output:




You can stop execution of the program by typing ctrl-c (the ctrl key and the c key at the same time), this will send an interrupt to the process and tell it to stop executing. Wave your hand in front of the sensor, pick it up and point it at the monitor, watch the values change.


Why would I use it?

Why would anyone use an Ultrasonic Distance Sensor? Well, they are commonly used in robotics as the "eyes" of the robot. When it detects it is getting too close to an obstacle, the robot can be commanded to change direction to avoid a collision. But

there are many potential uses. Googling around will probably provide several examples of applications that you never would even consider.





Hopefully I've given a simple example of how to use such a device, the code should be simple enough to pull out and use in your own designs. If this is your first exposure to such a measurement tool I hope that I have explained it well enough for you to  think up some interesting uses.


One final picture, the sensor in action: