dice-game/src/peripherals.rs
2025-09-13 19:37:06 +03:00

61 lines
1.2 KiB
Rust

use atmega_hal::{
Adc, Atmega,
adc::{AdcChannel, AdcOps},
pac::ADC,
port::{
Pin, PinOps,
mode::{self, PullUp},
},
};
use crate::CoreClock;
pub struct Button<T: PinOps> {
pin: Pin<mode::Input<PullUp>, T>,
was_pressed: bool,
pub is_pressed: bool,
}
impl<T: PinOps> Button<T> {
pub fn from(pin: Pin<mode::Input<PullUp>, T>) -> Button<T> {
Button {
pin,
is_pressed: false,
was_pressed: false,
}
}
pub fn poll(&mut self) -> bool {
self.is_pressed = self.pin.is_low();
if self.is_pressed {
if !self.was_pressed {
self.was_pressed = true;
true
} else {
false
}
} else {
self.was_pressed = false;
false
}
}
}
pub struct Knob<T: PinOps> {
pub pin: Pin<mode::Analog, T>,
pub adc: Adc<CoreClock>,
}
impl<T: PinOps> Knob<T>
where
Pin<mode::Analog, T>: AdcChannel<Atmega, ADC>,
{
pub fn poll(&mut self) -> f32 {
self.raw() as f32 / 1024f32
}
pub fn raw(&mut self) -> u16 {
self.pin.analog_read(&mut self.adc)
}
}