Skip to content

TwoWire::read_from and TwoWire::write_to millis rollover bug #195

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
delta-G opened this issue Nov 27, 2023 · 1 comment · Fixed by #196
Closed

TwoWire::read_from and TwoWire::write_to millis rollover bug #195

delta-G opened this issue Nov 27, 2023 · 1 comment · Fixed by #196
Labels
conclusion: resolved Issue was resolved topic: code Related to content of the project itself type: imperfection Perceived defect in any part of project

Comments

@delta-G
Copy link
Contributor

delta-G commented Nov 27, 2023

The code in bot TwoWire::read_from and TwoWire::write_to includes these lines:

 timeout_ms = millis() + timeout_ms;
 while(millis() < timeout_ms && bus_status == WIRE_STATUS_UNSET && err == FSP_SUCCESS) {

 }

which is not safe for millis rollover. In the rare occurrence that read_from or write_to is called within timeout_ms of rollover, the code will immediately timeout. The AVR code for this is written using subtraction as is preached daily on the forum.

  startMicros = micros();
  while(TWI_MRX == twi_state){
    if((twi_timeout_us > 0ul) && ((micros() - startMicros) > twi_timeout_us)) {
      twi_handleTimeout(twi_do_reset_on_timeout);
      return 0;
    }
  }

I propose fixing the code to use subtraction like the AVR code.

@per1234 per1234 added type: imperfection Perceived defect in any part of project topic: code Related to content of the project itself labels Nov 27, 2023
@JM-FRANCE
Copy link

twi_timeout_us is a uint32_tso it's always positive - you only want to check if it's not null

  startMicros = micros();
  while(TWI_MRX == twi_state){
    if((twi_timeout_us != 0ul) && ((micros() - startMicros) > twi_timeout_us)) {
      twi_handleTimeout(twi_do_reset_on_timeout);
      return 0;
    }
  }

I guess this is for efficiency reasons, avoid the call to micros() and the subtraction and compare if it's null...

maybe the compiler is smart enough to only check for 0 rather than the sign of an unsigned variable.

@per1234 per1234 linked a pull request Nov 28, 2023 that will close this issue
delta-G added a commit to delta-G/ArduinoCore-renesas that referenced this issue Nov 28, 2023
Fixes arduino#195
Includes review from @aentinger
@per1234 per1234 added the conclusion: resolved Issue was resolved label Nov 29, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
conclusion: resolved Issue was resolved topic: code Related to content of the project itself type: imperfection Perceived defect in any part of project
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants