avr-hal: Incorrect ADC readings after toolchain bump

Hi! We’re using avr-hal and avr-device with an atmega164pa uC.

We tried bumping our Rust toolchain, as you have done with 2eb28fa3024ecbf9898c8e900e744d1201ceffca. This causes incorrect ADC readings. We’ve literally changed nothing else, and suddenly an analog_read on Pin<Analog, PA0> returns usually 0, sometimes 1, but never a value in the hundreds, as would be expected in our situation.

I guess it could be due to some unsafe weirdness in our codebase, but I mean the ADC is set up normally, and then it’s just a call to analog_read, really. Not sure how much of our codebase I can share; I could probably build a minimal example to show the behavior. Just figured I’d ask first if anyone has any ideas about this. Works just fine on nightly-2023-12-28.

Thanks!

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Comments: 29 (10 by maintainers)

Commits related to this issue

Most upvoted comments

I don’t think the write_read implementation should create any problems as that is explicitly supported. I also don’t see why writing immediately after reading should cause any problems, especially because you’re only running it at 100kHz while the MCP supports up to 1.7MHz.

So even if the issue is resolved by changing the I2C code, I think it’s a good idea to check whether the root cause might be something else (similar to how inlining prevents/causes the issue).

That all sounds pretty plausible. Thank you so much for all that effort! I will try to play around with the I2C, I suppose. Will start with your suggestion, then maybe check if I can’t get our logic analyzer connected to the hardware. I think the earliest I can look at this will be next week, though.

Alright, I’m leaning towards a hardware quirk here - which I know sounds a bit crazy, but hear me out 😄

I’ve been looking at the firmware, analyzing the assembly by hand - and while the output is a bit different between toolchain versions, that’s mostly because LLVM does a better job at inlining constant expressions within update_register_bit() now (the calls to register_for_pin(), bit_for_pin() etc. get computed at compile-time).

Overall the newest binary looks correct, I’d say.

Since static eye-analysis can only get one so far, I’ve took a moment to add TWI (aka I2C) support to avr-tester, so that I could simulate the firmware together with a basic, fake mcp23017 (which does basically nothing here besides responding to the register reads and writes):

use avr_tester::AvrTester;

#[test]
fn test() {
    let mut avr = AvrTester::atmega164pa()
        .with_clock(10_000_000)
        .load("/home/pwy/t/projects/adc-read-compiler-bug/target/avr-atmega164pa/release/adc-read-compiler-bug.elf");

    avr.twi0().attach_slave_fn({
        let mut reg = None;
        let mut regs = [0; 256];

        move |packet| {
            if packet.is_start() {
                return Some(packet.respond_ack());
            }

            if packet.is_stop() {
                return Some(packet.respond_ack());
            }

            if packet.is_write() {
                if let Some(dev_reg) = reg.take() {
                    println!("write_register({}, {})", dev_reg, packet.data);

                    regs[dev_reg] = packet.data;
                } else {
                    reg = Some(packet.data as usize);
                }

                return Some(packet.respond_ack());
            }

            if packet.is_read() {
                let reg = reg.take().expect("No register picked");
                let reg_val = regs[reg];

                println!("read_register({}) = {}", reg, reg_val);

                return Some(packet.respond_data(reg_val));
            }

            None
        }
    });

    avr.run_for_ms(1500);
    avr.pins().pa0().set_high();
    avr.run_for_ms(1500);

    panic!("{}", avr.uart0().read::<String>());
}

… and the output looks exactly the same on both the older and the newer firmware:

test:
write_register(0, 255)
write_register(1, 255)
read_register(0) = 255
write_register(0, 253)
read_register(20) = 0
write_register(18, 2)
read_register(0) = 253
write_register(0, 189)
read_register(12) = 0
write_register(12, 64)
read_register(20) = 0
write_register(18, 64)

uart:
BUG
BUG
BUG
OK
OK

Now, of course it’s not a definite test - simavr could be emulating something differently (I know of https://github.com/buserror/simavr/issues/453, for which I’m applying a workaround within avr-tester), but I suspect that maybe the culprit lies within… timing?

My guess is that because the newer code uses substantially less instructions between the calls to MCP23017::read_register() and MCP23017::write_register(), maybe that device doesn’t have enough time to retrieve/process the data, which in turn causes bus errors/whatever, which happen to affect the PA0 pin? (not sure how your board looks like)

Another totally random observation is in regards to I2c::write_read(), called internally inside MCP23017 - it performs write+read in one transaction:

https://github.com/Rahix/avr-hal/blob/15080aa41e726bc720adf36ce0fc5a030390c822/avr-hal-generic/src/i2c.rs#L400

… which I guess makes sense, but for instance Arduino implementations usually (seem to) use two separate transactions:

https://github.com/blemasle/arduino-mcp23017/blob/02076b387157db25d3ca30b7e8b089c6da52c563/src/MCP23017.cpp#L153

Maybe it would be worthwhile to check whether we shouldn’t be doing two txs as well, like:

fn write_read(
    &mut self,
    address: u8,
    bytes: &[u8],
    buffer: &mut [u8],
) -> Result<(), Self::Error> {
    self.p.raw_start(address, Direction::Write)?;
    self.p.raw_write(bytes)?;
    self.p.raw_stop()?;
    self.p.raw_start(address, Direction::Read)?;
    self.p.raw_read(buffer)?;
    self.p.raw_stop()?;
    Ok(())
}

Thanks for the thorough report!

I’m going to NixCon tomorrow, so I won’t be able to take a look at it over the weekend, but I’ll try to take a stab the next week. Having all this here should be sufficient to reproduce the issue locally (or at least be able to compare the differences in generated assembly).

If you find anything else, of course please do write it down 😄

Small correction: the channel parameter in rust-toolchain.toml doesn’t seem to match the output of rustc --version.

So rustc --version yields:

  • working toolchain: rustc 1.77.0-nightly (f688dd684 2024-01-04)
  • bugged toolchain: rustc 1.77.0-nightly (595bc6f00 2024-01-05)

edit (don’t want to spam with too many comments): both versions use the same LLVM version, 17.0.6. The git log in the rust project between the two versions also does not show a change to the llvm-project submodule. So I’m guessing it’s fair to conclude that this is somehow caused by a change in rust itself.

Looks like it’s still broken. Digital reads still always return false, and analog reads mostly 0, sometimes 1 or 2. The nightly-2023-12-28 still gives correct-looking values in the 800s (analog read) and always true (digital read) on my hardware here.

$ rustc --version
rustc 1.84.0-nightly (27861c429 2024-10-13)