Saturday, April 01, 2023

Connecting an Encoder to Teensy 4.2

 Overview

An encoder is a digital input device that looks similar to a pot but can be rotated indefinitely and delta rotation in steps is measured by making or breaking contact between two pins and ground. The Teensy has an excellent and easy to use library for encoders. More than one encoder can be easily used. 


Hardware

The encoder portion of an encoder usually has three pins, these may be labelled A, B and C. B is a common ground and should be connected to ground. A and C should each be connected to an individual digital pin on the Teensy. As the encoder is turned, the connection between A and B, and A and C is made and broken. This is, in turn, read as a series of high and low signals by the digital input pins. 

This particular encoder also has a push switch. When pressed down, the encoder will make the connection between sw1 and sw2. sw1 can be connected to a third digital input pin on the Teensy and sw2 can be connected to ground. 







Software

The code uses the encoder library to create an encoder object on pins 0 and 1 as well as a button on pin 2. There is a boundary of 0 and 1023 for the encoder. Values of the button and encoder are printed to the serial monitor. 


#include <Encoder.h>

int enc_current;
int enc_previous;
int button = 2; // button on pin 2

int button_current;
int button_previous;

int enc_max = 255; // max value for encoder
int enc_min = 0; // min value for encoder

Encoder enc(0, 1); // create an encoder object named enc using digital pins 0 and 1

void setup() {
Serial.begin(57600);
pinMode(button, INPUT_PULLUP);
}

void loop() {
enc_current = enc.read();

if (enc_current != enc_previous) {
if (enc_current < enc_min) {
enc_current = enc_min;
enc.write(enc_min);
}
if (enc_current > enc_max) {
enc_current = enc_max;
enc.write(enc_max);
}

enc_previous = enc_current;
Serial.print("Encoder: ");
Serial.println(enc_current);

delay(5);
}

button_current = digitalRead(button);

if (button_current != button_previous) {
button_previous = button_current;

Serial.print("Button: ");
Serial.println(button_current);
delay(5);
}
}

0 comments: