#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 4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
const int sensorPin = 3; // Digital pin connected to the sensor
volatile int counter = 0; // Counter for the number of pulses
unsigned long startTime; // Start time of each measurement
void setup() {
pinMode(sensorPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(sensorPin), countPulse, FALLING);
Serial.begin(9600);
// SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3D)) { // Address 0x3D for 128x64
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
display.display();
delay(2000); // Pause for 2 seconds
display.clearDisplay();
}
void loop() {
// Reset the counter and start time for each measurement
counter = 0;
startTime = millis();
// Wait for one second to count pulses
delay(1000);
// Calculate RPM
unsigned long endTime = millis();
unsigned long elapsedTime = endTime - startTime;
float rpm = (float)counter / (float)elapsedTime * 60000.0; // RPM = (Pulses / Time) * 60000 (60 seconds * 1000 milliseconds)
// Display RPM in the serial monitor
Serial.print("RPM: ");
Serial.print(rpm);
Serial.print(" Count: ");
Serial.print(counter);
Serial.print(" Time: ");
Serial.println(elapsedTime);
}
void countPulse() {
counter++;
}