I am attempting to calculate the time between pulses by comparing the micros() timestamp. I understand that you cannot just simply subtract unsigned longs, but I cannot understand what the alternative for it is.
Below is a simplified version of code. On pin 6 I receive 2ms long pulses every 2ms comparing the times returns "-19728". I'm planning to make the pulses much shorter once I figure out this math problem.
Site note: I'm using pulses to make two Arduinos send simple data via digital pins.
Thanks you.
int pinReceiver = 6;
int val = 0;
int isReceiving = 0;
int pauseLength = 0;
unsigned long timeStart = 0;
void setup() {
Serial.begin(9600);
pinMode(pinReceiver,INPUT);
}
void loop() {
noInterrupts();
val = digitalRead(pinReceiver);
if(val==HIGH){
if(isReceiving==0){ //Pulse begins
isReceiving = 1;
pauseLength = micros() - timeStart;
Serial.println(pauseLength);
}
} else {
if(isReceiving==1){ //Pulse ends
isReceiving = 0;
timeStart = micros();
}
}
interrupts();
}
1 Answer 1
Long to Integer conversion will overflow the value and you'll get values in negative numbers.
Define the pauseLength
as unsigned long
to make it work.
unsigned long
forpauseLength
. That might be your problem