arduino / arduino/ArduinoCore-avr

Comparing an unsigned it fails if it is at 0xFFFF.

Open
#115 15 comments 0 reactions 0 assignees View on GitHub
Dominant language
C
Stars
1.5k
Forks
1.1k
PR merge metrics
No merged PRs in 30d

Description

Code snippets:
```
unsigned int toff; // also tried with uint16_t , same results
void setup(){ // .... .... .... ....
```
1) `toff=EEPROM.read(Toff)+256*EEPROM.read(Toff+1);if ((toff)>30000) toff=1500;`

2) `toff=EEPROM.read(Toff)+256*EEPROM.read(Toff+1);if ((toff-1)>30000) toff=1500;`

The idea is to put a sensible default in RAM if the EEPROM was not programmed.

Problem: after the 1st version of the code, toff==65535==0xFFFF ; Apparently the comparison fails with FFFF.

(The 2nd variant with the -1 hack was contributed by a colleague whom I asked to debug this.)

Checking the assembly code with avr-objdump shows only one difference in the 2 codes, the line shown with >>>>.
```
1898: 90 93 d6 02 sts 0x02D6, r25 ; 0x8002d6
189c: 80 93 d5 02 sts 0x02D5, r24 ; 0x8002d5
﹥﹥﹥﹥ 18a0: 01 97 sbiw r24, 0x01 ; 1
18a2: 81 33 cpi r24, 0x31 ; 49
18a4: 95 47 sbci r25, 0x75 ; 117
18a6: 30 f0 brcs .+12 ; 0x18b4
18a8: 8c e4 ldi r24, 0x4C ; 76
18aa: 94 e0 ldi r25, 0x04 ; 4
18ac: 90 93 d6 02 sts 0x02D6, r25 ; 0x8002d6
18b0: 80 93 d5 02 sts 0x02D5, r24 ; 0x8002d5
```

Not sure why the comparison fails when r24==0xFF and r25==0xFF but passes when r24=0xFE.
And if it is an AVR issue (the MCU used was an Atmega324A with the MightyCore library from MCUDUDE, using LTO), then the compiler should probably adjust for this.

Or is it an optimization issue?

At any rate, I fixed my project now with the hack, but it is still scary that one cannot compare for some input values.

If this is deemed a non-issue (due to it happening on 324A) is there any official way to prevent it other than the -1 which could fail on a zero?

Contributor guide

No contributing guide indexed for this repository

Research direction

Start by reproducing the comparison on the ATmega324A setup described, including MightyCore and LTO, then compare the generated avr-objdump output for both snippets. Done means determining whether the behavior is caused by the AVR, compiler, or optimization and documenting or fixing the issue if it is in ArduinoCore-avr.

Written by the indexing model from the issue text.

Assessment

Tech stack
c
Domain
embedded-iot
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.