Take 1

What’s the simplest way in which we can implement the LED compass? Even if it’s not perfect.

For starters, we’d only care about the X and Y components of the magnetic field because when youlook at a compass you always hold it in horizontal position thus the compass is in the XY plane.

For example, what LED would you turn on in the following case. EMF stands for Earth’s Magnetic Fieldand green arrow has the direction of the EMF (it points north).

Take 1 - 图1

Take 1 - 图2

In the previous example, the magnetic field was in the first quadrant (x and y were positive) and itmade sense to turn on the SouthEast LED. Similarly, we could turn a different LED if the magneticfield was in a different quadrant.

Let’s try that logic. Here’s the starter code:

  1. #![deny(unsafe_code)]
  2. #![no_main]
  3. #![no_std]
  4. #[allow(unused_imports)]
  5. use aux15::{entry, iprint, iprintln, prelude::*, Direction, I16x3};
  6. #[entry]
  7. fn main() -> ! {
  8. let (mut leds, mut lsm303dlhc, mut delay, _itm) = aux15::init();
  9. loop {
  10. let I16x3 { x, y, .. } = lsm303dlhc.mag().unwrap();
  11. // Look at the signs of the X and Y components to determine in which
  12. // quadrant the magnetic field is
  13. let dir = match (x > 0, y > 0) {
  14. // Quadrant ???
  15. (true, true) => Direction::Southeast,
  16. // Quadrant ???
  17. (false, true) => panic!("TODO"),
  18. // Quadrant ???
  19. (false, false) => panic!("TODO"),
  20. // Quadrant ???
  21. (true, false) => panic!("TODO"),
  22. };
  23. leds.iter_mut().for_each(|led| led.off());
  24. leds[dir].on();
  25. delay.delay_ms(1_000_u16);
  26. }
  27. }

There’s a Direction enum in the led module that has 8 variants named after the cardinal points:North, East, Southwest, etc. Each of these variants represent one of the 8 LEDs in thecompass. The Leds value can be indexed using the Direction enum; the result of indexing is theLED that points in that Direction.