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.
// First sample code
void main(){
}
For this to work, a number of things are required.
- The peripherals that the device will use must be declared.
- 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.