# How to subtract micros()?

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();
}
``````
• The calculation seems correct. Please try to also use `unsigned long` for `pauseLength`. That might be your problem Mar 29, 2020 at 21:59
• That definitely solved the problem. I assumed that since the difference would be such a short number it could be int. Thank you. I don't know how to mark this as solving answer. Mar 29, 2020 at 22:24
• I think its more about that you mixed unsigned and signed types. Tomorrow I will write an answer, that you can accept Mar 29, 2020 at 22:42
• what happens if you cast long to int ? ... pauseLength = (int)(micros() - timeStart); Mar 29, 2020 at 22:50

## 1 Answer

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.