#include <Arduino.h>
#include <U8g2lib.h>
#include <SPI.h>
#include <Wire.h>
// Create U8G2 object for the OLED display
U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE);
unsigned long rpmtime;
float rpmfloat;
unsigned int rpm;
bool tooslow = 1;
void setup() {
u8g2.begin();
u8g2.setFont(u8g2_font_profont29_tf);
TCCR1A = 0;
TCCR1B = 0;
TCCR1B |= (1 << CS12); // Prescaler 256
TIMSK1 |= (1 << TOIE1); // Enable timer overflow
pinMode(2, INPUT);
attachInterrupt(digitalPinToInterrupt(2), RPM, FALLING); // Use digitalPinToInterrupt for compatibility
}
ISR(TIMER1_OVF_vect) {
tooslow = 1;
}
void loop() {
delay(1000);
if (tooslow == 1) {
u8g2.clearBuffer();
u8g2.drawStr(1, 32, "SLOW!");
u8g2.sendBuffer();
} else {
if (rpmtime > 0) {
rpmfloat = 120.0 / (rpmtime / 31250.0);
rpm = round(rpmfloat);
} else {
rpm = 0;
}
u8g2.clearBuffer();
u8g2.setFontMode(1);
u8g2.setBitmapMode(1);
u8g2.drawFrame(2, 1, 124, 62);
u8g2.setDrawColor(2);
u8g2.setFont(u8g2_font_timR18_tr);
u8g2.drawStr(5, 24, "Cadence");
u8g2.setFont(u8g2_font_profont17_tr);
u8g2.drawStr(96, 22, "rpm");
u8g2.setDrawColor(1);
u8g2.setFont(u8g2_font_timR24_tr);
u8g2.setCursor(8, 54);
u8g2.print(rpm);
u8g2.drawLine(92, 9, 92, 25);
u8g2.sendBuffer();
}
}
void RPM() {
rpmtime = TCNT1;
TCNT1 = 0;
tooslow = 0;
}