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() {

void loop() {
  val = digitalRead(pinReceiver);

    if(isReceiving==0){ //Pulse begins
      isReceiving = 1;
      pauseLength = micros() - timeStart;

  } else {
    if(isReceiving==1){ //Pulse ends
      isReceiving = 0;
      timeStart = micros();
  • The calculation seems correct. Please try to also use unsigned long for pauseLength. That might be your problem
    – chrisl
    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
    – chrisl
    Mar 29, 2020 at 22:42
  • what happens if you cast long to int ? ... pauseLength = (int)(micros() - timeStart);
    – jsotola
    Mar 29, 2020 at 22:50

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.