您好,欢迎访问三七文档
当前位置:首页 > 行业资料 > 交通运输 > 51单片机控制舵机程序
#includereg52.h#defineStop0//宏定义,停止#defineLeft1//宏定义,左转#defineRight2//宏定义,右转sbitControlPort=P2^0;//舵机信号端口sbitKeyLeft=P1^0;//左转按键端口sbitKeyRight=P1^1;//右转按键端口sbitKeyStop=P1^2;//归位按键端口unsignedcharTimeOutCounter=0,LeftOrRight=0;//TimeOutCounter:定时器溢出计数LeftOrRight:舵机左右旋转标志voidInitialTimer(void){TMOD=0x10;//定时/计数器1工作于方式1TH1=(65535-500)/256;//0.25msTL1=(65535-500)%256;EA=1;//开总中断ET1=1;//允许定时/计数器1中断TR1=1;//启动定时/计数器1中断}voidControlLeftOrRight(void)//控制舵机函数{if(KeyStop==0){//while(!KeyStop);//使标志等于Stop(0),在中断函数中将用到LeftOrRight=Stop;}if(KeyLeft==0){//while(!KeyLeft);//使标志等于Left(1),在中断函数中将用到LeftOrRight=Left;}if(KeyRight==0){//while(!KeyRight);//使标志等于Right(2),在中断函数中将用到LeftOrRight=Right;}}voidmain(void)//主函数{InitialTimer();for(;;){ControlLeftOrRight();}}voidTimer1(void)interrupt3//定时器中断函数{TH1=(65535-500)/256;TL1=(65535-500)%256;TimeOutCounter++;switch(LeftOrRight){case0://为0时,舵机归位,脉宽1.5ms{if(TimeOutCounter=6){ControlPort=1;}else{ControlPort=0;}break;}case1://为1时,舵机左转,脉宽1ms(理论值),实际可以调试得出{if(TimeOutCounter=2){ControlPort=1;}else{ControlPort=0;}break;}case2://为2时,舵机右转,脉宽2ms(理论值),实际可以调试得出{if(TimeOutCounter=10){ControlPort=1;}else{ControlPort=0;}break;}default:break;}if(TimeOutCounter==80)//周期20ms(理论值),比较可靠,最好不要修改{TimeOutCounter=0;}}
本文标题:51单片机控制舵机程序
链接地址:https://www.777doc.com/doc-1357648 .html