-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
65 lines (59 loc) · 1.87 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
enum PingUnit {
//% block="μs"
MicroSeconds,
//% block="cm"
Centimeters,
//% block="inches"
Inches
}
enum I2Cadres {
adr_0X20 = 0X20,
adr_0X27 = 0X27,
adr_0X36 = 0X36,
adr_0X38 = 0X38,
}
enum pulseParam {
mm = 0.170145,
cm = 0.0170145,
}
/**
* Sonar I2C and ping utilities
*/
//% color="#2c3e50" weight=10
namespace sonar {
/**
* Send a ping and get the echo time (in microseconds) as a result
* @param adres i2c adres
* @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 I2Cadres %adres|trig %trig|echo %echo|unit %unit"
export function ping(adres: I2Cadres, trig: DigitalPin, echo: DigitalPin, unit: PingUnit, maxCmDistance = 500): number {
// send pulse
var _startPulse = Date.now();
pins.i2cWriteNumber(adres, 0, NumberFormat.Int16LE, false);
control.waitMicros(2);
pins.i2cWriteNumber(adres, 1, NumberFormat.Int16LE, false);
control.waitMicros(10);
pins.i2cWriteNumber(adres, 0, NumberFormat.Int16LE, false);
var _endPulse = Date.now();
//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 pulseLen = (_endPulse - _startPulse) * pulseParam.mm;
// const d = pins.pulseIn(echo, PulseValue.High, maxCmDistance * 58);
switch (unit) {
case PingUnit.Centimeters: return Math.idiv(pulseLen, 58);
case PingUnit.Inches: return Math.idiv(pulseLen, 148);
default: return pulseLen ;
}
}
}