Code works fine copy/pasted into my main.rs, but is ignored when run from its own external crate

95 Views Asked by At

tl;dr I'm trying to figure out why the avr-delay::delay function doesn't cause any delay when imported as an external crate, but when copy/pasting the code from avr-delay/src/lib.rs into my main.rs, it all works as expected and creates the 1000ms delays I was expecting. Source code for avr-delay here and my modified and working correctly avr-rust/blink code is here

I'm trying to learn Arduino the hard way, with Rust, and I'm doing a sort of Hello World by making an LED blink. I've gotten the light to blink at 1000ms intervals just as expected when I copy paste the contents of avr-delay's lib.rs into my main.rs, but when I import the avr-delay crate and use it that way, the delay is barely perceptible.

I've ensured I'm doing a 1:1 test by cloning the avr-delay repo and importing the local copy in my Cargo.toml, and I've tried hardcoding the CPU frequency on this line in my local copy of avr-delay just in case it was a problem with reading the env var that I'm setting or something.

I'm just really confused why the exact same code works in my main.rs but not in its own crate? Since this seems to be an issue with the build or Cargo.toml, here's how I'm actually building the bin. Could be related? I'm using the same command to build every time:

cargo +nightly-2021-01-07 build -Z build-std=core --target avr-atmega328p.json --release --verbose

Also worth mentioning that I'm playing with a knockoff Arduino, but it's still the same microcontroller (atmega328p) as an Arduino Uno, and since I can get the blinking to work sometimes it makes me think that's not the issue either.

Any help appreciated, I know this is a really specific question but I'm hoping there's something about the build or Cargo that I'm not understanding, since the code itself seems to be good.

1

There are 1 best solutions below

0
On BEST ANSWER

The solution was to add #[inline(always)] to the functions in avr-delay, or add lto = true to my project's Cargo.toml. The delay code simply doesn't work when not inlined. I'm still not fully understanding why, but I'm guessing some of the low-level stuff didn't work when not inlined.