Creating software PWM for multiple servos


Most servos need a signal refresh rate of 50Hz (20ms period). The pulse or the on time which determines the servo position is around 1-2ms and is shown in the image below.



Software PWM is created using an interrupt and Timer1 module to output the signals though standard IO pins on the microcontroller. Using this method enables us to create multiple PWM servo signals with varying pulse lengths and refresh rate of 50Hz.

Calculations for PWM

  1. Determine internal instruction clock cycle: (20 MHz Xtal is used in this project)
    • Internal Instruction cycle  = 1 / [Processor frequency/4] 
    • = 1 / [20E6/4] = 200E-9 
  2. Determine time to increment counter:
    • Timer 1 is a 16bit timer: 216 = 65536
    • Time to increment counter = Instruction cycle x 216 = 200E-9 x 65536 = 0.0131072s or 13.1072ms
    • So it takes 13.1072ms for Timer1 to count from 0 to 65536.
  3. Select a suitable prescaler:
    • 13.1072ms is still too fast. We need to use a prescaler to get our period to at least 20ms for the servo refresh rate of 50Hz. A prescaler value of 1:2 will give us:
      • 13.1072 x 10-3 x 2 = 26.2144ms
  4.  Now we have an overflow period of 26.2144ms. We need to calculate a starting value for Timer1 which would shorten the overflow period to 20ms. 
    • First we need to calculate what count value takes 20ms to count up to from 0.
      • Overflow period  of 26.2144ms = 200ns x 65536 x 2
    • Then to get 20ms we need to change the above equation: 20ms = 200ns x (count value) x 2
      • Rearranged equation: count value = 20ms / [200ns x 2] = 50000
    • So it takes 20ms for Timer1 to count from 0 to 50000. To get the Timer1 starting value we simply subtract 50000 from 65536.
      • 65536-50000 = 15536
    • We write this value to the Timer1 register so that Timer 1 starts at 15536 and takes 20ms to overflow giving us our 50Hz refresh rate.
  5. Calculating position values. To calculate the 1-2ms pulse times for position values up to 180 degree movement:
    • servo 180 degrees:  2ms / [200ns x 2] = 5000
    • servo 90 degrees :  1.5ms / [200ns x 2] = 3750
    • servo 0 degrees :  1ms / [200ns x 2] = 2500

The video below has a great explanation on controlling multiple servos using software PWM on standard IO pins as well as some great tips on reducing servo jitter. He demonstrates coding for AVR ATMEGA32 chip.



Source: Patrick Hood Daniel Youtube.com

Comments

Popular posts from this blog

Gesture Controlled Robot Arm Using PIC16F877A

HC-SR04 Ultrasonic Sensor code for Distance Measurement