-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathultrasonic.h
78 lines (68 loc) · 1.96 KB
/
ultrasonic.h
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
// Library for ultrasonic sensors - https://playground.arduino.cc/Code/NewPing
#include <NewPing.h>
NewPing *sensor;
#define MAX_DIST 400
#define SAFE_GAP 60
#define SHTWTMAX 5000
unsigned long shortwaitstart=0;
enum mstate prevmotion=FWD;
// NewPing(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE)
void _ultrasonic
(uint8_t t0, uint8_t t1, uint8_t e0, uint8_t e1) {
sensor=(NewPing*)calloc(2,sizeof(NewPing));
// Forward sensor
sensor[0]=NewPing(t0,e0,MAX_DIST);
// Reverse sensor
sensor[1]=NewPing(t1,e1,MAX_DIST);
}
// Do we have safe distance for the given sensor?
bool getsafe(uint8_t s) {
uint16_t d=sensor[s].ping_cm();
#ifdef DEBUG
Serial.print("Ultrasonic sensor (");
Serial.print(s?"REV":"FWD");
Serial.print(") :\t");
Serial.print(d);
Serial.println(" cm");
#endif
digitalWrite(LEDR2,0);
if(d==0 || d>SAFE_GAP)
return true;
digitalWrite(LEDR2,1);
return false;
}
inline bool is_waiting() {return (millis()-shortwaitstart)<SHTWTMAX;}
void ultracheck() {
if((motion==FWD && !getsafe(0)) || (motion==REV && !getsafe(1))) {
#ifdef DEBUG
Serial.print("Obstacle detected! Motion direction is ");
Serial.println((motion==FWD)?"FWD":"REV");
Serial.println("Halting for a short interval...");
#endif
prevmotion=motion;
motion=HLT;
shortwaitstart=millis();
}
else if(motion==HLT && is_waiting() && getsafe(prevmotion)) {
#ifdef DEBUG
Serial.println("Obstacle has been cleared!");
Serial.print("Restoring previous motion direction ");
Serial.println((prevmotion==FWD)?"FWD":"REV");
#endif
motion=prevmotion;
}
else if(motion==HLT && !is_waiting()) {
motion=(prevmotion==FWD)?REV:FWD;
// Unconditionally turn off pump while going backwards
if(motion==REV) {
digitalWrite(SOL_CTL,0);
t.stop(bchecker);
bchecker=t.every(BCHECK_INT,blockcheck,0);
}
#ifdef DEBUG
Serial.println("Short halting interval expired!");
Serial.print("Inverting motion direction to ");
Serial.println((motion==FWD)?"FWD":"REV");
#endif
}
}