简体   繁体   中英

How do you read or write to GPIO pins on a Raspberry Pi 4 without using a high-level library?

I'm attempting this Rust, but the code is segfaulting:

unsafe {
    const PERIPH_BASE: u32 = 0xFE000000;
    const GPIO_BASE: u32 = PERIPH_BASE + 0x00200000;

    // Turn on pin GPIO 24
    ptr::write_volatile(GPIO_BASE as *mut u32, 1 << 24);
}

I'm suspicious this is due to using the wrong address. The only info on the subject I've found is a RP forum post. I'm unable to find info in the RP4 datasheet, and can't find a manual for the Broadcom chipset.

I'm running this code on Raspian on a Raspberry Pi SBC. I'm attempting to generalize the code to make it easier to port to true embedded later, hence why I am avoiding libraries.

I've looked through rppal and embedded-hal, but was surprised to not find the solution. I've looked through every file in the gpio module 's code. mem.rs and ioctl.rs look the closest, but I've been unable to find it.

You're writing directly into the process address space. I think you might have more success writing directly to physical memory. Here is how RPPAL does it :

let mem_file = OpenOptions::new()
    .read(true)
    .write(true)
    .custom_flags(O_SYNC)
    .open(PATH_DEV_MEM)?;

// Memory-map /dev/mem at the appropriate offset for our SoC
let mem_ptr = unsafe {
    libc::mmap(
        ptr::null_mut(),
        GPIO_MEM_SIZE,
        PROT_READ | PROT_WRITE,
        MAP_SHARED,
        mem_file.as_raw_fd(),
        (device_info.peripheral_base() + device_info.gpio_offset()) as off_t,
    )
};

You can access physical memory at /dev/mem in Raspbian but you might need root.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM