Products > Embedded Computing

[arduino] can't subtract two time stamps

<< < (17/17)

Psi:

--- Quote from: Simon on October 24, 2021, 02:46:52 pm ---The problem with millis is in the speed calculation which in nested a couple more levels down. When I take that code and put it directly in the if count == 10 it works and displays the speed rather than 0.

--- End quote ---

Don't get too locked-in to this millis() issue being the problem. 
Yes, I believe you when you say that nesting millis() cause millis() to not work correctly, but that is just a symptom of some other bigger issue, like overwriting memory somewhere.

westfw:
What retiredfeline said.

Every 2s, your "if (loopcount == 10)" will be true EVERY LOOP until the next time you increment loopcount (ie 200ms), at short intervals.
Because of the way you display your data, you'll probably only see the text generated by the LAST of these display updates.

Easy fix:

--- Code: ---void loop() {
  if ((millis() - varLastLoopTime) > constLoopIntervalMs) { // check time since last loop counter update
    loopCount ++; // update loop count
    if (loopCount == 10) {
      loopCount = 0; // if loop count has eceeded 10 reset
      task2s();
    }
    varLastLoopTime = millis();
  }
}

--- End code ---

Although I'd be inclined to have separate timers for the 2s stuff and the 200ms stuff.  Much more straightforward, and insignificantly more code:

--- Code: ---boolean periodically (uint32_t *since, uint32_t time) {
  uint32_t currentmillis = millis();
  if (currentmillis - *since >= time) {
    *since = currentmillis;
    return true;
  }
  return false;
}

void loop() {
  static uint32_t timer200ms, timer2s;
  if (periodically(&timer200ms, 200)) {
    task200ms();
  }
  if (periodically(&timer2s, 2000)) {
    task2s();
  }
}
--- End code ---

Simon:

--- Quote from: Psi on October 24, 2021, 10:55:20 pm ---
--- Quote from: Simon on October 24, 2021, 02:46:52 pm ---The problem with millis is in the speed calculation which in nested a couple more levels down. When I take that code and put it directly in the if count == 10 it works and displays the speed rather than 0.

--- End quote ---

Don't get too locked-in to this millis() issue being the problem. 
Yes, I believe you when you say that nesting millis() cause millis() to not work correctly, but that is just a symptom of some other bigger issue, like overwriting memory somewhere.


--- End quote ---

What retiredfeline said.

However the code written by the student should have worked, but did not, so it looks like there may be something else as he did it differently and certainly not with the trap that I have.

Navigation

[0] Message Index

[*] Previous page

There was an error while thanking
Thanking...
Go to full version