-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathHCSR04.device.nut
More file actions
59 lines (47 loc) · 1.47 KB
/
HCSR04.device.nut
File metadata and controls
59 lines (47 loc) · 1.47 KB
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
// Ultrasonic Range Sensor HC-SR04
// https://docs.google.com/document/d/1Y-yZnNhMYy7rwhAgyL_pfa39RsB-x2qR4vP8saG73rE/edit
// Ultrasonic Range Sensor HC-SR04
// https://docs.google.com/document/d/1Y-yZnNhMYy7rwhAgyL_pfa39RsB-x2qR4vP8saG73rE/edit
class HCSR04 {
// consts
static TO = 500; // timeout in ms
// pins
_trig = null;
_echo = null;
// aliased methods
_tw = null;
_er = null;
_hu = null;
_hm = null;
// vars
_es = null; // echo start time
_ee = null; // echo end time
constructor(trig, echo) {
_trig = trig;
_echo = echo;
_hu = hardware.micros.bindenv(hardware);
_hm = hardware.millis.bindenv(hardware);
_tw = _trig.write.bindenv(_trig);
_er = _trig.read.bindenv(_echo);
}
function read_cm() {
local st = _hm(); // start time for timeout
// Quickly pulse the trig pin
_tw(0); _tw(1); _tw(0);
// Wait for the rising edge on echo
while (_er() == 0 && (_hm() - st) < TO);
_es = _hu();
// Time to the falling edge on echo
while (_er() == 1 && (_hm() - st) < TO);
_ee = _hu();
//if ((_hm() - st) >= TO) return -1;
return (_ee - _es)/58.0;
}
}
// Ex Usage
// trig <- hardware.pin8;
// echo <- hardware.pin9;
// trig.configure(DIGITAL_OUT,0);
// echo.configure(DIGITAL_IN);
// range <- HCSR04(trig, echo);
// server.log(range.read_cm()+" cm"");