{"id":1808,"date":"2018-06-21T21:04:14","date_gmt":"2018-06-21T21:04:14","guid":{"rendered":"https:\/\/deepbluembedded.com\/?p=1808"},"modified":"2023-08-17T23:53:33","modified_gmt":"2023-08-17T20:53:33","slug":"pic-microcontroller-programming-tutorial","status":"publish","type":"post","link":"https:\/\/deepbluembedded.com\/pic-microcontroller-programming-tutorial\/","title":{"rendered":"PIC Microcontrollers Programming | Introductory Tutorial – MPLAB XC8"},"content":{"rendered":"\n\n\n\n\n
\"Previous<\/a><\/td>\nPrevious Tutorial<\/strong><\/a><\/td>\nTutorial 1<\/span><\/strong><\/span><\/td>\nNext Tutorial<\/strong><\/a><\/td>\n\"Next<\/a><\/td>\n<\/tr>\n
<\/td>\nPIC Microcontrollers Programming<\/strong><\/span><\/td>\n<\/td>\n<\/tr>\n
<\/td>\nPIC Microcontrollers Course Home Page <\/strong><\/span>????<\/a><\/td>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n

 <\/p>\n

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.<\/span><\/p>\n

[toc]<\/p>\n


\n

\u00a0 \u00a0Introduction To Microcontrollers\u00a0 \u00a0<\/span><\/strong><\/span><\/h3>\n

 <\/p>\n

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\u00a0\u00b5C. 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.<\/span><\/p>\n

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.<\/span><\/p>\n

\"Embedded<\/p>\n

A typical drone will have an internal structure as shown in the diagram below.<\/span><\/p>\n

\"microcontroller-programming\"<\/p>\n

Well, this aerial robot consists of some mechanical & electrical parts. We’re only concerned with the electronic embedded system which has the following components<\/span><\/p>\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Sensors<\/span><\/strong><\/span><\/td>\nCamera<\/span><\/strong><\/span><\/td>\nElectronic sensor used for imaging and video recording.<\/span><\/td>\n<\/tr>\n
GPS<\/span><\/strong><\/span><\/td>\nThis sensor is used to get the coordinates information of the vehicle at any instance of time. Widely used for locomotion tasks.<\/span><\/td>\n<\/tr>\n
IMU<\/span><\/strong><\/span><\/td>\nAn 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.<\/span><\/td>\n<\/tr>\n
Compass<\/span><\/strong><\/span><\/td>\nThis sensor is used to measure the heading angle of the vehicle which is very helpful for controlling its orientational motion.<\/span><\/td>\n<\/tr>\n
Modules<\/span><\/strong><\/span><\/td>\nWiFi<\/span><\/strong><\/span><\/td>\nThis modules adds a WiFi internet connectivity to the vehicle. Used for control or data transfer<\/span><\/td>\n<\/tr>\n
RF<\/span><\/strong><\/span><\/td>\nThis modules adds a Radio Frequency connectivity to the vehicle. Used for communicating with the control station.<\/span><\/td>\n<\/tr>\n
External Memory<\/span><\/strong><\/span><\/td>\nOn-Board additional memory for data & settings storage<\/span><\/td>\n<\/tr>\n
Drivers Circuitry<\/span><\/strong><\/span><\/td>\nESCs<\/span><\/strong><\/span><\/td>\nElectronic Speed Controllers. These electronic circuits are pre-built and packaged devices that are being sold as an electronic driver solution used for brushless motors.<\/span><\/td>\n<\/tr>\n
Actuators<\/span><\/strong><\/span><\/td>\n4 x Brushless Motors<\/span><\/strong><\/span><\/td>\nThese are the actuators that cause motion for this vehicle.<\/span><\/td>\n<\/tr>\n
DC Power Source<\/span><\/strong><\/span><\/td>\nBatteries<\/span><\/strong><\/span><\/td>\nThe 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.<\/span><\/td>\n<\/tr>\n
Central Computer<\/span><\/strong><\/span><\/td>\nMicrocontroller<\/span><\/strong><\/span><\/td>\nThis 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<\/strong>) via the RF module to pass your commands to the vehicle which will follow them.<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n

There is no doubt that the\u00a0\u00b5C 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.<\/span><\/p>\n

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!\u00a0<\/span><\/p>\n


\n

\u00a0 \u00a0What is a Microcontroller?\u00a0 \u00a0<\/span><\/strong><\/span><\/h3>\n

 <\/p>\n

A Microcontroller<\/strong> 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.<\/span><\/p>\n

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.<\/span><\/p>\n\n\n\n\n\n\n\n\n\n
<\/td>\nComputer<\/span><\/strong><\/span><\/td>\nMicrocontroller<\/span><\/strong><\/span><\/td>\n<\/tr>\n
RAM<\/strong><\/span><\/td>\n1 – 8 GB<\/span><\/td>\n128byte – 512Kbyte<\/span><\/td>\n<\/tr>\n
ROM<\/strong><\/span><\/td>\nfew MBs<\/span><\/td>\n4 – 46Kbyte<\/span><\/td>\n<\/tr>\n
Clock Rate<\/strong><\/span><\/td>\n1 – 4GHz<\/span><\/td>\n32KHz – 20MHz<\/span><\/td>\n<\/tr>\n
CPU Cores<\/strong><\/span><\/td>\nup to 16<\/span><\/td>\n1<\/span><\/td>\n<\/tr>\n
Serial Ports<\/strong><\/span><\/td>\nUSB, RS422 & RS232<\/span><\/td>\nUART, SPI, I2C & USB<\/span><\/td>\n<\/tr>\n
Current Drain<\/strong><\/span><\/td>\n1.5Amps<\/span><\/td>\n50mA<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n\n\n\n\n
Note<\/span><\/strong><\/td>\n<\/td>\n<\/td>\n<\/td>\n<\/tr>\n
\n

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!<\/span><\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n

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.<\/span><\/p>\n

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!<\/span><\/p>\n


\n

\u00a0 \u00a0Variants Of Microcontrollers\u00a0 \u00a0<\/span><\/strong><\/span><\/h3>\n

 <\/p>\n

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.<\/span><\/p>\n

\u00a0 Bus Width\u00a0\u00a0<\/span><\/h4>\n

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.<\/span><\/p>\n

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.<\/span><\/p>\n\n\n\n
8-Bit\u00a0\u00b5Cs<\/strong><\/span><\/td>\n16-Bit\u00a0\u00b5Cs<\/strong><\/span><\/td>\n32-Bit\u00a0\u00b5Cs<\/strong><\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n

\u00a0 Memory Type\u00a0\u00a0<\/span><\/h4>\n

Microcontrollers’ memory may be embedded within the chip itself or the chip could be designed to operate using an external memory hooked to the\u00a0\u00b5C chip externally.<\/span><\/p>\n\n\n\n\n
Internal Memory MCUs<\/strong><\/span><\/td>\nExternal Memory MCUs<\/strong><\/span><\/td>\n<\/tr>\n
These devices are designed with all needed RAM and ROM memories built-in. There is no need for any external connections for memory.<\/span><\/p>\n

This represents the majority of the MCUs being manufactured nowadays.<\/span><\/td>\n

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.<\/span><\/p>\n

This type of MCUs had to disappear with the emergence of internal memory designs only 5 years later back in 1975.<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n

\u00a0 Instruction Set\u00a0\u00a0<\/span><\/h4>\n

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.<\/span><\/p>\n\n\n\n\n\n\n\n\n\n\n\n
Instruction Name<\/strong><\/span><\/td>\nThe Function It Performs<\/strong><\/span><\/td>\n<\/tr>\n
ADD<\/strong><\/span><\/td>\nAdds two operands together<\/span><\/td>\n<\/tr>\n
SUB<\/strong><\/span><\/td>\nSubtracts two operands<\/span><\/td>\n<\/tr>\n
MUL<\/strong><\/span><\/td>\nMultiplies two operands<\/span><\/td>\n<\/tr>\n
DIV<\/strong><\/span><\/td>\nDivide the first operand by the second one<\/span><\/td>\n<\/tr>\n
AND<\/strong><\/span><\/td>\nPerform logical AND<\/strong>ing Bit-Wise for two operands<\/span><\/td>\n<\/tr>\n
OR<\/strong><\/span><\/td>\nPerform logical OR<\/strong>ing Bit-Wise for two operands<\/span><\/td>\n<\/tr>\n
XOR<\/strong><\/span><\/td>\nPerform logical exclusive-ORing Bit-Wise for two operands<\/span><\/td>\n<\/tr>\n
And So On…<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n

Let’s consider a microcontroller which has a very basic instruction set that does not include the Modulus %<\/strong> 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)<\/span><\/p>\n

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.<\/span><\/p>\n

Hence, there are basically two categories for instructions sets. There are devices with only basic function instructions which are called RISC-Machines<\/strong>. (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<\/strong>. (CISC = Complex Instruction Set Computers). In conclusion, the 2 major computer architectures are the 2 listed down below.<\/span><\/p>\n\n\n\n
RICS<\/strong><\/span><\/td>\nCISC<\/strong><\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n

\u00a0 Architecture\u00a0\u00a0<\/span><\/h4>\n

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\u00a0data 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.<\/span><\/p>\n

\"microcontroller-programming\"<\/p>\n

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).<\/span><\/p>\n

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.<\/span><\/p>\n

Here is a brief summarized comparison between the Harvard & Von-Neumann computer architectures<\/span><\/p>\n\n\n\n\n\n\n\n\n\n
Harvard Architecture<\/strong><\/span><\/td>\nVon-Neumann Architecture<\/strong><\/span><\/td>\n<\/tr>\n
It uses tow separate memory spaces for program instructions and data variables<\/span><\/td>\nIt uses the same memory space for storing both of program instructions and also the data variables<\/span><\/td>\n<\/tr>\n
Allows for different bus widths<\/span><\/td>\nIt limits the operating bus width<\/span><\/td>\n<\/tr>\n
Data transfers and instruction fetches can be performed simultaneously<\/span><\/td>\nData transfers and instruction fetches cannot be performed simultaneously<\/span><\/td>\n<\/tr>\n
Creating a control unit for two different buses it too complicated and costly process<\/span><\/td>\nCreating a control unit for a single bus is much easier, cheaper and faster process<\/span><\/td>\n<\/tr>\n
The processor needs as low as one single clock cycle to execute an instruction<\/span><\/td>\nThe Processor needs more clock cycles to complete an instruction execution\u00a0<\/span><\/td>\n<\/tr>\n
Is widely used in microcontrollers and digital signal processing units (DSPs)<\/span><\/td>\nCommonly used in our personal desktop computers (PCs) and laptops as well<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n

\u00a0 Manufacturers’ Families\u00a0\u00a0<\/span><\/h4>\n

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\u00a0electric power utilization, and so on.<\/span><\/p>\n

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.<\/span><\/p>\n

Don’t care too much about the\u00a0exact 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.<\/span><\/p>\n

\u00a0 Which MCUs We’ll Be Using And Why?\u00a0\u00a0<\/span><\/h4>\n

For this microcontroller programming series of tutorials, we’ll be using an 8-Bit mid-range PIC microcontroller. It’s called PIC16F877A<\/strong> 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.<\/span><\/p>\n

We’ll also be using some variants of the 16F family and some members of the 18F family\u00a0in 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.<\/span><\/p>\n

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.<\/span><\/p>\n

Why<\/strong> we’ll use an 8-Bit mid-range MCU? Well, there are a few reasons to do so<\/span><\/p>\n