PIC Microcontrollers Programming | Introductory Tutorial – MPLAB XC8
|Previous Tutorial||Tutorial 1||Next Tutorial|
|PIC Microcontrollers Programming|
|PIC Microcontrollers Course Home Page 🏠|
In this tutorial, you’ll get to know what are microcontrollers? What’s inside a typical MCU chip? How do PIC microcontrollers operate? Set everything up, and become familiar with the development environment or the Microchip PIC microcontrollers ecosystem which we’ll be using through this series of tutorials. Using MPLAB X IDE, XC8 Compiler, and PICkit2 or 3.
- 1 Introduction To Microcontrollers
- 2 What is a Microcontroller?
- 3 Variants Of Microcontrollers
- 4 What’s Inside a Microcontroller?
- 5 Microcontrollers VS Microprocessors
- 6 Fundamental Terminologies
- 7 Cross-Development
- 8 Which Language To Use?
- 9 The compiler ( XC8 )
- 10 IDE ( MPLAB X )
- 11 How Does a µC Run a Program?
- 12 Computer Simulation
- 13 Development Hardware Kit
- 14 Prototyping Board
- 15 Share this:
- 16 Like this:
- 17 Related
Introduction To Microcontrollers
As we stated earlier, an embedded system is a computerized system that in most cases will not look like a computer. We’ve also mentioned numerous examples of embedded devices applications. The computers being embedded in these devices are small microcontrollers (MCUs) or also abbreviated as µC. You should also know that microcontrollers are not the only option out there for embedded solutions/devices, but MCUs are our main interest in this series of tutorials.
Now, we’ll consider one of the previous embedded devices examples to have a closer look at its main components. Let’s consider the Drone for example.
A typical drone will have an internal structure as shown in the diagram below.
Well, this aerial robot consists of some mechanical & electrical parts. We’re only concerned with the electronic embedded system which has the following components
|Sensors||Camera||Electronic sensor used for imaging and video recording.|
|GPS||This sensor is used to get the coordinates information of the vehicle at any instance of time. Widely used for locomotion tasks.|
|IMU||An IMU is an inertial measurement unit. It’s typically used to get information about the static/dynamic properties of the vehicle. Such as angular rates, tilt angle, and acceleration in 3 axes. In order to keep its balance and plan for smooth maneuvering.|
|Compass||This sensor is used to measure the heading angle of the vehicle which is very helpful for controlling its orientational motion.|
|Modules||WiFi||This modules adds a WiFi internet connectivity to the vehicle. Used for control or data transfer|
|RF||This modules adds a Radio Frequency connectivity to the vehicle. Used for communicating with the control station.|
|External Memory||On-Board additional memory for data & settings storage|
|Drivers Circuitry||ESCs||Electronic Speed Controllers. These electronic circuits are pre-built and packaged devices that are being sold as an electronic driver solution used for brushless motors.|
|Actuators||4 x Brushless Motors||These are the actuators that cause motion for this vehicle.|
|DC Power Source||Batteries||The rechargeable power source used for drones. It’s the bottleneck of the whole system which can definitely tell for how long can this machine fly in the air.|
|Central Computer||Microcontroller||This is the brain of the system that handles all computations implemented in the control system mathematical model. It also interfaces all sensors to collect all the needed data for a robust controlled behavior and also communicates with the operator (you) via the RF module to pass your commands to the vehicle which will follow them.|
There is no doubt that the µC or the embedded computer is the most important part of these components as it handles almost everything. A typical sensor or actuator may possibly have a datasheet associated with it that can take no longer than 10 pages. On the other hand, a very simple microcontroller will typically have a datasheet that is no less than 100 pages long. In fact, most MCUs chips have datasheets that are between 200-2000 pages long! Each module within these small chips can have a documentation that is 25 pages long on average.
That’s why in the following tutorials we’ll be more focused on the microcontroller programming and we’ll discuss each of the modules in detail to understand the underlying mechanics. However, we’ll also be interfacing many of the common modules & sensors on our way through. We’ll do our best to balance between understanding all the MCU’s modules in detail, and practically interface some sensors/actuators to create small projects. So stick with me! It’s gonna be tough indeed but it’s really worth it and definitely rewarding!
What is a Microcontroller?
A Microcontroller is a single-chip, self-contained computer which incorporates all the basic components of a personal computer on a much smaller scale. Microcontrollers are typically used as embedded controllers that control some parts of a larger system such as mobile robots, computer peripherals, etc.
A microcontroller is fundamentally a smaller version of your personal computers. It has the same exact component but with limited capabilities and resources. An arbitrarily-made comparison between X-Computer and Y-MCU may result in a table that looks like the one below.
|RAM||1 – 8 GB||128byte – 512Kbyte|
|ROM||few MBs||4 – 46Kbyte|
|Clock Rate||1 – 4GHz||32KHz – 20MHz|
|CPU Cores||up to 16||1|
|Serial Ports||USB, RS422 & RS232||UART, SPI, I2C & USB|
A microcontroller is not the same as a microprocessor. A microprocessor is a single-chip CPU used within other computer systems. While a microcontroller is itself a single-chip full computer system!
We use microcontrollers extensively in embedded systems design. You can spot its existence in a tremendous number of applications and devices around you. A microcontroller can possibly show a higher efficiency and performance in some sort of applications than any computer we use.
When it comes to low-end devices and minimal power utilization, there is nothing comparable with microcontrollers. It drains a few milli-amperes that will result in a substantial increase in the device’s battery life!
Variants Of Microcontrollers
Microcontrollers can be categorized in many different ways depending on numerous metrics. They could be categorized based on their memory architecture, bus width, CPU architecture, manufacturer and so on. Here I will list down some of these categories and finally will tell you which MCU chips we’ll be using in these tutorials and why.
The bus width (number of wires) determines the capability of the computer to handle data words of a specific length. An X-Bits microcontroller can manipulate data up to X bits in size. However, there are many MCUs that have a full instruction set that handles 8-Bit data alongside with a few ones for handling 16-Bit words. In this case, it should be called an 8-Bit machine! A specific microcontroller is considered as an X-Bit Computer if it has an instruction set that most of its instructions are designed to manipulate data words of X-Bits size.
The 8-Bit microcontrollers are the most common with highest shipping volume in the market. However, there are 16-Bit and 32-Bits microcontrollers that are used for high-performance applications that require excessive computational power. In conclusion, the microcontrollers’ market standards in bus widths are the 3 ones listed down below.
|8-Bit µCs||16-Bit µCs||32-Bit µCs|
Microcontrollers’ memory may be embedded within the chip itself or the chip could be designed to operate using an external memory hooked to the µC chip externally.
|Internal Memory MCUs||External Memory MCUs|
|These devices are designed with all needed RAM and ROM memories built-in. There is no need for any external connections for memory.
This represents the majority of the MCUs being manufactured nowadays.
|In the past, some chips had no program memory built-in and they had to connect it externally. That’s what happened with Intel’s 4004 MPUs back in the late 60’s.
This type of MCUs had to disappear with the emergence of internal memory designs only 5 years later back in 1975.
Every single microprocessor has its own instruction set which defines the basic function it only can handles. Some sophisticated functions could be achieved using the basic instructions available in the instruction set of a microprocessor. Here is an example of a set of assembly instructions that could be found in any device out there.
|Instruction Name||The Function It Performs|
|ADD||Adds two operands together|
|SUB||Subtracts two operands|
|MUL||Multiplies two operands|
|DIV||Divide the first operand by the second one|
|AND||Perform logical ANDing Bit-Wise for two operands|
|OR||Perform logical ORing Bit-Wise for two operands|
|XOR||Perform logical exclusive-ORing Bit-Wise for two operands|
|And So On…|
Let’s consider a microcontroller which has a very basic instruction set that does not include the Modulus % operation, which returns the remainder of the division. (e.g. 5%2 = 1 , 7%3 = 1 , 6%2 = 0 , 10%4 = 2 and so on)
Then, it’s going to be the programmer’s task to use the basic functions available in the MCU’s instruction set to implement the Modulus function. And so on for the rest of the functions.
Hence, there are basically two categories for instructions sets. There are devices with only basic function instructions which are called RISC-Machines. (RISC = Reduced Instruction Set Computers). And there are devices with a bunch of sophisticated functions hardware-implemented (with digital logic) which have complex instruction sets. That’s why these type of devices are called CISC-Machines. (CISC = Complex Instruction Set Computers). In conclusion, the 2 major computer architectures are the 2 listed down below.
Back in the late 40’s, both of Harvard and Princeton universities were asked by the US government to come up with an architecture for a computer that could be used in military applications. Princeton’s computer architecture was named after their genius mathematician John Von Neumann. Which had a single memory to store the program instructions as well as data variables. While the Harvard architecture had two separate memories. A ROM for program instructions and a RAM for data variables. The diagram below shows you the difference between those two architectures.
All in all, the Harvard architecture is the most common option for the microcontrollers used in embedded systems applications. However, sometimes you’ll encounter Von-Neumann machines specifically when you are working with larger computers (processors).
The microcontrollers we’ll be using in this series of tutorials is a Harvard machine like the most microcontrollers in the market obviously. That’s why we’ll be only concerned with this architecture and dedicated to understanding the mechanics in which a Harvard machine actually works. We’ll address this process hereafter in this tutorial so stick around.
Here is a brief summarized comparison between the Harvard & Von-Neumann computer architectures
|Harvard Architecture||Von-Neumann Architecture|
|It uses tow separate memory spaces for program instructions and data variables||It uses the same memory space for storing both of program instructions and also the data variables|
|Allows for different bus widths||It limits the operating bus width|
|Data transfers and instruction fetches can be performed simultaneously||Data transfers and instruction fetches cannot be performed simultaneously|
|Creating a control unit for two different buses it too complicated and costly process||Creating a control unit for a single bus is much easier, cheaper and faster process|
|The processor needs as low as one single clock cycle to execute an instruction||The Processor needs more clock cycles to complete an instruction execution|
|Is widely used in microcontrollers and digital signal processing units (DSPs)||Commonly used in our personal desktop computers (PCs) and laptops as well|
Each company in the microcontrollers manufacturing business is producing different series (families) of their architecture. The obvious reason for doing so is to satisfy the needs of many different segments that require microcontrollers chips with specific performance levels. Some applications require excessive computational power, some require less and some may require minimal electric power utilization, and so on.
The most common choices in the meantime will be a Microchip PIC, Atmel AVR or ARM chip. These are the most common widely-available architectures out there. An 8Bit MCU from the mid-range PIC family will help you so much to get started. Or equivalently an 8-Bit AVR will do the job indeed.
Don’t care too much about the exact devices that are being used at the production level. As the embedded industry is so broad and there is a room for every single architecture which at some point will be the best fit for the job.
Which MCUs We’ll Be Using And Why?
For this microcontroller programming series of tutorials, we’ll be using an 8-Bit mid-range PIC microcontroller. It’s called PIC16F877A which you may have seen at least once before. Despite being an old product it’s still very useful & cost-efficient for both learning and creating projects. The newly manufactured chips while having the same old name & architecture they are technically more efficient than before in terms of power utilization and the overall performance.
We’ll also be using some variants of the 16F family and some members of the 18F family in order to develop sophisticated USB drivers and create some interesting applications. Which will help you much see how easy it is to port your projects and transfer your mastery/knowledge from a platform to another.
You will always be free to use the chip you want, there is no restriction to the 16F877A chip. As long as you’ll make sure everything is correctly configured. In this case, please be advised to use my code listings at your own risk. Or just comment wherever it’s relevant to tell us your exact situation in order to get helped.
Why we’ll use an 8-Bit mid-range MCU? Well, there are a few reasons to do so
- It’s a beginner-friendly device with limited resources that will definitely help you be more focused on specific modules while writing efficient firmware that fits in these chips with limited resources
- Simple MCU architecture means a short read datasheet (around 200 pages) which is a lot easier to grasp
- Market availability. The 8-Bit MCUs have the lion’s share of the embedded systems market in terms of devices being shipped every single year. So it’s easier to get your starting kit locally
- The large community that was and still supporting these devices. Which means you’ll easily find helpful content online when you get stuck at any point
- Low cost. Obviously, an 8-Bit microcontroller is too way cheaper than a sophisticated one. Just in case you feel not interested enough in embedded systems, you won’t lose much money on a fancy kit.
I believe that platforms with very limited resources are the best choice to get started in embedded systems. Embedded systems design is all about optimization and doing more with less. Fewer instructions, less memory, less power, and less money. We are problem-solvers and optimizers. Having a platform with excessive resources contributes to growing bad coding habits that go forever uncorrected.
What’s Inside a Microcontroller?
A Microcontroller is usually a black IC with a bunch of pins coming out of It. The most common package type used for prototyping is the DIP (dual in-line) which fits nicely in a typical breadboard. While the QFP packages are the most efficient ones, usually used for creating professional PCBs that take much less space.
You should also note that the external packaging material is a solid epoxy for protection purposes. But the actual microcontroller is actually much smaller. Here is a picture of a microcontroller chip internal structure. In which you can see that a typical microcontroller is something that is even smaller than the smallest of your nails!
Can you see those tiny wires coming out the core? Well, these wires are actually connected to the external pins on both sides of the chip which we typically use for i/o (Input/Output) purposes. This essentially means that the maximum current could be sunk or sourced from an i/o pin will be a very few milli-amps in best cases.
We stated earlier that a microcontroller is just a smaller version of a full computer machine. Here is a brief table of the main components (modules) typically found in a generic microcontroller.
|CPU||The core processing unit|
|RAM||Random Access Memory for data storage|
|ROM||Read Only Memory for program storage|
|I/O Pins (Ports)||8,10,16,20,28,40 or more pins|
|Serial Ports||USART, SPI, I2C and maybe USB|
|Timers||1,2,3 or more timers|
|Interrupts||Full logic circuitry to generate and control interrupt signals|
|Peripherals||Additional features as EEPROMs, PWM, Comparators and so on.|
|Oscillator||Generate or control the input clock signal to guarantee a harmonic behavior for the whole machine|
The following hand-drawn diagram shows you the main components typically found in a generic microcontroller and how they are organized. With simplified interlinkings that connect all of these modules altogether.
This is the working horse of the microcontroller internal system. It handles your program instructions and executes them after the processes of fetching and decoding. It also has the ALU inside which does all the arithmetic and logical calculations. A typical simple 8-Bit CPU will execute a single instruction in about 4 machine cycle. While a pipelined design will be, seemingly, running 1 instruction/machine cycle.
The Random Access Memory is the unit which contains the data registers which are used for data storage and also for controlling the operation of all other modules. The registers of the RAM could be categorized into two categories: GPRs & SFRs.
GPRs: stands for General Purpose Registers. Which are used to store data variables that will allocate random addresses. Most of the registers in a typical RAM are GPRs.
SFRs: stands for Special Function Registers. Which are hard-wired to most of the modules within a microcontroller. This allows for the control of each module by moving 0’s and 1’s to the special register that corresponds to this module. For example, TIMERx could be turned ON/OFF by moving 1 or 0 to the bit TMRxON, where x may be 0,1 or 2. And so on
Read Only Memory. This memory unit is dedicated to storing the program instructions (assembly). Every single instruction is stored in an x-Bits register. The number of bits depends on the architecture and design of the CPU itself and its instruction set. The MCU we’ll be using has a ROM that is 14-Bit in width.
Program instructions are stored in consecutive order in the ROM unlike the random nature of a RAM. The instructions are addressed by a specific register called the program counter PC which points to the instruction that has to be executed now. Executing a full program is a matter of incrementing the PC that point to the instructions which will be executed by the CPU.
The input/output ports are the very basic way to communicate with a microcontroller. You can input digital signal to a microcontroller with a simple push button or a sensor. Likewise, you can get a digital output (0 or 1) out of microcontroller that could be used to blink a LED or trigger a motor driver circuity or whatever.
Serial ports allow for advanced communication with a microcontroller. As we can send or receive streams of data serially. This could be numbers, audio, images or even files. Serial ports are extensively used to create machine-machine interfaces as well as human-machine interfaces.
Serial ports include USART, SPI, I2C, USB and much more protocols that are specific-purpose. We’ll discuss each of them in depth hereafter in this series of tutorials.
There is no embedded application that does something real in a real-world application that is not using a timer in one way or another.
A typical microcontroller may have 1, 2 or more hardware timer modules. Which are mainly used for generating time intervals that separate specific events and control time-dependent events. It’s also used for calculating the time between any couple of hardware/software events as if it’s a stopwatch!
An interrupt is an event that suspends the main program execution while the event is serviced (Handled) by another program. Interrupts substantially increase the system’s response speed to external events. Different microcontrollers have different interrupt sources which may include timers, serial ports, IRQs or even software interrupt.
Immediately on receiving an interrupt signal, the current instruction is suspended, the interrupt source is then identified and the CPU branches (vectors) to an interrupt service routine stored in a specific address in memory. The interrupt handler program (code) is usually called interrupt service routine or ISR.
The interrupt circuitry unit is a digital logic circuit that controls the generation of interrupt signals and commands the CPU to handle these interrupts requests on time.
This module is responsible for the harmonic synchronous operation within the microcontroller itself. Even if the microcontroller has no internal oscillator this module will be right there to control the input clock signal to generate a unified clock signal (internally) that synchronizes all the events/operations within the microcontroller.
These are basically the wires that connect everything inside a microcontroller. The bus is defined by its width, this feature is called bus width. The bus width is the number of the physical wires that make up the bus itself. It could be 4, 8, 16, or any number obviously.
If a device A is connected to device B via a 4-wires bus, this could be symbolically represented as shown in the diagram below.
The bus could be drawn as a straight line that connects a digital circuit to another. And the bus width is abbreviated with a small number that tells how many wires are there.
A microcontroller may or may not have any of the following modules. It may have all of them as well. All in all, these modules are extra additional features that a microcontroller can run flawlessly without. You can always buy any of these modules as a separate IC package and hook it externally to your microcontroller so easily.
|EEPROM||Electrically Erasable Programmable Read Only Memory. This memory unit is used for storing data that we need our MCU to store even when the power goes OFF.|
|ADC||Analog To Digital Converter. This module is used to convert the analog voltage values 0-5v to a digital value on a scale that is dependent on the resolution of an ADC.
An 8-Bit ADC can convert (0-5v) to a scale of (0-255) and a 10-Bit ADC can convert it to a scale of (0-1024) and so on.
|DAC||Digital To Analog Converter. This module converts the digital values to analog voltage (0-5v) that could be used to generate audio waveforms or whatever.|
|PWM||Pulse Width Modulation. This module utilizes one of the hardware timer modules available on you MCU chip to generate a square-wave signal that you can control it’s average value (with changing its duty cycle). You also have a control over the output signal’s frequency.|
|Comparator||This module is an analog comparator that is integrated within the MCU chip itself. So you don’t need to convert analog signals to digital values for comparison. With this module, you can compare analog signals on the run.|
During this microcontroller programming series of tutorials, we’ll discuss all of the above modules and even much more. But this will be done after the end of the course’s core content itself.
Microcontrollers VS Microprocessors
There is a fundamentally huge difference between microcontrollers (MCUs) and microprocessors (MPUs). However, there many of who are still confuse these terms. So let’s put it in perspective.
The chip on the left is a Microcontroller. It’s an atmega16 from Atmel. This single chip has a built-in CPU, RAM, ROM, IO Ports, Serial Ports (SPI, I2C & UART), 3 Timers and many other peripherals. It’s a single chip full computer! On which you can flash and run your code and also take advantage of all the built-in peripherals.
The chip on the right is a Zilog Z80 Microprocessor. It’s an old microprocessor released back in 1976. This is a bare processor that needs a RAM, ROM, and interfaces to do any computing job as any microcontroller out there.
Now, I will connect some peripherals to my Z80 MPU such as a dynamic RAM, ROM, ADC, DAC, and an IO Controller. As shown in the image below
Now we’re talking! The microprocessor is now connected to a RAM & ROM. Which means that we can load a program for it to execute. It’s also connected to an ADC, DAC and IO Controller which means that it’s capable of doing some basic input/output operations.
But is it really comparable to a microcontroller? Nope! maybe after connecting the peripherals, as shown above, we can compare the MPU with its externally connected peripherals with an MCU which will still be too way ahead of the MPU. The MCU still has more peripherals, ports, and features than the few external ones which we added to the MPU.
The Bottom Line
A Microcontroller is typically a smaller version of a computer which has a microprocessor as its own CPU. With internal RAM, ROM and a bunch of peripherals. It’s a full computer system on a single chip!
While a Microprocessor is single chip CPU that cannot do anything without connecting some external hardware to create a computer system.
You should be familiar with the following fundamental terminologies. As a beginner in microcontroller programming, it’s absolutely substantial to understand all of the following terminologies. Read them carefully and mark the ones you can’t grasp right now. At the end of this tutorial, you’ll be sent again to read these definitions again. Then everything should be clear. If not, please use your search engine to find out what do these terms actually mean.
|Program||Set of instructions for a computer written in a programming language that implements an algorithm. Finally assembled in assembly instructions that are coded & flashed to the memory in form of 0‘s & 1‘s|
|Paging||A page is a logical block of memory. A paged memory system uses a page address and a displacement address to refer to a specific memory location.|
|Bank||A logical unit of memory, which is hardware-dependent. The size of a bank is further determined by the number of bits in a column and a row, per chip, multiplied by the number of chips in a bank.|
|Pointer||An address of a specific object in memory used to refer to that object.|
|Stack||The hardware Stack is a section of Memory which is used to store temporary data or registers’ values. A software stack is a last-in-first-out (LIFO) data structure that contains information that is saved (PUSHed) and restored (POPed).|
|Stack Pointer||A register that contains the address of the top of the hardware stack.|
|Program Counter||Abbreviated and well-known as the PC. It’s a register which holds the address of the next instruction to be executed. The program counter is incremented after each instruction is fetched (It’s incremented once/instruction cycle).|
|Interrupts||An interrupt is an event that suspends the main program execution while the event is serviced (Handled) by another program. Interrupts substantially increase the system’s response speed to external events|
|Interrupt Vector||The location from which the program continues execution. The location containing interrupt vector is usually passed over during regular program execution.|
|Clock||This is the beating heart of a Microcontroller. it’s Fixed-frequency signal that triggers or synchronizes CPU operation and events. A clock has a frequency which describes its rate of oscillation in MHz. The clock source could be an external RC network, Crystal Oscillator, Resonator or even a built-in internal clock source. The frequency of oscillation is usually referred to as FOSC|
|Machine Cycle||The machine cycle is the time it takes the system’s clock to repeat itself. For a microcontroller that has a 4MHz crystal OSC hooked to its clock input pins, the machine cycle will be 1/4000000 = 250 nanosecond|
|Instruction Cycle||The instruction cycle is the time it takes a microcontroller to complete the execution of a single instruction. This includes Fetching, decoding, execution and saving the result which takes 4 clock cycles for the MCU we’ll be using. So 1 instruction cycle = 4 machine cycles.
We can also say that a CPU that is running @ 4MHz executes FOSC/4 instructions per second = 1MIPS (million instructions per second)
We’ll be programming MCUs during these tutorials as you should expect. But what kind of development is this said to be? Well, when you’re coding on your PC to create applications that also run on PCs, this is said to be “Development” process. However, it’s not always the case.
In many situations, you’ll be writing code on a specific machine (e.g. your PC) which will eventually get compiled to a machine code that runs on another machine (e.g. Android, ios, MCUs, etc.). This is what we call “Cross-Development“, and this is the case for embedded firmware programming.
A compiler used for cross-development is often called a Cross-Compiler.
Which Language To Use?
There are actually many available programming languages to use for developing embedded software. However, the C-Programming language is the standard in this industry. It has been and still considered as the most efficient way to interact with the low-level hardware at the register level. Most of the advanced high-volume quality products are developed in C. We may mention Assembly at some points.
It’s been known for too long that you can do more optimizations in your system with the assembly language. And that’s true, but use it for learning purposes only at this phase. Otherwise, you’ll be wasting too much time without gaining profitable skills. As every processor has its own instructions, consequently it has its own assembly commands so it’ll only be an educational practice.
However, you’re not restricted to the other choices. Everybody has his own preferences. So I encourage you to use the language you’re familiar with. if it’s available for the device family which you’re using!
The compiler ( XC8 )
The programming language in which we’ll be writing firmware to the PIC MCUs is called the C-Language, the standard ANSI-C. Which has been the most efficient option for embedded software development during the past few decades. And still proves to be the best fit for writing firmware up till today.
And please be advised that this course is built upon the assumption of your familiarity with basic concepts in C-Language. However, all code listings are written to be newbie-friendly while maintaining the overall efficiency level as high as possible.
Almost all industrial machines, military fighters, rockets, spacecraft, compilers and even other programming languages all are built in C. With this fact in mind, you should appreciate the effort & time it takes a person to be good at this language. Just practice it as much as you can. It’s the key to mastery in almost every field of knowledge.
The C-Compiler we’ll be using is called XC8 from Microchip, for 8-Bit MCUs. You can download the suitable version for your OS from this Link.
Setting up the compiler is also a straightforward process that you can easily DIY it. Or you can follow the steps in the next tutorial for installing both MPLAB IDE + XC8 Compiler.
IDE ( MPLAB X )
The integrated development environment ( IDE ) is the software platform on which we’ll be developing our projects. This is computer software that gathers a bunch of tools that eliminates the overhead of less important tasks. This helps developers focus their attention on the whole system and spot their major problems that need more investigation.
The IDE which we’ll be using for this course (tutorials) is called MPLAB X from the Microchip inc itself, the same manufacturer of PIC microcontrollers. It’s the official option yet the most powerful one out there. It has too many great features which may possibly cause you a little bit of frustration. No need to worry anyway, you’ll get used to it very soon. You can download the suitable version for your operating system (Windows, Linux & MAC) through this link down below.
Other options of IDEs are some pirated (Cracked) software or drag-drop Arduino-like environments. This is based on what I’ve experienced myself, maybe there is a worthy choice that I wasn’t lucky enough to find. All in all, the official MPLAB IDE is more than enough for our course in the meantime.
For installation, you can follow the video down below (in Compiler’s section). However, you don’t actually have to. Installing MPLAB is kind of a straightforward process that sounds like: Next, Next, Next, Yes, Finish!
One thing to notice is that you MUST install the MPLAB IDE first before installing the compiler to avoid integration issues between both of them.
Despite the fact that IDEs are created to be very useful & efficient tools, the other face of the coin is that it gave us enough luxury to abandon all discipline at some points and tweak things here and there hopefully until a solution is successful. At the end of the day, we ended up having too many engineers with limited experience in the estimation of systems’ behavior under certain circumstances. Be Careful
How Does a µC Run a Program?
Now, we’re about to discuss how an embedded program runs on a typical microcontroller in technical terms. First of all, the program should be loaded into the microcontroller’s program memory (ROM). After writing the code in C, the compiler & assembler will generate a .hex file that you should burn (flash) to the microcontroller chip thereafter. The program instructions be a bunch of 0’s and 1’s obviously.
Next, the chip must be powered up as any electronic device. Typical microcontrollers run at 3.3 or 5v DC. We should also connect the crystal oscillator to provide the chip with the clock input.
Now, the microcontroller will start executing the instructions stored in memory sequentially. Each instruction execution take up to 4 clock cycles which work as follows
- An instruction is fetched by the CPU from the program memory. And the program counter PC gets incremented to point at the next instruction in the program memory.
- The fetched instruction will be decoded in the 2nd clock cycle.
- The instruction operation is performed (executed), it could be ADD, SUB, MOV, DIV or whatever. The execution happens during the third clock cycle.
- Finally, the result gets saved to the working register in the 4th cycle. Which was the final step in executing the first program instruction.
- Now, the PC is pointing to the 2nd instruction as you’ve seen in step 1. And everything is repeated over and over again forever or until the power goes OFF!
This obviously explains why a machine cycle = 1/4 instruction cycle. Or in other words, the MCU is said to perform Fosc/4 MIPS.
Using computer simulation software can substantially improve your learning experience with multiple embedded systems platforms (e.g. ARM, AVR, PIC, etc.). However, a typical simulation software (e.g. Proteus) will only catch you logical (Code) errors! even though it’s still a powerful tool that helps you avoid flashing and testing firmware on real hardware, as long as we can easily prove this firmware won’t run correctly or won’t give the expected results. With only a few clicks & drag-drop, you’ll have your schematics fully-connected and ready for some testing.
You can use whichever simulator you prefer. I’d strongly recommend Proteus for most beginners. And you can check their website to find a student version or whatever suits your budget.
If your code is running flawlessly in the simulator with 0% error. There is still no guarantee that it’ll run seamlessly in real-life settings on a real prototyping board. Any MCU-Based kind of system could possibly go really insane! just because of tiny hardware issues. These issues are impossible to be predicted by any means of computer simulation.
Development Hardware Kit
A typical course in embedded systems is practical in nature. Hence the importance of getting a decent hardware kit to play with. The list down below includes all the necessary parts & components needed for the practical LABs in the upcoming tutorials.
We can also categorize these components into 2 categories: Basic kit & Extra modules. The first one is everything you must have in order to follow-up these tutorials and create all the basic projects yourself in a real-world sense. The latter list has some extra modules, for larger budget beginners, which helps you complete almost all of the tutorials covered herein or create whatever project you’d like to develop at your own pace.
- The Basic Course Kit (Essentials)*
- Extra Modules For Advanced Tutorials (Optional)
Check out the specific components part names and quantities in the course kit resources page.
In embedded systems practice, you must be working with various hardware parts and especially microcontrollers which introduces the following issues.
I- Programming the microcontrollers in a generic way involves removing them from the breadboard and mounting it on the programmer circuitry. When the firmware is flashed to the MCU then you take it back to the breadboard testing environment. As you may have noticed that updating the firmware involves removing and reconnecting the MCU from the breadboard. Which will possibly damage your MCU and result in some bent & broken pins.
II- MCUs typically operate at 3.3v or 5v. Which requires that you’ve your own power supply and voltage regulation onboard in order to guarantee the operating power required specs.
For these reasons above, we’ll stick to a fixed on-board development connection. This means that you’ll have to construct the basic circuit down below only once. Then you’ll be able to easily test your projects on-board. This connection has the following features:
- On-board ICSP (In-Circuit Serial Programmer) port. Which means you can easily flash the chip without being removed from the breadboard.
- Regulated 5v power supply connection for powering the chip up. With LED indicator.
- Reset pin is pulled-up and hooked to a push button.
- Oscillator input pins are connected to our crystal oscillator.
The final fully connected circuit is shown down below.
At the end of this tutorial, please double-check the terminologies which you’ve seen earlier. Just to make sure these concepts are now clearer than before. Click the link down below
PIC Microcontrollers Course Home Page 🏠
|Previous Tutorial||Tutorial 1||Next Tutorial|