11use crate :: {
22 consts:: BATTERY_SEND_INTERVAL_MS , state:: sleep_state, utils:: rolling_average:: RollingAverage ,
33} ;
4- use embassy_time:: { Instant , Timer } ;
4+ use embassy_time:: { Duration , Instant , Timer } ;
55use esp_hal:: analog:: adc:: { Adc , AdcConfig , Attenuation } ;
66
7- type AdcCal = esp_hal:: analog:: adc:: AdcCalBasic < esp_hal:: peripherals:: ADC1 < ' static > > ;
7+ type AdcCal = esp_hal:: analog:: adc:: AdcCalCurve < esp_hal:: peripherals:: ADC1 < ' static > > ;
88
9- const BAT_MIN : f64 = 3200.0 ;
10- const BAT_MAX : f64 = 4200.0 ;
11- const BATTERY_CURVE : [ ( f64 , u8 ) ; 11 ] = [
9+ const BATTERY_CURVE : [ ( f64 , u8 ) ; 14 ] = [
1210 ( 3200.0 , 0 ) ,
1311 ( 3250.0 , 5 ) ,
1412 ( 3300.0 , 10 ) ,
1513 ( 3350.0 , 20 ) ,
1614 ( 3400.0 , 30 ) ,
15+ ( 3450.0 , 35 ) ,
1716 ( 3500.0 , 40 ) ,
17+ ( 3550.0 , 45 ) ,
1818 ( 3600.0 , 50 ) ,
1919 ( 3700.0 , 60 ) ,
2020 ( 3800.0 , 70 ) ,
2121 ( 3900.0 , 80 ) ,
22- ( 4200.0 , 100 ) ,
22+ ( 4000.0 , 90 ) ,
23+ ( 4100.0 , 100 ) ,
2324] ;
25+ const BAT_MIN : f64 = BATTERY_CURVE [ 0 ] . 0 ;
26+ const BAT_MAX : f64 = BATTERY_CURVE [ BATTERY_CURVE . len ( ) - 1 ] . 0 ;
2427
2528#[ embassy_executor:: task]
2629pub async fn battery_read_task (
@@ -33,7 +36,7 @@ pub async fn battery_read_task(
3336 let mut adc_pin = adc_config. enable_pin_with_cal :: < _ , AdcCal > ( adc_pin, Attenuation :: _11dB) ;
3437 let mut adc = Adc :: new ( adc, adc_config) . into_async ( ) ;
3538
36- let mut battery_start = Instant :: now ( ) ;
39+ let mut battery_start = Instant :: now ( ) . saturating_add ( Duration :: from_millis ( 300 ) ) ;
3740
3841 let base_freq = 2.0 ;
3942 let sample_freq = 1000.0 ;
@@ -43,21 +46,13 @@ pub async fn battery_read_task(
4346 let mut lcd_sent = false ;
4447
4548 loop {
46- Timer :: after_millis ( 100 ) . await ;
49+ Timer :: after_millis ( 10 ) . await ;
4750 if sleep_state ( ) {
4851 Timer :: after_millis ( 500 ) . await ;
4952 continue ;
5053 }
5154
5255 let read = adc. read_oneshot ( & mut adc_pin) . await ;
53- if !lcd_sent {
54- state
55- . show_battery
56- . signal ( bat_percentage ( calculate ( read as f64 ) ) ) ;
57-
58- lcd_sent = true ;
59- }
60-
6156 let read = smoother. tick ( read as f32 ) ;
6257 avg. push ( read) ;
6358
@@ -67,7 +62,16 @@ pub async fn battery_read_task(
6762 state. current_bat_read = Some ( read) ;
6863 }
6964
70- if ( Instant :: now ( ) - battery_start) . as_millis ( ) < BATTERY_SEND_INTERVAL_MS {
65+ let now = Instant :: now ( ) ;
66+ if !lcd_sent && battery_start <= now {
67+ state
68+ . show_battery
69+ . signal ( bat_percentage ( calculate ( read as f64 ) ) ) ;
70+
71+ lcd_sent = true ;
72+ }
73+
74+ if battery_start > now || ( now - battery_start) . as_millis ( ) < BATTERY_SEND_INTERVAL_MS {
7175 continue ;
7276 }
7377
@@ -123,5 +127,5 @@ fn bat_percentage(mv: f64) -> u8 {
123127}
124128
125129fn calculate ( x : f64 ) -> f64 {
126- 1.18323 * x + 276.754
130+ 1.69874 * x + 66.6103
127131}
0 commit comments