Skip to content

Conversation

@rdon-key
Copy link
Contributor

Summary

This PR fixes the implementation of ReadTemperature for the RP2040 target.
The previous code used int32 intermediates, which caused arithmetic overflow when the ADC voltage deviated more than ±56 mV from 706 mV.
Since the internal temperature sensor of the RP2040 typically operates between 537 mV and 821 mV (-40°C to 125°C), overflow occurred in normal conditions.
As a result, the function sometimes returned corrupted values such as -31.8°C.

Changes

  • Promote intermediate calculations in ReadTemperature (RP2040) to int64.
  • Keep the return type int32 (milli-°C) for API compatibility.

Before (buggy)

temperature: 32.8℃
temperature: 32.8℃
temperature: -31.8℃
temperature: -31.8℃
...

After (fixed)

temperature: 31.8℃
temperature: 32.8℃
temperature: 32.8℃
temperature: 32.8℃
temperature: 33.7℃
...

Impact

  • Prevents overflow in the normal RP2040 sensor range (-40°C to 125°C).
  • Produces stable, monotonic readings without spurious negative jumps.
  • No breaking API change.

@rdon-key
Copy link
Contributor Author

Diff int32 to int64

v_hex mV orig_mC orig_degC ref_mC ref_degC diff monoBreak
0x02B8127F 696.072250 -32768 -32.768 32768 32.768 true false
0x02B81280 696.072266 -32768 -32.768 32768 32.768 true false
0x02B81281 696.072281 -32768 -32.768 32768 32.768 true false
0x02B81282 696.072296 32767 32.767 32767 32.767 false true
0x02B81283 696.072311 32767 32.767 32767 32.767 false false
0x02B81284 696.072327 32767 32.767 32767 32.767 false false
0x02B81285 696.072342 32767 32.767 32767 32.767 false false
0x02B81286 696.072357 32767 32.767 32767 32.767 false false

Copy link
Member

@deadprogram deadprogram left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for looking into this @rdon-key

@deadprogram deadprogram merged commit e29e583 into tinygo-org:dev Sep 19, 2025
17 of 19 checks passed
@rdon-key rdon-key deleted the fix/rp2-internal-temperature branch September 25, 2025 08:03
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.

2 participants