Knowledge Base
...
Applied PIC Micro Development
PIC Programming

Program Structure

6min

Synopsis

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 program counter. With the advent of high-level language compilers, there is no need to write the code in an 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.

NoteFor further details on the nature of a hex file, see the following resource:ย Intel HEX File Formatย 

๏ปฟ

Introduction

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.

C
๏ปฟ

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.

C
๏ปฟ

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

C
๏ปฟ

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.

C
๏ปฟ

As your application grows, it is important to ensure that the code is structured in a way that 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 developers.