Toggling LEDs: Building on the basics

Hello World

LEDs

You may have noticed in the previous code sample that two outputs were configured. These outputs were configure to toggle with a 1 second interval. If you loaded the previous code sample, all you need to do is to ensure that jumper wires are connecting PORTB.B0 and PORTB.B1 to the header that is connected to the two LEDs. They will then light alternately.

When I have seen projects like this you do wonder how does this help with PIC coding proficiency. This code sample does teach a couple of things.

  1. The steps demonstrate a structured way to call functions from main(); this becomes very useful later on
  2. the ^ or (carat) toggles the value of a single bit so if the value was ‘1’ it would be toggled to ‘0’

Toggling bits is done when switching outputs or even if a protocol was implemented in software when a device does not have a particular integrated peripheral. Now days with more powerful natural language compilers and extensive libraries, machine level coding skills are not 100% necessary but they are useful to know.

Adding the push button

A push button is what is referred to as an input device, and as a mechanical switch it momentarily provides an input signal to the pin and that is used an input condition for the code.

The problem with a mechanical input device, is that the 20ms to 1 second that a user holds the button down is a life time for the PIC. As a result a snippet of code needs to be introduced to manage the de-bounce action of pushing the switch.

/*
Some Basic Stuff
*/
sbit pb at RB5_bit;
int count;
StartUp(){

TRISA = 0xFF;
TRISB = 0xFC;
ANSELB = 0x0;
PORTB.B1 = 1;
}

void debounce(){ 
Delay_ms(300); 
}

Flash_0(){
PORTB.B0 = PORTB.B0^1;
Delay_ms(1000);
}

Flash_1(){
PORTB.B0 = PORTB.B0^1; 
PORTB.B1 = PORTB.B1^1; 
Delay_ms(1000); } 

void main() { 

StartUp();

do{

if(!pb){

debounce();

count++;
}

if(count == 1){
Flash_0();
}

if(count == 2){
Flash_1();
}

if(count == 3){count = 0;}
 
}while(1); 
}
}

The above code will do the following:

  • Not flash an LED until you push the button once
  • Flash 1 LED if you push the button once
  • Toggle 2 LEDs if you push the button a second time
  • Switch both LEDs when you push the button again

Once you get that up and running you have a project responding to the input of the push button.

Enjoy the coding.

[E]