舵机的控制一般需要一个20ms的时基脉冲,该脉冲的高电平部分一般为0.5ms~2.5ms范围内的角度控制脉冲部分。以180度角度舵机为例,那么对应的控制关系是这样的:
0.5ms--------------0度;
1.0ms------------45度;
1.5ms------------90度;
2.0ms-----------135度;
2.5ms-----------180度;
如下图可形象地表示脉冲与角度关系
[cpp] view
plain copy
-
#include
-
unsigned char count;
-
sbit pwm=P1^0;
-
sbit jia=P1^1;
-
sbit jan=P1^2;
-
char jd;
-
void delay(unsigned int i)
-
{
-
unsigned int j,k;
-
for(j=i;j>0;j--)
-
for(k=125;k>0;k--);
-
}
-
void Time0_init()
-
{
-
TMOD=0x01;
-
IE=0x82;
-
TH0=0xff;
-
TL0=0x19;
-
TR0=1;
-
}
-
void Time0_int() interrupt 1
-
{
-
TH0=0xff;
-
TL0=0x19;
-
if(count
-
pwm=1;
-
else
-
pwm=0;
-
count++;
-
count=count%40;
-
}
-
void keyscan()
-
{
-
if(jia==0)
-
{
-
delay(50);
-
if(jia==0)
-
{
-
jd++;
-
count=0;
-
if(jd==50)
-
jd=9;
-
while(jia==0);
-
}
-
}
-
if(jan==0)
-
{
-
delay(10);
-
if(jd==0);
-
{
-
jd--;
-
count=0;
-
if(jd==0)
-
jd=1;
-
while(jan==0);
-
}
-
}
-
}
-
-
void main()
-
{
-
jd=1;
-
count=0;
-
Time0_init();
-
while(1)
-
{
-
keyscan();
-
-
}
-
}