Using pulseIn function to measure a pulse, but unable to get desired results

I am using two arduinos in master / slave configuration to transmit data from the master to slave over I2C. The following master code is written to measure the pulse duration from an external switch on red_pin (pin 2) using pulseInLong function, and I unable to get desired results. I am at a loss to understand why. The pulse could be between 15 secs - 180 secs long. I have observed the following:

a. The moment the external switch closes, pin 13 goes high
b. Once the test duration of 30 secs is completed, the switch opens, but pin 13 remains high for another 4 - 11 secs.
c. The serial monitor always shows red_duration = 0

#include <Wire.h>

const int red_pin = 2;
const int indi_pin = 13;
unsigned long red_duration = 0;

void setup() {
  pinMode(red_pin, INPUT);
  pinMode (indi_pin, OUTPUT);
  Wire.begin();
  Serial.begin(9600); // initialize serial communication with baud rate of 9600
}

void loop() 
{
  digitalWrite (indi_pin, LOW);
  if (digitalRead(red_pin) == HIGH) 
  {
    digitalWrite (indi_pin, HIGH);
    red_duration = pulseInLong(red_pin, HIGH, 180000000); // measure the duration for which the red_pin was high in microseconds
    digitalWrite (indi_pin, LOW);
    int red_seconds = red_duration / 1000000; // convert the duration to seconds
    delay(1000);
    Serial.print("red_seconds=");
    Serial.println(red_seconds); // print the red_seconds value to the serial monitor
    Wire.beginTransmission(9); // transmit the red_seconds to the slave Arduino
    Wire.write(red_seconds);
    Wire.endTransmission();
  }
 else 
 {
    red_duration = 0;
 }
}

pulseInLong() will wait for the input pin to change from LOW to HIGH before it begins timing the pulse. But in your code, the input pin is already HIGH. So pulseInLong() will wait for the input pin to go LOW, then wait until it goes HIGH again before it starts timing the pulse.

I would not use pulseInLong() for this. Just use millis() or micros().

Do you have a pulldown resistor from red_pin to GND so pin is not floating when switch is open?

Thank you for your time PaulRB, I will try with millis() and update.

Thank you for your time JCA34F, yes, I do have a pull down resistor of 4.7K from red_pin to GND. I will check for the possibility of a dry solder and will update here.

Thank you for your inputs PaulRB and JCA34F. I apologize for the delay in getting back to the forum. The problem was resolved with a change in the board. Once again thank you for your support.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.