Encoder
#Description
This can be used similarly to a rotary potentiometer, however, it does not have a limit, it can rotate indefinitely. This is why it counts up and down and does not give a clear degree unit.
This component requires 2 pins.
#Links
#Aliases
- Rotary Encoder
#Functions
#JavaScript / Node.js
Rotary encoder component. Tracks a signed count value and emits directional events on each detent.
#Constructor options
| Option | Type | Required | Description |
|---|---|---|---|
pin1 | number | DigitalPin | required | — |
pin2 | number | DigitalPin | required | — |
initialValue | number | optional | — |
invert | boolean | optional | — |
#Events
| Event | Parameters | Description |
|---|---|---|
change | value: number | — |
up | — | — |
down | — | — |
#Methods
updateOptions(options: { invert?: boolean })Update runtime options such as invert direction.
setCountTo(value: number)Set the encoder count to a specific value. Note: This updates the local state but does not communicate with the Arduino. For hardware reset, use a serial command.
countUp()Increment the encoder count by 1.
countDown()Decrement the encoder count by 1.
get count→ numberGet the current encoder count value
get value→ number | undefinedfrom ComponentBaseGet the current value of the component.
#Example
import { Board, Encoder } from "@blokdots/components";
const board = new Board("/dev/ttyACM0");
await board.open();
const encoder = new Encoder({ board, pin1: "D5", pin2: "D5" });
encoder.on("change", (value) => {
console.log("Encoder changed:", value);
});#C++ (Arduino)
Emits events: - evtChanged : whenever the value changes - evtUp : when the value increments - evtDown : when the value decrements Notes: - The Encoder library counts transitions; many encoders produce 2 or 4 counts per detent. Use `step` to normalize (common values: 1, 2, 4).
#Required libraries
#include <Encoder.h>— Encoder v1.4.4
#Setup
#include "blokdots.h"
EncoderComponent myComponent(eventBus, 0, 0, MY_EVENT, MY_EVENT, MY_EVENT);#Constructor
EncoderComponent(bus, pinA, pinB, evtChanged, evtUp, evtDown, initialValue, invert, pollIntervalMs, step)| Parameter | Type | Default |
|---|---|---|
bus | EventBus | required |
pinA | uint8_t | required |
pinB | uint8_t | required |
evtChanged | uint8_t | required |
evtUp | uint8_t | required |
evtDown | uint8_t | required |
initialValue | int | 0 |
invert | bool | false |
pollIntervalMs | uint16_t | 2 |
step | int | 4 |
#Methods
value()→ intemittedValue()→ intlastDelta()→ intOptional: expose last delta (+/-)