diff --git a/ch32v-insert-coin/src/app.rs b/ch32v-insert-coin/src/app.rs index c48a073..4cc0dd7 100644 --- a/ch32v-insert-coin/src/app.rs +++ b/ch32v-insert-coin/src/app.rs @@ -301,6 +301,7 @@ pub struct Sequences { // things that touch hardware pub struct Interfaces { pub pwm_core: SimplePwmCore<'static, ch32_hal::peripherals::TIM1>, + pub adc_core: crate::AdcCore, } pub struct App { @@ -388,8 +389,12 @@ impl App { } if self.timers.batt_adc_timer.need_service() { self.timers.batt_adc_timer.service(); + let bv = self.interfaces.adc_core.get_battery_voltage(); #[cfg(feature = "enable_print")] - println!("batt adc service"); + println!("batt adc service: {bv}"); + + // TODO: + // do stuff if the battery voltage is below some threshold } if self.timers.usb_adc_timer.need_service() { self.timers.usb_adc_timer.service(); diff --git a/ch32v-insert-coin/src/main.rs b/ch32v-insert-coin/src/main.rs index 1e9e74c..d8dc81d 100644 --- a/ch32v-insert-coin/src/main.rs +++ b/ch32v-insert-coin/src/main.rs @@ -44,6 +44,30 @@ use crate::app::sequencer::{DynamicSequence, SequenceEntry}; static LED0_SEQ: [u8; 8] = [0u8, 25u8, 50u8, 75u8, 100u8, 75u8, 50u8, 25u8]; +use hal::adc::Adc; +use hal::peripherals::{ADC1, PD4}; + +pub struct AdcCore { + adc: Adc<'static, ADC1>, + battery_pin: PD4, +} + +impl AdcCore { + pub fn new(mut adc: Adc<'static, ADC1>, pin: PD4) -> Self { + adc.calibrate(); + Self { + adc, + battery_pin: pin, + } + } + + // TODO make this a float or something + pub fn get_battery_voltage(&mut self) -> u16 { + self.adc + .convert(&mut self.battery_pin, hal::adc::SampleTime::CYCLES241) + } +} + #[derive(Debug)] struct Flag { value: bool, @@ -205,13 +229,13 @@ fn app_main(mut p: hal::Peripherals) -> ! { // adc let mut adc = hal::adc::Adc::new(p.ADC1, Default::default()); let mut batt_monitor_pin = p.PD4; + let adc_core = AdcCore::new(adc, batt_monitor_pin); // adc2 // let mut usb_detect_dc = hal::adc::Adc::new(p.ADC1, Default::default()); let mut usb_detect_pin = p.PD5; // println!("ADC_PIN CHANNEL: {}", adc_pin.channel().channel()); - let adc_cal = adc.calibrate(); // #[cfg(feature = "enable_print")] // println!("ADC calibration value: {}", adc_cal); @@ -289,7 +313,7 @@ fn app_main(mut p: hal::Peripherals) -> ! { audio: &SEQUENCE_LIST, }; - let app_interfaces = Interfaces { pwm_core }; + let app_interfaces = Interfaces { pwm_core, adc_core }; let mut app = App::new(app_config, app_services, app_sequences, app_interfaces);