-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIServo.cpp
48 lines (37 loc) · 1.05 KB
/
IServo.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include "IServo.h"
IServo::IServo(int _servo)
{
servo = _servo;
}
//给一个脉冲
void IServo::pulse(int _pulsewidth)
{
digitalWrite(servo,HIGH);
delayMicroseconds(_pulsewidth);
digitalWrite(servo,LOW);
delayMicroseconds(20000-_pulsewidth);
}
//包含初始舵机复位(从90°开始)
void IServo::init()
{
pinMode(servo,OUTPUT);
digitalWrite(servo,LOW);
//初始复位
angle = 90;
int pulsewidth = (90.0*(max_PWM-min_PWM)/angle_range)+min_PWM;
//注意Arduino Uno是8位机,int是2字节,中间变量可能超出范围!
for(int i=0;i<60;i++) pulse(pulsewidth);
}
//角度范围[0,angle_range],执行成功返回1
int IServo::rotating(float _des_angle)
{
if(angle<0 || angle>angle_range)
return 0;
int pulsewidth = (float(_des_angle)*(max_PWM-min_PWM)/angle_range)+min_PWM;
float delta_angle = _des_angle-angle;
delta_angle = abs(delta_angle);//Arduino的abs不能在里面执行算术运算
//给60个周期足够转180°
for(int i=0;i<delta_angle*60/angle_range;i++) pulse(pulsewidth);
angle = _des_angle;
return 1;
}