Post History
How do I handle errors in my embedded system? I have learned that it is a de facto standard for driver functions to return an error code that reveals if the function fulfilled its main purpose or i...
#1: Initial revision
Error handling in embedded systems
How do I handle errors in my embedded system? I have learned that it is a de facto standard for driver functions to return an error code that reveals if the function fulfilled its main purpose or if it encountered an error. If we take a look at the switch-case construct in [Lundin's state machine](https://electrical.codidact.com/posts/295939) for a coffee machine, we see that a special function `error_handler()` is called and takes the error code as input argument if the result is `COFFEE_NO_WATER`.
```C
#include <stdio.h>
int main()
{
static coffee_state_t state = COFFEE_SCAN_BUTTONS;
coffee_result_t result;
for(;;)
{
result = state_machine[state]();
state = evaluate_result(state, result);
}
}
static coffee_state_t evaluate_result (coffee_state_t current_state,
coffee_result_t result)
{
// stay in the same state as default behavior:
coffee_state_t next_state = current_state;
switch(current_state)
{
case COFFEE_MIX_WATER:
{
if(result == COFFEE_NO_WATER)
{
next_state = COFFEE_MAINTENANCE;
error_handler(COFFEE_NO_WATER);
}
break;
}
}
return next_state;
}
static void error_handler (coffee_result_t error_code)
{
// do something meaningful here based on error code
(void)error_code;
}
```
My question is, what is `error_handler()` supposed to do? What does its innards look like? Is its purpose to make visible to the user/programmer which errors has happened? Or is its purpose something else?
To this end, I might add that I have understood that there are at least two kinds of errors - "soft errors" and "hard errors". A soft error could be that an opcode is received correctly via UART, but it is an operation that our microcontroller program does not recognize/support. Since the UART connection is still intact we can send a message to the other end (which might be a PC) stating what went wrong, giving a clear indication that an error happened.
A hard error could be that the UART connection disconnects or that baud rates are not correctly configured. In such instances, how should the error be handled?
