Tachometer - Arduino Uno code
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 // Reset pin 4 (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define interrupt_pin 2
unsigned int rpm;
volatile unsigned int counter = 0;
unsigned long passedtime = 0;
void draw(unsigned int _rpm) {
unsigned int cnt;
cnt = counter / 6;
display.clearDisplay();
display.setTextSize(2); // Normal 1:1 pixel scale
display.setTextColor(WHITE); // Draw white text
display.setCursor(0,0); // Start at top-left corner
display.print("RPM:");
display.setCursor(0,16);
display.print(_rpm, DEC);
display.setCursor(0,32);
display.print("Hz:");
display.setCursor(0,48);
display.print(cnt, DEC);
display.display();
}
void isr() {
counter++;
}
void setup() {
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.setTextSize(2); // Normal 1:1 pixel scale
display.setTextColor(WHITE); // Draw white text
display.setCursor(0,0); // Start at top-left corner
display.print("START");
display.display();
attachInterrupt(digitalPinToInterrupt(interrupt_pin), isr, RISING);
passedtime = millis();
}
void loop() {
if ((millis() - passedtime) > 2999){
detachInterrupt(digitalPinToInterrupt(interrupt_pin)); //Interrupts are disabled
// noInterrupts(); no working
rpm = 10 * counter; // 60 * counter(12) / 2 / 3
draw(rpm);
counter = 0;
passedtime = millis();
attachInterrupt(digitalPinToInterrupt(interrupt_pin), isr, RISING);
}
}