Skip navigation

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:



Hi all,


In this blog post, I show how to read the temperature from a DS18B20 temperature sensor using Python on the Raspberry Pi.

This sensor is nice not only in that it's inexpensive, but it's also a digital sensor. Given that the Raspberry Pi doesn't easily handle analog inputs, the DS18B20 is a great choice.


In case you need it, here are my previous posts to help you get started with Python programming and IO pins for the Raspberry Pi:

Raspberry Pi - HelloWorld

Raspberry Pi - Blink


For this tutorial, I am using:

1x Raspberry Pi Model B+ running Raspbian (other models should work fine too)

1x breadboard to make the connections

1x DS18B20 temperature sensor - I'm using a waterproof one with a foot long cable containing red, black, and yellow leads

3x M-F jumper wires

1x 10KΩ resistor


Edit: I tried this on a new RaspberryPi and it didn't work. Turns out I missed this step:

- Add the following line to /boot/config.txt


- You can edit that file with the leafpad editor by running "sudo leafpad /boot/config.txt" and then adding that line at the very bottom.

- Save, and reboot.


The hardware connections:

- put the 3 leads of the DS18B20 into the breadboard. (I found this worked ok enough, but ideally it's better to solder some good tips onto them for stronger connections.)

- connect a jumper wire from the yellow (data) wire to pin 7 (GPIO4) on the Raspberry Pi

- connect a jumper wire from the red (power) wire to pin 1 (3.3v) on the Raspberry Pi

- connect a jumper wire from the black (ground) wire to pin 9 (GND) on the Raspberry Pi

- add a 10KΩ resistor between data and power


So that's the hard part.

This is what is looks like:


(Check out my duct tape Pi case!)


Now open up the attached example ( and run it, and you should see temperature numbers showing up on the Python console.

If you see error messages, it is most likely due to a loose wire. In my case the DS18B20 leads are a little short and one popped out, which caused some scary looking error messages when I tried to run the script!

The other thing I forgot at first was that 10K resistor - it is vitally important too.


This is what the output should look like, with numbers depending on your temperature, of course. Try putting your fingers on the sensor to see how that affects the readings.



For more details, also check out this Adafruit tutorial, which I used as a guide to get started.

The attached Python code is also derived from their example.


Edit: This has been tested and works on both the RPi model B+ and the RPi 2 model B.




About a year ago, I got my first Raspberry Pi, and sometime in the past year, I have come to understand it as a powerful computer that I can dedicate to a specific task.  A couple weeks ago I got the Raspberry Pi Camera Board, a simple camera that...well...takes pictures.


The obvious thing to try is time lapse photography since I know I can make the RPi take a lot of pictures, and another piece of software can stitch them into a movie.  So I have the method I used for doing it here.  There are lots of ways to do this.  I am just showing how I was able to do it in a short period of time.


Connect the Camera


This was pretty straightforward, and there is a tutorial for this here.


Take a Picture (probably a selfie)


No additional software is needed to do this.  You just need a simple command:


raspistill -o picture.jpg


This captures a picture and stores it on the Pi.  If you want to specify a location for it then you can put that in there (/home/pi/camera/picture.jpg).  I am a folders kind of guy.




Now you can set up for your actual experiment.  This is actually the hard part.  You want to find something that changes dramatically, but does it very slowly.  Obvious things include clouds, traffic, etc.  I didn't have access to a good view or anything I would consider to be weather-proof.  So I went with lettuce leaves changing their color when placed in a small amount of food coloring.  Here they are at the start of my experiment.



Over time, through capillary action and some other processes, these lettuce leaves should absorb the food coloring in the beakers.  So now I am ready to get it moving.


raspistill -o /home/pi/camera/lettuce/lettuce_%04d.jpg -tl 60000 -t 43200000 &


This command has a few basic parts

  • raspistill - the name of the program I am calling up
  • -o /home/pi/camera/lettuce/lettuce_%04d.jpg - an output file to a specific folder.  This command will automatically make a new file with a four digit number.  So the first file will be lettuce_0001.jpg.  The next will be lettuce_0002.jpg and so on.  This is very handy when it comes time to sequence them.
  • -tl 60000 (this is the letters 't' and 'l'.  I tried the number '1' and a capital 'I' and failed both times).  This is an interval.  The camera will take a picture every 60000 milliseconds, or 60 seconds.
  • -t 43200000 - the total time for this experiment.  It will run for 12 hours.

So when all is said and done, I should have one picture every minute for 12 hours, which comes out to 720 pictures.  Unless you change something about the size of the photo you take, each picture will be about 2.4MB. 

Getting the pictures from the camera, can be a bit of a trick.  There are a couple methods you can use.  In the big picture sense (pun!), you will probably want to transfer these pictures to a computer with a little more processing power than the Raspberry Pi.  There area few methods for this.  Below are the ones I researched before settling on something that I really liked.


  • Rsync - This method will sync a folder on the Raspberry Pi with a local folder on another machine.  This uses an SSH connection between the two machines. 
  • Dropbox - This method makes a lot sense (though I haven't tried it yet).  It basically allows you to save the files to your drop box folder as it goes.  There are a lot of benefits to this method as you can access the pictures from anywhere. 


I finally settled on using WinSCP.  This is something I ended up using for other web work I was doing.  It occurred to me that knowing the IP address of the RPi, I could SFTP to go in there and transfer the files I needed.  This worked great, and allowed me to use some software I was already familiar with. 




With all of the files selected and organized, I could use another piece of software to sequence the pictures into a time lapse movie.  Some photographer friends recommended Cineform Studio, which is the free software that accompanies the GoPro camera.  Just a word on this kind of thing.  I am already well outside my comfort zone, and trying to discern between different photo editing packages is like asking me to learn Shakespeare in Latin.  There probably lots of ways to go here, but this one seemed intuitive for me.




This would be the part where I put the finished video, but I am letting this run for another few hours, so that will have to wait.  But until then, I hope you have found this helpful!