用Pic单片机控制8路MG995舵机(servo motor)的实现方法
下面就用这种方法进行编程。
#include
unsigned char servo_angle_H[8];
unsigned char servo_angle_L[8];
unsigned char compensate_TL;
unsigned char compensate_TH;
unsigned char p;
void set_servo (unsigned char angle0,unsigned char angle1,
unsigned char angle2,unsigned char angle3,
unsigned char angle4,unsigned char angle5,
unsigned char angle6,unsigned char angle7)
{
unsigned int temp,temp0,value[8];
unsigned char i;
for(i=0;i<8;i++){
servo_angle_H[i]=64468/256;
servo_angle_L[i]=64468%256;
}
compensate_TL=50268%256;
compensate_TH=50268/256;
temp = angle0+angle1+angle2+angle3+angle4+angle5+angle6+angle7;
value[0]=65068-(100*angle0)/9;
value[1]=65068-(100*angle1)/9;
value[2]=65068-(100*angle2)/9;
value[3]=65068-(100*angle3)/9;
value[4]=65068-(100*angle4)/9;
value[5]=65068-(100*angle5)/9;
value[6]=65068-(100*angle6)/9;
value[7]=65068-(100*angle7)/9;
for(i=0;i<8;i++){
servo_angle_H[i]=value[i]/256;
servo_angle_L[i]=value[i]%256;
}
temp0=46068+(100*temp)/9;
compensate_TL=temp0%256;
compensate_TH=temp0/256;
}
//主程序***********************************************************************
void main(void)
{unsigned int a;unsigned int b;
INTCON=0;
GIE=1;//;打开总中断
PEIE=1;//;打开外部中断使能位
TMR1IE=1;//;打开TMR1中断
TRISD=0X00;
PORTD= 0X00;//脉冲波形起始状态
T1CON=0x01;//设置TMR1的控制字
TMR1IF=0;
unsigned char i;
set_servo (13,34,56,87,80,123,156,13);
while(1){;}
}
//中断服务程序*************************************************************
voidinterrupttimer1(void)
{
TMR1IF=~TMR1IF;
switch(p){
case 0:TMR1L=servo_angle_L[p];TMR1H=servo_angle_H[p];PORTD=0X01;
break;
case 1:TMR1L=servo_angle_L[p];TMR1H=servo_angle_H[p];PORTD=0B00000010;
break;
case 2:TMR1L=servo_angle_L[p];TMR1H=servo_angle_H[p];PORTD=0B00000100;
break;
case 3:TMR1L=servo_angle_L[p];TMR1H=servo_angle_H[p];PORTD=0B00001000;
break;
case 4:TMR1L=servo_angle_L[p];TMR1H=servo_angle_H[p];PORTD=0B00010000;
break;
case 5:TMR1L=servo_angle_L[p];TMR1H=servo_angle_H[p];PORTD=0B00100000;
break;
case 6:TMR1L=servo_angle_L[p];TMR1H=servo_angle_H[p];PORTD=0B01000000;
break;
case 7:TMR1L=servo_angle_L[p];TMR1H=servo_angle_H[p];PORTD=0B10000000;
break;
default:TMR1L=compensate_TL;TMR1H=compensate_TH;PORTD=0B00000000;p=0;
break;
}
p++;
}
评论