Instead of displaying the RPM every 20 revolutions, this version displays the RPM many times per second if it changes. I changed it to using microseconds instead of milliseconds to get more resolution.
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
const unsigned long MICROSECONDS_PER_HALF_MINUTE = 30 * 1000000UL;
const byte OLED_RESET_PIN = 4;
Adafruit_SSD1306 display(OLED_RESET_PIN);
#if (SSD1306_LCDHEIGHT != 32)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif
volatile unsigned long MicrosecondsInHalfRevolution = 0;
void setup() {
Serial.begin(9600);
attachInterrupt(0, HalfRevolutionISR, RISING); // the output from spark plug sensor
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // initialize with the I2C addr 0x3C (for the 128x32)
}
void HalfRevolutionISR()
{
static unsigned long lastMicroseconds = 0;
unsigned long currentMicroseconds = micros();
MicrosecondsInHalfRevolution = currentMicroseconds - lastMicroseconds;
lastMicroseconds = currentMicroseconds;
}
void loop() {
static unsigned int OldRPM = 0;
// Copy volatile varaibles while interrupts are disabled
noInterrupts();
unsigned long microsecondsHalfRev = MicrosecondsInHalfRevolution;
interrupts();
// Calculate RPM
unsigned int RPM = MICROSECONDS_PER_HALF_MINUTE / microsecondsHalfRev;
// Display only on change to avoid flicker
if (RPM != OldRPM) {
display.clearDisplay();
drawPercentbar( 0, 16, 128, 15, map(RPM, 0, 8000, 0, 100));
text(RPM);
display.display();
OldRPM = RPM;
}
}
void text (unsigned int RPM) {
display.setCursor (0, 0) ;
display.setTextSize(2);
display.setTextColor(WHITE);
display.print (RPM) ;
display.print (" RPM") ;
}
void drawPercentbar(int x, int y, int width, int height, int progress)
{
progress = constrain(progress, 0, 100);
float bar = ((float)(width - 4) / 100) * progress;
display.drawRect(x, y, width, height, WHITE);
display.fillRect(x + 2, y + 2, bar , height - 4, WHITE);
if ( height >= 15) {
display.setCursor((width / 2) - 3, y + 5 );
display.setTextSize(1);
display.setTextColor(WHITE);
if ( progress >= 50)
display.setTextColor(BLACK, WHITE);
display.print(progress);
display.print("%");
}
}