Analog Inputs for Raspberry Pi using the MCP3008

by Jun 11, 2019Raspberry Pi

Can Raspberry Pi read Analog Input?

Of course NOT! but it CAN. The Raspberry Pi has GPIO digital pins where it can read the data either high or low ie., 0 or 1. The analog sensors such as piezoelectric sensors, thermistors, potentiometers, pressure sensors, etc give us the raw value. The analog sensors work mostly based on external factors.

The analog sensor measures the amount of pressure applied to the sensor is called the pressure sensor. The sensor which detects the vibration, the stress is proportional to the voltage in the piezoelectric sensor. Hence, a definite purpose is served for each and every sensor. the Raspberry Pi fails at this moment to read the analog sensor data since it has only digital pins.

In Arduino Uno and ESP8266, an ADC helps to convert the analog raw value to digital sensor and processes the data, but in RPi there are no digital pins present.

Analog Readings : Basic Recap

The analogread() reads the value from the specific analog pin.  The development boards used in the experiment have a 10-bit analog to digital converters. This indicates that it will meet the range of 0V and the operating voltage of  5V or 3.3V mapped into the integer values between 0 and 1023. In some boards, a 12-bit Analog to Digital Converter is used. In that case, the operating voltage is mapped into the integer values of 0 and 4095.

 It only takes about 100 microseconds to read one single analog input. Hence the maximum reading rate is 10,000 times per second.  Each analog pin is a 10-bit ADC and it can store 1024 values. For instance, if the operating voltage is 5V with a 10-bit ADC then it yields a resolution of 0.49mV per unit. This calculation reports a ratiometric value. The 5V can be assumed to be the integer value of 1023 and 0V will be the integer value of 0.

Resolution of the ADC/System voltage = ADC Reading/ Analog Voltage Measured

The System Voltage and the Resolution of the ADC are known from the development board. The ADC reading is measured from the analog devices connected to the analog pin. The analog voltage can be calculated from the ratio. For instance, if the ADC reading is 500 and the System voltage is 3.3 V which has a 10-bit ADC then the analog voltage measured is 1.61V. Alternately, the Analog Voltage can be measured using a digital multimeter.

An approach using MCP3008 ADC chip

Since RPi is a digital-only system and no Analog pins are available, an Analog-to-Digital would be required to interface and such interface would allow RPi to read the analog data fetched by sensors, which are associated with RPi.

The SPI protocol is used for communication with the analog pins. This can be done by installing the SPI package in the terminal window. Under the configuration menu, the SPI is enabled. The MCP3008 chip is an ADC and is connected to the Raspberry Pi. It has totally 16 pins, CH0- CH1 i.e, pin 1- pin 8 is the analog pins and rest of the pin from 9- 16 have a whole range of different pins. The pin 9 is called the DGND which is the digital ground, pin 10 is the chip select, pin 11 DIN is the data in and pin 12 DOUT is the data out from the Raspberry Pi, pin 13 is the clock pin, pin14 is the analog ground pin. The pin 15 is the VREF which is the analog reference voltage and the pin 16 is the VDD. Both the pins are wired to the 3.3 V.

MCP3008
Layout of MCP3008

Example:

Below is a circuit of the Raspberry Pi connected with the MCP3008, Piezoelectric sensor and a resistor of 1 Megaohm. Later the setup is fixed on the tap to detect the vibrations from the pipe. The aim is to obtain the information of whether the water is flowing inside the tap or not.

The Raspberry Pi’s GPIO pins are digital and the inputs are set to either high or low. Therefore by using Analog to Digital Converters, analog inputs can be read. The MCP3008 is placed on the breadboard with the notch on the top considering Pin 1 starts from the left of the notch. 

There are totally 8 analog pins (CH0 to CH8) available to connect to the analog input devices to read their values. At a time, eight analog sensor inputs can be connected. The VDD and the V-REF are connected to the 3.3 V while AGND and DGND pins are grounded. The CLK is wired to the SCLK. The DOUT and DIN pins are connected to MISO and MOSI respectively. Finally, the CS pin is wired to CE0.

Python Code:

# Importing modules
import spidev # To communicate with SPI devices
from time import sleep
import datetime

# To add delay
# Start SPI connection
spi = spidev.SpiDev() # Created an object
spi.open(0,0) 
# Read MCP3008 data
def analogInput(channel):
  spi.max_speed_hz = 1350000
  adc = spi.xfer2([1,(8+channel)<<4,0])
  data = ((adc[1]&3) << 8) + adc[2]
  return data



# Below function will convert data to voltage
def Volts(data):
  volts = (data * 3.3) / float(1023)
  volts = round(volts, 2) # Round off to 2 decimal places
  return volts
 
while True:
  temp_output = analogInput(1) # Reading from CH0
  temp_volts = Volts(temp_output)                                                                                          
  x = datetime.datetime.now()
  print("vibration : {} {} ({}V)".format(temp_output,x,temp_volts))
  if (temp_output > 200):
    print ("The tap is ON")
  
  sleep(5)

Creating a multiplication Skill in Alexa using python

Written By Monisha Macharla

Hi, I'm Monisha. I am a tech blogger and a hobbyist. I am eager to learn and explore tech related stuff! also, I wanted to deliver you the same as much as the simpler way with more informative content. I generally appreciate learning by doing, rather than only learning. Thank you for reading my blog! Happy learning!

RELATED POSTS

How to Setup an NGINX Server on Raspberry Pi ?

How to Setup an NGINX Server on Raspberry Pi ?

What is NGINX ? NGINX is a popular lightweight web server application you can install on the Raspberry Pi to allow it to serve web pages. In its initial release, it functioned for HTTP web serving. It is a web server that can also be used as...

FM Radio Transmitter with Raspberry Pi

FM Radio Transmitter with Raspberry Pi

We’ve all listened to the radio and sang along to the songs, atleast in the car. But have you ever found yourself switching through several channels because you couldn’t find even one song that YOU like? In this article we will learn how to build a FM radio...

Raspberry Pi Camera and its Variety

Raspberry Pi Camera and its Variety

Choosing a suitable raspberry pi camera for your projects can get really difficult. RPI camera v1, RPI camera v2, RPI NOIR camera, and the list continues. Each one has different properties and should be used according to them. They have been used in various fields and...

WiFi extender using Raspberry Pi

WiFi extender using Raspberry Pi

It is always useful to know how to use your Raspberry Pi in pet projects that are actually useful around the house. Especially when you aren’t building something new – using your dormant Raspberry Pi to build useful devices around the house is a fun idea. If you are...

Using Raspberry Pi as various Servers

Using Raspberry Pi as various Servers

Raspberry Pi is a widely popular SoC, that is versatile and easy to use for even beginners. If you are new and are unfamiliar with Pi, take a look at these articles. Regardless of the model of Raspberry Pi you have, I am sure you have discovered a plethora of projects...

SQLite Database on Raspberry Pi

Welcome to another tutorial on Raspberry Pi. In this tutorial, we will see how to use the SQLite Database on Raspberry Pi. Apart from the installation and a few basic commands, in the end, we shall look at a simple project to log sensor data into an SQLite database....

Mosquitto MQTT Broker on Raspberry Pi

This tutorial will show you what is Mosquitto MQTT Broker and how to install it on Raspberry Pi. Contents What is MQTT?Installing Mosquitto MQTT on Raspberry PiCreating an MQTT Broker on Raspberry PiSubscribe to a TopicPublish a message to a TopicSample...

Evolution of the Raspberry Pi – A Comparison

Evolution of the Raspberry Pi – A Comparison

The Raspberry Pi is an inexpensive credit card-sized micro-computer. The Raspberry Pi was originally designed as a way to teach how computers work and the rest of computer science in general. It was originally developed in the UK by a team that included Eben Upton,...

Recording audio on your Raspberry Pi

Recording audio on your Raspberry Pi

Raspberry Pi can record and playback fairly good quality audio through its USB 2.0 ports. For recording audio and playback we need two peripheral devices, a USB microphone, and a speaker. You can choose to use a USB speaker, or a speaker with a 3.5mm sound jack....

Tutorial: Dropbox with Raspberry Pi

Tutorial: Dropbox with Raspberry Pi

Many Raspberry Pi projects require synchronization of files over more than just one device. Dropbox, which is a popular file-hosting service, can be used for this with ease. Synchronizing data between different devices may seem a little tricky, especially since the...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....