Friendly Wire

Discover the joy of electronics

Tag: tutorial

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 πŸ™‚

LEDs 101 – what do you need to know?

LEDs, or Light Emitting Diodes, are everywhere. Your smartphone? Check. Your microwave? Check. Your electric toothbrush? Check. In this article I want to present the basic ideas of how LEDs work and how you can use them in simple projects without having to rely on expensive after market solutions (such as wired LEDs with battery drivers that are expensive and often of questionable quality). Here we go!

Basic parameters that describe an LED

There are a few parameters and technical terms that you should keep in mind when looking at LEDs. They have the following names and meanings:

  • Current: Usually aroundΒ 20mA, this is how much current your LED needs to glow. There are also low current LEDs out there that require less current, typically aroundΒ 2-5mA. The exact value will be listed in your LED’s datasheet.
  • Voltage: Depending on the color of the LED, the voltage that drops across them is slightly different. You can calculate it using Planck’s constant and the exact wavelength of your LED, but typically the voltage is aroundΒ 2V – 2.5V. It is a bit higher for blue LEDs (they have a shorter wavelength and therefore one blue photon requires more energy) and a bit lower for red and infrared LEDs. Again, the exact value will be listed in your LED’s datasheet.
  • Clear or diffused: This is pretty self-explanatory, but it is important to keep in mind. Some LEDs come with a diffused body, that is, the light will spread more isotropically, whereas others come with a clear body that will direct the light in a narrow cone.
  • Beam angle: In case of a clear LED, light exits the LED body in a cone shape and there is usually an opening angle specified somewhere in the datasheet. A typical beam angle is between 30 – 60 degrees, but you can also look for more focused LEDs that have angles below 10 degrees.
  • LEDs come with a different diameter. Typical LEDs have 3mm, 5mm, 8mm, or 10mm diameter. There are other sizes and shapes as well, but they are less common. The larger the LED is, the more current it typically needs to glow. The voltage will be the same (for differently sized LEDs of the same color), provided there is only one LED chip in the body. If the LED consists of several chips in series, the voltages will add up.
  • RGB: Yes, there are also RGB LEDs. These LEDs are special types that actually contain a red, green, and blue LED combined in one housing. Treat each one of these LEDs as a separate LED πŸ™‚
  • Blinking: Some LEDs have a blinking-circuit built-in. This can be useful but it can also be pretty annoying if you don’t pay attention and actually needed a static LED instead of a blinky one. The datasheet is your friend!
  • Pre-wired: Especially on online stores such as Amazon or Ebay you can often find “LEDs for 5V” or “LEDs for 12V.” What does that mean? These LEDs come with a resistor that is calculated to work well with the specified voltage. These LEDs then do not need a current limiting resistor (see more below) and can be directly connected to the specified voltage.

Why are they called diodes?

LEDs stands for light emitting diode, and diodes are devices that have a polarity. The positive terminal is called the anode, and the negative terminal is called the cathode. The short leg is the cathode, and the long leg is the anode. But don’t worry: if you wire up an LED correctly and just get the polarity wrong, nothing happens. It just won’t glow. In that case just switch the plus and minus cables and then everything will be alright. But don’t forget the current limiting resistor that we will talk about next!

How do I calculate the LED resistor?

Usually, there are three parameters that you know when you are dealing with LEDs. The first one is the supplyvoltage that your circuit works with. That can be 5V, 9V, 12V, whatever you want. The second parameter is the LED current. If it is too high, it dies. Typical LED currents are in the range of 10-20mA (but the exact value is listed in the datasheet). We also know that LEDs have a typical voltage drop across the chip (this is the energy that is needed to emit light). This is roughly between 2V – 2.5V.

It is not very difficult to calculate the resistor that is needed to limit the LED current. You simply take the supply voltage and subtract the voltage that drops over the LED. Say your circuit works with 9V and your LED has a voltage drop of 2V. Then you need your resistor to kill the remaining 9V-2V=7V. You also know that the current should be, say, 20mA. Then we just use Ohm’s law:

R = V / I = 7V / 0.02A = 350 Ohms

To be safe you can just go with 470 Ohms in that case. Another example? Sure! Say you have a 10mA LED at a 5V circuit (and the LED drops, again, 2V):

R = 3V / 0.01A = 300 Ohms

You get the idea. These parameters are not super critical. For standard LEDs I typically use 470 Ohms at 12V or 9V, and 220 Ohms at 5V.

Deluxe variant: constant current source!

Sometimes it is important to get the current exactly right. What, for example, if you have three LEDs in series? Then the voltage drop over all of these add up, sure. But manufacturing inaccuracies can lead to fluctuations of a few 0.1V when you have more than two or three LEDs in series. And what if one LED shorts out at some time? Then all other LEDs will surely die because the voltage drop is too high resulting in an increased current.

The solution is given by the voltage regulator IC LM317. Here you can see how to wire it up:

All you need to know now is the current you want to achieve. Say, it is 12mA. Then the resistor R1 in the above diagram has to have the value

R1 = 1.25V / 0.012A = 105 Ohms.

That was easy, wasn’t it? The reason this is so simple lies in the fact that the LM317 is a smart device: an integrated circuit that regulates the current if it is wired up as indicated above. The voltage drop that was killed by the current limiting resistor in the previous example is now just dissipated as heat through the heat sink of the LM317.

A word of caution: This works well when you want to drive, say, four LEDs in series at a voltage of 12V. It does not work well if the voltage drop is too high because then the LM317 will have to dissipate too much heat.

Sometimes it is a good idea to combine these tools: put in a small current limiting resistor (to kill, say, 5V or so) and then do the fine-tuning with the LM317-circuit in series. Then you have the best out of two worlds: current regulation (in the word’s true meaning) and not too much heat dissipated. Great!

The LED rainbow – have fun!

LEDs are everywhere, and I hope that with this article you feel more confident when it comes to choosing an LED for your next project. Let me know if this article was helpful or not, and what you want to read about next! Thanks for reading πŸ™‚

Getting started with electronics in 2019! What do you need?

We live in a world that becomes more and more dominated by technology. I think this is a good thing, because it tends to improve the quality of our lives. But it is also easier and easier to get lost in the brave new tech world. When I was in high school, I decided that I wanted to learn how wires work, and eventually I took my first steps: I connected a battery, a switch, and a lamp, and that was my first circuit.

Fast forward to 2019: Circuits with actual wires become less and less every day. Almost every electronic circuit is now artfully etched into a PCB, and the electronic components are becoming smaller by the day. This is great, but it makes it more difficult to understand what is going on. Children in high school, nowadays, grow up with smartphones and tablet computers that were not even dreamed of twenty years ago.

When personal computers were new in the early 1980s, it was possible for a single person to read the entire manual and understand the entire product, start to finish. If there was a problem, you could read the schematic and fix it. This has become impossible nowadays: the circuits are just too complex.

But now we can decide: do we want to accept the status quo, or do we want to break with the routine and do something about it? I strongly recommend the second route πŸ™‚ It is never too late to learn something about the world that surrounds us.

Okay, so let’s say we decided to learn electronics in 2019. Now what? There is an approximately infinite number of tutorials, videos, books, e-courses, and electronics kits out there, just waiting for you to discover them. Really, one might say that it is a saturated market. Ironically, that makes it worse for the absolute beginner. How should I know which steps to follow when I want to learn electronics in 2019? There are just too many options!

It is easy if you have a concrete question: how does an OPAMP work? How can I program a PIC microntroller in-circuit? How do I calulate the optimal value of this buffering capacitor? But when you are new, it is difficult and sometimes impossible to know which question to ask. After all, knowing which question to ask is the most difficult part of any problem, I find.

So what to do?

Roughly, electronics can be divided into a few subcategories:

  • digital electronics with discrete logic ICs (the electronics of the 1970’s and 1980’s)
  • digital electronics with embedded microcontrollers (a.k.a. the electronics of today)
  • analog electronics (for example: audio electronics, amplifiers, measuring devices, …)

Instead of trying to understand everything at once I always recommend to start small. Pick one thing that you would like to understand, and get your hands dirty as soon as possible. No procrastination along the lines of “Hmmm, I wonder which book I should read. Let’s read the reviews instead!” but, rather, a simple-enough project that sparks some joy.

Friendly Wire

This is the title of this blog, because I really believe it. Wires are friendly. What do I mean by that? Over the next couple of months I want to present here a few simple electronics projects that will get you started in 2019. Projects you can follow at home, with an absolute minimum of special tools or equipment. Projects that are fun, that will hopefully make you want to learn more, that inspire you, and that give you a sense of understanding!

It is not the goal to explain everything there is to know about electronics on this blog. Others have done this way better than I could ever imagine to do. Instead, I want to pick you up in your everyday life, and shove an interesting circuit in your face πŸ™‚

We can do it! Let’s build it and figure out what it does! And in the end, we will have an interesting new piece of electronics that we build ourselves! That you built, because you can do it! With wires! And LEDs! And switches! Oh, and a battery maybe.

This is a picture of a so-called breadboard. These are nice because you can stick any electronic component in there with minimal effort. Then you can use wires to connect the components. In the above picture you can see LEDs, capacitors, resistors, a potentiometer is hiding at the bottom right, and in the top right you can see a battery clip for a 9V battery.

It is my goal for 2019 to present on this blog a variety of nice breadboard-based circuits. You can build them at home, you don’t even need a screwdriver. The most important detail: I will explain every thing along the way!

This is where I feel many tutorials are lacking, when it comes to beginners: they always assume some prior knowledge. But what if you don’t have time to read up on all of this on your own time? What if you have a job, a family to take care of, and you just have one hour on the weekend?

My goal is to create short, self-contained tutorials that have all the information you need to finish the project, start to finish, with no hidden tricks and without any strings attached.

Let me know in the comments if you are interested, and if you have a particular field of electronics you would like to know more about. It’ll take me a while to get this all figured out, but I already have a few ideas. Stay tuned.

If you want to stay in touch, consider signing up for our newsletter on the right side. I try to post once a week, and the electronics content will steadily increase.

And remember: you can do it! See you around!

© 2019 Friendly Wire

Theme by Anders NorenUp ↑