#include <AccelStepper.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
//Define stepper motor connections
const byte dirPin = 3;
const byte stepPin = 5;
const byte isrPin = 2;
const int maxSpeed = 1200;
const int StepsPerRevolution = 200;
const int StepsPerSecond = 200;
//Create stepper object
AccelStepper stepper(1, stepPin, dirPin); //motor interface type must be set to 1 when using a driver.
volatile unsigned long Steps = 0;
void INTERRUPT()
{
Steps++;
}
void setup()
{
lcd.init();
lcd.backlight();
Serial.begin(115200);
attachInterrupt(digitalPinToInterrupt(isrPin), INTERRUPT, RISING);
stepper.setMaxSpeed(maxSpeed); //maximum steps per second
stepper.setSpeed(StepsPerSecond); //steps per second
lcd.setCursor(0, 0);
lcd.print(" Tachometer ");
lcd.setCursor(0, 1);
lcd.print("RPM: ");
lcd.setCursor(5, 1);
lcd.print(0);
lcd.print(" ");
}
void loop()
{
stepper.runSpeed();
calcAndPrintRPM();
}
void calcAndPrintRPM(){
static unsigned long lastTime = 0;
unsigned long Interval = 1000;
if (lastTime == 0) { // Do not provide data on the first entry to this function
lastTime = millis();
return;
}
if (millis()-lastTime > Interval){
lastTime = millis();
int rpm_value = round((Steps * 60000.0) / StepsPerRevolution / Interval);
Steps = 0;
Serial.print("RPM = ");
Serial.println(rpm_value);
lcd.setCursor(5, 1);
lcd.print(rpm_value);
lcd.print(" ");
}
}