|
| 1 | +# Performing math functionality with `#[no_std]` |
| 2 | + |
| 3 | +If you want to perform math related functionality like calculating the squareroot or |
| 4 | +the exponential of a number and you have the full standard library available, your code |
| 5 | +might look like this: |
| 6 | + |
| 7 | +```rs |
| 8 | +//! Some mathematical functions with standard support available |
| 9 | + |
| 10 | +fn main() { |
| 11 | + let float: f32 = 4.82832; |
| 12 | + let floored_float = float.floor(); |
| 13 | + |
| 14 | + let sqrt_of_four = floored_float.sqrt(); |
| 15 | + |
| 16 | + let sinus_of_four = floored_float.sin(); |
| 17 | + |
| 18 | + let exponential_of_four = floored_float.exp(); |
| 19 | + println!("Floored test float {} to {}", float, floored_float); |
| 20 | + println!("The square root of {} is {}", floored_float, sqrt_of_four); |
| 21 | + println!("The sinus of four is {}", sinus_of_four); |
| 22 | + println!( |
| 23 | + "The exponential of four to the base e is {}", |
| 24 | + exponential_of_four |
| 25 | + ) |
| 26 | +} |
| 27 | +``` |
| 28 | + |
| 29 | +Without standard library support, these functions are not available. |
| 30 | +An external crate like [`libm`](https://crates.io/crates/libm) can be used instead. The example code |
| 31 | +would then look like this: |
| 32 | + |
| 33 | +```rs |
| 34 | +#![no_main] |
| 35 | +#![no_std] |
| 36 | + |
| 37 | +use panic_halt as _; |
| 38 | + |
| 39 | +use cortex_m_rt::entry; |
| 40 | +use cortex_m_semihosting::{debug, hprintln}; |
| 41 | +use libm::{exp, floorf, sin, sqrtf}; |
| 42 | + |
| 43 | +#[entry] |
| 44 | +fn main() -> ! { |
| 45 | + let float = 4.82832; |
| 46 | + let floored_float = floorf(float); |
| 47 | + |
| 48 | + let sqrt_of_four = sqrtf(floored_float); |
| 49 | + |
| 50 | + let sinus_of_four = sin(floored_float.into()); |
| 51 | + |
| 52 | + let exponential_of_four = exp(floored_float.into()); |
| 53 | + hprintln!("Floored test float {} to {}", float, floored_float).unwrap(); |
| 54 | + hprintln!("The square root of {} is {}", floored_float, sqrt_of_four).unwrap(); |
| 55 | + hprintln!("The sinus of four is {}", sinus_of_four).unwrap(); |
| 56 | + hprintln!( |
| 57 | + "The exponential of four to the base e is {}", |
| 58 | + exponential_of_four |
| 59 | + ) |
| 60 | + .unwrap(); |
| 61 | + // exit QEMU |
| 62 | + // NOTE do not run this on hardware; it can corrupt OpenOCD state |
| 63 | + // debug::exit(debug::EXIT_SUCCESS); |
| 64 | + |
| 65 | + loop {} |
| 66 | +} |
| 67 | +``` |
| 68 | + |
| 69 | +If you need to perform more complex operations like DSP signal processing or advanced linear |
| 70 | +algebra on your MCU, the following crates might help you |
| 71 | + |
| 72 | +- [CMSIS DSP library binding](https://github.com/jacobrosenthal/cmsis-dsp-sys) |
| 73 | +- [`micromath`](https://github.com/tarcieri/micromath) |
| 74 | +- [`microfft`](https://crates.io/crates/microfft) |
| 75 | +- [`nalgebra`](https://github.com/dimforge/nalgebra) |
0 commit comments