# Calculating the time between the signal when its ON and when it gets OFF

``````class Channel
{
private:
uint8_t _pin;
uint8_t _state;
uint32_t _rise;
uint32_t _fall;
uint8_t _count;
uint8_t _channel;

static uint8_t channelCount;

void display()
{
uint32_t diff = (_fall - _rise) / 1000;
uint32_t secs = diff % 60;
uint32_t mins = diff / 60;
//  Serial.print(",");
Serial.print(_channel);
Serial.print(",");
Serial.print(mins);
Serial.print(",");
Serial.print(secs-4);
Serial.print(",");
Serial.println(_count);
}

public:
Channel(int pin) : _pin(pin), _count(0)
{
_pin = pin;
_count = 0;
_channel = channelCount;
channelCount++;
}
void process()
{
if (s != _state)
{
_state = s;
if (s == LOW)  // Fell
{
_fall = millis();
_count++;
display();
}
else
{
_rise = millis();
}
}
}
void begin()
{
pinMode(_pin, INPUT);
}
};

uint8_t Channel::channelCount = 0;

Channel channels[] = { 3,5 };
#define NUM_CHANNELS (sizeof(channels) / sizeof(channels[0]))

void setup()
{
Serial.begin(115200);
Serial.println("Channel,Minutes,Seconds,Count");
for (unsigned int i = 0; i < NUM_CHANNELS; i++)
{
channels[i].begin();
}
}

void loop()
{
for (unsigned int i = 0; i < NUM_CHANNELS; i++)
{
channels[i].process();
}
}
``````

This code works normally in some cases, (i.e.) It provides the exact time between the signal when it's ON and when it gets OFF in seconds.

In some cases, it spits out a 10 digit number. The correct value follows the unknown number in the screenshot attached below

• bro that 10 digit is the 0xFFFFFFFF maximum value that an unsigned 32 bit integer can attain. – Vaibhav Apr 9 '19 at 11:26
• @Vaibhav: No, the maximum value is 4294967295. The value he is seeing is −4. C.f. Reezy's answer. – Edgar Bonet Apr 9 '19 at 11:32
• You have not yet explained why you have put the bug in there. I mean the "secs-4" instead of "secs". – Jot Apr 9 '19 at 23:37
• The values which I get in seconds is four seconds more than the actual value. So I used "sec-4" instead of seconds – Rajesh10 Apr 11 '19 at 8:55