本帖最后由 一只小学生 于 2021-6-14 14:13 编辑  
 
舵机一个周期是20ms 
一个周期中有0.5~2.5ms高电平 
  
所以我们可以控制高电平的时间来控制舵机 
 
程序用keil编译 
  
hex文件在“ABC”里 用STC-isp烧写进51单片机 
			
			
			- #include <STC12C5A60S2.h>
 - 
 - /*******************************************************************************************************************************************************
 - 编写人:一只小学生
 - 舵机控制器:舵机接P0.0    按键1接P2.0     按键2接P2.1     12M晶振
 - *******************************************************************************************************************************************************/
 - 
 - sbit dj=P0^0;
 - 
 - void Dela (unsigned int a){                  //0.1ms延迟函数
 -         unsigned int i;
 -         while( --a != 0){
 -                 for(i = 0; i < 60; i++);
 -         }
 - }
 - 
 - void Delay (unsigned int ad){             //1ms延迟函数
 -         unsigned int i;
 -         while( --ad != 0){
 -                 for(i = 0; i < 600; i++);
 -         }
 - }
 - 
 - void DJ(unsigned int q){               //舵机函数(需配合0.1ms延迟函数)
 -       dj = 1;
 -       Dela (q);
 -           dj = 0;
 -           Dela (200-q);
 -           
 - }
 - 
 - void main (void){
 -   unsigned int a = 15;
 -   P2M0 = 0xff;
 -   P2M1 = 0xff;
 -   while(1){
 -     DJ (a);
 -     if (P2 ^ 1 == 1){
 -       Delay (20);
 -       if (P2 ^ 1 == 1){
 -                   if (a !=5){
 -                     if(a != 25){
 -             a--;
 -                          }
 -                   }
 -       }
 -     }
 -     if (P2 ^ 0 == 1){
 -       Delay (20);
 -       if (P2 ^ 0 == 1){
 -         if (a != 5){
 -                     if(a != 25){
 -             a++;
 -                          }
 -                   }
 -       }
 -     }
 -     if (a == 5){
 -            a++;
 -          }
 -          if (a == 25){
 -            a--;
 -          }
 -   }
 - }
 
  复制代码
  51单片机舵机.zip 
 |