Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

その2

今回は、磁場が磁力計の X 軸と Y 軸となす角度を正確に求めるために、数学を使います。

atan2 関数を使います。この関数は、-PI から PI の範囲の角度を返します。以下の 図は、この角度がどのように測定されるかを示しています:

この図では明示的には示されていませんが、X 軸は右を向き、Y 軸は上を向いています。

これがスターターコードです。ラジアン単位の theta は、すでに計算されています。theta の値に基づいて、どの LED を点灯するかを選ぶ必要があります。

#![deny(unsafe_code)]
#![no_main]
#![no_std]

// これは便利ですよ ;-)
use core::f32::consts::PI;

#[allow(unused_imports)]
use aux15::{entry, iprint, iprintln, prelude::*, switch_hal::OutputSwitch, Direction, I16x3};
// このトレイトは `atan2` メソッドを提供します
use m::Float;

#[entry]
fn main() -> ! {
    let (leds, mut lsm303dlhc, mut delay, _itm) = aux15::init();
    let mut leds = leds.into_array();

    loop {
        let I16x3 { x, y, .. } = lsm303dlhc.mag().unwrap();

        let _theta = (y as f32).atan2(x as f32); // ラジアン単位

        // FIXME `theta` の値に基づいて指す方向を選んでください
        let dir = Direction::Southeast;

        leds.iter_mut().for_each(|led| led.off().unwrap());
        leds[dir as usize].on().unwrap();

        delay.delay_ms(100_u8);
    }
}

提案 / ヒント:

  • 円を 1 周すると 360 度です。
  • PI ラジアンは 180 度に相当します。
  • theta が 0 なら、どの LED を点灯しますか?
  • 代わりに theta が 0 に非常に近い値なら、どの LED を点灯しますか?
  • theta が増え続けるとしたら、どの値で別の LED を点灯しますか?