-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathky040.ts
82 lines (77 loc) · 2.59 KB
/
ky040.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
let ri: DigitalPin;
let dv: DigitalPin;
let dsw: DigitalPin;
let lastPressed = 1;
let pressedID = 5600;
let rotatedLeftID = 5601;
let rotatedRightID = 5602;
let rotateReady = true;
enum RotationDirection {
Left = 0,
Right = 1
}
//% color=50 weight=80
//% icon="\uf01e"
namespace RotaryEncoder {
/**
* rotary encoder was rotated.
*/
//% blockId=rotary_ky_rotated_left_event
//% block="on rotated |%dir"
export function onRotateEvent(dir: RotationDirection, body: () => void): void {
serial.setBaudRate(115200);
if (dir == RotationDirection.Left) control.onEvent(rotatedLeftID, dir, body);
if (dir == RotationDirection.Right) control.onEvent(rotatedRightID, dir, body);
control.inBackground(() => {
while (true) {
const riValue = pins.digitalReadPin(ri);
const dvValue = pins.digitalReadPin(dv);
serial.writeValue("ri", riValue);
serial.writeValue("dv", dvValue);
if (riValue == 1 && dvValue == 1) rotateReady = true;
else if (rotateReady) {
if (riValue == 1 && dvValue == 0) {
serial.writeLine("Right!");
rotateReady = false;
control.raiseEvent(rotatedRightID, RotationDirection.Right);
}
else if (riValue == 0 && dvValue == 1) {
serial.writeLine("Left!")
rotateReady = false;
control.raiseEvent(rotatedLeftID, RotationDirection.Left);
}
}
basic.pause(5);
}
})
}
/**
* rotary encoder button was pressed.
*/
//% blockId=rotary_ky_pressed_event
//% block="on button pressed"
export function onPressEvent(body: () => void): void {
control.onEvent(pressedID, 0, body);
control.inBackground(() => {
while (true) {
const pressed = pins.digitalReadPin(dsw);
if (pressed != lastPressed) {
lastPressed = pressed;
if (pressed == 0) control.raiseEvent(pressedID, 0);
}
basic.pause(50);
}
})
}
/**
* initialises local variables and enables the rotary encoder.
*/
//% blockId=rotary_ky_init
//% block="connect clk %clk|dt %dt|sw %sw"
//% icon="\uf1ec"
export function init(clk: DigitalPin, dt: DigitalPin, sw: DigitalPin): void {
ri = clk;
dv = dt;
dsw = sw;
}
}