單片機控制舵機的C51程序
用stc89c51單片機來控制舵機的程序,測試成功,僅供大家參考.
#include "reg52.h"unsigned char count; //0.5ms次數(shù)標(biāo)識sbit pwm =P3^0 ; //PWM信號輸出sbit jia =P3^7; //角度增加按鍵檢測IO口sbit jan =P3^6; //角度減少按鍵檢測IO口unsigned char jd; //角度標(biāo)識void delay(unsigned char i)//延時{unsigned char j,k;for(j=i;j>0;j--)for(k=125;k>0;k--);}void Time0_Init() //定時器初始化{TMOD = 0x01; //定時器0工作在方式1 IE = 0x82;TH0 = 0xfe;TL0 = 0x33; //11.0592MZ晶振,0.5msTR0=1; //定時器開始}void Time0_Int() interrupt 1 //中斷程序{TH0 = 0xfe; //重新賦值TL0 = 0x33;if(count jd) //判斷0.5ms次數(shù)是否小于角度標(biāo)識pwm=1; //確實小于,PWM輸出高電平elsepwm=0; //大于則輸出低電平count=(count+1); //0.5ms次數(shù)加1count=count%40; //次數(shù)始終保持為40 即保持周期為20ms}void keyscan() //按鍵掃描{ if(jia==0) //角度增加按鍵是否按下{delay(10); //按下延時,消抖if(jia==0) //確實按下{jd++; //角度標(biāo)識加1count=0; //按鍵按下 則20ms周期從新開始if(jd==6)jd=5; //已經(jīng)是180度,則保持while(jia==0); //等待按鍵放開}}if(jan==0) //角度減小按鍵是否按下{delay(10);if(jan==0){jd--; //角度標(biāo)識減1count=0;if(jd==0)jd=1; //已經(jīng)是0度,則保持while(jan==0);}}}void main(){jd=1;count=0; Time0_Init(); while(1){keyscan(); //按鍵掃描}}
評論