surfacedial_encoder_demo.ino
1 // SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries 2 // 3 // SPDX-License-Identifier: MIT 4 5 #include <Adafruit_NeoPixel.h> 6 #include <RotaryEncoder.h> 7 #include "HID-Project.h" // https://github.com/NicoHood/HID 8 9 // Create the neopixel strip with the built in definitions NUM_NEOPIXEL and PIN_NEOPIXEL 10 Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_NEOPIXEL, PIN_NEOPIXEL, NEO_GRB + NEO_KHZ800); 11 int16_t neo_brightness = 20; // initialize with 20 brightness (out of 255) 12 13 RotaryEncoder encoder(PIN_ENCODER_A, PIN_ENCODER_B, RotaryEncoder::LatchMode::FOUR3); 14 // This interrupt will do our encoder reading/checking! 15 void checkPosition() { 16 encoder.tick(); // just call tick() to check the state. 17 } 18 19 int last_rotary = 0; 20 bool last_button = false; 21 22 void setup() { 23 Serial.begin(115200); 24 //while (!Serial); 25 delay(100); 26 27 Serial.println("Rotary Trinkey Surface Dial"); 28 29 // start neopixels 30 strip.begin(); 31 strip.setBrightness(neo_brightness); 32 strip.show(); // Initialize all pixels to 'off' 33 34 attachInterrupt(PIN_ENCODER_A, checkPosition, CHANGE); 35 attachInterrupt(PIN_ENCODER_B, checkPosition, CHANGE); 36 37 // set up the encoder switch, which is separate from the encoder 38 pinMode(PIN_ENCODER_SWITCH, INPUT_PULLDOWN); 39 40 // Sends a clean report to the host. This is important on any Arduino type. 41 SurfaceDial.begin(); 42 } 43 44 45 void loop() { 46 // read encoder 47 int curr_rotary = encoder.getPosition(); 48 RotaryEncoder::Direction direction = encoder.getDirection(); 49 // read switch 50 bool curr_button = !digitalRead(PIN_ENCODER_SWITCH); 51 52 if (direction != RotaryEncoder::Direction::NOROTATION) { 53 Serial.print("Encoder value: "); 54 Serial.print(curr_rotary); 55 Serial.print(" direction: "); 56 Serial.print((int)direction); 57 58 if (direction == RotaryEncoder::Direction::CLOCKWISE) { 59 Serial.println(" Rotate+"); 60 SurfaceDial.rotate(40); 61 } 62 if (direction == RotaryEncoder::Direction::COUNTERCLOCKWISE) { 63 Serial.println(" Rotate-"); 64 SurfaceDial.rotate(-40); 65 } 66 67 last_rotary = curr_rotary; 68 } 69 70 if (curr_button && !last_button) { // switch pressed! 71 Serial.println("Press"); 72 SurfaceDial.press(); 73 } 74 if (!curr_button && last_button) { // switch released! 75 Serial.println("Release"); 76 SurfaceDial.release(); 77 } 78 last_button = curr_button; 79 80 delay(10); // debounce 81 }