Reading Analog Values From Digital Pins Of Raspberry Pi

Unfortunately all the 17 pins of Raspberry Pi are digital which can either output HIGH or LOW. But by using a simple circuit (poor man's A/D converter) you can measure multiple level of values using a single GPIO pin. It consists of a basic “RC” charging circuit in which a Resistor in placed series with a Capacitor. The voltage across the capacitor rises when voltage is applied across the RC network. Using the formula [t = RC ] where t is the time,R is resistance in ohms,and C is capacitance in Farads and the time taken to register a HIGH on a GPIO pin we can roughly estimate the analog value.

Algorithm:-

Step 1: Set any GPIO pin as an output and set it Low.This ensures that no charge is present in capacitor and both the terminals are at 0V.

Step 2: Now set the GPIO pin as an input.This will starts a flow of current through the resistors and through the capacitor to ground. The voltage across the capacitor starts to rise. The time taken will be proportional to the input.

Step 3: Read the value from GPIO pin and keep incrementing a counter variable until the value is LOW.

Step 4:  At some point the value from GPIO will register a HIGH. When it does return the value of the counter.

Step 5: Set the GPIO pin as an output and repeat the process as required.

Python Implementation:-


#!/usr/local/bin/python
# GPIO   : RPi.GPIO v3.1.0a

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)

# Define function to measure charge time
def RC_Analog (Pin):
  counter = 0
  # Discharge capacitor
  GPIO.setup(Pin, GPIO.OUT)
  GPIO.output(Pin, GPIO.LOW)
  time.sleep(0.1)
  GPIO.setup(Pin, GPIO.IN)
  # Count loops until voltage across capacitor reads high on GPIO
  while(GPIO.input(Pin)==GPIO.LOW):
        counter =counter+1
  return counter

# Main program loop

while True:
  print RC_Analog(4) # Measure timing using GPIO4

Example Circuit:-





Note:- The above technique will only work with sensors that act like resistors like photocells, thermistors, flex sensors, force-sensitive resistors, etc.

It cannot be used with sensors that have a pure analog output like IR distance sensors or analog accelerometers.


Source:- Adafruit

0 comments