esp-rs / esp32-hal

A hardware abstraction layer for the esp32 written in Rust.
Apache License 2.0
193 stars 28 forks source link

Add a downgrade mechanism so GPIOs and Timers can be stored in arrays #66

Open D1plo1d opened 3 years ago

D1plo1d commented 3 years ago

This is a feature request to add a function similar to https://docs.rs/stm32f1xx-hal/0.7.0/stm32f1xx_hal/gpio/gpioa/struct.PA1.html#method.downgrade to allow users to create arrays of structs that include GPIO pins and Timers in their type on the stack / without needing to move those structs to the heap via alloc and Box.

For example this doesn't work at present due to the pins having different types (and therefore Rust assumes possibly different sizes):

let pin2 = pins.gpio2.into_push_pull_output();
let pin4 = pins.gpio4.into_push_pull_output();

let ws2812s = [ // <= error here because ws2812s doesn't contain structs of the same type
  ws2812_timer_delay::Ws2812::new(timer0, pin27),
  ws2812_timer_delay::Ws2812::new(timer1, pin27),
];

ws2812s.iter_mut().for_each(|ws| ws.write(data));

Currently this workaround might work but requires alloc to be enabled:

let pin2 = pins.gpio2.into_push_pull_output();
let pin4 = pins.gpio4.into_push_pull_output();

let ws2812s = [
  Box::new(ws2812_timer_delay::Ws2812::new(timer0, pin27)),
  Box::new(ws2812_timer_delay::Ws2812::new(timer1, pin27)),
];

ws2812s.iter_mut().for_each(|ws| ws.write(data));

However ideally with a downgrade function something like this could conceivably compile without any need for alloc:

let pin2 = pins.gpio2.into_push_pull_output().downgrade();
let pin4 = pins.gpio4.into_push_pull_output().downgrade();

let ws2812s = [ // <= both gpios and timers are downgraded to less specific types so the compiler is happy here
  ws2812_timer_delay::Ws2812::new(timer0.downgrade(), pin27),
  ws2812_timer_delay::Ws2812::new(timer1.downgrade(), pin27),
];

ws2812s.iter_mut().for_each(|ws| ws.write(data));
MabezDev commented 2 years ago

This is a good idea! We've recently had a PR for the esp-idf-hal crate adding this. PR's welcome for this crate too :).