0

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();
}
asked Mar 29, 2020 at 21:57
4
  • The calculation seems correct. Please try to also use unsigned long for pauseLength. That might be your problem Commented 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. Commented 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 Commented Mar 29, 2020 at 22:42
  • what happens if you cast long to int ? ... pauseLength = (int)(micros() - timeStart); Commented Mar 29, 2020 at 22:50

1 Answer 1

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.

answered Mar 30, 2020 at 0:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.