Any calculations x / y
(where both operands are 32bit floats) yield 0 in Rust when I compile for the AVR ISA. Specifically, I use avr_hal for interacting with the Arduino. I read unsigned integer values, convert them to floating point numbers, divide to get a relative quantity, and multiply with another number (such that f*(x/y) > 1
) and cast back to an unsigned integer:
let mut read_value: u16 = 0;
loop {
read_value = pot.analog_read(&mut adc); // between 0 and 1023, potentiometer input
let relative: f32 = (read_value as f32) / 1023.0; // between 0.0 and 1.0
let v: f32 = relative * 1800.0; // > 1.0 in most cases
ufmt::uwriteln!("{}", v as u16); // always 0
}
This problem doesn't seem to occur with seemingly equivalent C++ code:
float read_value = 0;
void loop() {
read_value = analogRead(A0);
float relative = read_value / 1023.0f;
float v = relative * 1000.0;
Serial.println(static_cast<int>(v));
}
What exactly is this Rust-quirk?