Basic Programme Structure

Document Information

Document Title Basic Program Structure
Document Number & Revision 403 - 0001 - 1.0
Release Date April  3, 2019
Document Status Original Document, no ammendments



PIC Microcontrollers use a HEX file which is programmed into the device. The hex file contains the machine code which the device uses to step through the programme counter. With the advent of high level language compliers, there is no need to write the code in assembler. However, structured code is required to ensure that the device starts up correctly and runs properly.

The developer writes the source code for the file in c, in a [mycode].c file for example, which is part of a project of files and the code compiles producing the HEX file.

For further details on the nature of a hex file, see the following resoruce: Intel HEX File Format


The internal structure of the [mycode].c file, starts with the void main() function. This is where the main loop of the code will be. This type of source code is not OOP, rather it is sequential logic including calls to other functions. However, if we run the code file below it will run once and there is no structure to our code.


// First sample code void main(){ }


For this to work, a number of things are required.
  1. The peripherals that the device will use must be declared.
  2. The conditional logic which determines how the device will run must be created

To create a condition so that the device continuously repeats we create an infinite loop. Infinite loops are essential, but care must be exercised not to create an infinite loop that never exits is the same as a non responsive application. In the example shown below, the code will loop infinitely. // Basic Infinite Loop void main(){ while(1){ } }

Shown in the developing example below, the PICs ports have been configured. PORTB is an 8-BIT, bidirectional port and digital IO has been configured with all analogues disabled. However, we have not told the PIC what to do.

void main(){ TRISB = 0x0; //All I/O to outputs ANSELB = 0xFF; // Analogues disabled while(1){ LATB = 0xFF; DelayMS(500); LATB = 0x00; DelayMS(500); } }

The above code is rudimentary, with the PIC initialised and the outputs toggled as the device loops through the code.

To extend the code sample, see below.

/* Variable Declarations */ /* Function Declarations */ void MyCall(); void MyCall(){ LATB = 0xFF; DelayMS(500); LATB = 0x00; DelayMS(500); } void main(){ TRISB = 0x0; //All I/O to outputs ANSELB = 0xFF; // Analogues disabled while(1){ MyCall(); } }

As your application grows, it is important to ensure that the code is structured in a way that it is readable and that it makes sense. The PIC will only ever do EXACTLY what it is told to do in code, and therefore any bugs are the developer's.