Skip to content

Instantly share code, notes, and snippets.

@inre
Created July 31, 2015 20:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inre/ff7be9aa272f122f2dda to your computer and use it in GitHub Desktop.
Save inre/ff7be9aa272f122f2dda to your computer and use it in GitHub Desktop.
Blink led on raspberry pi 9 (Rust lang)
#![feature(core_intrinsics)]
#[warn(dead_code)]
//#[warn(unused_assignments)]
extern crate mmap;
extern crate libc;
use libc::*;
use std::ffi::CString;
use std::path::Path;
use mmap::{MemoryMap,MapOption};
use std::os::unix::io::AsRawFd;
use std::fs::OpenOptions;
use std::intrinsics::offset;
use std::thread;
const BCM2708_PERI_BASE: usize = 0x20000000;
const GPIO_BASE: usize = BCM2708_PERI_BASE + 0x200000; /* GPIO controller */
const PAGE_SIZE: usize = 4*1024;
const BLOCK_SIZE: usize = 4*1024;
macro_rules! inp_gpio {
($gpio:expr, $pin:expr) => {
unsafe {
let out_pin = $pin;
let p = std::intrinsics::offset($gpio.data() as *const u32, out_pin/10) as *mut u32;
println!("{:b}", *p);
*p &= !(7 << ( (out_pin % 10) * 3 ));
println!("{:b}", *p);
}
}
}
macro_rules! out_gpio {
($gpio:expr, $pin:expr) => {
unsafe {
let out_pin = $pin;
let p = std::intrinsics::offset($gpio.data() as *const u32, out_pin/10) as *mut u32;
println!("{:b}", *p);
*p |= 1 << ( (out_pin % 10) * 3 );
println!("{:b}", *p);
}
}
}
fn main() {
let gpio;
/* Map GPIO ports into memory */
{
//let path = &b"/dev/mem"[..];
//let path = CString::new(path).unwrap();
let mem = OpenOptions::new().read(true).write(true).open("/dev/mem").unwrap();
let mem_fd = mem.as_raw_fd();
//let mem_fd = unsafe {
// libc::open(path.as_ptr(), libc::O_RDWR | libc::O_SYNC, 0o666)
//};
gpio = MemoryMap::new(4*1024, &[
MapOption::MapReadable,
MapOption::MapWritable,
MapOption::MapFd(mem_fd),
MapOption::MapOffset(GPIO_BASE),
MapOption::MapNonStandardFlags(libc::MAP_SHARED)
]).unwrap();
}
/* Set pin 17 as output */
inp_gpio!(gpio, 17);
out_gpio!(gpio, 17);
/* Set pin 17 to high */
unsafe {
let gpio_set = std::intrinsics::offset(gpio.data() as *const u32, 7) as *mut u32;
*gpio_set = 1<<17;
println!("{:b}", *gpio_set);
}
thread::sleep_ms(4000);
unsafe {
let gpio_clr = std::intrinsics::offset(gpio.data() as *const u32, 10) as *mut u32;
*gpio_clr = 1<<17;
println!("{:b}", *gpio_clr);
}
thread::sleep_ms(4000);
println!("end.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment