-
Notifications
You must be signed in to change notification settings - Fork 19
/
orbit_planet.c
95 lines (84 loc) · 1.97 KB
/
orbit_planet.c
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <kilolib.h>
// Constants for orbit control.
#define TOO_CLOSE_DISTANCE 40
#define DESIRED_DISTANCE 60
// Constants for motion handling function.
#define STOP 0
#define FORWARD 1
#define LEFT 2
#define RIGHT 3
int current_motion = STOP;
int distance;
int new_message = 0;
// Function to handle motion.
void set_motion(int new_motion)
{
// Only take an action if the motion is being changed.
if (current_motion != new_motion)
{
current_motion = new_motion;
if (current_motion == STOP)
{
set_motors(0, 0);
}
else if (current_motion == FORWARD)
{
spinup_motors();
set_motors(kilo_straight_left, kilo_straight_right);
}
else if (current_motion == LEFT)
{
spinup_motors();
set_motors(kilo_turn_left, 0);
}
else if (current_motion == RIGHT)
{
spinup_motors();
set_motors(0, kilo_turn_right);
}
}
}
void setup()
{
}
void loop()
{
// Update the motion whenever a message is received.
if (new_message == 1)
{
new_message = 0;
// If too close, move forward to get back into orbit.
if (distance < TOO_CLOSE_DISTANCE)
{
set_color(RGB(0, 1, 0));
set_motion(FORWARD);
}
// If not too close, turn left or right depending on distance,
// to maintain orbit.
else
{
if (distance < DESIRED_DISTANCE)
{
set_color(RGB(1, 0, 0));
set_motion(LEFT);
}
else
{
set_color(RGB(0, 0, 1));
set_motion(RIGHT);
}
}
}
}
void message_rx(message_t *m, distance_measurement_t *d)
{
new_message = 1;
distance = estimate_distance(d);
}
int main()
{
kilo_init();
kilo_message_rx = message_rx;
kilo_start(setup, loop);
return 0;
}