-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathservo_control.ino
72 lines (60 loc) · 1.57 KB
/
servo_control.ino
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <Servo.h>
#include <ros.h>
#include "keyboard/Key.h"
#include <std_msgs/Float32MultiArray.h>
#include <std_msgs/Float32.h>
Servo myservo;
ros::NodeHandle nh;
int pos = 105; // variable to store the servo position
int forwardPos = 105 // position when wheel is looking forward
bool keyR = 0;
bool keyL = 0;
unsigned long lastTime = 0;
void keydown_cb(const keyboard::Key& key_msg) {
if(key_msg.code == 100) { // Right
keyR = 1;
}
else if(key_msg.code == 97) { // Left
keyL = 1;
}
}
void keyup_cb(const keyboard::Key& key_msg) {
if(key_msg.code == 100) { // Right
keyR = 0;
pos = forwardPos;
}
else if(key_msg.code == 97) { // Left
keyL = 0;
pos = forwardPos;
}
}
void servDir_cb (const std_msgs::Float32& serv_msg) {
pos = serv_msg.data; // Set the position.
lastTime = millis();
}
ros::Subscriber<keyboard::Key> keydown_sub ("keyboard/keydown", keydown_cb);
ros::Subscriber<keyboard::Key> keyup_sub ("keyboard/keyup", keyup_cb);
ros::Subscriber<std_msgs::Float32> serv_sub ("/serv_dir", servDir_cb);
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
nh.initNode();
nh.subscribe(keydown_sub);
nh.subscribe(keyup_sub);
nh.subscribe(serv_sub);
}
void loop() {
if (millis() - lastTime > 1000) {
pos = forwardPos; // if there is no action for 1 sec, go to forward position
}
while ((keyR && pos < 160)) { // Right
pos += 2;
delay(1);
}
while (keyL && pos > 40) { // Left
pos -= 2;
delay(1);
}
myservo.write(pos);
nh.spinOnce();
delay(1);
}