123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- //Conversion factors
- #define MILLIS_TO_SEC 1000.0f
- #define SEC_TO_MIN 60.0f
- bool detect_on = true;
- int n_magnets = 1;
- volatile byte n_rev;
- float rpm;
- float prev_time;
- void setup()
- {
- Serial.begin(9600);
- attachInterrupt(0, detect, RISING);//Initialize the intterrupt pin (Arduino digital pin 2)
- n_rev = 0;
- rpm = 0.0f;
- prev_time = 0.0f;
- }
-
- void loop()//Measure RPM
- {
- //Only do rpm calculation after 20 rotations has past.
- if (n_rev >= 20) {
- rpm = SEC_TO_MIN*MILLIS_TO_SEC/(millis() - prev_time)*n_rev/n_magnets;
- //reset prev_time to now
- prev_time = millis();
- //reset rotation counter
- n_rev = 0;
- //print rpm value to serial console
- Serial.println(rpm,DEC);
- }
- }
- //This function is called whenever a magnet/interrupt is detected by the arduino
- void detect()
- {
- n_rev++;
- if (detect_on == true) {
- Serial.println("Magnet Detected");
- }
- }
|