编译完成后,可在target/armv7-unknown-linux-gnueabihf/debug/examples 目录下看到生成的可执行文件blinky,将该文件复制到开发板中,加入可执行权限。
- $ git clone github.com/rust-embedded/rust-sysfs-gpio
- $ cd rust-sysfs-gpio
输入./blinky,可看到提示Usage: ./blinky
- $ cargo build --example blinky --target armv7-unknown-linux-gnueabihf
可看到对应管脚电平高低变化5次。
- # ./blinky 26 10000 100
下面解释一下执行过程,
- fn blink_my_led(led: u64, duration_ms: u64, period_ms: u64) -> sysfs_gpio::Result<()> {
- let my_led = Pin::new(led);
- my_led.with_exported(|| {
- my_led.set_direction(Direction::Low)?;
- let iterations = duration_ms / period_ms / 2;
- for _ in 0..iterations {
- my_led.set_value(0)?;
- sleep(Duration::from_millis(period_ms));
- my_led.set_value(1)?;
- sleep(Duration::from_millis(period_ms));
- }
- my_led.set_value(0)?;
- Ok(())
- })
- }
构建一个Pin
- let my_led = Pin::new(led);
导出GPIO, 想当于执行 echo N > /sys/class/gpio/export, 这里使用了闭包的语法
- my_led.with_exported(|| {
- ....
设置端口为输出,并输出低电平
- my_led.set_direction(Direction::Low)?
设置端口输出高电平引用: my_led.set_value(1)?
- extern crate sysfs_gpio;
- use sysfs_gpio::{Direction, Pin};
- use std::time::Duration;
- use std::thread::sleep;
- use std::env;
- struct Arguments {
- pin: u64,
- duration_ms: u64,
- period_ms: u64,
- }
- // Export a GPIO for use. This will not fail if already exported
- fn blink_my_led(led: u64, duration_ms: u64, period_ms: u64) -> sysfs_gpio::Result<()> {
- let my_led = Pin::new(led);
- my_led.with_exported(|| {
- my_led.set_direction(Direction::Low)?;
- let iterations = duration_ms / period_ms / 2;
- for _ in 0..iterations {
- my_led.set_value(0)?;
- sleep(Duration::from_millis(period_ms));
- my_led.set_value(1)?;
- sleep(Duration::from_millis(period_ms));
- }
- my_led.set_value(0)?;
- Ok(())
- })
- }
- fn print_usage() {
- println!("Usage: ./blinky
");
- }
- fn get_args() -> Option
{
- let args: Vec
= env::args().collect();
- if args.len() != 4 {
- return None;
- }
- let pin = match args[1].parse::
() {
- Ok(pin) => pin,
- Err(_) => return None,
- };
- let duration_ms = match args[2].parse::
() {
- Ok(ms) => ms,
- Err(_) => return None,
- };
- let period_ms = match args[3].parse::
() {
- Ok(ms) => ms,
- Err(_) => return None,
- };
- Some(Arguments {
- pin: pin,
- duration_ms: duration_ms,
- period_ms: period_ms,
- })
- }
- fn main() {
- match get_args() {
- None => print_usage(),
- Some(args) => {
- match blink_my_led(args.pin, args.duration_ms, args.period_ms) {
- Ok(()) => println!("Success!"),
- Err(err) => println!("We have a blinking problem: {}", err),
- }
- }
- }
- }
更多回帖