伺服电机的Arduino库函数

servo.attach(pin)  //连接伺服电机的信号线于控制板的引脚,9或10号引脚
servo.attach(pin, min, max)

servo: a variable of type Servo

pin: the number of the pin that the servo is attached to

min (optional): the pulse width, in microseconds, corresponding to the minimum (0-degree) angle on the servo (defaults to 544)

max (optional): the pulse width, in microseconds, corresponding to the maximum (180-degree) angle on the servo (defaults to 2400)

Description:Attach the Servo variable to a pin. Note that in Arduino 0016 and earlier, the Servo library supports only servos on only two pins: 9 and 10.

 

servo.write(angle)   ///用度控制伺服电机的角度,0-180度

angle: the value to write to the servo, from 0 to 180

Description:On a continuous rotation servo, this will set the speed of the servo (with 0 being full-speed in one direction, 180 being full speed in the other, and a value near 90 being no movement).

 

servo.writeMicroseconds(uS)   //用微妙控制伺服电机角度,1000-1500-2000微妙

uS: the value of the parameter in microseconds (int)

Description:On standard servos a parameter value of 1000 is fully counter-clockwise, 2000 is fully clockwise, and 1500 is in the middle.

 

servo.read()   //读取伺服电机的旋转角度,1-180度

Returnsthe angle of the servo, from 0 to 180 degrees.

Description:Read the current angle of the servo (the value passed to the last call to write())

 

servo.attached()  //伺服电机信号线是否连接到控制板

Returnstrue if the servo is attached to pin; false otherwise.

Description:check whether the Servo variable is attached to a pin.

 

servo.detach()  //解除伺服电机与控制板的信号连接

Description:Detach the Servo variable from its pin. If all Servo variables are detached, then pins 9 and 10 can be used for PWM output with analogWrite().

 

举例

 1 #include <Servo.h> 
 2 Servo myservo;
 3 
 4 void setup() 
 5 { 
 6   myservo.attach(9);   // attach servo to pin 9
 7 } 
 8 
 9 void loop()
10 {
11   if(myservo.attached()==true)  
12   {
13     myservo.write(90);   // set servo to mid-point
14     delay(10);
15     myservo.write(0);   // set servo to 0 degree
16     delay(10);
17     myservo.write(180);   // set servo to 180 degree
18     delay(20);
19 
20     myservo.writeMicroseconds(1500);  // set servo to mid-point
21     delay(10);
22     myservo.writeMicroseconds(1000);  // set servo to 0 degree
23     delay(10);
24     myservo.writeMicroseconds(1500);  // set servo to 180 degree
25     delay(20);
26   }
27   delay(2000);
28   myservo.detach();
29 }

运行效果

如果伺服电机连接到控制板,则先回到中点,再转到0度,再转到180度,重复循环一次,延时,解除伺服电机与控制板的连接。

原文地址:https://www.cnblogs.com/MyAutomation/p/9289825.html