Friendly Wire

Discover the joy of electronics

Tag: how-to

Your first microcontroller program!

So last week I showed you how you can transfer a hex file onto a PIC microcontroller using the PICkit3 and the MPLAB IPE X software. For this week’s post I think it will be nice to go through a very simple program that makes an LED blink.

In this post you find everything you need to know to create a program (also called “source code”) that makes an LED blink. At the end of this article you will have a hex file that you can transfer to your controller! Exciting!

Yes, yes, I know, it is the stereotypical beginner’s program, but I think for a good reason. I hope it is not too boring for you, but I think it is always a good idea to start simple. Who has the time to go through an entire detailed in-depth tutorial on their first trip into the wonderful land of microcontrollers?

So, instead of giving an in-depth tutorial, I rather want to take a simple program and just explain what it does. Others have written many many excellent coding tutorials for PIC controllers, and it would be a bit silly in my opinion if I tried to compete with that.

Let’s pick a controller

I decided to focus on the controller with the name PIC16F627A. The name is a mouthful, I know. So let us just call it the 627A from now on. The PIC just differentiates its name from other controllers, and the 16F just indicates that it belongs to the 8bit-midrange class of controllers. For us, it will be the 627A.

Alright, so let us take a careful look at the complete program, and then we can disect it line by line. Let’s do it! 🙂

Step 1: Set up a project in MPLAB IDE X

In the first step, we need to set up a project in the MPLAB IDE X which is a lot easier than it seems. Start MPLAB and wait for it to load.

MPLAB IDE X, once launched, will look like this:

Click on File and then on New Project:

As a device we will select the PIC16F627A.

Then lick on Next, and also on Next in the window that follows:

Then we select our programming tool, for which I am using the PICkit3, so this is what I select in this list. Click on PICkit3 if you also use it, and then click on Next.

As a compiler just select any XC8 compiler (which will be automatically installed when you install MPLAB IDE X, so don’t worry abot it). Select XC8 and click on Next.

Then we are almost done, all we have to do is select the location of our project and give it a name. After you have made these life-changing decisions click on Finish.

The project is all set up and ready to go!

Step 2: Create the main.c file

Now we need to tell the project that we want to start writing our program! For that we have to create a source file. Right-click on Source Files on the left-hand side, click on New, and then select main.c in the menu:

In the next window you can select the file name, for which I suggest main, but it can be anything you want. Then click on Finish.

You will be presented with the automatically generated main.c file:

Step 3: Set the configuration bits!

Okay, now we need to set the so-called configuration bits. If you don’t understand this part at the first reading that is completely OK, just follow the steps and you will be fine.

Configuration bits tell the controller in which operation mode we want to run it. Controllers come with many features, and some of them can be turned on or turned off using the configuration bits. These are bits (meaning that they can be set to either 0 or 1) which work as switches for each functionality.

Luckily, MPLAB IDE X has a built-in manager for these bits to make it easy and convenient for us mortals. Simply click on Window, then on Target Memory Views and then on Configuration Bits:

In the lower bottom of the screen you will see the following Configuration Bits menu pop up. You can increase its size by pulling up that part of the window with your mouse. It looks like this:

Under Field we see the option that we are changing, and under Option we see our choice for that, well, option. Never mind, sounds confusing. Click on the Option boxes and select the following choices:

We can talk about what these options mean some other time, not now 🙂

Now click on Generate Source Code to Output to proceed. You will get this prompt here which you can highlight with your mouse and then copy:

Then go back to your main.c file, which is still open in the background, and paste this code into the beginning of the file like so:

It is important that you paste this code before the #include line, just like in the image above. That’s it, we have told the program what configuration bits we want successfully! Hooray!

Step 4: Writing the sample program

Without going into too much detail, this is the program we will insert after the #include line:

Here is the code ready to copy & paste:

#define LED RB0
#define _XTAL_FREQ 4000000

void main(void) {
    TRISB0 = 0;
    while (1) {
        LED = 1;
        LED = 0;

Okay, let’s talk a little bit about what that means, line by line:

  • Line 1: We define the pin RB0 (which is one of the pins of the 627A) as the LED pin. This is done just for convenience.
  • Line 2: We define the frequency of the internal oscillator to be 4MHz. It is not terribly important, we’ll get back to that later.
  • Line 4: This is the beginning of the main function. It is automatically generated by MPLAB IDE X, so we don’t have to think a lot about what it means. All we need to know is that our program goes into the lines between line 4 and line 17.
  • Line 6: We configure the pin RB0 to be of type OUTPUT since we want to connect an LED to it.
  • Line 8: This is the main “loop” of the program. It will run forever and it will repeat everything between Lines 9-14.
  • Line 10: we switch on the LED.
  • Line 11: we wait one second (or, rather, 1000 milliseconds). This is why we had to specify the oscillator frequency in line 2. If we hadn’t specified it, the controller would not know how many instruction cycles it takes to wait one second.
  • Line 12: we switch the LED off.
  • Line 13: we wait another second.

And that’s it! Not too bad, eh?

Step 5: Compile the program and generate the .hex file

In last week’s post we learned how to “flash” a controller with a hex file. Now we are at the point where we can create our own hex file! Isn’t this exciting?

To create our hex file we need to compile the source code we just wrote, and what that does is translate the human-readable code we just wrote into machine-readable hexadecimals. To do so, just press F11 (or click the hammer symbol in the toolbar). It will look like this:

See that green thing at the bottom? BUILD SUCCESSFUL. That’s what I like to hear (and you too, I hope)! It means that our hex file has been successfully generated! Hooray!

But where is it? Go to your project folder, and go to the subdirectory dist/default/production . There are many files in there, but one of them has the ending .hex, and, you guessed it, that is our hex file!

Step 6: Transfer your hex file to the PIC

Now you are done! Last week we already talked about how to transfer your hex file to your PIC controller, and I invite you to look at that article 🙂

In next week’s post I will talk about the electronics part. How do we assemble the LED test circuit, what tools do we need, and what should we think about.

Please let me know if you find this helpful, and please also tell me if something was not clear enough, and I will do my best to update it accordingly.

Thanks for reading this week’s article, and I will see you again next week! Stay tuned!

Appendix: The complete source code

Here is the complete source code for your reference, feel free to copy & paste it into MPLAB IDE X and have fun with it! Let me know if something doesn’t work.

 * File:   main.c
 * Author: boos
 * Created on April 18, 2019, 9:50 PM

#pragma config FOSC = INTOSCIO  // Oscillator Selection bits (INTOSC oscillator: I/O function on RA6/OSC2/CLKOUT pin, I/O function on RA7/OSC1/CLKIN)
#pragma config WDTE = OFF       // Watchdog Timer Enable bit (WDT disabled)
#pragma config PWRTE = OFF      // Power-up Timer Enable bit (PWRT disabled)
#pragma config MCLRE = ON       // RA5/MCLR/VPP Pin Function Select bit (RA5/MCLR/VPP pin function is MCLR)
#pragma config BOREN = ON       // Brown-out Detect Enable bit (BOD enabled)
#pragma config LVP = OFF        // Low-Voltage Programming Enable bit (RB4/PGM pin has digital I/O function, HV on MCLR must be used for programming)
#pragma config CPD = OFF        // Data EE Memory Code Protection bit (Data memory code protection off)
#pragma config CP = OFF         // Flash Program Memory Code Protection bit (Code protection off)

#include <xc.h>

#define LED RB0
#define _XTAL_FREQ 4000000

void main(void) {
    TRISB0 = 0;
    while (1) {
        LED = 1;
        LED = 0;

How to “flash” a PIC microcontroller?

Many interesting online electronics projects make use of microcontrollers, and for the beginner this tends to be a pretty intimidating word. At least it was for me when I started with hobby electronics many years ago. But there is really no reason you should be afraid of this topic. It is a bit involved, sure, but you will be amazed how fast you can make progress when you shake off that initial fear 🙂

Okay, so let’s say you have found a cool electronics project that you want to build yourself. On some website of some tinkerer who was kind enough to include the schematic and all other details you need. But the problem is: the project contains a microcontroller! What can you do?

Can you still build a project with a microcontroller, even if you don’t know anything about them? The answer is yes! Yes, you can! In this article I will focus on PIC microcontrollers by the company MicroChip, but the general idea works for all others as well. Let me know in the comments if you have any questions or if anything wasn’t clear 🙂

Step 1: Obtain the .hex file!

Microcontrollers are little computers, and they need a program to tell them what to do. It is a set of instructions, and that set of instructions needs to be transferred onto the controller to make it work. Usually this set of instructions is written in a programming language like C, Basic, Assembler, or whatever else. The good thing is: you don’t need to know any of this if all you want to do is transfer that program onto the controller!

All you need is the so-called .hex file. This is a file, only a few kilobytes large, which is unreadable to the human eye. It contains machine code written in hexadecimal, which is where the name comes from. This file is all that you need, and if you look closely on an electronics blog where somebody presents their project that includes a microcontroller, there will be a .hex file for download somewhere. If it isn’t, just ask! 🙂

Step 2: get a programming device

Okay, so now you have the .hex file. Next you need a programmer. What is that? It is a device, usually powered off of USB, that connects your computer to the microcontroller. Using a special software (see step 4 below), you will be able to transfer the .hex file into the microcontroller’s memory. Then, when the controller powers on, it will do whatever the .hex file tells it to do!

I suggest using the PICkit3. A simple Amazon search will show you many offers, usually around $30. I have used it for many years and it works great for programming PICs.

This is my PICkit3 that I bought many years ago, and it still works. Worth the money!

Oh, I almost forgot to mention: transferring the .hex file onto the controller is most of the times referred to as “programming” a PIC or “flashing” a PIC. Just so you know 🙂

Step 3: Connecting the PIC controller to the programmer

OK, now you have your PIC controller, you have your PICkit3, and now what? Now you have to connect the PIC to the PICkit3, of course! 😉 But how?

There are five connections you need to know about, and we will talk about them one by one. First, have a look at this picture of my PICkit3:

The six connections in the PICkit3.

There are six connections in a pin header at the PICkit3 called LVP, PGC, PGD, VSS, VDD, and MCLR. We will not be using LVP so let us ignore it in this article. So what do the five others stand for? Let us start with the two easy ones:

  • VDD is the positive operating voltage.
  • VSS is the ground potential.

And the others?

  • MCLR stands for Master Clear, and grounding this pin puts the PIC controller into programming mode. During normal operation it has to be connected to VDD so that the PIC controller does not reset.
  • PGD stands for Programming Data, and this is where the bits that are written into the controller during programming are transferred, much like in a shift register. It is the data line, and it can be high or low, depending on whether the PICkit3 is transferrring a high or low bit at that time.
  • PGC, finally, is the Programming Clock. Whenever there is a pulse on this line the current bit at PGD gets written into the PIC and internally the PIC moves to the next slot to write the next bit. It is the heartbeat of the programming cycle.

And the best thing: this is nice information, but we don’t need to know this! All we have to do is stick the PIC to a breadboard, add a pin-header, and connect the pins accordingly. Look up the datasheet of your PIC controller, where these pin names (MCLR, VDD, VSS, PGD, PGC) are clearly labelled. Then, use jumper wires to connect the PIC pins to the corresponding pin header, as you can see here:

Then you can stick the PICkit3 into the circuit, and connect it to a computer. In my case I did not really have a 45 degree pin header which is why I flipped the breadboard onto its side, but guess what, it works just fine 🙂

Step 4: Software stuff!

Now, finally, we need to download a free software by the company MicroChip. It is called MPLAB IPE X, which stands for Integrated Programming Environment 10. You can download it here. Yes, I know, it says MPLAB IDE instead of MPLAB IPE, but the IPE is included in this download.

Install the software and then run the MPLAB X IDE. it looks something like this:

Make sure that under Device you select your controller. Under Tool you should already see the PICkit3 if it is plugged in. Go ahead and plug it in now if you haven’t done it yet 🙂 Then, click on Connect. Click ‘OK’ on this message that appears:

Perhaps you get an error message like this:

“Target device was not found (could not detect target voltage VDD). You must connect to a target device to use PICkit 3.”

If yes, then click on Power on the left-hand side, and check Power Target circuit from Tool. Make sure it is set to the correct voltage (5V for a 5V controller, 3.3V for a 3.3V controller):

Then, click back on Operate and click Connect for the second time. Maybe it already shows that it is connected, if not, just click Connect again. Now it should look like this:

Click on Verify and click OK on this prompt:

Everything should work now, but you might get this error message:

Target Device ID (0x0) is an Invalid Device ID. Please check your connections to the Target Device. Would you like to continue?

Check your connections! It might be that one of the cables is loose! After that all should be OK and you should see this message:

Alright! Now we are in business! It’s time to load the .hex file! Click on File then on Import and then Hex to select your file, after which it should look like this:

Amazing! Now click on Program and watch the miracle ensue! This is what you will see:

Programming complete! You did it! The hex file is now securely stored on your controller!

Finish line! You did it!

Now simply unplug the PICkit3, turn off the software, and unplug the controller from the breadbord. It is ready to be plugged into its final destination!

I hope this tutorial was helpful. If you feel like I missed a few parts here and there, or something is wrong or incorrect, please let me know in the comments below and I will try to add the missing information!

On a personal note: I know it can be frustrating to venture off into the unknown. But it can also be so rewarding. Learning how to flash microcontrollers is taking a first step into an entirely new world! What used to be unattainable is now within your reach 🙂

© 2019 Friendly Wire

Theme by Anders NorenUp ↑