Home > Articles

Using Analog Sensors with the Raspberry Pi

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:

http://192.168.1.77

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:

#!/usr/bin/python3
import spidev
spi = SpiDev()
spi.open(0,0)
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('')
print('<html>')
print('<head>')
print('<title>Temperature Sensor</title>')
print('</head>')
print('<body>')
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')
print('</body>')
print('</html>')
spi.close()

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.

Testing

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

http://localhost/cgi-bin/gettemp.cgi

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020