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;
}
}