Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add dynamic output gpio example to demonstrate how to use AnyPin and Flex #1903

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions esp-hal/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- Added the dynamic_output_gpio example
- Added new `Io::new_no_bind_interrupt` constructor (#1861)

### Changed
Expand Down
68 changes: 68 additions & 0 deletions examples/src/bin/dynamic_output_gpio.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
//! Iterates over an array of LEDs, demonstrating how to use AnyPin and Flex to drive GPIOs.
//!
//! The following wiring is assumed:
//! - LED => GPIO0
//! - LED => GPIO1
//! - LED => GPIO2

//% CHIPS: esp32c6

#![no_std]
#![no_main]

use esp_backtrace as _;
use esp_hal::{
clock::ClockControl,
delay::Delay,
gpio::{any_pin::AnyPin, Flex, Io},
peripherals::Peripherals,
prelude::*,
system::SystemControl,
};

pub struct FlexIo<'a> {
pub gpio0: Flex<'a, AnyPin<'a>>,
pub gpio1: Flex<'a, AnyPin<'a>>,
pub gpio2: Flex<'a, AnyPin<'a>>,
}

impl<'a> FlexIo<'a> {
pub fn new(io: Io) -> Self {
FlexIo {
gpio0: Flex::new(AnyPin::new(io.pins.gpio0)),
gpio1: Flex::new(AnyPin::new(io.pins.gpio1)),
gpio2: Flex::new(AnyPin::new(io.pins.gpio2)),
}
}
pub fn get_pin(&mut self, index: u32) -> &mut Flex<'a, AnyPin<'a>> {
match index {
0 => &mut self.gpio0,
1 => &mut self.gpio1,
2 => &mut self.gpio2,
_ => panic!("No such pin"),
}
}
}

#[entry]
fn main() -> ! {
let peripherals = Peripherals::take();
let system = SystemControl::new(peripherals.SYSTEM);
let clocks = ClockControl::boot_defaults(system.clock_control).freeze();

let io = Io::new(peripherals.GPIO, peripherals.IO_MUX);
let delay = Delay::new(&clocks);

let mut flexIo = FlexIo::new(io);
// You can also use set_as_input() to use those GPIOs easily as input too
flexIo.gpio0.set_as_output();
flexIo.gpio1.set_as_output();
flexIo.gpio2.set_as_output();

loop {
for n in 0..3 {
flexIo.get_pin(n).toggle();
delay.delay_millis(250);
}
}
}