Controlling multiple servos with potentiometers with Raspberry Pi 4

30 Views Asked by At

I am having some trouble with some code that I have written for the Raspberry Pi to control a servo using a potentiometer. I have found many tutorials, but I cannot quite get the following to work:

#Setup
import RPi.GPIO as GPIO
from time import sleep
import busio
import digitalio
import board
import adafruit_mcp3xxx.mcp3008 as MCP
from adafruit_mcp3xxx.analog_in import AnalogIn
spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)
cs = digitalio.DigitalInOut(board.D5)
mcp = MCP.MCP3008(spi, cs)

# Potientiometer Channel Setups
BasePot = AnalogIn(mcp, MCP.P0)
ShoulderPot = AnalogIn(mcp, MCP.P1)
Elbow = AnalogIn(mcp, MCP.P2)

# Servo GPIO Setup


#Base Servo at GPIO 2
GPIO.setup(2, GPIO.OUT)
BaseServo = GPIO.PWM(2, 50)
BaseServo.start(0)

#Shoulder Servo at GPIO 3
GPIO.setup(3, GPIO.OUT)
ShoulderServo = GPIO.PWM(3, 50)
ShoulderServo.start(0)

#Elbow Servo at GPIO 4
GPIO.setup(4, GPIO.OUT)
ElbowServo = GPIO.PWM(4, 50)
ElbowServo.start(0)

def setBaseAngle(angle):
    duty = angle / 18 + 2
    GPIO.output(2, True)
    BaseServo.ChangeDutyCycle(duty)
    sleep(.01)
    
    BaseServo.ChangeDutyCycle(duty)


while True:
    value=BasePot.value   #read Potentiometer value
    print(value)
    degree=value*180/65500 #convert Potentiometer value to a servo position angle
    setBaseAngle(degree)         #rotate servo to that angle     
    sleep(0.001)


With the above, I can get a reading from the potentiometer, but I can't get it to actually move the servo. I am thinking that the trouble is somewhere in the "setBaseAngle" function, but I have tried a lot to no avail. Any suggestions to fix it? Thanks in advance!

I can control a servo directly in python, and read potentiometer values, but I cant figure out hoe to correlate the two. Ive seen many tutorials online, but the code that I've written just won't work, and I'm not sure why.

0

There are 0 best solutions below