/* Tiny85 encoder
*
* pin I2C: SDA = 5 = PB0; SCL = 7 = PB2
* pin Enc: A = PB3; B = PB4; Switch = PB1
*
*/
#include <TinyWireM.h>
#include "avr/interrupt.h";
#include <Tiny4kOLED.h>
#define TARGET_ADDR 0x08
#define encA 3
#define encB 4
#define swtc 1
volatile byte currentValue = 0;
int Valore = 0;
volatile int lastEncoded = 0;
volatile byte lastValue = 0;
volatile byte lastSwitch = 0;
void setup() {
TinyWireM.begin();
oled.begin(128, 64, sizeof(tiny4koled_init_128x64br), tiny4koled_init_128x64br);
// Two fonts are supplied with this library, FONT8X16 and FONT6X8
oled.setFont(FONT6X8);
// To clear all the memory
oled.clear();
oled.on();
delay(3000);
prepareDisplay();
pinMode(encA, INPUT_PULLUP);
pinMode(encB, INPUT_PULLUP);
pinMode(swtc, INPUT_PULLUP);
digitalWrite(encA, HIGH);
digitalWrite(encB, HIGH);
GIMSK = 0b00100000; // Enable pin interrupts
PCMSK = 0b00011010; // Enable pin interrupt PB3,PB4,PB1
sei(); // Turn on interrupts
}
void loop() {
byte currentSwitch = digitalRead(swtc);
if ((lastValue != currentValue)||(lastSwitch != currentSwitch)) {
TinyWireM.beginTransmission(TARGET_ADDR);
TinyWireM.send(currentValue);
TinyWireM.send(currentSwitch);
TinyWireM.endTransmission();
lastValue = currentValue;
lastSwitch = currentSwitch;
if (lastSwitch == 0) Valore = 0;
unsigned int i, k;
unsigned char ch[5];
oled.clear();
oled.begin();
oled.setCursor(20, 1);
oled.print(F("ATtiny85+SSD1306"));
oled.setCursor(20, 2);
oled.print(F("Prova encoder "));
oled.setCursor(57, 4);
oled.print(Valore);
oled.setCursor(57, 5);
oled.print(currentSwitch);
}
delay(10);
}
void prepareDisplay() {
unsigned int i, k;
unsigned char ch[5];
}
ISR(PCINT0_vect) {
byte MSB = digitalRead(encA); //MSB = most significant bit
byte LSB = digitalRead(encB); //LSB = least significant bit
int encoded = (MSB << 1) |LSB; //converting the 2 pin
//value to single number
int sum = (lastEncoded << 2) | encoded; //adding it to
//the previous
//encoded value
if(sum==0b1101||sum==0b0100||sum==0b0010||sum==0b1011) currentValue++;
if(sum==0b1110||sum==0b0111||sum==0b0001||sum==0b1000) currentValue--;
if(sum==0b1101||sum==0b0100||sum==0b0010||sum==0b1011) Valore++;
if(sum==0b1110||sum==0b0111||sum==0b0001||sum==0b1000) Valore--;
lastEncoded = encoded; //store this value for next time
}