Skip to content

Instantly share code, notes, and snippets.

@smukkejohan
Created May 10, 2024 11:08
Show Gist options
  • Save smukkejohan/ebb2ededeffec5f380cdc950dfa92f5a to your computer and use it in GitHub Desktop.
Save smukkejohan/ebb2ededeffec5f380cdc950dfa92f5a to your computer and use it in GitHub Desktop.
rotary-encoder-teensy3.5
#include "Arduino.h"
// Written by Johan Bichel Lindegaard <public@johan.cc>
int aPin = 19;
int bPin = 20;
long lastPosition = 0;
long position = 0;
// values based on calibration with min max A: 8 26 B: 8 31
int aHigh = 14;
int aLow = 12;
int bHigh = 18;
int bLow = 12;
int aL = 0;
int a = 0;
int b = 0;
/*
// calibration
int maxA = 0;
int minA = 1024;
int maxB = 0;
int minB = 1024;
*/
void setup() {
Serial.begin(9600); // Teensy USB Serial object always communicates at native USB speed, either 12 or 480 Mbit/sec. The baud rate setting with Serial.begin(baud) is ignored
pinMode(aPin, INPUT_PULLUP);
pinMode(bPin, INPUT_PULLUP);
analogReadResolution(6); // 6 bits = 0 - 63
analogReadAveraging(2);
Serial.println(position);
}
void loop() {
//calibration
// Last result: A: 8 26 B: 8 31
/*
int s1 = analogRead(aPin);
int s2 = analogRead(bPin);
int changed = 0;
if(s1 > maxA){
maxA = s1;
changed = 1;
}
if(s1 < minA){
minA = s1;
changed = 1;
}
if(s2 > maxB){
maxB = s2;
changed = 1;
}
if(s2 < minB){
minB = s2;
changed = 1;
}
if(changed){
Serial.print(s1);
Serial.print(" ");
Serial.println(s2);
Serial.print("A: ");
Serial.print(minA);
Serial.print(" ");
Serial.print(maxA);
Serial.print(" B: ");
Serial.print(minB);
Serial.print(" ");
Serial.println(maxB);
}*/
int rA = analogRead(aPin);
if(rA > aHigh){
a = 1;
} else if(rA < aLow){
a = 0;
}
if(a != aL) {
int rB = analogRead(bPin);
if(rB > bHigh){
b = 1;
} else if(rB < bLow){
b = 0;
}
if(b != aL) {
position++;
} else {
position--;
}
}
aL = a;
if(position != lastPosition){
Serial.println(position);
lastPosition = position;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment