In the previous example, I use ATMega32 to rotate a servo motor without the hardware PWM.
ATMega32 controls a servo motor with three angles rotation. |
In this example, I use the popular PIC16F84A microcontroller to rotate the angle of servo motor via two button. These two buttons could rotate between -90 degree to _90 degree with about 5 degree per step.
A rotating servo motor in simulator. The PIC16F84A CPU clocks at 20MHz giving more precise timing. |
Since PIC16F84A doesn't have any hardware PWM module. I use a built-in delay function of CCS PICC compiler. Any non negative variable could make the delay.
RB0 is used to increase the rotating angle. While RB1 is used to decrease the rotating angle.
To make the servo rotate, we make a high pulse ranging from 1500 uS to 2000 us, within a 20 ms period.
source code could be download here:
#include<16F84A.h>
#fuses HS
//for delay function
#use delay(clock=20M)
void main(){
int16 highTime=0;
unsigned int16 _H=0,_L=0;
output_b(0x00);
//make RB0.1 inputs
set_tris_b(0x03);
//turn on port b input pullups
port_b_pullups(true);
while(1){
//increase the angle
if(input(pin_B0)==0){
delay_ms(5);
if(_H<2000)
highTime+=50;
//making high pulse
_H=1000+(highTime/18);
//calculate the total 20 ms period
_L=20000-_H;
//start the rotation
output_high(PIN_B2);
delay_us(_H);
output_low(PIN_B2);
delay_us(_L);
}
//decrease the angle
if(input(pin_B1)==0){
delay_ms(5);
if(_H>1000)
highTime-=50;
//making high pulse
_H=1000+(highTime/18);
//calculate the total 20 ms period
_L=20000-_H;
//start the rotation
output_high(PIN_B2);
delay_us(_H);
output_low(PIN_B2);
delay_us(_L);
}
}
}
No comments:
Post a Comment