Add TouchSensor class with events
This commit is contained in:
parent
aeb326fac6
commit
b79fd7096f
@ -1,4 +1,12 @@
|
|||||||
namespace input {
|
namespace input {
|
||||||
|
|
||||||
|
//% shim=pxt::unsafePollForChanges
|
||||||
|
function unsafePollForChanges(
|
||||||
|
periodMs: int32,
|
||||||
|
query: () => int32,
|
||||||
|
changeHandler: (prev: int32, curr: int32) => void
|
||||||
|
) { }
|
||||||
|
|
||||||
let analogMM: MMap
|
let analogMM: MMap
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@ -31,8 +39,48 @@ namespace input {
|
|||||||
if (!analogMM) control.fail("no analog sensor")
|
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()
|
init()
|
||||||
|
port--
|
||||||
port = Math.clamp(0, 3, port | 0)
|
port = Math.clamp(0, 3, port | 0)
|
||||||
return analogMM.getNumber(NumberFormat.UInt16LE, 2 * (port + 4))
|
return analogMM.getNumber(NumberFormat.UInt16LE, 2 * (port + 4))
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user