Takaitra.com

Controlling the MCP4151 Digital Potentiometer with the Raspberry Pi

We’re going to use the Raspberry Pi’s SPI bus to control Microchip’s MCP4151 8-bit digital potentiometer.  The MCP4151 is an 8 pin SPI device that can be used to programmatically control output voltage. The GPIO pins on the pi run at 3.3 volts meaning that we can command the pot to output between 0 and 3.3 volts. However, if we instead power the pot with 5 volts then we can control a voltage between 0 and 5 volts. Note that PWM is a possible alternative to a digital pot that doesn’t require an extra chip. However, this can add  noise to the signal that wasn’t acceptable for my project.

Microchip’s datasheet is recommended reading before starting this project.

Parts List

Step 1: Configure SPI on the Raspberry Pi

Follow the first two steps in Controlling an SPI device with the Raspberry Pi.

Step 2: Wire up the components

Being a pin-limited device, the SPI input and output on the MCP4151 shares one pin. That’s not a problem in our case since we’re only interested in writing to the device.

You’ll notice that we’re powering the pot with 5 volts despite the Raspberry Pi being a 3.3 volt device. This is fine because 1) The Pi sends commands to the pot but receives nothing back. Therefore, there is no risk of overvoltage on the Pi’s pins. And 2) The pot recognizes any SPI input over 0.7 volts as a high signal. This means the 3.3 volts from the Pi is plenty to communicate with the pot.

As you can see, the power, ground and the SPI signals take up most of the pins. The actual potentiometer terminals are pins 5, 6 and 7.

Pin Description
1 SPI chip select input
2 SPI clock input
3 SPI serial data input/output
4 Ground
5 Potentiometer terminal A
6 Potentiometer wiper terminal
7 Potentiometer terminal B
8 Positive power supply input

Step 3: Create the python script

To test out the device, we’re going to continuously loop through all the possible values for the potentiometer. This will cause the voltage at the wiper terminal grow and shrink between 0 and 5 volts. Create the following script on your Pi.

#!/usr/bin/python
import spidev
import time

spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 976000

def write_pot(input):
    msb = input >> 8
    lsb = input & 0xFF
    spi.xfer([msb, lsb])

while True:
    for i in range(0x00, 0x1FF, 1):
        write_pot(i)
        time.sleep(.005)
    for i in range(0x1FF, 0x00, -1):
        write_pot(i)
        time.sleep(.005)

Step 4: Run the script

Make the script executable and run it with the following commands.

chmod +x pot-control.py
sudo ./pot-control.py

If all goes well, you should see the LED continuously fade to full brightness then off again.

Exit mobile version