diff --git a/src/display.rs b/src/display.rs index 50e2d1a..edaec65 100644 --- a/src/display.rs +++ b/src/display.rs @@ -35,7 +35,7 @@ impl Rgb565 { Rgb565(255, 255, 0) } - pub fn purple() -> Rgb565 { + pub fn magenta() -> Rgb565 { Rgb565(255, 0, 255) } diff --git a/src/main.rs b/src/main.rs index 0cbc359..71e60bd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,17 +6,22 @@ use atmega_hal::{ Adc, Usart, + port::{Pin, mode}, spi::{self, Settings}, usart::Baudrate, }; use embedded_hal::delay::DelayNs; use panic_halt as _; -use crate::display::{Display, Position, Rgb565}; +use crate::{ + display::{Display, Position, Rgb565}, + peripherals::{Button, Knob}, +}; mod display; mod font; mod image; +mod peripherals; type CoreClock = atmega_hal::clock::MHz8; @@ -64,25 +69,40 @@ fn main() -> ! { let mut adc: Adc = atmega_hal::Adc::new(dp.ADC, Default::default()); - let button = pins.pd5.into_pull_up_input(); - let potentiometer = pins.pc1.into_analog_input(&mut adc); + let mut button = Button::from(pins.pd5.into_pull_up_input()); + let mut knob = Knob { + pin: pins.pc1.into_analog_input(&mut adc), + adc, + }; - let colors = [Rgb565::red(), Rgb565::green(), Rgb565::blue()]; + let colors = [ + Rgb565::red(), + Rgb565::green(), + Rgb565::blue(), + Rgb565::cyan(), + Rgb565::magenta(), + Rgb565::yellow(), + ]; let mut idx = 0; let mut delay = atmega_hal::delay::Delay::::new(); - loop { - let raw_input = potentiometer.analog_read(&mut adc); - let input = raw_input as f32 / 1024f32; - display.draw_rect( - Position { x: 0, y: 0 }, - Position { x: 200, y: 200 }, - (colors[idx] * input).as_color(), - ); - if button.is_low() { + let mut last_input = 0f32; + loop { + let input = knob.poll(); + let button_poll = button.poll(); + + if button_poll { idx = (idx + 1) % colors.len(); } - delay.delay_ms(1000); + + if last_input != input || button_poll { + last_input = input; + display.draw_rect( + Position { x: 0, y: 0 }, + Position { x: 200, y: 200 }, + (colors[idx] * input).as_color(), + ); + } } } diff --git a/src/peripherals.rs b/src/peripherals.rs new file mode 100644 index 0000000..6e12f1a --- /dev/null +++ b/src/peripherals.rs @@ -0,0 +1,57 @@ +use atmega_hal::{ + Adc, Atmega, + adc::{AdcChannel, AdcOps}, + pac::ADC, + port::{ + Pin, PinOps, + mode::{self, PullUp}, + }, +}; + +use crate::CoreClock; + +pub struct Button { + pin: Pin, T>, + was_pressed: bool, + pub is_pressed: bool, +} + +impl Button { + pub fn from(pin: Pin, T>) -> Button { + 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 { + pub pin: Pin, + pub adc: Adc, +} + +impl Knob +where + Pin: AdcChannel, +{ + pub fn poll(&mut self) -> f32 { + let read = self.pin.analog_read(&mut self.adc); + read as f32 / 1024f32 + } +}