-
Notifications
You must be signed in to change notification settings - Fork 33
/
main.ts
41 lines (38 loc) · 1.18 KB
/
main.ts
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
enum PingUnit {
//% block="μs"
MicroSeconds,
//% block="cm"
Centimeters,
//% block="inches"
Inches
}
/**
* Sonar and ping utilities
*/
//% color="#2c3e50" weight=10
namespace sonar {
/**
* Send a ping and get the echo time (in microseconds) as a result
* @param trig tigger pin
* @param echo echo pin
* @param unit desired conversion unit
* @param maxCmDistance maximum distance in centimeters (default is 500)
*/
//% blockId=sonar_ping block="ping trig %trig|echo %echo|unit %unit"
export function ping(trig: DigitalPin, echo: DigitalPin, unit: PingUnit, maxCmDistance = 500): number {
// send pulse
pins.setPull(trig, PinPullMode.PullNone);
pins.digitalWritePin(trig, 0);
control.waitMicros(2);
pins.digitalWritePin(trig, 1);
control.waitMicros(10);
pins.digitalWritePin(trig, 0);
// read pulse
const d = pins.pulseIn(echo, PulseValue.High, maxCmDistance * 58);
switch (unit) {
case PingUnit.Centimeters: return Math.idiv(d, 58);
case PingUnit.Inches: return Math.idiv(d, 148);
default: return d ;
}
}
}