So this is part of a program I'm working on. Trying to get the individual sections working before attempting to merge them into one.
For this part, I have built an electronic circuit that will clean the dirty 12V pulse from a distributor on a car and reduce it down to a 5V signal to be read by the Arduino and then be converted to RPMs displayed on a screen,
I have it kind of working but as the code was modified from a much larger program, I wondered if I had missed anything significant or if anything could be done to improve what I currently have. I was reading up on interrupts and got a bit confused about if i should include a detach interrupt.
Looking for any tips or constructive criticism. TIA.
/*
Arduino 2x16 LCD RPM meter
Modified code found at https://github.com/seanauff/classic-car-sensor-interface/blob/master/sensor_interface_2560.ino
Trying to read a cleaned pulse from a distributor and convert it to a digital readout of RPM
*/
const byte tachPin = 3; // tach signal on digital pin 3 (interrupt 1)
const byte tachInterrupt = 1; // tach signal on interrupt 1 (digital pin 3)
byte engineCylinders = 8; // for tach calculation (pulses per revolution = 2 * cylinders / cycles)
byte engineCycles = 4; // for tach calculation
int refreshInterval = 750; // milliseconds between sensor updates
unsigned long previousMillis = 0;
volatile int RPMpulses = 0;
#include <LiquidCrystal.h>
//LCD pin to Arduino
const int pin_RS = 8;
const int pin_EN = 9;
const int pin_d4 = 4;
const int pin_d5 = 5;
const int pin_d6 = 6;
const int pin_d7 = 7;
const int pin_BL = 10;
LiquidCrystal lcd( pin_RS, pin_EN, pin_d4, pin_d5, pin_d6, pin_d7);
void setup()
{
lcd.begin(16, 2); // Initialize LCD
pinMode(tachPin, INPUT); // Set tachPin to read +V input pulses
attachInterrupt(tachInterrupt, countRPM, RISING); // starts counting when pulse received from distributor
Serial.begin(9600);
}
void loop()
{
if (millis() - previousMillis > refreshInterval)
{
previousMillis = millis();
lcd.setCursor(0, 0);
lcd.print("RPM ");
lcd.print(getRPM());
lcd.print(" ");
}
}
// counts tach pulses
void countRPM()
{
RPMpulses++;
}
// checks accumulated tach signal pulses and calculates engine speed
// returns engine speed in RPM
// Resolution: 30000 * engineCycles / refreshInterval / engineCylinders RPM (for default values = 20 RPM)
int getRPM()
{
int RPM = int(RPMpulses * (60000.0 / float(refreshInterval)) * engineCycles / engineCylinders / 2.0 ); // calculate RPM
RPMpulses = 0; // reset pulse count to 0
RPM = min(9999, RPM); // don't return value larger than 9999
return RPM;
}