Skip to content

Fix for off-by-one in get_max_duty()#959

Merged
jbeaurivage merged 2 commits intoatsamd-rs:masterfrom
codepainters:get_max_duty_fix
Jan 13, 2026
Merged

Fix for off-by-one in get_max_duty()#959
jbeaurivage merged 2 commits intoatsamd-rs:masterfrom
codepainters:get_max_duty_fix

Conversation

@codepainters
Copy link
Copy Markdown
Contributor

Summary

This PR fixes off-by-one issue in TC/TCC get_max_duty() function, for details see #911.

Change verified with Adafruit ItsiBitsy M4 and Sparkfun ATSAMD21G Mini boards.

@jbeaurivage jbeaurivage linked an issue Nov 18, 2025 that may be closed by this pull request
@jbeaurivage
Copy link
Copy Markdown
Contributor

Thanks @codepainters. However I would suggest, if we want the functions to keep returning u16s, to use saturating_add() instead of the regular + operator to cover the case where CC == u16::MAX. What do you think?

@codepainters
Copy link
Copy Markdown
Contributor Author

Hmm, fair point. Actually it's quite interesting what the chip actually do if 0 is used as a duty cycle value, let me check the datasheet (and perhaps the hardware).

@codepainters
Copy link
Copy Markdown
Contributor Author

Finally found a moment to take a look, I've done some experiments with ItsyBits M4.

I've tried setting maximum period (2^16 1) and try various duty cycle values (CC1 register):

  • 0 - output constantly low
  • 2^16 - 1 - gives 100% - 1 tick (as expected)

So, with maximum period value it is not possible to get 100% PWM.

All that said, I guess that saturating add is a good approach here (the configuration with maximum period is somewhat pathological anyway).

@jbeaurivage
Copy link
Copy Markdown
Contributor

Sounds good, if you just want to make that change, I can get this merged.

@codepainters
Copy link
Copy Markdown
Contributor Author

Just added saturating_add() (and rebased on master branch).

Note: I only added saturating_add() for TC timer, where CC0 register is 16-bit and return type is u16. For TCC, PER is 24-bit and return type is u32, so there's no overflow possibility.

@jbeaurivage jbeaurivage merged commit 09a2188 into atsamd-rs:master Jan 13, 2026
109 checks passed
@github-actions github-actions Bot mentioned this pull request Jan 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TccPwm::get_max_duty() is -1 too small

2 participants