Search code examples
arduinointerruptreal-time-clock

Recording real-time data collection with interrupt on Arduino


I've been working on collecting flow rates using the Arduino interrupt and I want to time stamp the data using a real-time clock.

I have both sketches working individually using the Arduino examples, but when I combine them it only writes to the serial port once and I am not sure why.

Once I have the pulse count I will save to a SD card for data manipulation.

#include "RTClib.h"

RTC_DS1307 rtc;
int Pulses =2;            //Digital Pin 2 on Uno
volatile int pulsecount;  //Volatile integer to store pulse count in

void setup() {
  Serial.begin(9600); 
  rtc.begin();            //start rtc
    
  pinMode(Pulses, INPUT); //Make Pin2 Input
  attachInterrupt(digitalPinToInterrupt(Pulses), CountPulses ,FALLING); //Use interrupt on "Pulses" Pin, count on the falling edge, store in CountPulses
}

//create a function that adds up the pulsecount
void CountPulses() {
  pulsecount++;
}

void loop() {
  DateTime time = rtc.now();  //Get the time from RTC
  Serial.print(String("DateTime::TIMESTAMP_TIME:\t") + time.timestamp(DateTime::TIMESTAMP_TIME)); //Print the time to serial monitor

  pulsecount = 0; // set initial count to zero
  interrupts();   // start interrupt
  delay(5000);    // count pulses for 5 seconds
  noInterrupts(); // stop interrupt

  Serial.print(",");  
  Serial.println(pulsecount); //Feed pulse count to serial

  Serial.flush(); //flush the serial port to avoid errors in counting
}

Solution

  • The function noInterrupts() stops all interrupts, not just the one you set up yourself. Any Arduino library code that uses interrupts in the background could stop working when you do this.

    You should enable and disable only the interrupt you set up yourself.

    Try replacing interrupts(); with attachInterrupt(digitalPinToInterrupt(Pulses), CountPulses, FALLING); and replacing noInterrupts(); with detachInterrupt(digitalPinToInterrupt(Pulses));

    You can then also remove the attachInterrupt() from setup(), as it is no longer needed.