PIC Microcontroller – Flash an LED
14th August 2022In this tutorial, we will show the Hello World of embedded microcontrollers the simple humble and satisfying flashing LED. For this we will be programming in C and using our MEB micro board which includes a PIC18F45K40 microcontroller and all of it’s required support components. The board also has an RGB LED, so we will be using the Red LED to indicate the status of the output.
Hardware Requirements:
- PIC microcontroller board e.g https://themachineshop.uk/product/meb-micro/ or a PIC microcontroller on a breadboard with it’s required components e.g. crystal, voltage regulator, pull-up resistors etc and an LED and resistor.
- Microchip PICkit programmer
- USB Cable for the PICkit e.g https://themachineshop.uk/product/micro-usb-cable-power-data-1m/
Software Requirements:
- Microchip MPLAB X – https://www.microchip.com/en-us/tools-resources/develop/mplab-x-ide
- C compiler – https://www.microchip.com/en-us/tools-resources/develop/mplab-xc-compilers/downloads-documentation#XC8
Step 1 – Create a New Project
If you already know how to do this, skip to step 2
Before we start, make sure you have your PICkit plugged in to your computer
In MPLab X click File > New Project… and you will be presented with the New Project window.
Click on Standalone Project and click Next >
Then in Device, type in the microcontroller you are using. If you are awesome and you are using the MEB micro board, this uses the PIC18F45K40. Click on the drop down next to Tool: and select your PICkit. Then click Next >. If your PICkit does not appear then it is because MPLab hasn’t detected it.
We are going to be writing this in the C programming language so close the XC8 compiler from the list of toolchains, then click Next >.
Now that the project is setup, we need to create a new source file to put our code in. in the Projects tab, you will find the project you just made, if it’s not expanded already click it little > next to it and then right click on Source Files and select New > main.c…
A window will pop up. Give your new source file a name and click Finish
Great, now we have a black file to put our code in.
Step 2 – Setup the Configuration Bits
The configuration bits setup the microcontroller before any code is ran. We can access the configuration bits window by going to Window > Target Memory Views > Configurations Bits.
Here you will see a list of abbreviations and even more complicated options. don’t worry there are only a few default bits that we need to change from the default values.
Look for these fields and then click on the drop down next to it under Option to change it value to match these ones:
Field | Option |
RSTOSC | HFINTOSC_64MHZ |
BOREN | OFF |
WDT | OFF |
Let me explain what each one of these mean:
RSTOSC – Reset Oscillator. Every Microcontroller needs a clock pulse to synchronise all of it’s internal components. When the microcontroller is reset, it will use this oscillator to start running the code. We will set this to HFINTOSC_64MHZ – High Frequency Internal Oscillator 64MHz.
BOREN = Brown Out Enable. Each of the components in the microcontroller have a minimum voltage they can operate at. let’s say for example the ADC (Analogue to Digital Converter) requires at least 3v. If the input voltage drops below this value then the ADC could shutdown and the code would be reading 0 from the conversion’s output, instead of the proper value. This could be extremely bad if it caused an error in a calculation. The Brown Out feature will detect this drop in the voltage at a certain threshold and reset the whole microcontroller. For this tutorial we don’t have anything that critical so we will set it to OFF.
WDT = Watch Dog Timer. This device in the microcontroller is like the passenger in the car next to the sleepy driver. If the driver stops responding to the riveting conversation then the passenger will give them a nudge to wake them back up. Please don’t drive tired! The watchdog expects a response from the processor at a timed interval. If the processor gets stuck in the code somewhere, then the watchdog will reset the processor. Again for this tutorial we aren’t doing anything critical so we will set this to OFF
Everything else can be left as default. Now click on the Generate Source Code to Output. This will open the Output tab that contains all of the configuration bits. Select all of the code and copy it to your clipboard. Then go back into your new .c file you made earlier, delete the “#include <xc.h>” and paste your config code in there.
Step 3 – Write the code
ok, let’s get onto some code – if you don’t want the explanation and just want the full code, skip to the end.
First things first we want the LED to flash at a particular speed e.g on for 1 second and off for 1 second so we need to tell the code what speed the oscillator is running at, 64MHz. after #include <xc.h> add:
#include <xc.h>
#define _XTAL_FREQ 64000000
void main(void) {
The main code for our program needs to fit inside the curly brackets { }. In the void main(void) section of the code we need to setup the pins to become digital outputs. Edit the code to look like this:
void main(void){
TRISD = 0b00000000; // sets all the pins on PORT D as outputs
ANSELD = 0b00000000; // sets all the pins on PORT D as digital
LATD = 0b00000111; // switches off the on-board LEDs
}
TRIS sets the direction of the port, 0 for output and 1 for input
ANSEL sets the port to be either digital (0) or analogue (1)
LATD sets all of the latches on port D to on which switches off the onboard RGB LED
If we wanted to set the whole of port D outputs then we could say TRISD = 0. If we wanted to set some of the pins in port D to inputs and some to outputs then we can send it a binary value e.g. TRISD = 0b11110000 This would set pins 7-4 to be inputs and pins 3-0 to be outputs. We could also send it the hexadecimal version of this number (0xF0) or the decimal (240). I find binary a lot easier to see. If you want to set an individual pin to be an output, then you can add bits.TRIS followed by the pin value to the end. TRISDbits.TRISD0 = 0; would set D0 as an output. The same goes for ANSEL and most other registers.
You probably know this already but the // tells the compiler to ignore every after this on this line, we can use this to add comments to our code.
Now we need to add a loop so our program can continuously flash the LED, add a while loop with it’s own curly brackets. The (1) is a condition that never changes so nothing can break our processor from the loop.
LATD = 0b00000111; // switch off the on-board LEDs
while (1){ // setup a loop
}
}
now in our loop we need to tell the LED to turn on, wait turn off and then wait again, this will repeat in the loop and make our red LED flash. Add this to the loop
while (1){ // setup a loop
LATDbits.LD0 = 0; // illuminate the RED LED
__delay_ms(1000); // delay for 1000 milliseconds (1 second)
LATDbits.LD0 = 1; // extinguish the RED LED
__delay_ms(1000); // delay for 1000 milliseconds (1 second)
}
}
The __delay_ms(1000) tells the processor to wait 1000 milliseconds. This is why we needed that #define _XTAL_FREQ 64000000 at the start. You can set this value to whatever you want, if you set them both to 100 then the LED will be on for 100 milliseconds and off for 100 milliseconds. If you set the first one to 100 and the second one to 10000 then the led will quickly flash every 10 seconds.
And That’s it. Your code after the configuration stuff should look something like this:
Click on the Click and Build Main Project button and MPLab will check through your code to make sure there are no syntax errors.
Hopefully you will get the satisfying “BUILD SUCCESSFUL” notification in the output tab
If you got this first time. Stick a comment below saying “First Try!!!!!!” it’ll make me so proud!
Step 4 – Program the PIC
Ok so now we have written our code, let’s send it to our PIC. I’m going to show you a little trick that the PICkit has up it’s sleeve, it can actually power and program the MEB micro board. Click on the Project Properties button in the dashboard. You can also get to it from File > Project Properties
In the Project Properties window, click on your PICkit on the left, then under Option Categories select Power and click the tickbox next to Power target circuit from PICkit. If you are using a 3.3v PIC then make sure you change the voltage below it to 3.3 or you’ll blow up the PIC. The PIC18F45K40 on the MEB Micro is 5v so we shall leave it. Then click OK.
Plug your PICkit into your board or wire it up to your PIC if you are using something else. If you want to know more about wiring up a PICkit then check out the quick start guide from Microchip https://ww1.microchip.com/downloads/en/DeviceDoc/50002721B.pdf for you awesome people, plug it in like this, you can see the little arrow on the PICkit should line up with the left pin.
Now we just need to click on the Make and Program device button
MPLab X will compile your code, download it to your PIC and the PIC should start flashing it’s LED
Yea Boiiii, you’ve just managed to make a PIC do something!!! Now this output could be used for all sorts. if you connect this to a transistor then you could power some serious still like motors and relays to make high powered stuff flash like Christmas tree lights!!!!!