Write header, configure I/O pins and use delay function
Here is a simple program whose purpose just to turn on a few LEDs on PORTB. Use this example to study what a real program looks like. Figure below shows appropriate connection schematic, while the related program is on the next page.
When the power supply goes on, every second LED on PORTB will emit light, thus indicating that the microcontroller is properly connected and operates normally.
This example shows how a correctly written header looks like. Header is the same for all the programs described herein so it will be skipped in the following examples. Anyway, it is considered to be at the beginning of every program marked as Header.
To make this example more interesting, we will enable LEDs connected to PORTB to blink. There are several ways to do it:
As soon as the microcontroller is turned on, all LEDs will emit light for a second. The Delay function is in charge of it in the program. You just need to set delay expressed in milliseconds.
After one second, the program enters the for loop and remains there as long as variable k is less than 20. The variable is incremented by 1 after each iteration. Within the for loop, duty cycle of pulses is 5:1 (500mS:100mS) and any change of logic state on output pins causes all LEDs to blink.
When the program exits the for loop, the PORTB logic state changes (0xb 01010101) and the program enters the endless while loop and remains there as long as 1=1(endless loop). In this loop the PORTB logic state is inverted each 200mS.