#include <Wire.h>
#define encoder0PinA 3
#define encoder0PinB 2
volatile unsigned int encoder0Pos = 0;
int value = 0;
void setup() {
pinMode(encoder0PinA, INPUT);
digitalWrite(encoder0PinA, HIGH); // turn on pullup resistor
pinMode(encoder0PinB, INPUT);
digitalWrite(encoder0PinB, HIGH); // turn on pullup resistor
attachInterrupt(0, doEncoder, HIGH); // encoder pin on interrupt 0 - pin 2
Wire.begin(); // set up I2C on 4 and 5 analog
Wire.beginTransmission(0x09);// join I2C, talk to BlinkM 0x09
Wire.send("o");
Wire.endTransmission();
Wire.beginTransmission(0x09);
Wire.send("c");
Wire.send(0xff); // value for red channel
Wire.send(0x00); // value for blue channel
Wire.send(0x00); // value for green channel
Wire.endTransmission(); // leave I2C bus // debug - remember to comment out
// before final program run
}
void loop(){
// set up I2C on 4 and 5 analog
Wire.beginTransmission(0x09);// join I2C, talk to BlinkM 0x09
Wire.send("c"); // ‘c’ == fade to color
Wire.send(value); // value for red channel
Wire.send(value); // value for blue channel
Wire.send(value); // value for green channel
Wire.endTransmission(); // leave I2C bus // debug - remember to comment out
// do some stuff here - the joy of interrupts is that they take care of themselves
}
void doEncoder(){
/* If pinA and pinB are both high or both low, it is spinning
* forward. If they're different, it's going backward.
*
* For more information on speeding up this process, see
* [Reference/PortManipulation], specifically the PIND register.
*/
if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB)) {
encoder0Pos++;
} else {
encoder0Pos--;
}
if ( encoder0Pos < 0){
encoder0Pos = encoder0Pos + 255;
}
else if ( encoder0Pos > 255){
encoder0Pos = encoder0Pos -255;
}
value = encoder0Pos;
}
Same code as before, but this time, the encoder will change the value up, but never down, I have experimented with the interrupt being triggered on HIGH, LOW and CHANGED. No difference.