51单片机mg995舵机代码
时间: 2023-07-02 21:18:41 浏览: 104
以下是51单片机控制MG995舵机的基本代码:
```
#include <reg51.h>
#define uchar unsigned char
#define uint unsigned int
sbit PWM = P1^1; //P1.1口定义为PWM输出口
void DelayMs(uint ms)
{
uint i, j;
for(i=0; i<ms; i++)
for(j=0; j<120; j++); //在12M晶振下延时1ms
}
void main()
{
uchar i;
while(1)
{
for(i=0; i<=180; i++) //从0度到180度转动
{
PWM = 1; //PWM输出高电平
DelayMs(i+600); //输出脉宽
PWM = 0; //PWM输出低电平
DelayMs(20-i); //输出周期-输出脉宽
}
for(i=180; i>=0; i--) //从180度到0度反向转动
{
PWM = 1; //PWM输出高电平
DelayMs(i+600); //输出脉宽
PWM = 0; //PWM输出低电平
DelayMs(20-i); //输出周期-输出脉宽
}
}
}
```
需要注意的是,该代码仅适用于晶振频率为12MHz的单片机。如果使用其他频率的晶振,需要相应地修改延时函数中的参数。此外,MG995舵机的工作电压为4.8V至7.2V,需要注意电源的选择。