Loading...

Acceleration support for Rotary Encoders

This is my attempt to make a more intelligent processing of a rotary encoder. I have gone through the article for rotary encoders http://arduino.cc/playground/Main/RotaryEncoders and tried the hints. The code did work, but the cheap encoder I got was bouncing, i.e. rotating the knob constantly only in increasing direction every now and then produced a signal for decreasing. So I needed to de-bounce the encoder readings somehow and I wanted it to be software only de-bouncing.

Ok. I made the software de-bouncing but in my application the encoder was used to count from 50 to 5000. This is quite a span and rotating the encoder 5000 steps is by far not user friendly. I needed to take into account the speed at which the encoder is rotated - the faster the encoder is rotated the greater the step of increment/decrement will be and keeping in mind that the encoder must be able to step by 1 if rotated slowly enough.

Next I wanted to make this as a re-usable library that can be used with and without attaching the encoder to an interrupt.

The attached zip file contains the needed libraries (maybe it became over-re-using)... Attach:RotaryEncoderAcceleration.zip

Bellow is a small sample code to implement an accelerated rotary encoder support in an Arduino sketch. The rotary encoder pinA is connected to Adruino pin 2 and pinB - to Arduino pin 3. A speaker connected to pin 8.

Code without using interrupt:


#include <WProgram.h> // This include should go first, otherwise does not compile.
#include <Button.h>
#include <TicksPerSecond.h>
#include <RotaryEncoderAcelleration.h>

const int rotorPinA = 2;
const int rotorPinB = 3;
const int speakerPin = 8;

RotaryEncoderAcelleration rotor;

void setup() {
	pinMode(speakerPin, OUTPUT);
	rotor.initialize(rotorPinA, rotorPinB);
	rotor.setMinMax(50, 5000);
	rotor.setPosition(500);
}

void loop() {
	rotor.update();
	tone(speakerPin, rotor.getPosition());
}

Code using interrupt:


#include <WProgram.h> // This include should go first, otherwise does not compile.
#include <Button.h>
#include <TicksPerSecond.h>
#include <RotaryEncoderAcelleration.h>

const int rotorPinA = 2;
const int rotorPinB = 3;
const int speakerPin = 8;

RotaryEncoderAcelleration rotor;

void UpdateRotor() {
	rotor.update();
}

void setup() {
	pinMode(speakerPin, OUTPUT);
	rotor.initialize(rotorPinA, rotorPinB);
	rotor.setMinMax(50, 5000);
	rotor.setPosition(500);
	attachInterrupt(0, UpdateRotor, CHANGE);
}

void loop() {
	tone(speakerPin, rotor.getPosition());
}