About Benn Thomsen

Lecturer in Electronic Engineering, UCL. Research: Optical comms, Distractions: Embedded Systems, IoT and inspiring the next generation of engineers.

Copying code snippets

Featured

I had some feedback on the blog that said it wasn’t so obvious how to copy the code snippets for pasting into your own designs. So here is some guidance

If you float the mouse over the code snippet below then you will see a pop up appear in the upper right hand corner with four icons in it. If you select the copy icon the code snippet will be copied to the clipboard. The copy icon is the one that looks like two pages.

int i;
for (i=0,i<10,i++)
{ expression; }

Switch debouncing

For a comprehensive introduction to the need for switch debouncing in microprocessor applications and approaches to doing so. Take a look at this excellent guide by The Ganssle Group.

A simple software debounce routine for debouncing the press of an active low switch, such as a momentary push switch directly attached from the input pin (with pullups enabled) of the microcontroller down to ground, is shown below. In this case the switch is attached to pin0 on port B.

char debounce(void)
{
static char count=0;
if (PINB & (1<<PB0)) count=0;
else count++;
if (count > 10) return 1;
else return 0;
}

This code simply implements a counter that requires the pin to be in the logic zero state for 10 successive samples, before returning a one. The count can be increased or decreased as necessary to ensure robust operation of the switch. Software debouncing can also be realised in an more efficient form by simply using a char variable and a logical shift left to count the successive samples. In this implementation the maximum count is 8.

char debounce(void)
{
static char state=0xFF;
state=(state << 1)|(PINB & (1 << PB0));
if state==0 return 1;
else return 0;
}