LoginSignup
10
4

More than 3 years have passed since last update.

Rustで、初めてのLチカ

Last updated at Posted at 2019-10-22

LED.JPG

Rustを勉強中のiOSエンジニアです。今回はRustでGPIOについて調べて、Lチカを試しました。Raspberry Pi Zero WHとJetson Nanoは、両方ともにLinuxベースなのでLチカできました。

LEDの割り当てはGPIOの12番です。基板上のピンアサインはGPIO表を参照してください。

Rustをインストールする

curl -sSf https://sh.rustup.rs | sh
インストール済みの場合は飛ばしてください。

ledプロジェクトを作成する

cargo new led

ledプロジェクトフォルダへ切り替える

cd led

Cargo.tomlにGPIOを追記する。

[dependencies]
sysfs_gpio = "0.5"

GPIO制御のため、Cargo.tomlに追記してファイル保存して終了します。

Lチカ・ソースコード(src/main.rs)

extern crate sysfs_gpio;

use std::thread::sleep;
use std::time::Duration;
use sysfs_gpio::Pin;
use sysfs_gpio::Direction;

const GPIO_PIN_NUM : u64 = 12;

fn main() {
    let pin = Pin::new( GPIO_PIN_NUM );

    println!("Lチカ");
    pin.with_exported( || {
        pin.set_direction( Direction::Out ).unwrap();
        loop {
            pin.set_value(0).unwrap();
            sleep(Duration::from_millis(200));
            pin.set_value(1).unwrap();
            sleep(Duration::from_millis(200));
        }
    }).unwrap();
}

srcディレクトリ下のmain.rsファイルをLチカに上書きします。

ビルド

cargo build

実行

sudo ./target/debug/led
GPIO制御は、root権限が必要なので、上記の通りです。

 Raspberry pi Zero WH GPIO表

 sysfs GPIO   name   Pin   Pin   name   sysfs GPIO 
   3.3V   1   2   5.0V   
 2   GPIO2   3   4   5.0V   
 3   GPIO3   5   6   GND   
 4   GPIO4   7   8   GPIO14   
   GND   9   10   GPIO15   
 17   GPIO17   11   12   GPIO18   18 
 27   GPIO27   13   14   GND   
 22   GPIO22   15   16   GPIO23   23 
   3.3V   17   18   GPIO24   24 
 10   GPIO10   19   20   GND   
 9   GPIO9   21   22   GPIO25   25 
 11   GPIO11   23   24   GPIO8   8 
   GND   25   26   GPIO7   7 
   DNC   27   28   DNC   
 5   GPIO5   29   30   GND   
 6   GPIO6   31   32   GPIO12   12 
 13   GPIO13   33   34   GND   
 19   GPIO19   35   36   GPIO16   16 
 26   GPIO26   37   38   GPIO20   20 
   GND   39   40   GPIO21   21 

 Jetson Nano GPIO表

 sysfs GPIO   name   Pin   Pin   name   sysfs GPIO 
   3.3V   1   2   5.0V   
   D2/SDA   3   4   5.0V   
   D3/SCL   5   6   GND   
 216   D4   7   8   D14/TXD   
    GND   9   10   D15/RXD   
 50   D17   11   12   D18   79 
 14   D27   13   14   GND   
 194   D22   15   16   D23   232 
   3.3V   17   18   D24   15 
 16   D10   19   20   GND   
 17   D9   21   22   D25   13 
 18   D11   23   24   D8   19 
    GND   25   26   D7   20 
   D0/ID_SD   27   28   D1/ID_SC   
 149   D5   29   30   GND   
 200   D6   31   32   D12   168 
 38   D13   33   34   GND   
 76   D19   35   36   D16   51 
 12   D26   37   38   D20   77 
   GND   39   40   D21   78 
10
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
4