add Grove - Thumb Joystick

This commit is contained in:
jerryyip
2018-09-14 14:11:57 +08:00
parent 1154cb2fef
commit fe28f60f66
3 changed files with 197 additions and 44 deletions

98
main.ts
View File

@ -61,13 +61,40 @@ enum GroveGesture {
Wave = 9
}
enum GroveJoystickKey {
//% block=None
None = 0,
//% block=Right
Right = 1,
//% block=Left
Left = 2,
//% block=Up
Up = 3,
//% block=Down
Down = 4,
//% block=Upper left
UL = 5,
//% block=Upper right
UR = 6,
//% block=Lower left
LL = 7,
//% block=Lower right
LR = 8,
//% block=press
Press = 9
}
/**
* Functions to operate Grove module.
*/
//% weight=10 color=#9F79EE icon="\uf108" block="Grove"
namespace grove {
const gestureEventId = 3100;
const joystickEventID = 3101;
let lastGesture = GroveGesture.None;
let lastJoystick = GroveJoystickKey.None;
let joystick: GroveJoystick = undefined;
let paj7620: PAJ7620 = undefined;
let distanceBackup: number = 0;
/**
@ -92,6 +119,31 @@ namespace grove {
})
}
}
/**
* Do something when a key is detected by Grove - Thumb Joystick
* @param key type of joystick to detect
* @param xpin
* @param ypin
* @param handler code to run
*/
//% blockId=grove_joystick_create_event block="on Key|%key"
export function onJoystick(key: GroveJoystickKey, xpin: AnalogPin, ypin: AnalogPin, handler: () => void) {
control.onEvent(joystickEventID, key, handler);
control.inBackground(() => {
while(true) {
const key = joystick.read(xpin, ypin);
if (key != lastJoystick) {
lastJoystick = key;
control.raiseEvent(joystickEventID, lastJoystick);
}
basic.pause(50);
}
})
}
/**
* Create a new driver of Grove - Ultrasonic Sensor to measure distances in cm
@ -464,4 +516,50 @@ namespace grove {
this.bit(0x7f, 0x03);
}
}
export class GroveJoystick
{
/**
* Detect position from Grove - Thumb Joystick
* @param xPin
* @param yPin
*/
//% blockId=grove_joystick_read block="%strip|read position of joystick"
//% advanced=true
read(xPin: AnalogPin, yPin: AnalogPin): number {
let xdata = 0, ydata = 0, result = 0;
if (xPin && yPin) {
xdata = pins.analogReadPin(xPin);
ydata = pins.analogReadPin(yPin);
if (xdata > 1000) {
result = GroveJoystickKey.Press;
}
else if (xdata > 600) {
if (ydata > 600) result = GroveJoystickKey.UR;
else if (ydata < 400) result = GroveJoystickKey.LR;
else result = GroveJoystickKey.Right;
}
else if (xdata < 400) {
if (ydata > 600) result = GroveJoystickKey.UL;
else if (ydata < 400) result = GroveJoystickKey.LL;
else result = GroveJoystickKey.Left;
}
else {
if (ydata > 600) result = GroveJoystickKey.Up;
else if (ydata < 400) result = GroveJoystickKey.Down;
else result = GroveJoystickKey.None;
}
}
else {
result = GroveJoystickKey.None;
}
return result;
}
}
// export class GroveHicell {
// }
}