Generic set gpio state

This commit is contained in:
2025-05-20 10:14:18 +02:00
parent 87fa14257b
commit 209b4babb7
2 changed files with 22 additions and 8 deletions

View File

@@ -4,7 +4,19 @@ const GPFSEL_BASE: u32 = 0x3F20_0000;
const GPSET_BASE: u32 = 0x3F20_001C; const GPSET_BASE: u32 = 0x3F20_001C;
const GPCLR_BASE: u32 = 0x3F20_0028; const GPCLR_BASE: u32 = 0x3F20_0028;
unsafe fn set_gpio_to_output(gpio: u8) -> Result<(), &'static str> { #[repr(u32)]
pub enum GPIOState {
input = 0b000,
output = 0b001,
alternative0 = 0b100,
alternative1 = 0b101,
alternative2 = 0b110,
alternative3 = 0b111,
alternative4 = 0b011,
alternative5 = 0b010,
}
pub unsafe fn set_gpio_state(gpio: u8, state: GPIOState) -> Result<(), &'static str> {
if gpio > 53 { if gpio > 53 {
return Err("GPIO out of range"); return Err("GPIO out of range");
} }
@@ -18,16 +30,15 @@ unsafe fn set_gpio_to_output(gpio: u8) -> Result<(), &'static str> {
let mask = !(0b111 << register_offset); let mask = !(0b111 << register_offset);
let cleared = current & mask; let cleared = current & mask;
let new_val = cleared | (0b001 << register_offset); let new_val = cleared | ((state as u32) << register_offset);
core::ptr::write_volatile(register_addr as *mut u32, new_val); core::ptr::write_volatile(register_addr as *mut u32, new_val);
Ok(()) Ok(())
} }
pub fn pull_up_gpio(gpio: u8) -> Result<(), &'static str> { pub fn gpio_high(gpio: u8) -> Result<(), &'static str> {
unsafe { unsafe {
uart::print("Pull Up\n"); uart::print("Pull Up\n");
set_gpio_to_output(29)?;
let register_index = gpio / 32; let register_index = gpio / 32;
let register_offset = gpio % 32; let register_offset = gpio % 32;
@@ -38,7 +49,7 @@ pub fn pull_up_gpio(gpio: u8) -> Result<(), &'static str> {
Ok(()) Ok(())
} }
pub fn pull_down_gpio(gpio: u8) -> Result<(), &'static str> { pub fn gpio_low(gpio: u8) -> Result<(), &'static str> {
unsafe { unsafe {
uart::print("Pull Down\n"); uart::print("Pull Down\n");

View File

@@ -4,7 +4,7 @@
use core::{arch::asm, panic::PanicInfo}; use core::{arch::asm, panic::PanicInfo};
use gpio::{pull_down_gpio, pull_up_gpio}; use gpio::{gpio_high, gpio_low, set_gpio_state};
mod gpio; mod gpio;
mod uart; mod uart;
@@ -26,15 +26,18 @@ pub unsafe extern "C" fn _start() {
#[no_mangle] #[no_mangle]
extern "C" fn main() { extern "C" fn main() {
uart::configure_uart(); uart::configure_uart();
unsafe {
let _ = set_gpio_state(29, gpio::GPIOState::output);
}
// Delay so clock speed can stabilize // Delay so clock speed can stabilize
unsafe { delay(50000) } unsafe { delay(50000) }
uart::print("Hello World!\n"); uart::print("Hello World!\n");
loop { loop {
let _ = pull_up_gpio(29); let _ = gpio_high(29);
unsafe { delay(1_000_000) } unsafe { delay(1_000_000) }
let _ = pull_down_gpio(29); let _ = gpio_low(29);
unsafe { delay(1_000_000) } unsafe { delay(1_000_000) }
} }
} }