For this tutorial we will be using the same circuit set up as last time; a 1k resistor and a red LED connected to the pins RE2 and ground of the board, only the software will change in order to flash the LED but you’ll recognize most of the code from the last tutorial , How To Turn On an LED With The PIC18 Board, so I’ll just explain what is new.
Check out the video below to see the result and scroll down to see the code.
The Code
We’ll be using the delays.h library to turn the led on and off, this could also be done with for loops but using this library is a more elegant approach.
#include <p18f8722.h> // include the respective pic file #include <delays.h> // include the delays library #pragma config OSC=HS // high speed oscillator #pragma config WDT=OFF // watch dog off void main () { PORTEbits.RE2=1; // set port RE2 to 1 TRISE = 0; // set E ports to be outputs while(1) { Delay10KTCYx(255); // delay 255x100,000 cycles PORTEbits.RE2=0; // turn off the led Delay10KTCYx(255); // delay 255x100,000 cycles PORTEbits.RE2=1; // turn on the led } }
As you can see I have added another library, delays.h
#include <delays.h> // include the delays library
This library has a set of functions that allow you to delay the next action.
while(1) { Delay10KTCYx(255); // delay 255x100,000 cycles PORTEbits.RE2=0; // turn off the led Delay10KTCYx(255); // delay 255x100,000 cycles PORTEbits.RE2=1; // turn on the led }
Last time there was nothing inside the while() loop, that’s because we did not need to repeat anything but this time we want to change the state of the RE2 pin from 0 to 1 (off and on respectively). Now before each change of state I have added the line
Delay10KTCYx(255); // delay 255x100,000 cycles
this tells the microcontroller to delay the next action for 25,500,000 cycles. You can change the number 255 to be any number between 1 and 255, setting the number equal to 0 will delay the next action to 256×100,000 cycles.
That’s it for this tutorial, be sure to check back for more.