I measure the current via an I2C current sensor by using this STM32F302 Nucleo board. And I display internal temperature and the averaged current value in an OLED display.
But I do everything in while loop like polling as follows:
while (1)
{
HAL_Delay(100);
get_time();
uint16_t I2C_value = averaging_data();
current_val = (I2C_value/4096.0 - 0.5) *50*1000;
if(current_val>threshold){
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_SET);
}
else{
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_RESET);
}
//Rest of the code for OLED display and temperature readings
}
static uint16_t averaging_data( void )
{
uint8_t avg_num = 250;
uint32_t sum_data = 0;
uint16_t new_data = 0;
uint8_t cnt = 0;
for ( cnt = 0; cnt < avg_num; cnt++ )
{
new_data = amrcurrent_read_value();
sum_data = sum_data + new_data;
HAL_Delay(1);
}
new_data = sum_data / avg_num;
return new_data;
}
uint16_t amrcurrent_read_value ( void )
{
uint8_t data_buf[ 2 ];
uint16_t temp_data;
HAL_I2C_Master_Receive(&hi2c1, SLAVE_ADDR << 1, data_buf, 2, HAL_MAX_DELAY);
temp_data = data_buf[ 0 ];
temp_data = temp_data << 8;
temp_data = temp_data | data_buf[ 1 ];
return temp_data;
}
As seen above, I average 250 samples for the current. So I can update an LED less than 500ms after current is above a threshold value. So I want LED to respond the current threshold change as soon as possible.
My problem is that, adding OLED functions and ADC measurement functions inside the same while loop makes the LED to respond slower to the current's value change.
I thought about an interrupt but in this case I couldn't figure out how to use it. What can be a remedy which doesn't require an extra circuitry? Seems not possible but I wanted to ask here anyway.