方案一:使用PWM波库控制-----------------------------------
include <Servo.h> //加载文件库
int pos = 0;
Servo myservo;
void setup()
{
myservo.attach(9, 500, 2500); //修正脉冲宽度
}
void loop()
{
for (pos = 0; pos <= 180; pos += 1) { //pos+=1等价于pos=pos+1
myservo.write(pos);
delay(15);
}
for (pos = 180; pos >= 0; pos -= 1) {
myservo.write(pos);
delay(15);
}
}
方案二:使用IO高低电平模拟PWM波-----------------------------------
include <Servo.h> //加载文件库
// 引脚命名
define analogPin 5
void setup()
{
pinMode(analogPin,OUTPUT);
}
void loop()
{
steer(0);
delay(100);
steer(1);
delay(100);
}
void steer(unsigned char direction) //参数是方向;
{
if(direction >= 1) //正转
{
for(int i=0;i<=20;i++)
{
digitalWrite(5,HIGH);
delayMicroseconds(1500);//旋转180度,1.5ms;正转
digitalWrite(5,LOW);
delay(10);
}
}
else //反转
{
for(int i=0;i<=20;i++)
{
digitalWrite(5,HIGH);
delayMicroseconds(2500);//旋转180度,2.5ms;反转
digitalWrite(5,LOW);
delay(10);
}
}
}