Take 2

This time, we’ll use math to get the precise angle that the magnetic field forms with the X and Yaxes of the magnetometer.

We’ll use the atan2 function. This function returns an angle in the -PI to PI range. Thegraphic below shows how this angle is measured:

Take 2 - 图1

Although not explicitly shown in this graph the X axis points to the right and the Y axis points up.

Here’s the starter code. theta, in radians, has already been computed. You need to pick which LEDto turn on based on the value of theta.

  1. #![deny(unsafe_code)]
  2. #![no_main]
  3. #![no_std]
  4. // You'll find this useful ;-)
  5. use core::f32::consts::PI;
  6. #[allow(unused_imports)]
  7. use aux15::{entry, iprint, iprintln, prelude::*, Direction, I16x3};
  8. // this trait provides the `atan2` method
  9. use m::Float;
  10. #[entry]
  11. fn main() -> ! {
  12. let (mut leds, mut lsm303dlhc, mut delay, _itm) = aux15::init();
  13. loop {
  14. let I16x3 { x, y, .. } = lsm303dlhc.mag().unwrap();
  15. let _theta = (y as f32).atan2(x as f32); // in radians
  16. // FIXME pick a direction to point to based on `theta`
  17. let dir = Direction::Southeast;
  18. leds.iter_mut().for_each(|led| led.off());
  19. leds[dir].on();
  20. delay.delay_ms(100_u8);
  21. }
  22. }

Suggestions/tips:

  • A whole circle rotation equals 360 degrees.
  • PI radians is equivalent to 180 degrees.
  • If theta was zero, what LED would you turn on?
  • If theta was, instead, very close to zero, what LED would you turn on?
  • If theta kept increasing, at what value would you turn on a different LED?