I want to measure the wheel speed on my bicycle. I have:
- bicycle
- hall effect position sensor (honeywell 103SR5A-1)
- arduino nano every
I will make a bracket to mount the sensor to the chain stay such that it will sense the steel spokes passing by. I have some rough code written so far:
#include <util/atomic.h>
// update interval
const byte update_interval = 100;
unsigned long update_time = 0;
// vehicle speed sensor
const byte vss_pin = 2;
volatile unsigned long vss_count_volatile = 0;
volatile unsigned long vss_period_volatile = 0;
unsigned long vss_time = 0;
void setup()
{
pinMode(vss_pin, INPUT);
attachInterrupt(digitalPinToInterrupt(vss_pin), vss_isr, RISING);
}
void loop()
{
unsigned long time_millis = millis();
if (time_millis - update_time > update_interval)
{
update_time += update_interval;
}
else
{
return;
}
unsigned long vss_count;
unsigned long vss_period;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
vss_count = vss_count_volatile;
vss_period = vss_period_volatile;
}
// todo: calculate distance from vss_count
// todo: calculate speed from vss_period
}
void vss_isr()
{
unsigned long time_micros = micros();
vss_count_volatile++;
vss_period_volatile = time_micros - vss_time;
vss_time = time_micros;
}
My concern is that I could get a pulse while inside my atomic block, delaying the reading of micros(). I guess the effect will be very small, but I thought the mega could store a timer value in a register at the moment the interrupt is triggered. However, I haven't been able to find any reference to this feature in the atmega4809 datasheet.