#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define outputA 2 //CLK pin
#define outputB 3 //DT pin
#define rstbtn 4 //reset button pin
int counter = 0;
const float pi = 3.14; // Pi value
const int R = 7; //Radius of the wheel from center to edge
const int N = 40; //no of steps for one rotation
float distance = 0;
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// declare an SSD1306 display object connected to I2C
Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
void setup() {
Serial.begin(9600);
// initialize OLED display with address 0x3C for 128x64
if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
while (true);
}
delay(2000); // wait for initializing
oled.clearDisplay(); // clear display
oled.setTextSize(1); // text size
oled.setTextColor(WHITE); // text color
oled.setCursor(0, 10); // position to display
oled.println ("ricci culo"); // text to display
oled.display(); // show on OLED
// Initialize encoder pins
pinMode(outputA, INPUT);
pinMode(outputB, INPUT);
pinMode(rstbtn, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(outputA), readEncoder, FALLING);
delay(2000);
oled.clearDisplay(); // clear display
}
void readEncoder() {
int bValue = digitalRead(outputB);
if (bValue == HIGH) {
counter++; // Clockwise
}
if (bValue == LOW) {
counter--; // Counterclockwise
}
}
// Get the counter value, disabling interrupts.
// This make sure readEncoder() doesn't change the value
// while we're reading it.
int getCounter() {
int result;
noInterrupts();
result = counter;
interrupts();
return result;
}
void resetCounter() {
noInterrupts();
counter = 0;
interrupts();
}
void loop() {
oled.clearDisplay(); // clear display
distance = ((2*pi*R)/N) * getCounter();
oled.setCursor(0, 0); // position to display
oled.println("Distanza: in cm");
oled.setCursor(0, 10);
oled.println(distance);
oled.println(" ");
oled.display(); // show on OLED
if (digitalRead(rstbtn) == LOW) {
resetCounter();
}
}