Home > Articles

Using Analog Sensors with the Raspberry Pi

  • Print
  • + Share This
Richard Blum, co-author of Sams Teach Yourself Python Programming for Raspberry Pi in 24 Hours, Second Edition, walks through how to use analog sensors to capture data with your Raspberry Pi.
Like this article? We recommend

The Raspberry Pi and Sensors

The Raspberry Pi has quickly become a popular platform for Linux hobbyists as well as professional developers. Its small size and versatility have made it a favorite for developers to use in small devices that require Linux support. The Raspberry Pi’s General Purpose Input/Output (GPIO) interface provides a digital interface for easy control of motors, activating switches, or monitoring digital sensors. Unfortunately, though, the GPIO interface doesn’t support analog inputs.

With the popularity of hobbyist microcontrollers such as the Arduino and BeagleBone devices, analog sensors for monitoring such data as temperature, humidity, light, and even wind speed are readily available. With the addition of a single integrated circuit (IC) chip, you can interface any type of analog sensor with your Raspberry Pi.

This article explains how to use the common MCP3008 analog-to-digital converter (ADC) chip to convert any type of analog signal to a digital signal that your Raspberry Pi can process. I’ll demonstrate this process using a TMP36 temperature sensor, including creating a web page you can use to display the current temperature from anywhere on your network.

Background Info: The Serial Peripheral Interface

The Raspberry Pi GPIO interface primarily supports digital input and output signals, and it supports two popular digital communications standards:

  • The Serial Peripheral Interface (SPI) standard provides a way for digital devices to share data serially.
  • The Inter-integrated Circuit (I2C) standard was developed to attach peripheral ICs to microcontrollers.

You can use either of these protocols from the Raspberry Pi to communicate with external devices.

For this example, we’ll use the SPI feature in the Raspberry Pi GPIO interface to communicate with an MCP3008 IC chip to retrieve data from the analog-to-digital converter. This setup allows you to connect up to eight analog sensors to the chip, using a Python program to read the data from those sensors, using the SPI protocol.

The SPI protocol requires four wires to connect between the GPIO interface and the MCP3008:

  • SCLK: Serial clock
  • MOSI: Master out, slave in
  • MISO: Master in, slave out
  • SS: Slave select

Because the SPI standard uses a bus architecture for communication, you can connect multiple SPI receiving devices to the same bus, as shown in Figure 1.

Figure 1

Figure 1 Connecting the Raspberry PI GPIO to multiple devices using SPI.

The SPI host enables each individual receiving device by activating the slave select (SS) line connected to that device.

Enabling SPI on the Raspberry Pi

Before you can communicate with SPI on the Raspberry Pi, you must enable the SPI device in Linux, and load the software driver (called a module) into the Linux kernel. To enable the SPI device, you can use the raspi-config utility. From the Raspbian command line, just enter the following command:

sudo raspi-config

In the raspi-config menu, select the Advanced Options menu entry, and then select the option to enable the SPI interface. When prompted whether you want to load the SPI module at boot time as well, select Yes, and then exit the raspi-config menu. After rebooting your Raspberry Pi, you can check for the SPI devices in the /dev folder:

ls -l /dev/spi*

To be able to use the SPI device to communicate with the MCP3008 sensor, you’ll need to load the spidev library into your Python libraries. The next section provides the details.

Using the spidev Library

To get your Python programs to communicate with SPI devices, you’ll need a special library of functions. The spidev library was developed to provide a software interface to the SPI device on the Raspberry Pi. Unfortunately, that library is not installed by default in the Raspberry Pi Python library, so you’ll need to add it. You can download the spidev code from the GitHub repository website and then compile it into your Raspberry Pi library with just a few simple commands:

sudo apt-get install python3-dev
wget https://github.com/Gadgetoid/py-spidev/archive/master.zip
unzip master.zip
rm master.zip
cd py-spidev-master
sudo python3 setup.py install

The python3-dev library provides the development environment for your Python library. The wget command retrieves the current spidev code from GitHub, and then the setup.py script installs it into your Python3 library. (If you’re using Python2 instead, just use python instead of python3 in the command.)

Now that you have the SPI device and your Python SPI library set up, you’re ready to start building a project. For this project, we’ll connect a TMP36 analog temperature sensor to the MCP3008 to monitor the temperature. We’ll use a web page to display the current temperature, and then any device on your local network can access the web page and the temperature data.

Installing a Web Server

To communicate remotely with the Raspberry Pi to see the temperature, we’ll use a standard web server. Several web server packages are available in the Raspbian software repository; we’ll use the standard Apache web server. To install it, enter this command:

sudo apt-get install apache2

That’s all you need to do. The Apache web server is installed and activated automatically. You can test it by opening a browser (either using the graphical desktop on your Raspberry Pi, or from another workstation on your local network), and then connecting to the IP address assigned to your Raspberry Pi. My network used the following URL:

To allow your web programs running on the Apache web server to talk to the SPI devices, you’ll need to give the user account that runs the Apache web server permissions for the SPI devices. Enter this command:

sudo usermod -a -G spi www-data

This instruction adds the www-data user account to the spi group on the system.

Now you’re ready to build the electronics for the project. The next section covers how it works.

Building the Project

To connect the MCP3008 ADC and TMP36 temperature sensor to the Raspberry PI GPIO, you’ll most likely want to use a breadboard. The Pi Cobbler provides a ribbon cable and breakout device that allow you to plug into the GPIO interface and access the ports on a breadboard easily. After plugging in the Pi Cobbler breakout device, the MCP3008 chip, and the TMP36 device in separate locations on your breadboard, wire up by following this chart:

GPIO Pin????? MCP3008 Pin
?1??????????? 15,16? (Vref and Vin (3.3V))
?5? ??????????9,14?? (GND)
19? ??????????11???? (Pi MOSI -> MCP3008 Din)
21? ??????????12???? (Pi MISO -> MCP3008 Dout)
23? ??????????13???? (Pi SCLK -> MCP3008 CLK) (clocks)
24? ??????????10???? (Pi CE0 -> MCP3008 CS) (chip select)

For the TMP36 device, connect pin 1 (Vin) to the 3.3V power bus, pin 3 (GND) to the ground bus, and pin 2 (Vout) to pin 1 (Channel 0) on the MCP3008.

In addition to these connections, place a 0.01uF capacitor across TMP36 pins 2 and 3 to help stabilize the output from the sensor. Without the capacitor, the output can be somewhat erratic, and is prone to be wrong. Figure 2 shows the basic connections.

Figure 2

Figure 2 Wiring the MCP3008, TMP36, and capacitor to the GPIO interface.

Writing the Code

Now you’re ready to code the project. In your Home folder, open an editor and enter this code:

import spidev
spi = SpiDev()
channel = 0
vRef = 3300
result = spi.xfer2([1, (8 + channel) << 4, 0])
adcValue = ((result[1] & 3) << 8) + result[2]
mVolts = round((adcValue * (vRef / 1024.0)),2)
tempC = round(((mVolts - 500) / 10.0), 2)
tempF = round((tempC * (9.0/5.0) + 32.0), 2)
print('Content-Type: text/html')
print('<title>Temperature Sensor</title>')
print('<h2>Current Temperature Sensor Info</h2>')
print('The ADC value is:', data, '<br />')
print('The voltage is:', mVolts,'millivolts<br />')
print('The temperature is:',tempC,'degrees C<br />')
print('The temperature is:',tempF,'degrees F')

Save the text file as gettemp.cgi in your Home folder.

The spidev library uses the SpiDev() method to communicate with the SPI device on the Raspberry Pi. The open() method enables communication, and the xfer2() method both sends and receives a message with the SPI device. The trick is in telling the MCP3008 that you want to take a sample reading, and then reading that value from the MCP3008. According to the MCP3008 specifications, to activate a reading the MCP must receive a three-byte message:

00000001 1ddd0000 xxxxxxxx

The first byte must be a 1, and the second byte uses three bits to indicate which channel to read. For channel 0, we’ll use the value 10000000. The value of the last byte doesn’t matter.

When the MCP3008 chip receives the command, it takes a sample reading from the designated analog channel, and converts the analog value into a 10-bit digital value based on the relationship of the voltage to the reference voltage applied to the Vref pin (pin 15). The resulting 10-bit digital value is sent back to the requesting host as a three-byte value:

???????? ?????0bb bbbbbbbb

where bbbbbbbbbb is the 10-bit value.

So, to send the data to activate a reading, we use the following line:

result = spi.xfer2([1, (8 + channel) << 4, 0])

This command sends three byte values down the communication line. The first byte is the 1 value. The second byte sets the high bit to a 1, adds the channel value, and then shifts the four-bit value to the high part of the byte. Thus, for channel 0, we send the value 10000000, or 128. The third byte is irrelevant, so we just send a 0 value.

The xfer2() method waits for a response from the MCP3008, and returns the value as a list datatype:

adcValue = ((result[1] & 3) << 8) + result[2]

To retrieve the 10-bit value, we mask out the first two bits in the second byte value, shift it eight bits, and then add the value from the third byte. This technique returns a value between 0 (for 0 volts) and 1023 (for 3.3 volts), producing 1,024 possible values. To convert that digital value into the original millivolt analog value, we use this statement:

mVolts = round((adcValue * (vRef / 1024.0)),2)

The TMP36 sensor produces a 100mV output value at ?40? C, and a 2000mV output value at 150? C. Using the equation found in the TMP36 data sheet, we can convert the millivolt output value into a temperature in Celsius:

tempC = round(((mVolts - 500) / 10.0), 2)

If you prefer, you can convert the Celsius temperature value to Fahrenheit by using the standard conversion equation shown in the code.

After you save the program code, you’ll need to copy it into the Apache cgi-bin folder so you can run it as a web page, and then give the code permissions for the Apache web server to run it:

sudo cp gettemp.cgi /usr/lib/cgi-bin
sudo chmod +x /usr/lib/cgi-bin/gettemp.cgi

Now you’re ready to test the setup.


Plug the Pi Cobbler ribbon cable into the GPIO interface. Then open a browser and go to the following URL:


Your temperature sensor data now appears on the web page!

Final Thoughts

Now you know how to get and use analog data on your digital device. With the power of the Raspberry Pi, you don’t have to stop here. You can archive temperature data by storing the values in a MySQL database (using the Python MySQL connector), send them to an email address (using the Python SMTP methods), and so on. These features and much more are demonstrated in my book Sams Teach Yourself Python Programming for Raspberry Pi in 24 Hours, Second Edition.

  • + Share This
  • 🔖 Save To Your Account