#include <FastLED.h>
#include <TM1637Display.h>
#define LED_PIN 6
#define NUM_LEDS 8
CRGB leds[NUM_LEDS];
#define SENSOR_PIN 2
#define BUTTON_PIN 3
#define LDR_PIN 4
#define DIGIT_CLK 7
#define DIGIT_DIO 8
TM1637Display display(DIGIT_CLK, DIGIT_DIO);
volatile unsigned long time_old = 0;
volatile unsigned long time_new = 0;
volatile unsigned long rpm = 0;
volatile unsigned long starting_time = 0;
volatile unsigned long current_time = 0;
volatile unsigned long time_delay = 1000; // time to filter out spikes and noise
volatile unsigned long zero_time = 2000000; // time to zero out display when no pulse detected
unsigned long update_interval = 50000; // Update interval in microseconds
unsigned long last_update_time = 0;
int rpm_1 = 100;
int rpm_2 = 200;
int rpm_3 = 300;
int rpm_4 = 400;
int rpm_5 = 500;
int rpm_6 = 600;
int rpm_7 = 700;
int rpm_8 = 800;
int flashing_speed = 200; // bigger value, slower speed
void setup() {
pinMode(SENSOR_PIN, INPUT);
pinMode(BUTTON_PIN, INPUT);
pinMode(LDR_PIN, INPUT);
attachInterrupt(digitalPinToInterrupt(SENSOR_PIN), rpm_isr, RISING);
FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
FastLED.setBrightness(255);
display.setBrightness(7);
}
void loop() {
//uncomment following line for testing flashing lighs
//rpm = 850;
unsigned long current_time = micros();
if (current_time - last_update_time >= update_interval)
{
last_update_time = current_time;
if (digitalRead(LDR_PIN))
{
FastLED.setBrightness(100);
}
else
{
FastLED.setBrightness(255);
}
update_leds();
update_display();
}
if(current_time - starting_time > zero_time)
{
rpm = 0;
}
if(digitalRead(BUTTON_PIN))
{
rpm_1 = 100;
rpm_2 = 200;
rpm_3 = 300;
rpm_4 = 400;
rpm_5 = 500;
rpm_6 = 600;
rpm_7 = 700;
rpm_8 = 800;
}
else
{
rpm_1 = 50;
rpm_2 = 100;
rpm_3 = 150;
rpm_4 = 200;
rpm_5 = 250;
rpm_6 = 300;
rpm_7 = 350;
rpm_8 = 400;
}
if(rpm>=850)
{
delay(flashing_speed);
for(int a=0; a<8; a++)
{
leds[a] = CRGB::Black;
}
FastLED.show();
delay(flashing_speed);
}
}
void update_leds() {
if (rpm >= rpm_1) {
leds[0] = CRGB::Green;
} else {
leds[0] = CRGB::Black;
}
if (rpm >= rpm_2) {
leds[1] = CRGB::Green;
} else {
leds[1] = CRGB::Black;
}
if (rpm >= rpm_3) {
leds[2] = CRGB::Green;
} else {
leds[2] = CRGB::Black;
}
if (rpm >= rpm_4) {
leds[3] = CRGB::Green;
} else {
leds[3] = CRGB::Black;
}
if (rpm >= rpm_5) {
leds[4] = CRGB::Yellow;
} else {
leds[4] = CRGB::Black;
}
if (rpm >= rpm_6) {
leds[5] = CRGB::Yellow;
} else {
leds[5] = CRGB::Black;
}
if (rpm >= rpm_7) {
leds[6] = CRGB::Yellow;
} else {
leds[6] = CRGB::Black;
}
if (rpm >= rpm_8) {
leds[7] = CRGB::Red;
} else {
leds[7] = CRGB::Black;
}
FastLED.show();
}
void update_display() {
display.showNumberDec(rpm, false, 4, 0);
}
void rpm_isr()
{
starting_time = micros();
while(digitalRead(SENSOR_PIN)==HIGH);
current_time = micros();
if(current_time - starting_time >= time_delay)
{
time_new = micros();
rpm = 60000000 / (time_new - time_old);
time_old = time_new;
}
}