Add TouchSensor class with events

This commit is contained in:
Michal Moskal 2017-07-08 11:35:23 +01:00
parent aeb326fac6
commit b79fd7096f

View File

@ -1,4 +1,12 @@
namespace input {
//% shim=pxt::unsafePollForChanges
function unsafePollForChanges(
periodMs: int32,
query: () => int32,
changeHandler: (prev: int32, curr: int32) => void
) { }
let analogMM: MMap
/*
@ -31,8 +39,48 @@ namespace input {
if (!analogMM) control.fail("no analog sensor")
}
export function readAnalogPin6(port: number) {
export class TouchSensor {
port: number;
id: number;
private downTime: number;
constructor(port: number) {
this.port = port;
this.id = 200 + port;
init()
unsafePollForChanges(50,
() => this.isPressed() ? 1 : 0,
(prev, curr) => {
if (prev == curr) return
if (curr) {
this.downTime = control.millis()
control.raiseEvent(this.id, ButtonEvent.Down)
} else {
control.raiseEvent(this.id, ButtonEvent.Up)
let delta = control.millis() - this.downTime
control.raiseEvent(this.id, delta > 500 ? ButtonEvent.LongClick : ButtonEvent.Click)
}
})
}
isPressed() {
return readAnalogPin6(this.port) > 2500
}
/**
* Do something when a touch sensor is clicked, double clicked, etc...
* @param button the button that needs to be clicked or used
* @param event the kind of button gesture that needs to be detected
* @param body code to run when the event is raised
*/
onEvent(ev:ButtonEvent, body: () => void) {
control.onEvent(this.id, ev, body)
}
}
function readAnalogPin6(port: number) {
init()
port--
port = Math.clamp(0, 3, port | 0)
return analogMM.getNumber(NumberFormat.UInt16LE, 2 * (port + 4))
}