0

I have an EEPROM AT24C256. I want to write to this EEPROM from Timer Interrupt routine. But when I try, STM gets stuck. It's not going on for other code rows.

void TIM3_IRQHandler(void)
{
    //read adc 
    adc_value = HAL_ADC_GetValue(&hadc1);
    normalized_adc_value = (255.0f/4095.0f) * adc_value;  // range 0..255 
        
    _writeEEPROM(&hi2c2, 0xA0, pointerOfEeprom, normalized_adc_value);

    HAL_TIM_IRQHandler(&htim3);
}
void _writeEEPROM(I2C_HandleTypeDef *i2cbus, uint8_t devAdres, uint16_t memAdres, uint8_t value) {
    uint8_t val[3] = { 0 };
    val[0] = (memAdres >> 8) & 0xFF;
    val[1] = (memAdres & 0xFF);
    val[2] = value;

    uint8_t buf2[50] = { 0 };
    ret = HAL_I2C_Master_Transmit(i2cbus, devAdres, val, 3, 1000);
    HAL_Delay(10);
    if (ret != HAL_OK) {
        strcpy((char*) buf2, "EEPROM Write Error I2C-TX\r\n");
    } else {
        strcpy((char*) buf2, "EEPROM Write Success I2C-TX\r\n");
    }
}

My code is like this.

How can I manage this?

0andriy
  • 4,183
  • 1
  • 24
  • 37
Melih
  • 35
  • 7
  • And how do you think it's supposed to work when you are calling _sleeping_ functions in atomic (_non-sleeping_) context? Your design is broken, it can't be fulfilled like this. Hint: you need a way better environment, like RTOS (use Zephyr, for example), which helps you a lot, but doesn't replace the need of understanding the 101 concept of _sleeping_ vs. _non-sleeping_ context, etc. – 0andriy Jun 04 '21 at 21:41
  • Actually, I am new to these topics. I am wondering the only problem is HAL_Delay() function? If it is, when I remove it, it should be working. It's not working. – Melih Jun 05 '21 at 09:07
  • 1
    What if using a debugger breaking into the ISR and step through the code to see what’s going wrong ? However, doing lengthy ops like EEPROM write in an ISR is generally a bad idea. ISRs should kept as short as possible. – HS2 Jun 05 '21 at 09:36
  • Are you ever clearing that interrupt ? – Sorenp Jun 06 '21 at 12:11

2 Answers2

1

You need to defer work into a thread. It is precisely situations like this that highlight the need for an RTOS.

Martin
  • 3,509
  • 3
  • 26
  • 31
0

Many issues in this code:

The main one:

  1. Do not use HAL_Delay() in the interrupt context. this function relays on the counter incremented in sysTick interrupt which can have lower priority.

Secondary: 2. Do not use any delays in the interrupt routines.

  1. Try to do not call functions that execute a long time. Do not call any HAL_ unless you are sure that they do not use HAL_Delay

  2. uint8_t buf2[50] = { 0 }; is a local automatic variable.

0___________
  • 60,014
  • 4
  • 34
  • 74