From 4ba6863eaea03800aa524332e15e0d001a0d28e4 Mon Sep 17 00:00:00 2001 From: jakeg00dwin Date: Fri, 18 Oct 2024 22:15:45 -0700 Subject: [PATCH] Wrote code to pass new tests for hysteresis --- src/load/load.c | 50 ++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 41 insertions(+), 9 deletions(-) diff --git a/src/load/load.c b/src/load/load.c index faebc69..3cf13e8 100644 --- a/src/load/load.c +++ b/src/load/load.c @@ -40,7 +40,29 @@ static bool is_valid_load(uint16_t val) static bool is_below_target(uint16_t val) { - if(val < HYSTERESIS){ + if(val < HYSTERESIS_HI){ + return true; + } + return false; +} + +static bool is_high_valid(uint16_t val, bool output_level) +{ + if(val < HYSTERESIS_LO){ + return true; + } + else if(val <= HYSTERESIS_HI && output_level) { + return true; + } + return false; +} + +static bool is_low_valid(uint16_t val, bool output_level) +{ + if(val > HYSTERESIS_HI) { + return true; + } + else if(val >= HYSTERESIS_HI && output_level) { return true; } return false; @@ -60,18 +82,23 @@ static uint16_t sample_adc(uint8_t adc_pin) void Load_HandleLoadPortA(uint8_t adc_pin, uint8_t out_pin) { uint16_t val = sample_adc(adc_pin); - if(porta_disabled[adc_pin]){ + bool out_state = RegEdit_IsBitSet((void *) &PORTA.OUT, out_pin); + + if(porta_disabled[adc_pin]) { RegEdit_ClearBit((void *) &PORTA.OUT, out_pin); } - else if(!is_valid_load(val)){ + else if(!is_valid_load(val)) { RegEdit_ClearBit((void *) &PORTA.OUT, out_pin); porta_disabled[adc_pin] = true; } - else if(is_below_target(val)){ + else if(is_high_valid(val, out_state)) { RegEdit_SetBit((void *) &PORTA.DIR, out_pin); RegEdit_SetBit((void *) &PORTA.OUT, out_pin); } - else{ + else if(is_low_valid(val, out_pin)) { + RegEdit_ClearBit((void *) &PORTA.OUT, out_pin); + } + else { RegEdit_ClearBit((void *) &PORTA.OUT, out_pin); } } @@ -79,18 +106,23 @@ void Load_HandleLoadPortA(uint8_t adc_pin, uint8_t out_pin) void Load_HandleLoadPortB(uint8_t adc_pin, uint8_t out_pin) { uint16_t val = sample_adc(adc_pin); - if(portb_disabled[adc_pin]){ + bool out_state = RegEdit_IsBitSet((void *) &PORTB.OUT, out_pin); + + if(portb_disabled[adc_pin]) { RegEdit_ClearBit((void *) &PORTB.OUT, out_pin); } - else if(!is_valid_load(val)){ + else if(!is_valid_load(val)) { RegEdit_ClearBit((void *) &PORTB.OUT, out_pin); portb_disabled[adc_pin] = true; } - else if(is_below_target(val)) { + else if(is_high_valid(val, out_state)) { RegEdit_SetBit((void *) &PORTB.DIR, out_pin); RegEdit_SetBit((void *) &PORTB.OUT, out_pin); } - else{ + else if(is_low_valid(val, out_pin)) { + RegEdit_ClearBit((void *) &PORTB.OUT, out_pin); + } + else { RegEdit_ClearBit((void *) &PORTB.OUT, out_pin); } }