Hi all,
I am working on a project that i need to count rpm. I have found a few people doing this but not 100% satisfied with the code. It will be a rotating drum so all metal. Im not sure if i should put a magnet on it for hall effect or a strip for IR reflector. What does everything think is best or any other ideas. Also how to i read a hall effect sensor. I understand how to turn pins on and rear what a pin is getting but how to i read a pin over a period of time say for a second so i can count how many times the pin has gone high then low. So i understand digitalRead but this only reads once i need to read over a period of time.
Thanks all
Well one technique that you can use is to connect the relevant pin to an interrupt (pins 2 or 3 on regular Arduinos) and have the interrupt handler record the time difference between successive pulses.
#define MINUTE (60 * 1000000L)
#define FIVE_MINUTES (5 * MINUTE)
volatile unsigned long last_ts, current_ts, last_period, rotation_count ;
setup ()
{
current_ts = micros () ;
last_period = FIVE_MINUTES ;
last_ts = current_ts - last_period ; // force initial period to be large enough that RPM reads 0
rotation_count = 0L ;
attachInterrupt (0, handle_ints, RISING) ; // pin 2 is channel 0. Can trigger on RISING or FALLING, shouldn't matter
}
void handle_ints ()
{
current_ts = micros () ; // get time of transition
rotation_count ++ ;
last_period = current_ts - last_ts ; // determine period of last rotation
last_ts = current_ts ;
}
unsigned long latest_period ()
{
cli () ; // inhibit interrupts while reading the long value to prevent garbling
unsigned long result = last_period ;
sei () ;
return result ;
}
unsigned long get_rotations ()
{
cli () ; // inhibit interrupts while reading the long value to prevent garbling
unsigned long result = rotation_count ;
sei () ;
return result ;
}
Or similar - calling latest_period() gives the most recent rotation period, which can be converted to RPM thus:
rpm = MINUTE / latest_period() ;
You can also keep track of total rotations against the clock using get_rotations ()