diff --git a/ch32v-insert-coin/src/app.rs b/ch32v-insert-coin/src/app.rs index 4cc0dd7..3904630 100644 --- a/ch32v-insert-coin/src/app.rs +++ b/ch32v-insert-coin/src/app.rs @@ -183,7 +183,7 @@ use crate::synthesizer::SynthesizerService; pub use settings::Settings; -#[cfg(feature = "enable_print")] +// #[cfg(feature = "enable_print")] use ch32_hal::println; pub struct TimerConfig { @@ -390,8 +390,15 @@ 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: {bv}"); + let avg = self.interfaces.adc_core.get_average(); + // #[cfg(feature = "enable_print")] + // println!("batt adc service: {bv}, {avg}"); + if avg < 421 { + // self.services + // .sequencer + // .play_sequence(&crate::sequences::COIN_CHIRP, 0); + self.set_state(State::DeepSleep); + } // TODO: // do stuff if the battery voltage is below some threshold diff --git a/ch32v-insert-coin/src/main.rs b/ch32v-insert-coin/src/main.rs index d8dc81d..facacbf 100644 --- a/ch32v-insert-coin/src/main.rs +++ b/ch32v-insert-coin/src/main.rs @@ -50,21 +50,41 @@ use hal::peripherals::{ADC1, PD4}; pub struct AdcCore { adc: Adc<'static, ADC1>, battery_pin: PD4, + batt_values: [u16; 10], + index: usize, } impl AdcCore { pub fn new(mut adc: Adc<'static, ADC1>, pin: PD4) -> Self { + riscv::asm::delay(20_000); adc.calibrate(); Self { adc, battery_pin: pin, + batt_values: [1024; 10], + index: 0, } } // 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) + let val = self + .adc + .convert(&mut self.battery_pin, hal::adc::SampleTime::CYCLES241); + self.batt_values[self.index] = val; + self.index += 1; + if self.index > &self.batt_values.len() - 1 { + self.index = 0; + } + val + } + + pub fn get_average(&self) -> u16 { + let mut sum = 0; + for value in &self.batt_values { + sum += value; + } + sum / self.batt_values.len() as u16 } } @@ -272,7 +292,7 @@ fn app_main(mut p: hal::Peripherals) -> ! { let timer_config = TimerConfig { sp_timer_ms: 1000, lp_timer_ms: 3000, - batt_adc_timer_ms: 10000, + batt_adc_timer_ms: 1000, usb_adc_timer_ms: 10000, led0_timer_ms: 100, led1_timer_ms: 100, @@ -289,11 +309,11 @@ fn app_main(mut p: hal::Peripherals) -> ! { let dac_tick_per_service = tick_rate_hz / dac_sample_rate_hz; let dac_service_data = TickServiceData::new(dac_tick_per_service); - let coin_sound = include_bytes!("../audio/coin5.raw"); + // let coin_sound = include_bytes!("../audio/coin5.raw"); // let coin_sound = include_bytes!("../audio/coin2.raw"); let sample_player = DacService::new(ch32_hal::timer::Channel::Ch4, dac_service_data); - sample_player.load_data(coin_sound); + // sample_player.load_data(coin_sound); let sequencer = app::sequencer::DynamicSequence::new(&SEQUENCE_LIST[0].0, tick_rate_hz);