Analog Sensors without Analog Inputs on the Raspberry Pi

The Raspberry Pi does not have any analog inputs, but that does not mean that you can't use some types of analog sensors. Using a couple of resistors and a capacitor, you can use a “step response” method to measure resistance. Which is just great if you are using a pot, photoresistor or thermistor.

The Recipe that follows is taken from my new book “The Raspberry Pi Cookbook”. This way of using sensors was inspired by this work from Adafruit.

To make this recipe, you will need:

• Breadboard and jumper wires
• 10kΩ trimpot 
• Two 1kΩ resistors 
• 220 nF capacitor 
Open an editor (nano or IDLE) and paste in the following code. As with all the program
examples in this book, you can also download the program from the Code section of
Analog Sensors without Analog Inputs on the Raspberry Pi the Raspberry Pi Cookbook website, where it is called
import RPi.GPIO as GPIO
import time
a_pin = 18
b_pin = 23
def discharge():
  GPIO.setup(a_pin, GPIO.IN)
  GPIO.setup(b_pin, GPIO.OUT)
  GPIO.output(b_pin, False)
def charge_time():
  GPIO.setup(b_pin, GPIO.IN)
  GPIO.setup(a_pin, GPIO.OUT)
  count = 0
  GPIO.output(a_pin, True)
  while not GPIO.input(b_pin):
  count = count + 1
  return count
def analog_read():
  return charge_time()
  while True:
When you run the program, you should see some output like this:
$ sudo python
The reading will vary between about 10 and about 170 as you rotate the knob of the
Analog Sensors without Analog Inputs on the Raspberry Pi.jpg
To explain how this program works, I first need to explain how the step response technique
 can be used to measure the resistance of the variable resistor.
This way of doing things is called step response because it works by seeing how the circuit
responds from the step change when an output is switched from low to high.
You can think of a capacitor as a tank of electricity, and as it fills with charge, the voltage
across it increases. You can’t measure that voltage directly, because the Raspberry Pi
doesn’t have an ADC converter. However, you can time how long it takes for the capacitor
to fill with charge to the extent that it gets above the 1.65V or so that constitutes
a high digital input. The speed at which the capacitor fills with charge depends on the
value of the variable resistor (Rt). The lower the resistance, the faster the capacitor fills
with charge and the voltage rises.

About The Author

Ibrar Ayyub

I am an experienced technical writer with a Master's degree in computer science from BZU Multan University. I have written for various industries, mainly home automation, and engineering. I have a clear and simple writing style and am skilled in using infographics and diagrams. I am a great researcher and is able to present information in a well-organized and logical manner.

Follow Us:
Scroll to Top