Design patterns for embedded systems in c
- User
Design patterns for embedded systems in c
- Assistant
Design patterns in embedded systems development help improve code maintainability, scalability, and efficiency. While traditional software design patterns apply to embedded systems, they must be adapted to resource constraints, real-time requirements, and hardware interactions.
Common Design Patterns in Embedded C
- State Machine Pattern
Use Case:Event-driven applications, protocol handling, device control logic.
Example:Implementing a finite state machine (FSM) for a motor controller.
Implementation:cCopytypedefenum{ IDLE, RUNNING, ERROR } State; State currentState = IDLE;voidstateMachine(Event event){switch(currentState) {caseIDLE:if(event == START) currentState = RUNNING;break;caseRUNNING:if(event == STOP) currentState = IDLE;if(event == FAULT) currentState = ERROR;break;caseERROR:if(event == RESET) currentState = ; } }
Use Case:Event-driven applications, protocol handling, device control logic.
Example:Implementing a finite state machine (FSM) for a motor controller.
Implementation:
────────────────────────────────────────────────────────────────────
cCopytypedef enum { IDLE, RUNNING, ERROR } State; State currentState = IDLE;
void stateMachine(Event event) { switch (currentState) { case IDLE: if (event == START) currentState = RUNNING; break; case RUNNING: if (event == STOP) currentState = IDLE; if (event == FAULT) currentState = ERROR; break; case ERROR: if (event == RESET) currentState = IDLE; break; } }
- Singleton Pattern
Use Case:Managing a single instance of a hardware peripheral (e.g., UART, I2C).
Example:Ensuring only one instance of a UART driver is initialized.
Implementation:cCopytypedefstruct{uint32_tbaudRate; } UART;
UART*getUARTInstance(void) {staticUART uartInstance = { .baudRate =115200};return&uartInstance; }
Use Case:Managing a single instance of a hardware peripheral (e.g., UART, I2C).
Example:Ensuring only one instance of a UART driver is initialized.
Implementation:
────────────────────────────────────────────────────────────────────
cCopytypedef struct { uint32_t baudRate; } UART;
UART* getUARTInstance(void) { static UART uartInstance = { .baudRate = 115200 }; return &uartInstance; }
- Observer Pattern
Use Case:Event notification, sensor data updates, interrupt handling.
Example:Notifying multiple tasks when a button is pressed.
Implementation:cCopy#defineMAX_OBSERVERS 5typedefvoid(*ObserverCallback)(void); ObserverCallback observers[MAX_OBSERVERS];voidregisterObserver(ObserverCallback cb){for(inti =0; i < MAX_OBSERVERS; i++) {if(observers[i] ==NULL) { observers[i] = cb;break; } } }voidnotifyObservers(void) {for(inti =0; i < MAX_OBSERVERS; i++) {if(observers[i]) observers; } }
- User
I'm on stm32f767zi ...give me some excercise to practice design patterns
- Assistant