Archive

Archive for April, 2013

Programming PIC 18 using XC8 (MPLAB X) : IO ports

April 14th, 2013 35 comments

When you start the project, the main.c (or newmain.c, depends on what you named your main c file). You should be able to compile the code without any error or warning.

#include <stdio.h> #include <stdlib.h> /* * */ int main(int argc, char** argv) { return (EXIT_SUCCESS); }

The code given above does nothing. Its just a way to make sure you programming environment is set properly.

Follow the following steps

1) add config.h (remember the configuration bits?)

2) add xc.h – the compiler header

3) change int main to void main (the return type int has a reason, I’ll cover about it later)

Now your code should look like this and able to compile without a problem.

#include <xc.h> #include "config.h" /* * */ void main(int argc, char** argv) { }

 


PIC18 IO Setup

 

In order to set the pin of PIC controller you need to know the registers associated with it. There are 3 registers

  1. TRIS – Set a pin as Input or Output
  2. LAT – Buffer of each pin (tells you the value you wrote into it)
  3. PORT – To make a pin high or low/on or off

Regarding LAT, you can program the PIC without using the LAT bits, but good to know about it. If you write into LAT, it is equivalent to writing directly to the pin. But if you read from LAT bits, you will be reading the buffer, not the voltage at the pin. Instead if you use PORT bits, you will directly to the pin and read from it. This whole stuff I’m doing is to make you start programming quickly. But please read the datasheet to know more.

Set TRIS bit

1 = Input (1 looks like I – input )

0 = Output ( 0 looks like o = output)

 

Set PORT bit

1 = Makes pin high

0 = Makes pin low

 

Ctrl + Space bar will activate the intelli-sense that looks like this

tris

To set Pin RB0 as output pin do the following

rb0

 

Lets try flip RB0 high and low

#include <xc.h> #include "config.h" void main(int argc, char** argv) { TRISBbits.RB0 = 0; while(1) //infinite loop { PORTBbits.RB0 = 1; //Set the PIN RB0 high PORTBbits.RB0 = 0; //Set the PIN RB0 low } }

 

The program will run fast that you won’t even see the difference. So we need to add some delay. You got to set some delay. XC compiler gives you delay function, but you need to set a few parameters (well actually its one line).

#define _XTAL_FREQ 1000000 //set your internal(or)external oscillator speed #include <xc.h> #include "config.h" int i = 0; void Delay1Second(void); void main(int argc, char** argv) { TRISBbits.RB0 = 0; while(1) //infinite loop { PORTBbits.RB0 = 1; //Set the PIN RB0 high Delay1Second(); PORTBbits.RB0 = 0; //Set the PIN RB0 low Delay1Second(); } } void Delay1Second() { for(i=0;i<100;i++) __delay_ms(10); }

Categories: Uncategorized Tags: