Wednesday, October 24, 2012

Design Patterns for Embedded Software (1)



SA..

Introduction

Design patterns is a group of  reusable solutions for problems that appear in software design. Those solutions commonly appear while writing high level object-oriented software for a desktop. A great book that is usually called gang of four book is Design Patterns: Elements of Reusable Object-Oriented Software, it explains design patterns in details .

Commonly, It is very rare to work with objects oriented programming while writing a firmware, however there are c++ compilers available like IAR C/C++ Compiler. I have searched also for resources for commonly design patterns for embedded software and I only found one book that explains design patterns for embedded software, and he tried to mix Gang of Four Patterns, like observer, strategy pattern,..etc and tried to give them the taste for firmware. The book is Design Patterns for Embedded Systems in C: An Embedded Software Engineering Toolkit . The book is really bad and I didn't like it at all, considering using UML for C Code is awful.

1. Polled Input Pattern

The first pattern that I would like to discuss is the Polled Input. Sometimes when you try to read an input from a switch for example, you try to poll switch for reading by a loop like that while(switchInput!=0);   This means the microcontroller will stuck here waiting for the switch to be at ground. This kind of reading an input, is okey for not real time or time triggered embedded systems, you would better utilize an ISR(Interrupt Service Routine) that keeps checking the sensor falling or rising edge, but as you know it will let the CPU to stop it's current task and then completes the ISR. This kind of  Context Switching is an overhead, and rises serious complications in embedded systems. 

The Pattern that solves that should have the following properties:
1. In a real time operating system, or any scheduler  a period task should poll the input for the occurence of the event
2.The period of the  task should Ttask should be <= min Tevent.
Suppose you would like to poll a push button as shown in the following figure with a pull up resistor 10k and VCC. A common problem for push-button or any switch is the residual frequencies due to mechanics, and you need to filter and "debounce" them. Of course you can use the electronics way of filtering the noise, and that's called a hardware filtering and of course the easier way is use Software for filtering those spikes.
Following figure, shows the spikes from pushing on/off a switch.

A simple code that shows the pattern idea



Note that the previous update function should be run in a task scheduler or timer  for example every 50ms to 500ms. Note it also solves the debouching issue with switches.

No comments:

Post a Comment