I'm trying to make a DIY electronic fuel injection system for a gasoline engine. I've got most of the things working but I struggle with trying to measure the time between two analog voltage pulses in order to calculate the current RPM of the engine. The signal I get from the engine looks like this:
When the engine is not running it just outputs a +5V signal. When it is running and the magnet on the flywheel passes the first sensor, it creates the first voltages drop (as you can see this in the picture at 1.). When the magnet on the flywheel passes the second sensor it creates the second voltages drop (which can be seen at 2. in the picture). The two sensors are spaced exactly 35° appart.
My question is; how can I with this signal measure the RPM of the motor using an Arduino? What would a script that could do that look like? I would like to use the two voltage drops (1. and 2. in the picture), spaced only a few milliseconds appart to calculate the RPM. It would also need to be quite accurate because the timing when the fuel injector opens is calculated from the current RPM. Therefore the refresh rate of the RPM counter would also need to be quite high.
I also apologize for any grammar mistakes I probably made. English is not my native language.
The simplest approach to measure those timings is to use input polling (fast digital reads) to determine the falling edges, and store the value of the built in microsecond timer.
This very simple, blocking code works to capture and time two falling edges, assuming input is on Port D, pin 2 (digital pin 2):
while( PIND&4); //wait for LOW on digital pin 2
unsigned long start = micros();
while ( (PIND&4) == 0); //wait for HIGH
while (PIND&4); //wait for LOW
unsigned long pulse_time = micros()-start;
Use of interrupts is also possible, but for beginners, this creates more problems than it solves.
For more precision, you can use the Input Capture feature of the UNO, Nano, Mini, Mega, Leonardo, or Micro. That will let you measure rising or falling edges with a precision of 1/16th microseconds. The 'micros()' function is limited to 4-microseconds precision and subject to various interruptions.
Example code for the Uno/Nano/Mini:
// Measures the HIGH width, LOW width, frequency, and duty-cycle of a pulse train
// on Arduino UNO/Nano Pin 8 (ICP1 pin).
// Note: Since this uses Timer1, Pin 9 and Pin 10 can't be used for
// analogWrite().
void setup()
{
Serial.begin(115200);
while (!Serial);
// For testing, uncomment one of these lines and connect
// Pin 3 or Pin 5 to Pin 8
// analogWrite(3, 64); // 512.00, 1528.00, 2040.00, 25.10%, 490.20 Hz
// analogWrite(5, 64); // 260.00, 764.00, 1024.00, 25.39%, 976.56 Hz
noInterrupts (); // protected code
// reset Timer 1
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;
TIMSK1 = 0;
TIFR1 |= _BV(ICF1); // clear Input Capture Flag so we don't get a bogus interrupt
TIFR1 |= _BV(TOV1); // clear Overflow Flag so we don't get a bogus interrupt
TCCR1B = _BV(CS10) | // start Timer 1, no prescaler
_BV(ICES1); // Input Capture Edge Select (1=Rising, 0=Falling)
TIMSK1 |= _BV(ICIE1); // Enable Timer 1 Input Capture Interrupt
TIMSK1 |= _BV(TOIE1); // Enable Timer 1 Overflow Interrupt
interrupts ();
}
volatile uint32_t PulseHighTime = 0;
volatile uint32_t PulseLowTime = 0;
volatile uint16_t Overflows = 0;
ISR(TIMER1_OVF_vect)
{
Overflows++;
}
ISR(TIMER1_CAPT_vect)
{
static uint32_t firstRisingEdgeTime = 0;
static uint32_t fallingEdgeTime = 0;
static uint32_t secondRisingEdgeTime = 0;
uint16_t overflows = Overflows;
// If an overflow happened but has not been handled yet
// and the timer count was close to zero, count the
// overflow as part of this time.
if ((TIFR1 & _BV(TOV1)) && (ICR1 < 1024))
overflows++;
if (PulseLowTime == 0)
{
if (TCCR1B & _BV(ICES1))
{
// Interrupted on Rising Edge
if (firstRisingEdgeTime) // Already have the first rising edge...
{
// ... so this is the second rising edge, ending the low part
// of the cycle.
secondRisingEdgeTime = overflows; // Upper 16 bits
secondRisingEdgeTime = (secondRisingEdgeTime << 16) | ICR1;
PulseLowTime = secondRisingEdgeTime - fallingEdgeTime;
firstRisingEdgeTime = 0;
}
else
{
firstRisingEdgeTime = overflows; // Upper 16 bits
firstRisingEdgeTime = (firstRisingEdgeTime << 16) | ICR1;
TCCR1B &= ~_BV(ICES1); // Switch to Falling Edge
}
}
else
{
// Interrupted on Falling Edge
fallingEdgeTime = overflows; // Upper 16 bits
fallingEdgeTime = (fallingEdgeTime << 16) | ICR1;
TCCR1B |= _BV(ICES1); // Switch to Rising Edge
PulseHighTime = fallingEdgeTime - firstRisingEdgeTime;
}
}
}
void loop()
{
noInterrupts();
uint32_t pulseHighTime = PulseHighTime;
uint32_t pulseLowTime = PulseLowTime;
interrupts();
// If a sample has been measured
if (pulseLowTime)
{
// Display the pulse length in microseconds
Serial.print("High time (microseconds): ");
Serial.println(pulseHighTime / 16.0, 2);
Serial.print("Low time (microseconds): ");
Serial.println(pulseLowTime / 16.0, 2);
uint32_t cycleTime = pulseHighTime + pulseLowTime;
Serial.print("Cycle time (microseconds): ");
Serial.println(cycleTime / 16.0, 2);
float dutyCycle = pulseHighTime / (float)cycleTime;
Serial.print("Duty cycle (%): ");
Serial.println(dutyCycle * 100.0, 2);
float frequency = (float)F_CPU / cycleTime;
Serial.print("Frequency (Hz): ");
Serial.println(frequency, 2);
Serial.println();
delay(1000); // Slow down output
// Request another sample
noInterrupts();
PulseLowTime = 0;
interrupts();
}
}
If there are 40 samples in a circle, I need to correctly output the RPM information. do we need to counting 40 time in the ISR ?would you please share how to update the code? any comments or suggestion will be great appreciate.
I posted this code a while ago
my encoder has 400 pulses per revolution
#define ClockPin 3 // Must be pin 2 or 3
//#define DataPin 9 // can be any other pin
// My Encoder has 400 Clock pulses per revolution
// note that 150000.0 = (60 seonds * 1000000 microseconds)microseconds in a minute / 400 pulses in 1 revolution)
// change the math to get the proper multiplier for RPM for your encoder
// yours has 4 pulses in 1 revolution
// note that 150000.0 = (60 seonds * 1000000 microseconds)microseconds in a minute / 4 pulses in 1 revolution)
#define Multiplier 15000000.0 // don't forget a decimal place to make this number a floating point number
volatile long count = 0;
volatile long EncoderCounter = 0;
volatile int32_t dTime; // Delt in time
volatile bool DataPinVal;
void onPin2CHANGECallBackFunction(){
static uint32_t lTime; // Saved Last Time of Last Pulse
uint32_t cTime; // Current Time
cTime = micros(); // Store the time for RPM Calculations
/*
// Encoder Code
DataPinVal = digitalRead(DataPin);
// We know pin 2 just went high to trigger the interrupt
// depending on direction the data pin will either be high or low
EncoderCounter += (DataPinVal) ? 1 : -1; // Should we step up or down?
// End Encoder Code
*/
// calculate the DeltaT between pulses
dTime = cTime - lTime;
lTime = cTime;
}
void setup() {
Serial.begin(115200); //115200
// put your setup code here, to run once:
pinMode(ClockPin, INPUT);
// pinMode(DataPin, INPUT);
attachInterrupt(digitalPinToInterrupt(ClockPin),onPin2CHANGECallBackFunction,RISING);
}
void loop() {
// long Counter;
// bool DataPinValue
float DeltaTime;
float SpeedInRPM = 0;
noInterrupts ();
// Because when the interrupt occurs the EncoderCounter and SpeedInRPM could be interrupted while they
// are being used we need to say hold for a split second while we copy these values down. This doesn't keep the
// interrupt from occurring it just slightly delays it while we maneuver values.
// if we don't do this we could be interrupted in the middle of copying a value and the result get a corrupted value.
// Counter = EncoderCounter;
// DataPinValue = DataPinVal;
DeltaTime = dTime;
interrupts ();
// SpeedInRPM = Multiplier / ((DataPinValue) ? DeltaTime: (-1 * DeltaTime)); // Calculate the RPM Switch DeltaT to either positive or negative to represent Forward or reverse RPM
SpeedInRPM = Multiplier / DeltaTime; // Calculate the RPM Switch DeltaT to either positive or negative to represent Forward or reverse RPM
// use the speed and counter values for whatever you need to do.
static unsigned long SpamTimer;
if ( (unsigned long)(millis() - SpamTimer) >= (100)) {
SpamTimer = millis();
// Serial.print(Counter );
// Serial.print("\t");
Serial.print(SpeedInRPM , 3);
Serial.print(" RPM");
Serial.println();
SpeedInRPM = 0; // if no pulses occure in the next 100 miliseconds then we must assume that the motor has stopped
}
}
Try the following setup (Fig-1) and the sketch; where, the two falling edges coming from the sensors are interrupting the MCU. The MCU measures the time interval between the two interrupts and then calculates the RPM based on the information given in post #1.
This method may work if the RPM is above 1000. If the RPM is 1000, the time interval between two falling edges is: 5.28 ms. If TCNT1 is running at prescale 1, it will have to count 16000000x.00582 = 93120 which is greater than its capacity of 65535.
I'm not that great at the timer stuff but I would like to use your method instead of micros() in my example and other code as it relates to the original post.
@GolamMostafa
I'm digging into timer 1 I'm not completely familiar with the differences per pulse between the two but comparing the actual Arduino micros() Function with our code I see the following concern:
Another thought about the math... on a 16MHz mpu like the atmega328p every clock tick = 4 microseconds
does your math account for that?
The Micros function has the following in its function to do just that
m = overflow counter
t = timer0 value return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
1. Clock Tick means the period of one clock pulse which is for 16 MHz UNO Board:
= 1/16000000 = .0625 us
2. Let us carry out the following experiment to very the method by measuring the time interval (500 ms) between the falling edges of signals marked Ch-A and Ch-B in Fig-1. Signals at Ch-A (non-invert) and Ch-B (invert) are of opposite polarity and synchronized, which being generated using TC1 in Fast PWM Mode-14.
Figure-1:
=======================
Total Count = 7999748
Time between two falling edges = 499.98 ms
=======================
3. Change the frequency to 2 Hz and check that the display shows: ~-250 ms. Output:
================================================
Total Count = 3999748
Time between two falling edges = 249.98 ms
================================================
The latest example was Extremely helpful!
While @sheep060 's tachometer is different with 2 separate pulses while mine is an encoder with clock and data pins the end result is the same and I can use your latest example to fine-tune my NEW version. I'll shortly start a new post and tag you in it as your assistance has been extremely helpful.
ZHomeSlice