Professional Documents
Culture Documents
5 Measuring a Voltage
Problem
You want to measure an analog voltage.
Solution
The Raspberry Pi GPIO connector has only digital inputs. If you wish to measure a
voltage, you need to use a separate analog-to-digital converter (ADC).
Use the MCP3008 eight-channel ADC chip. This chip actually has eight analog
inputs, so you can connect up to eight sensors to one of these and interface to the
chip using the Raspberry Pi SPI interface.
To make this recipe, you will need:
Figure 13-11 shows the breadboard layout for using this chip. Make sure that you get
the chip facing the right way. The little notch in the package should be toward the top
of the breadboard.
spi = spidev.SpiDev()
spi.open(0, 0)
def analog_read(channel):
r = spi.xfer2([1, (8 + channel) << 4, 0])
adc_out = ((r[1]&3) << 8) + r[2]
return adc_out
while True:
reading = analog_read(0)
voltage = reading * 3.3 / 1024
print("Reading=%d\tVoltage=%f" % (reading, voltage))
time.sleep(1)
The interesting part of the program is contained in the analog_read function. This
takes a parameter that should be between 0 and 7 and specifies which of the eight
analog inputs down the lefthand side of the chip should be read.
The bit manipulation sets up a request for the appropriate channel and then sends the
bits to the MCP3008, which reads the resultant data:
$ sudo python adc_test.py
Reading=0 Voltage=0.000000
Reading=126 Voltage=0.406055
Reading=221 Voltage=0.712207
Reading=305 Voltage=0.982910
Reading=431 Voltage=1.388965
Reading=527 Voltage=1.698340
Reading=724 Voltage=2.333203
Reading=927 Voltage=2.987402
Reading=1020 Voltage=3.287109
Reading=1022 Voltage=3.293555
Discussion
The MCP3008 has 10-bit ADCs, so when you take a reading, it gives you a number
between 0 and 1023. The test program converts this into a voltage reading by multi‐
plying the reading by the voltage range (3.3V) and then dividing it by 1,024.
See Also
If you’re just interested in detecting the turning of a knob, you can use a rotary
encoder instead of a pot (Recipe 12.7).
You can also detect the position of a pot without the use of an ADC chip by using the
step response method (Recipe 13.1).
Check out the datasheet for the MCP3008.
The Explorer HAT Pro from Pimoroni also has an ADC (Recipe 9.17).
Solution
Use a pair of resistors to act as a voltage divider to reduce the voltage to a suitable
range.
To try this recipe, you will need:
Figure 13-12 shows the arrangement for this, using a breadboard. The setup will
measure the voltage of the battery.