Search code examples
pythonraspberry-pimicrocontrollerpwmservo

MG 996R servo Raspberry Pi angle control


I am using an MG 996R servo connected to a Raspberry Pi and an external power supply. I am using this code:

import RPi.GPIO as GPIO
import time

servoPIN = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(servoPIN, GPIO.OUT)

p = GPIO.PWM(servoPIN, 50) # GPIO 17 for PWM with 50Hz
p.start(2.5) # Initialization
try:
  while True:
    p.ChangeDutyCycle(5)
    time.sleep(0.5)
    p.ChangeDutyCycle(7.5)
    time.sleep(0.5)
    p.ChangeDutyCycle(10)
    time.sleep(0.5)
    p.ChangeDutyCycle(12.5)
    time.sleep(0.5)
    p.ChangeDutyCycle(10)
    time.sleep(0.5)
    p.ChangeDutyCycle(7.5)
    time.sleep(0.5)
    p.ChangeDutyCycle(5)
    time.sleep(0.5)
    p.ChangeDutyCycle(2.5)
    time.sleep(0.5)
except KeyboardInterrupt:
  p.stop()
  GPIO.cleanup()

But all I get is a continuous rotation with some random slowing downs.

My aim is to be able to rotate +90 and -90 degrees.


Solution

  • Some MG996R servos have been modified for continuous rotation. This means that what you send it doesn't set the angle, but the direction and speed of rotation.

    I suspect you have one of those modified servos.

    Strangely, here's a post of somebody having about the opposite problem with the same type of servo.