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 note for further details on the nature of a hex file, see the following resource intel hex file format http //microchipdeveloper com/ipe\ sqtp 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 // first sample code void main(){ // code goes here } 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){ // code here } } 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 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 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