Raspberry PI 2 – Servo Control

Using pulse modulation, the Raspberry PI can adjust a servo.
https://www.youtube.com/watch?v=ddlDgUymbxc

2015-04-22+12.06.15[1]

Here I combined the LED blinking example with the servo example.

#!/usr/bin/env python

import RPi.GPIO as GPIO
import time
led_pin = 15
led_pin2 = 16
led_pin3 = 36
led_pin4 = 37

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)

GPIO.setup(led_pin, GPIO.OUT)
GPIO.setup(led_pin2, GPIO.OUT)
GPIO.setup(led_pin3, GPIO.OUT)
GPIO.setup(led_pin4, GPIO.OUT)

GPIO.setup(22, GPIO.OUT)

p = GPIO.PWM(22, 50)
p.start(7.5);

try:
 while True:

  GPIO.output(led_pin, GPIO.HIGH)
  GPIO.output(led_pin2, GPIO.HIGH)
  GPIO.output(led_pin3, GPIO.HIGH)
  GPIO.output(led_pin4, GPIO.HIGH)
  p.ChangeDutyCycle(7.5)
  time.sleep(1)

  GPIO.output(led_pin, GPIO.LOW)
  GPIO.output(led_pin2, GPIO.LOW)
  GPIO.output(led_pin3, GPIO.HIGH)
  GPIO.output(led_pin4, GPIO.HIGH)
  p.ChangeDutyCycle(12.5)
  time.sleep(1)

  GPIO.output(led_pin, GPIO.HIGH)
  GPIO.output(led_pin2, GPIO.HIGH)
  GPIO.output(led_pin3, GPIO.HIGH)
  GPIO.output(led_pin4, GPIO.HIGH)
  p.ChangeDutyCycle(7.5)
  time.sleep(1)

  GPIO.output(led_pin, GPIO.HIGH)
  GPIO.output(led_pin2, GPIO.HIGH)
  GPIO.output(led_pin3, GPIO.LOW)
  GPIO.output(led_pin4, GPIO.LOW)
  p.ChangeDutyCycle(2.5)
  time.sleep(1)

except KeyboardInterrupt:

 print '\r\nBack to neutral...'
 p.ChangeDutyCycle(7.5)
 time.sleep(1)

 print '\r\nProgam complete.'
 GPIO.cleanup();