Performing math functionality with #[no_std]

If you want to perform math related functionality like calculating the squareroot or the exponential of a number and you have the full standard library available, your code might look like this:

  1. //! Some mathematical functions with standard support available
  2. fn main() {
  3. let float: f32 = 4.82832;
  4. let floored_float = float.floor();
  5. let sqrt_of_four = floored_float.sqrt();
  6. let sinus_of_four = floored_float.sin();
  7. let exponential_of_four = floored_float.exp();
  8. println!("Floored test float {} to {}", float, floored_float);
  9. println!("The square root of {} is {}", floored_float, sqrt_of_four);
  10. println!("The sinus of four is {}", sinus_of_four);
  11. println!(
  12. "The exponential of four to the base e is {}",
  13. exponential_of_four
  14. )
  15. }

Without standard library support, these functions are not available. An external crate like libm can be used instead. The example code would then look like this:

  1. #![no_main]
  2. #![no_std]
  3. use panic_halt as _;
  4. use cortex_m_rt::entry;
  5. use cortex_m_semihosting::{debug, hprintln};
  6. use libm::{exp, floorf, sin, sqrtf};
  7. #[entry]
  8. fn main() -> ! {
  9. let float = 4.82832;
  10. let floored_float = floorf(float);
  11. let sqrt_of_four = sqrtf(floored_float);
  12. let sinus_of_four = sin(floored_float.into());
  13. let exponential_of_four = exp(floored_float.into());
  14. hprintln!("Floored test float {} to {}", float, floored_float).unwrap();
  15. hprintln!("The square root of {} is {}", floored_float, sqrt_of_four).unwrap();
  16. hprintln!("The sinus of four is {}", sinus_of_four).unwrap();
  17. hprintln!(
  18. "The exponential of four to the base e is {}",
  19. exponential_of_four
  20. )
  21. .unwrap();
  22. // exit QEMU
  23. // NOTE do not run this on hardware; it can corrupt OpenOCD state
  24. // debug::exit(debug::EXIT_SUCCESS);
  25. loop {}
  26. }

If you need to perform more complex operations like DSP signal processing or advanced linear algebra on your MCU, the following crates might help you