資源簡介
51單片機:4路舵機控制
編寫語言:C
運行情況:完美運行

代碼片段和文件信息
#include
sbit?xh1=P1^0;
sbit?xh2=P1^1;
sbit?xh3=P1^2; ?//四個舵機的信號口
sbit?xh4=P1^3;
sbit?left1=P2^0;
sbit?right1=P2^1;
sbit?left2=P2^2;
sbit?right2=P2^3; ?//一個舵機兩個按鍵控制
sbit?left3=P2^4;
sbit?right3=P2^5;
sbit?left4=P2^6;
sbit?right4=P2^7;
unsigned?char?pwm1=10;
unsigned?char?pwm2=10; ??//每個舵機由一個pwm控制
unsigned?char?pwm3=10;
unsigned?char?pwm4=10;
unsigned?char?n=0; ??
void?delay1ms(unsigned?int?i)
{
??unsigned?char?j;
??while(i--)
??{
????for(j=0;j<115;j++) ??//一ms基準延時程序
{
??;
}
??
??}
}
void?key()
{
??EA=1;
??ET0=1;
??TMOD=0x01; ?//定時,中斷的開關
??TH0=(65536-92)/256;
??TL0=(65536-92)%256;
??TR0=1;
}
void?no1()? ???//第一個舵機控制
{ ??
??if(left1==0)
??{
????delay1ms(15);??//消抖
if(left1==0)
{ ??
??pwm1=pwm1+1; ?//左轉
??n=0;
??if(pwm1==18) //限制其轉動角度,防止角度轉過損壞舵機
?????????pwm1=17;
}
??}
??while(left1==0);??//松手檢測
??if(right1==0)
??{
????delay1ms(15); ?//消抖
if(right1==0)
{
??pwm1=pwm1-1; //右轉
??n=0;
??if(pwm1==3) //限制角度!
?????????pwm1=4;
}
??}
??while(right1==0); ??//松手檢測
}
/*******************************************************/
void?no2()? ??//第二個舵機控制
{
??if(left2==0)
??{
????delay1ms(15);
if(left2==0)
{
??pwm2=pwm2+2;
??if(pwm2>18)
?????????pwm2=17;
?n=0;
}
??} ???//原理同上
??while(left2==0);
??if(right2==0)
??{
????delay1ms(15);
if(right2==0)
{
??pwm2=pwm2-2;
??
??if(pwm2<5)
?????????pwm2=4;
?n=0;
}
??}
??while(right2==0);
}
/******************************************************/
??void?no3()? ??//第三個舵機控制
{
??if(left3==0)
??{
????delay1ms(15);
if(left3==0)
{
??pwm3=pwm3+1;
??n=0;
??if(pwm3==18)
?????????pwm3=17;
}
??}
??while(left3==0);
??if(right3==0) //原理同上
??{
????delay1ms(15);
if(right3==0)
{
??pwm3=pwm3-1;
??n=0;
??if(pwm3==3)
?????????pwm3=4;
}
??}
??while(right3==0);
}
/********************************************************/
void?no4()? ???//第四個舵機控制
{
??if(left4==0)
??{
????delay1ms(15);
if(left4==0)
{
??pwm4=pwm4+2;
??if(pwm4>18)
?????????pwm4=17;
?n=0;
}
??}
??while(left4==0);
??if(right4==0) ???//原理同上
??{
????delay1ms(15);
if(right4==0)
{
??pwm4=pwm4-2;
??
??if(pwm4<5)
?????????pwm4=4;
?n=0;
}
??}
??while(right4==0);
}
//*****************************************************//
void?main() ???//主函數
{
??key();
??while(1)
??{
??? ??no1();
??no2();
??????no3();
??????no4();
??}
}
void?timer0(void)?interrupt?1 ???//中斷服務函數
{
??n++;
??
??if(n ????xh1=1; ??//no1
??else
????xh1=0;
?/******************/
??if(n ????xh2=1;
??else ??//no2
????xh2=0;
?/*******************/
if(n ????xh3=1;
??else
????xh3=0; ???//no3
?/*******************/
??if(n ????xh4=1;
??else ???//no4
????xh4=0;
?/********************/
??if(n==200)
?????n=0;
??TH0=(65536-92)/256;
??TL0=(65536-92)%256;
}
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件????????3088??2017-05-16?17:23??51-4路舵機控制.c
評論
共有 條評論