Note

Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.

Why Join?

  • Expert Support: Solve post-sale issues and technical challenges with help from our community and team.

  • Learn & Share: Exchange tips and tutorials to enhance your skills.

  • Exclusive Previews: Get early access to new product announcements and sneak peeks.

  • Special Discounts: Enjoy exclusive discounts on our newest products.

  • Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.

👉 Ready to explore and create with us? Click [here] and join today!

2.1.4 Potentiometer(MCP3008)

Note

_images/mcp3008_and_adc0834.jpg

Depending on your kit version, please identify whether you have ADC0834 or MCP3008 and proceed with the matching section.

Introduction

The ADC function is used to convert analog signals into digital values. In this experiment, we use the MCP3008 ADC chip to perform this conversion. A potentiometer is used to generate a variable voltage, which changes the physical quantity. The MCP3008 then converts this analog voltage into a digital value that can be read and processed by the Raspberry Pi.

Required Components

In this project, we need the following components.

_images/list2_2.1.4_potentiometer.png

Principle

MCP3008

MCP3008 is a 10-bit successive approximation analog-to-digital converter (ADC) with 8 input channels and an SPI (Serial Peripheral Interface) communication protocol. It is capable of interfacing with a microcontroller to convert analog input signals into digital data for further processing.

_images/MCP3008.jpg

Sequence of Operation

A conversion on the MCP3008 begins by setting the CS (chip select) pin low, which activates communication with the device. The microcontroller then sends a 3-byte control stream via the SPI interface to specify the configuration and select the input channel.

The first byte sent contains the start bit and the single/differential selection bit. The next bits indicate which of the 8 channels (CH0–CH7) to read from. Data is shifted into the device on each rising edge of the SPI clock (SCLK), and the conversion result is returned simultaneously.

A short delay is included internally for the selected input channel to settle before conversion begins. The MCP3008 then performs a 10-bit analog-to-digital conversion using a sample-and-hold circuit and a successive approximation register (SAR) comparator.

The conversion result is transmitted back to the microcontroller through the MISO (Master In Slave Out) line. The most significant bit (MSB) of the 10-bit result is sent first, followed by the remaining bits. The microcontroller reads the result over the SPI bus during this time.

After the full 10-bit digital value is shifted out, the MCP3008 completes the cycle and waits for the next command.

_images/MCP3008detail.png

Potentiometer

Potentiometer is also a resistance component with 3 terminals and its resistance value can be adjusted according to some regular variation. Potentiometer usually consists of resistor and movable brush. When the brush is moving along the resistor, there is a certain resistance or voltage output depending on the displacement.

_images/image310.png

The functions of the potentiometer in the circuit are as follows:

  1. Serving as a voltage divider

Potentiometer is a continuously adjustable resistor. When you adjust the shaft or sliding handle of the potentiometer, the movable contact will slide on the resistor. At this point, a voltage can be output depending on the voltage applied onto the potentiometer and the angle the movable arm has rotated to or the distance it moves.

Schematic Diagram

T-Board Name

physical

WiringPi

BCM

SPICE0

pin24

10

8

SPIMOSI

pin19

12

10

SPIMISO

pin21

13

9

SPISCLK

pin23

14

11

GPIO22

pin15

3

22

_images/schematic_2.1.7_potentiometer_mcp3008.png

Experimental Procedures

Step 1: Build the circuit.

_images/july24_2.1.7_potentiometer_mcp3008.png

Note

Please place the chip by referring to the corresponding position depicted in the picture. Note that the grooves on the chip should be on the left when it is placed.

For C Language Users

Step 2: Open the code file.

cd ~/davinci-kit-for-raspberry-pi/c/2.1.4-2/

Step 3: Compile the code.

gcc 2.1.4_Potentiometer.c -lwiringPi

Step 4: Run.

sudo ./a.out

After the code runs, rotate the knob on the potentiometer, the intensity of LED will change accordingly.

Note

If it does not work after running, or there is an error prompt: "wiringPi.h: No such file or directory", please refer to Install and Check the WiringPi.

Code

#include <wiringPi.h>
#include <wiringPiSPI.h>
#include <stdio.h>
#include <softPwm.h>

#define SPI_CHANNEL 0  // CE0
#define SPI_SPEED   1000000  // 1MHz
#define LedPin      3

int readADC(int channel) {
    if (channel < 0 || channel > 7) return -1;

    unsigned char buffer[3];
    buffer[0] = 1;                             // Start bit
    buffer[1] = (8 + channel) << 4;            // Single-ended mode, channel
    buffer[2] = 0;

    wiringPiSPIDataRW(SPI_CHANNEL, buffer, 3);

    int value = ((buffer[1] & 3) << 8) | buffer[2];
    return value;
}

int main(void) {
    if (wiringPiSetup() == -1) {
        printf("WiringPi init failed!\n");
        return 1;
    }

    if (wiringPiSPISetup(SPI_CHANNEL, SPI_SPEED) == -1) {
        printf("SPI setup failed!\n");
        return 1;
    }

    softPwmCreate(LedPin, 0, 100);

    while (1) {
        int analogVal = readADC(0);  // CH0
        printf("ADC Value: %d\n", analogVal);

        int pwmVal = analogVal * 100 / 1023;  // Normalize to 0–100
        softPwmWrite(LedPin, pwmVal);

        delay(100);
    }

    return 0;
}

Code Explanation

#define SPI_CHANNEL 0  // CE0
#define SPI_SPEED   1000000  // 1MHz
#define LedPin      3

Define the SPI channel as CE0 (chip enable 0), set the SPI speed to 1MHz, and assign GPIO3 to the LED pin.

int readADC(int channel) {
    if (channel < 0 || channel > 7) return -1;

    unsigned char buffer[3];
    buffer[0] = 1;                             // Start bit
    buffer[1] = (8 + channel) << 4;            // Single-ended mode, channel
    buffer[2] = 0;

    wiringPiSPIDataRW(SPI_CHANNEL, buffer, 3);

    int value = ((buffer[1] & 3) << 8) | buffer[2];
    return value;
}

This function is used to read analog data from MCP3008.

  • First, it checks if the channel number is within the valid range (0 to 7).

  • It initializes a 3-byte array, where:

    • buffer[0] = 1: Start bit for MCP3008 communication.

    • buffer[1] = (8 + channel) << 4: Constructs the configuration byte for single-ended mode and selects the desired channel.

    • buffer[2] = 0: Placeholder byte to receive the result.

  • wiringPiSPIDataRW sends and receives data through the SPI channel.

  • The return value is extracted from the last two bytes using bitwise operations to obtain a 10-bit ADC result.

int main(void) {
    if (wiringPiSetup() == -1) {
        printf("WiringPi init failed!\n");
        return 1;
    }

    if (wiringPiSPISetup(SPI_CHANNEL, SPI_SPEED) == -1) {
        printf("SPI setup failed!\n");
        return 1;
    }

    softPwmCreate(LedPin, 0, 100);

    while (1) {
        int analogVal = readADC(0);  // CH0
        printf("ADC Value: %d\n", analogVal);

        int pwmVal = analogVal * 100 / 1023;  // Normalize to 0–100
        softPwmWrite(LedPin, pwmVal);

        delay(100);
    }

    return 0;
}

In the main function:

  • wiringPiSetup() initializes the WiringPi library.

  • wiringPiSPISetup() initializes SPI communication on channel 0 at 1MHz.

  • softPwmCreate() sets up software PWM on GPIO3 with an initial duty cycle of 0 and a range of 0–100.

The program enters an infinite loop where:

  • It reads the ADC value from channel 0 (connected to a potentiometer).

  • Prints the ADC value to the terminal.

  • Converts the 10-bit ADC value to a PWM duty cycle between 0 and 100.

  • Writes the PWM value to the LED, so the brightness reflects the potentiometer’s position.

delay(100) pauses for 100 milliseconds before the next read/write cycle.

For Python Users

Step 2: Set up the SPI interface and install the spidev library (see SPI Configuration for detailed instructions). If you have already completed these steps, you can skip this.

Step 3: Open the code file

cd ~/davinci-kit-for-raspberry-pi/python

Step 4: Run.

sudo python3 2.1.4-2_Potentiometer.py

After the code runs, rotate the knob on the potentiometer, the intensity of LED will change accordingly.

Warning

If there is an error prompt RuntimeError: Cannot determine SOC peripheral base address, please refer to If gpiozero doesn’t work.

Code

Note

You can Modify/Reset/Copy/Run/Stop the code below. But before that, you need to go to source code path like davinci-kit-for-raspberry-pi/python. After modifying the code, you can run it directly to see the effect.

#!/usr/bin/env python3

import spidev
import time
import RPi.GPIO as GPIO

# GPIO pin for PWM output
PWM_PIN = 22

# Setup GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(PWM_PIN, GPIO.OUT)

# Initialize PWM on GPIO22 at 1000Hz
pwm = GPIO.PWM(PWM_PIN, 1000)
pwm.start(0)  # Start with 0% duty cycle

# Initialize SPI
spi = spidev.SpiDev()
spi.open(0, 0)  # Bus 0, CE0
spi.max_speed_hz = 1000000

def read_adc(channel):
    """
    Read analog value from MCP3008
    :param channel: ADC channel (0-7)
    :return: 10-bit integer (0-1023)
    """
    if channel < 0 or channel > 7:
        return -1
    adc = spi.xfer2([1, (8 + channel) << 4, 0])
    value = ((adc[1] & 3) << 8) | adc[2]
    return value

def MAP(x, in_min, in_max, out_min, out_max):
    """
    Map a value from one range to another
    """
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

try:
    while True:
        # Read analog value from CH0
        res = read_adc(0)
        print('res = %d' % res)

        # Convert to 0–100% duty cycle
        duty_cycle = MAP(res, 0, 1023, 0, 100)

        # Update PWM duty cycle
        pwm.ChangeDutyCycle(duty_cycle)

        time.sleep(0.2)

except KeyboardInterrupt:
    pass

finally:
    pwm.stop()
    GPIO.cleanup()
    spi.close()

Code Explanation

  1. RPi.GPIO is used to generate PWM signals to control an LED. spidev is used for SPI communication with the MCP3008. time is used to add delays in the loop.

    #!/usr/bin/env python3
    
    import spidev
    import time
    import RPi.GPIO as GPIO
    
  2. Configure GPIO pin 22 for PWM output using RPi.GPIO. Set up SPI communication with the MCP3008 (Bus 0, CE0) at 1 MHz.

    PWM_PIN = 22
    
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(PWM_PIN, GPIO.OUT)
    
    pwm = GPIO.PWM(PWM_PIN, 1000)  # 1kHz frequency
    pwm.start(0)  # Start with 0% duty cycle
    
    spi = spidev.SpiDev()
    spi.open(0, 0)
    spi.max_speed_hz = 1000000
    
  3. This function reads analog data from the MCP3008 on the specified channel (0–7) using the SPI protocol. The result is a 10-bit integer ranging from 0 to 1023.

    def read_adc(channel):
        if channel < 0 or channel > 7:
            return -1
        adc = spi.xfer2([1, (8 + channel) << 4, 0])
        value = ((adc[1] & 3) << 8) | adc[2]
        return value
    
  4. This function maps a value from one numerical range to another. It’s used to scale ADC values to PWM duty cycle percentages.

    def MAP(x, in_min, in_max, out_min, out_max):
        return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
    
  5. In the main loop, the program continuously reads analog data from channel 0 of the MCP3008, maps the value to a PWM range (0–100), and sets the LED brightness accordingly. The loop updates every 0.2 seconds. If interrupted (e.g., Ctrl+C), the program stops the PWM signal and cleans up the GPIO configuration.

    try:
        while True:
            res = read_adc(0)
            print('res = %d' % res)
    
            duty_cycle = MAP(res, 0, 1023, 0, 100)
            pwm.ChangeDutyCycle(duty_cycle)
    
            time.sleep(0.2)
    
    except KeyboardInterrupt:
        pass
    
    finally:
        pwm.stop()
        GPIO.cleanup()
        spi.close()