Skip to content

Instantly share code, notes, and snippets.

@mmoskal
Created May 30, 2019 17:21
Show Gist options
  • Save mmoskal/d40c8854c5ce45b178268792cd126990 to your computer and use it in GitHub Desktop.
Save mmoskal/d40c8854c5ce45b178268792cd126990 to your computer and use it in GitHub Desktop.
rotary encoder for makecode
// based on https://github.com/PaulStoffregen/Encoder/blob/master/Encoder.h
class Encoder {
state: number
position: number
onChange: (n: number) => void
constructor(public pinA: DigitalInOutPin, public pinB: DigitalInOutPin) {
this.state = 0
this.position = 0
const updatePins = () => {
let s = this.state & 3;
if (this.pinA.digitalRead()) s |= 4;
if (this.pinB.digitalRead()) s |= 8;
this.state = (s >> 2);
switch (s) {
case 0: case 5: case 10: case 15:
return;
case 1: case 7: case 8: case 14:
this.position++; break;
case 2: case 4: case 11: case 13:
this.position--; break;
case 3: case 12:
this.position += 2; break;
default:
this.position -= 2; break;
}
if (this.onChange)
this.onChange(this.position)
}
this.pinA.onEvent(PinEvent.Rise, updatePins)
this.pinB.onEvent(PinEvent.Fall, updatePins)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment