The situation we find ourselves today in the field of microcontrollers has its beginnings in the development of technology of integrated circuits. It enabled us to store hundreds of thousands of transistors into one chip, which was a precondition for the manufacturing of microprocessors. The first computers were made by adding peripherals, such as memory, input/output lines, timers and other circuits, to it. Further increase in package density resulted in designing an integrated circuit which contained both processor and peripherals. This is how the first chip with an integrated microcomputer, later known as the microcontroller, was developed.
Novices in electronics usually think that the microcontroller is the same as the microprocessor. That's not true. They differ from each other in many ways. The first and most important difference in favour of the microcontroller is its functionality. In order for the microprocessor to be used, other components, first of all memory, must be added to it. Even though it is considered a powerful computing machine, it is not capable of establishing direct communication with the peripherals. Instead, specialized circuits must be used for this purpose. This is how it was in the beginning and remains the same today.

On the other hand, the microcontroller is designed to be all of that in one. No other specialized peripheral components are needed for its operation as all necessary circuits, which otherwise belong to peripherals, have been already built into it. It saves both time and space required when designing a device.
Microcontrollers are very popular nowadays. Just pay attention to the example below and you will understand the reasons for their great success. It won't take up much of your time, just a couple of minutes.
Around ten years ago, the process of designing an electronic device controlling an elevator in a multistory building was extremely difficult, even for a team of experts. Have you ever thought of what requirements an ordinary elevator has to meet? How to deal with situation when two or more people call the same elevator at the same time? Which call has the priority? How to handle the security questions? Loss of electricity? Operation failure? Misuse? After solving these basic questions, a tough process of designing an appropriate electronics using a large number of special-purpose chips comes next. Depending on the device complexity, such process can take weeks, even months. Then it's time to make a printed circuit board and assemble device. A huge device! It is another long-lasting and trying work. Finally, when your device is finished and tested many times, the crucial moment comes. The moment when you take a deep breath and switch the power supply on. The party is over at this point as electronic devices almost never start to operate immediately. Get ready for many sleepless nights, corrections, improvements... and don't forget, we are still talking about running an ordinary elevator.
When your device finally works perfectly and everybody is satisfied and you get paid for the work you have done, other constructing companies will become interested in your work. Of course, if you are lucky, another day will bring you a locking offer from a new investor. A new building has four stories more. You know what it is all about? You think you can control destiny? You are going to make a universal device which can be used in buildings of 4 to 40 stories, a masterpiece of electronics? Even if you manage to make such an electronic jewel, your investor will wait in front of your door asking for a camera in the elevator. Or for relaxing music in case of elevator failure. Or for a two-door elevator. Anyway, Murphy's law is inexorable and you will certainly not be able to make advantage of all the effort you have made. Unfortunately, everything said so far is true. This is what 'handling electronics' really means. No, no, wait, let us correct ourselves, this is how it was until the first microcontrollers were designed - small, powerful and cheap devices. Since the moment their programming stopped being a science, everything went in another direction...
Electronics capable of controlling a small submarine, a crane or an elevator are now built into one single chip. Microcontrollers offer a wide range of applications, but only a few of them are normally used. It's up to you to decide what you want from the microcontroller and dump a program accordingly containing appropriate instructions into it. Prior to turning the device on, its operation should be tested by simulation. If everything works fine, build the microcontroller into your device. If you ever need to change, improve or upgrade the program, just do it. Until when? Until you feel satisfied. That's all.

Did you know that all people can be classified into one out of 10 groups- those who are familiar with binary number system and those who are not familiar with it. You don't understand? Then you still belong to the latter group. If you want to change your status read the following text which briefly describes some of the basic concepts used further in this book (just to be sure we are on the same page).
Mathematics is such a good science! Everything is so logical... The whole universe can be described with ten digits only. But, does it really have to be like that? Do we need exactly ten digits? Of course not, it is only a matter of habit. Remember the lessons from school. For example, what does the number 764 mean: four units, six tens and seven hundreds. It's as simple as that! Could it be described in a more complicated way? Of course: 4 + 60 + 700. Even more complicated? Definitely: 4*1 + 6*10 + 7*100. Could this number look more scientific? The answer is yes again: 4*100 + 6*101 + 7*102. What does it actually mean? Why do we use exactly these numbers: 100, 101 and 102 ? Why is it always about the number 10? The answer is because we use ten different digits (0, 1, 2, ... 8, 9). In other words, we use the base-10 number system, i.e. decimal numeric system.

What would happen if only two digits were used- 0 and 1? Or if we didn't not know how to determine whether something is 3 or 5 times greater than something else? Or if we were restricted when comparing two sizes, i.e. if we could only state that something exists (1) or doesn't exist (0)? The answer is 'nothing special', we would keep on using numbers in the same way as we do now, but they would look a bit different. For example: 11011010. How many pages of a book does the number 11011010 include? In order to learn that, you just have to follow the same logic as in the previous example, but in reverse order. As you can see here, it's all based on only two digits- 0 and 1, i.e. on the base-2 numeric system (binary numeric system).

It is clearly the same number represented in two different numeric systems. The only difference between these two formats is the number of digits they consist of. One digit (2) is used for writing number 2 in decimal system, whereas two digits (1 and 0) are used for its writing in binary system. Do you now agree that there are 10 groups of people? Welcome to the world of binary arithmetic! Do you have any idea where it is used?
Except in strictly controlled laboratory conditions, even the most complex electronic circuits cannot accurately determine the difference between two sizes (two voltage values, for example) if they are too small (lower than several volts). The reason for it lies in the noise and something known as a ‘real working environment’ (unpredictable changes of power supply voltage, temperature change, tolerance to values of built-in components etc.). Imagine a computer which operates upon decimal numbers by interpreting them as follows: 0=0V, 1=5V, 2=10V, 3=15V, 4=20V...9=45V.
Did anybody say batteries?
A far simpler solution is the binary logic where 0 indicates that there is no voltage and 1 indicates that there is a voltage. It is easier to write 0 or 1 instead of full sentences ‘there is no voltage’ or ‘there is a voltage’, respectively. It is about a logic zero (0) and a logic one (1) which electronics perfectly copes with, and easily performs all those endlessly complex mathematical operations. Obviously, the electronics we are talking about applied mathematics in which all the numbers are represented by two digits only and where it is only important to know whether there is a voltage or not. Of course, we are talking about digital electronics.
At the very beginning of the computer development there were many problems when working with binary numbers. For this reason, a new numeric system, using 16 different symbols was established and called a hexadecimal numeric system. It is comprised of ten digits we are used to (0, 1, 2, 3,... 9) and six letters of alphabet A, B, C, D, E and F. You probably wonder what’s the purpose of this seemingly bizarre combination? Just look how perfectly it fits the story about binary numbers and you will understand.

The largest number that can be represented by 4 binary digits is the number 1111. It corresponds to the number 15 in a decimal system, whereas it is represented by letter F in hexadecimal system. It is the largest 1-digit number in the hexadecimal system. Do you see how skillfully it is used? The largest number written with eight binary digits is at the same time the largest 2-digit hexadecimal number. Remember that computers use 8-digit binary numbers. Coincidence?
A BCD code is a binary code for decimal numbers only (Binary-Coded Decimal). It consists of 4-digit binary numbers representing the first ten digits (0, 1, 2, 3 ... 8, 9). Even though four bits can give 16 possible combinations in total, the BCD code makes advantage of the first ten only.
The binary numeric system is the most commonly used, the decimal system is the most understandable, while the hexadecimal system is somewhere in the middle. Therefore, it is very important to learn how to convert numbers from one numeric system to another, i.e. how to turn a sequence of zeros and ones into understandable values.
Same digits in a binary number have different values depending on their position in that number. Each position may contain either 1 or 0 and its value can be easily determined by counting its position from the right. To perform a binary to decimal number conversion it is necessary to multiply digits (0 or 1) with their position value (20, 21, 22, 23 etc.) and add all the results. The magic of binary to decimal number conversion works... Look at the example below:

In order for decimal numbers from 0 to 3 to be represented, you need only two binary digits. For larger numbers, extra binary digits must be used. Thus, in order for the decimal numbers from 0 to 7 to be represented, three binary digits are required, for numbers from 0 to 15, four digits etc. Simply put, the largest binary number consisting of n digits is obtained when the base 2 is raised by n and the respective result is subtracted by 1. For example, if n=4:
24 - 1 = 16 - 1 = 15
Accordingly, 4 binary digits enable you to represent decimal numbers from 0 to 15, which amounts to 16 different values in total.
To perform a hexadecimal to decimal number conversion, each hexadecimal digit should be multiplied with 16 raised by its position value and after that, the obtained results should be added. For example:

It is not necessary to perform any calculations to convert hexadecimal numbers to binary. Hexadecimal digits are simply replaced by appropriate binary digits. Since the maximum value of a hexadecimal digit is equivalent to decimal number 15, it is necessary to use four binary digits to represent one hexadecimal digit. For example:

A comparative table on the left shows the values of numbers 0-255 represented in three different number systems. This is probably the easiest way to understand the common logic applied to all numeric systems.

The hexadecimal numeric system is, along with binary and decimal numeric systems, considered the most important for us. It is easy to convert any hexadecimal number to binary. It is also easy to remember it. However, such conversions may confuse us. For example, what does the sentence ‘It is necessary to count up 110 products on the assembly line’ actually mean? Depending on whether it is about binary, decimal or hexadecimal system, the result could be 6, 110 or 272 products, respectively. To avoid such and similar situations, different prefixes and suffixes are directly added to the numbers. Prefixes $ and 0x mark hexadecimal numbers. For example, hexadecimal number 10AF looks either as $10AF or 0x10AF. Similarly, binary numbers usually get the prefix %. If a number has neither suffix nor prefix it is considered decimal. Unfortunately, this way of marking numbers is not standardized, yet depends on specific application.
In theory, a bit is the basic unit of information... Let’s forget this for a moment and take a look at what it is in practice. The answer is- nothing special- a bit is just a binary digit. Similar to the decimal numeric system where the same digits of a number do not have the same value (for example, digits in decimal number 444), the ‘significance’ of bits depends on their positions in the binary number. Unlike the decimal numeric system, binary digits are not referred to as units, tens etc, but zero bit (rightmost bit), first bit (second from the right) etc. Since the binary system uses only two different digits (0 and 1), the value of one bit can be either 0 or 1.
Don’t be confused if you come across a bit having value 4, 16 or 64. It means that its value is represented in the decimal system. We are simply so much accustomed to the usage of decimal numbers that such expressions are very common. It would be correct to say for example, ‘the value of the sixth bit of any binary number is equivalent to decimal number 64’. But we are human and old habits die hard... Besides, how would it sound ‘number one-one-zero-one-zero...’?
A byte consists of eight bits grouped together. If a bit is a digit, then bytes represent numbers. All mathematical operations can be performed upon them, like upon common decimal numbers. Similar to digits of any number, byte digits do not have the same significance either. The largest value has the leftmost bit called the most significant bit (MSB). The rightmost bit has the least value and is therefore called the least significant bit (LSB). Since eight zeros and ones of one byte can be combined in 256 different ways, the largest decimal number which can be represented by one byte is 255 (one combination represents a zero).
A nibble is referred to as half a byte. Depending on which half of the register we are talking about (left or right), there are ‘high’ and ‘low’ nibbles, respectively.

Have you ever wondered what electronics within digital integrated circuits, microcontrollers or processors look like? What do circuits performing complicated mathematical operations and making decisions look like? Do you know that their seemingly complicated schematics comprise only a few different components called logic circuits or logic gates?
The operation of logic circuits is based on principles established by a British mathematician George Boole in the middle of the 19th century, even before the first bulb was invented. Originally, the main idea was to express logical forms through algebraic functions. It soon had lead to a real product which, much later, evaluated in what today is known as AND, OR and NOT logic circuits. The principle of their operation is known as Boolean algebra.
Some of the program instructions give the same results as logic gates. The principle of their operation will be discussed below.

The logic gate ‘AND’ has two or more inputs and one output. Let us presume that the gate used in this example has only two inputs. A logic one (1) will appear on its output only if both inputs (A AND B) are driven high (1). Table on the right shows mutual dependence between the AND gate’s inputs and output.

The principle of operation is the same even when the gate has more than two inputs: a logic one (1) will appear on its output only when all inputs are driven high (1). Any other combination of input voltages will result in a logic zero (0) on its output. When used in the program, the logic AND is performed by a program instruction to be discussed later. Just remember that logic AND in the program refers to the corresponding bits of two registers.

Similarly, OR gates also have two or more inputs and one output. If the gate has only two inputs the following applies. A logic one (1) will appear on its output if either input (A OR B) is driven high (1). If the OR gate has more than two inputs then the following applies. A logic one (1) appears on its output if at least one input is driven high (1). If all inputs are at logic zero (0), the output will be at logic zero (0) as well.

In the program, the peration is performed in the same manner as the logic AND operation.
The logic gate NOT has only one input and only one output. It operates in an extremely simple way. When a logic zero (0) appears on its input, a logic one (1) appears on its output and vice versa. It means that this gate inverts the signal and is therefore often called inverter.
The logic NOT operation in the program is performed upon one byte. The result is a byte with inverted bits. If byte bits are considered a number, the inverted value is actually a complement thereof. The complement of a number is a value which added to that number makes it reach the largest 8-digit binary number. In other words, the sum of an 8-digit number and its complement is always 255.
The EXCLUSIVE OR (XOR) gate is a bit complicated compared to other gates. It is a sort of combination of all of them. A logic one (1) appears on its output only when its inputs have different logic states.
In the program, the appropriate instruction is commonly used to compare two bytes. Subtraction has the same purpose (if the result is 0, bytes are equal), but the advantage of the EXCLUSIVE OR logic operation is that it never gives negative results.
In short, a register or a memory cell is an electronic circuit which can memorize the state of one byte.

In addition to registers which do not have any special and predefined function, every microcontroller also has a number of special-function registers (SFR’s) the function of which is predefined by the manufacturer. Their bits are connected (literally) to the integrated circuits within the microcontroller such as timers, A/D converter, oscillators etc. It means that they are directly in command of the operation of these circuits, i.e. the microcontroller. Imagine eight switches controlling the operation of a small circuit within the microcontroller - Special Function Registers do exactly that.
In other words, the state of register bits is changed from within the program, registers run small integrated circuits within the microcontroller, these circuits are via microcontroller pins connected to peripherals which are used for... Well, it’s up to you to decide for what.
In order for the microcontroller to be useful, it has to be connected to additional electronics, i.e. peripherals. Each microcontroller has one or more registers connected to the microcontroller I/O pins. Such connections make I/O ports. Why input/output? Because you can change a pin function as you wish. For example, suppose you want your device to turn on/off three signal LEDs and simultaneously monitor the logic state of five sensors or push buttons. Some of the ports need to be configured so as to have three outputs (connected to LEDs) and five inputs (connected to sensors). It can be easily done from within the software, which means that a pin function can be changed during the operation.

One of the important features of input/output (I/O) pins is a maximum current they can handle. For most microcontrollers, current supplied from one pin is sufficient to activate a LED or some other low-consumption device (10-20 mA).
Another important pin feature is a pull-up resistor it may be provided with. The pull-up resistor connects the appropriate pin to the positive power supply voltage. It can also be used when the pin is configured as an input connected to a switch or a push button. Later versions of microcontrollers have pull-up resistors configurable by software.
Each I/O port is usually under control of one SFR, which means that each bit of that register determines the state of the corresponding microcontroller pin. For example, by writing a logic one (1) to some of the register bits, the appropriate microcontroller pin is automatically configured as an input. The voltage supplied to that pin is visible on its port as 0 or 1. Otherwise, by writing a logic zero to the SFR, the appropriate port pin is configured as an output. Voltage provided on such an output pin (0V or 5V) reflects the state of the appropriate register bit (logic 0 or 1, respectively).
Memory module is a part of the microcontroller used for data storage. The easiest way to explain it is by comparing it with a filing cabinet with many drawers. Suppose, the drawers are clearly marked so that their contents can be easily available by reading labels on the front of the drawers. In the same way, each memory address corresponds to one memory location. The contents of any location can be accessed and read by its address. Memory can either be written to or read from.
There are several types of memory within the microcontroller:
Read Only Memory (ROM) is used to permanently save the program to be executed by the microcontroller. The size of a program to be written depends on the size of this memory. Today’s microcontrollers commonly use 16-bit addressing, which means that they are able to address up to 64 Kb of memory, i.e. 65535 locations. If you are a novice, your program will hardly exceed several hundred instructions. There are several types of ROM.
Masked ROM is a special type of ROM the content of which is determined by the manufacturer. The term ‘masked’ comes from the manufacturing process, where parts of the chip are masked off before the process of photolithography. In case of a large-scale production, the price is very low. Forget it...
One time programmable ROM enables you to download a program into it, but, as its name states, one time only. If an error is detected after the process of loading a program, the only thing you can do is to load the program to another chip.
Both the manufacturing process and characteristics of UV EPROM memory are fully identical to OTP ROM. However, the package of the microcontroller with this memory has a recognizable ‘window’ on its top side. It enables data to be erased under strong ultraviolet light. After a few minutes of such ‘sunbathing’ it is possible to load a new program into it. The installation of this window is complicated, which normally affects the price. In our opinion, unfortunately negative...
Flash memory, known as the successor to the UV EPROM, was made in the 80s in the laboratories of INTEL. Since such memory can be rewritten practically an unlimited number of times, microcontrollers with Flash ROM are ideal for learning, experimentation and small-scale production. Due to its great popularity, most microcontrollers are today manufactured in flash technology. So, if you are going to buy a microcontroller, the type to look for is definitely Flash!
Once the power supply is off the contents of RAM is cleared. It is therefore used for temporary storing data and intermediate results created and used during the operation of the microcontroller. For example, if the program performs an addition, it is necessary to have a register which stands for what in everyday life is called the ‘sum’. For this reason, one of the registers of RAM is called the ‘sum’ and used for storing results of addition.
The contents of EEPROM may be changed during operation (similar to RAM), but remains permanently saved even after the loss of power (similar to ROM). Accordingly, EEPROM is often used to store values, created during operation, which must be permanently saved. For example, if you design an electronic lock or an alarm, it would be great to enable the user to create and enter the password, but it’s useless if lost every time the power supply goes off. The ideal solution is a microcontroller with an embedded EEPROM.
Most programs use interrupts in their regular execution. The purpose of the microcontroller is mainly to respond to changes in its surrounding. In other words, when an action takes place, the microcontroller does something... For example, when you push a button on a television remote control, the microcontroller will register it and respond by changing a channel, turn the volume up or down etc. As such, the microcontroller would spend most of its time endlessly checking a few buttons for hours or days, which is not practical at all.
This is why the microcontroller has learnt a trick during its evolution. Instead of constant checking each pin or bit, the microcontroller delegates the ‘wait issue’ to a ‘specialist’ which will respond only when something attention worthy happens.
A signal which informs the central processor unit about such action is called an INTERRUPT.
A bus consists of 8, 16 or more wires. There are two types of buses: the address bus and the data bus. The address bus consists of as many lines as necessary for memory addressing. It is used to tranfer an address from the CPU to the memory. The data bus is as wide as data, in this case it is 8 bits or wires wide. It is used to connect all the circuits within the microcontroller.
As its name suggests, the CPU is a unit which monitors and controls all processes within the microcontroller. It consists of several subunits, of which the most important are:

A parallel connection between the microcontroller and peripherals established via input/output ports is an ideal solution when the distance between them is up to several meters. Otherwise, when it is necessary to establish communication on longer distances the parallel connection is out of the question. Serial communication is used instead.
Today, most microcontrollers have several different modules for serial communication built into them as a standard equipment. Which of these modules will be used depends on many factors of which the most important are:

One of the most important things about the serial communication is the Protocol which should be strictly observed. It is a set of rules which enables devices to correctly interpret data they exchange. Fortunately, the microcontroller itself takes care of this, so that the work of the programmer/user boils down to simple writing (data to be sent) and reading (received data).
The term data rate is used to denote the number of bits transferred per second [bps]. Note that it refers to bits, not bytes. According to the protocol, each byte is transferred along with several control bits. It means that one byte in serial data stream may consist of 11 bits. For example, if the data rate is 300 bps then maximum 37 and minimum 27 bytes may be transferred per second.
The most commonly used serial communication modules are:
An inter-integrated circuit is a module for serial data exchange between microcontrollers and specialized integrated circuits of a new generation. It is used when the distance between these devices is short (receiver and transmitter are usually on the same printed board). The connection is established via two conductors. One is used for data transfer, while the other is used for synchronization (clock signal). As can be seen in figure below, one device is always a master device. It performs addressing of one slave device before communication starts and controls the process of data transfer. In this way one microcontroller can communicate with 112 different devices using I2C. Data rate is usually 100 Kb/sec (standard mode) or 10 Kb/sec (slow data rate mode). Devices with a data rate of 3.4 Mb/sec have recently appeared. The distance between devices which communicate over an I2C bus is limited to several meters.

A serial peripheral interface (SPI) bus is a module for serial communication which uses three or four conductors. One conductor is used to receive data, one to send data, one for synchronization and one alternatively for selecting a device to communicate with. It is a full duplex connection, which means that data can be sent and received simultaneously.
The maximum data rate is higher than that in the I2C communication module.

As its name suggests, the USART communication is asynchronous, which means that no special line for clock signal transfer is used. In some applications, such as radio connection or infrared waves remote control, this feature is crucial. Since only one communication line is used, both receiver and transmitter operate at the same predefined rate in order to maintain necessary synchronization. This is a very simple way of transferring data as it basically comes down to the conversion of 8-bit data from parallel to serial format. Data rate is not high, up to 1 Mbit/sec.
Even pulses generated by the oscillator enable a harmonic and synchronous operation of all circuits within the microcontroller. The oscillator is usually configured so as to use a quartz crystal or ceramic resonator for frequency stabilization, but it can also operate as a stand-alone circuit (like RC oscillator). It is important to say that instructions are not executed at the rate imposed by the oscillator itself, but several times slower. It happens because each instruction is executed in several steps. In some microcontrollers, the same number of cycles is required to execute all instructions, while in others, the number of cycles is different for different instructions. Accordingly, if the microcontroller uses quartz crystal with a frequency of 20 Mhz, the execution time of an instruction is not 50nS, but 200, 400 or 800 nS, depending on the microcontroller type.
There are two things worth attention when speaking of the microcontroller power supply circuit:
The microcontroller oscillator uses quartz crystal for its operation. Even though it is not the best solution, there are still many reasons to use it. The frequency of such oscillator is precisely defined and very stable, so that pulses it generates are always the same width, which makes them ideal for time measurement. Such oscillators are also used in quartz watches. If it is necessary to measure time between two events, it is sufficient to count up pulses generated by this oscillator. This is exactly what the timer does.

Most programs use these miniature electronic ‘stopwatches’. Their heart make 8- or 16- bit SFRs, the contents of which is automatically incremented by each coming pulse. Once a register is fully loaded, an interrupt may be generated.
If the timer uses an internal quartz oscillator for its operation, then it can be used to measure time between two events (if the value stored in the timer register is T1 at the moment the measurement starts, and T2 at the moment it terminates, then the time elapsed is equal to the result of subtraction T2-T1). If registers use pulses supplied from an external source then such timer is turned into a counter.
This is just a simple explanation of the operation of timer/counter. As you already know, it is more complicated in practice.
This is how the timer operates in practice: pulses generated by the quartz oscillator are directly, or via a prescaler, brought to the circuit which increments the number stored in the timer register. By embedding a quartz crystal with a frequency of 4MHz the following applies: if one instruction (one machine cycle) lasts for four quartz oscillator periods then by embedding a quartz crystal with a frequency of 4MHz this number will be incremented a million times per second (each microsecond).

It is easy to measure short time intervals, up to 256 microseconds, in the way described above because it is the largest number that one register can store. This restriction may be easily made up by using a slower oscillator, registers with more bits, prescaler or interrupts. The first two solutions have some drawbacks so that it is more advisable to use prescalers or interrupts.
A prescaler is an electronic device used to reduce frequency by a predefined division rate. In order to generate one pulse on its output, it is necessary to bring 1, 2, 4 or more pulses on its input. Most microcontrollers have one or more bulit-in prescalers and their division rate may be changed from within the program. The prescaler is used when it is necessary to measure longer periods of time.

If the timer register consists of 8 bits, the largest number it can store is 255. For 16-bit registers it is the number 65.535. If such number is exceeded, the timer will be automatically reset and counting will start from zero again. This condition is called an overflow. If enabled from within the program, the overflow can cause an interrupt, which gives completely new possibilities. For example, the state of registers used for counting seconds, minutes or days can be changed in an interrupt routine. The whole process (except for the interrupt routine) is automatically performed behind the scenes, which enables the main circuits of the microcontroller to operate normally.

Figure above illustrates the use of an interrupt in timer operation. Delays of arbitrary duration, having almost no influence on the main program execution, can be easily obtained by assigning a prescaler to the timer.
If the timer is supplied with pulses from the microcontroller input pin, then it turns into a counter. It is clear that the same electronic circuit is able to operate in two different modes. The only difference is that in this case pulses to be counted come via the microcontroller input pin and their duration (width) is usually undefined. This is why they cannot be used for time measurement, but can be used for other purposes such as counting products on an assembly line, number of axis rotation, passengers etc. (depending on sensor in use).
A watchdog timer is a timer connected to a stand-alone RC oscillator within the microcontroller.
If the watchdog timer is enabled, every time it counts up to the maximum value, the microcontroller reset occurs and the program execution starts from the first instruction. The point is to prevent this from happening by using a specific command.
Anyway, the whole idea is based on the fact that every program is executed in several longer or shorter loops. If instructions for the watchdog timer reset are set at the appropriate program locations, in addition to commands being regularly executed, then the operation of the watchdog timer will not affect the program execution. If for any reason, usually due to manufacturing noise, the program counter ‘gets stuck’ at some memory location from which there is no return, the watchdog timer will not be cleared, so the register’s value being constantly incremented will reach the maximum et voila! Reset occurs and the program will be executed from the beginning.

External signals are usually fundamentally different from those the microcontroller recognizes (0V and 5V only) and therefore have to be converted into recognizable values. An analog to digital converter is an electronic circuit which converts continuous signals to discrete digital numbers. In other words, this circuit converts an analogue value into a binary number and forwards it to the CPU for further processing. This module is thus used for input pin voltage (analogue value) measurement.
The result of measurement is a number (digital value) used and processed later in the program.

All upgraded microcontrollers implement one of the two basic design models called Harvard and von-Neumann architecture.
They represent two different ways of exchanging data between the CPU and memory.
Microcontrollers using the von-Neumann architecture have only one memory block and one 8-bit data bus. As all data is exchanged through these 8 lines, the bus is overloaded and communication is slow and inefficient. The CPU can either read an instruction or read/write data from/to the memory. Both processes cannot be performed at the same time since instructions and data use the same bus. For example, if a program line reads that a RAM memory register called ‘SUM’ should be incremented by one (instruction: incf SUM), the microcontroller will do the following:
incf’ instruction for increment is to be performed).The same data bus is used for all these intermediate operations when data is exchanged between the CPU and memory.
Microcontrollers which implement the Harvard architecture have two different data buses. One is 8 bits wide and connects the CPU to RAM. The other consists of 12, 14 or 16 lines and connects the CPU to ROM. Accordingly, the CPU can read an instruction and access data memory at the same time. Since all RAM memory registers are 8 bits wide, all data being exchanged is of the same width. During the writing process, only 8-bit data is included. In other words, all you can change from within the program and all you can deal with is 8 bits wide. All the programs written for these microcontrollers will be stored in the microcontroller internal ROM after being compiled to machine code. However, ROM memory locations are not 8, but 12, 14 or 16 bits wide. The rest of bits 4, 6 or 8, respectively, represents the instruction alone specifying for the CPU what to do with the 8-bit data.
The advantages of this architecture are as follows:
All instructions recognizable by the microcontroller are colectivelly called the Instruction Set. When you write a program in assembly language, you actually specify instructions in such order as they should be executed. The main restriction here is the number of available instructions. The manufacturers usually employ one of the two opposite solutions and design microcontrollers which implement the smallest or the largest possible number of instructions. In other words - they choose between RISC and CISC instruction sets, respectively.
In this case, the microcontroller recognizes and executes basic operations only (addition, subtraction, copying etc.). Other, more complicated operations are performed by combining them. For example, multiplication in the program must be performed as a successive addition. It’s the same as if you try to explain to someone, using only a few different words, how to reach the airport in a big city. However, it’s not as black as it’s painted. As a matter of fact, it is not so difficult to explain where the airport is if you use the right words such as left, right, kilometers etc.
CISC is the opposite to RISC. Microcontrollers designed to recognize more than 200 different instructions can do a lot of things at high speed. However, one needs to understand how to take all that such a rich instruction set offers, which is not easy at all...
OK, you are a beginner and you have made a decision to go on an adventure of working with microcontrollers. Congratulations on your choice. But, it is not as easy to choose the right microcontroller as it may seem. The problem is not a limited range of devices, but the opposite.
Before you start designing a microcontroller-based device, think of the following: how many inputs/outputs does your project require? Should it perform some other operations than to simply turn relays on/off? Does it need some specialized modules such as serial communication, A/D converter etc.? When you create a clear picture of what you need, the selection range is considerably reduced and it’s time to think of the price. Are you going to make several such devices? Several hundred? A million? Anyway, you get the point.
If you think of all these things for the very first time then everything seems a bit complicated. Make it simple and go step by step. First of all, select the manufacturer, i.e. the microcontroller family you can easily get. Study one particular model. Learn as much as you need, don’t go into details. Solve a specific problem and something incredible will happen- you will be able to handle any model belonging to that microcontroller family.
Remember learning to ride a bicycle. After several bruises you got when you started, you were able to keep the balance and then easily ride any other bicycle. And of course, you will never forget programming just as you will never forget riding bicycles!
The original name of the PIC microcontroller is PICmicro (Peripheral Interface Controller), but it is better known as a PIC. Its ancestor, called the PIC1650, was designed in 1975 by General Instruments. It was intended for totally different purposes. About ten years later, this circuit evolved into a real PIC microcontroller by adding EEPROM memory.
If you want to learn more about it, just keep on reading.
The main purpose of this book is to provide the user with necessary information he/she needs to know in order to be able to use microcontrollers in practice. In order to avoid tedious explanations and endless stories about the useful features of different microcontrollers, this book deals with the operation of one particular model belonging to the ‘high middle class’. It is the PIC16F887 microcontroller - powerful enough to be worth attention and simple enough to be easily learned by everybody. So, even though the following chapters describe this microcontroller in detail, they actually refer to the whole PIC family.
All PIC microcontrollers implement the Harvard architecture, which means that their program memory is connected to the CPU via more than 8 lines. Depending on the bus width, there are 12-, 14- and 16-bit microcontrollers. Table below shows the main features of these three categories of PIC microcontrollers.
| Family | ROM [Kbytes] | RAM [bytes] | Pins | Clock Freq. [MHz] | A/D Inputs | Resolution of A/D Converter | Compar- ators | 8/16 – bit Timers | Serial Comm. | PWM Outputs | Others |
| Base-Line 8 - bit architecture, 12-bit Instruction Word Length | |||||||||||
| PIC10FXXX | 0.375 - 0.75 | 16 - 24 | 6 - 8 | 4 - 8 | 0 - 2 | 8 | 0 - 1 | 1 x 8 | - | - | - |
| PIC12FXXX | 0.75 - 1.5 | 25 - 38 | 8 | 4 - 8 | 0 - 3 | 8 | 0 - 1 | 1 x 8 | - | - | EEPROM |
| PIC16FXXX | 0.75 - 3 | 25 - 134 | 14 - 44 | 20 | 0 - 3 | 8 | 0 - 2 | 1 x 8 | - | - | EEPROM |
| PIC16HVXXX | 1.5 | 25 | 18 - 20 | 20 | - | - | - | 1 x 8 | - | - | Vdd = 15V |
| Mid-Range 8 - bit architecture, 14-bit Instruction World Length | |||||||||||
| PIC12FXXX | 1.75 - 3.5 | 64 - 128 | 8 | 20 | 0 - 4 | 10 | 1 | 1 - 2 x 8 1 x 16 | - | 0 - 1 | EEPROM |
| PIC12HVXXX | 1.75 | 64 | 8 | 20 | 0 - 4 | 10 | 1 | 1 - 2 x 8 1 x 16 | - | 0 - 1 | - |
| PIC16FXXX | 1.75 - 14 | 64 - 368 | 14 - 64 | 20 | 0 - 13 | 8 or 10 | 0 - 2 | 1 - 2 x 8 1 x 16 | USART I2C SPI | 0 - 3 | - |
| PIC16HVXXX | 1.75 - 3.5 | 64 - 128 | 14 - 20 | 20 | 0 - 12 | 10 | 2 | 2 x 8 1 x 16 | USART I2C SPI | - | - |
| High-End 8 - bit architecture, 16-bit Instruction Word Length | |||||||||||
| PIC18FXXX | 4 - 128 | 256 - 3936 | 18 - 80 | 32 - 48 | 4 - 16 | 10 or 12 | 0 - 3 | 0 - 2 x 8 2 - 3 x 16 | USB2.0 CAN2.0 USART I2C SPI | 0 - 5 | - |
| PIC18FXXJXX | 8 - 128 | 1024 - 3936 | 28 - 100 | 40 - 48 | 10 - 16 | 10 | 2 | 0 - 2 x 8 2 - 3 x 16 | USB2.0 USART Ethernet I2C SPI | 2 - 5 | - |
| PIC18FXXKXX | 8 - 64 | 768 - 3936 | 28 - 44 | 64 | 10 - 13 | 10 | 2 | 1 x 8 3 x 16 | USART I2C SPI | 2 | - |
All PIC microcontrollers use Harvard architecture, which means that their program memory is connected to the CPU over more than 8 lines. Depending on the bus width, there are 12-, 14- and 16-bit microcontrollers. Table above shows the main features of these three categories.
As can be seen in the table on the previous page, if we disregard ‘16-bit monsters’- PIC 24FXXX and PIC 24HXXX for a moment- all PIC microcontrollers have 8-bit Harvard architecture and belong to one out of three large groups. Accordingly, depending on the size of the program word there are the first, second and third microcontroller category, i.e. 12-, 14- or 16-bit microcontrollers. Having similar 8-bit core, all of them use the same instruction set and the basic hardware ‘skeleton’ connected to more or less peripheral units.
PIC microcontrollers with 14-bit program words are most likely the best choice for beginners. Here is why...
The instruction set for the 16F8XX includes 35 instructions in total. The reason for such a small number of instructions lies in the RISC architecture. Instructions are well optimized from the operating speed aspect, simplicity in architecture and code compactness. The drawback to the RISC architecture is that the user is expected to cope with these instructions. Of course, this is relevant only if you use assembly language for programming. This book deals with programming in a high-level programming language called Basic, which means that most work has been already done by somebody else. You just have to use relatively simple instructions.
All instructions for PIC microcontrollers are single-cycle instructions. The only exception are conditional branch instructions (if condition is met) and instructions performed upon the program counter. In both cases, two cycles are required for instruction execution, while the second cycle is executed as an NOP (No Operation). Single-cycle instructions consist of four clock cycles. It means that if a 4MHz oscillator is used, it will take 1µS for an instruction to be executed. The instruction execution time for jump instructions is 2µS.
Instruction set of 14-bit program words PIC microcontrollers:
| Instruction | Description | Operation | Flag | CLK | * |
|---|---|---|---|---|---|
| Data Transfer Instructions | |||||
| MOVLW k | Move constant to W | k -> w | 1 | ||
| MOVWF f | Move W to f | W -> f | 1 | ||
| MOVF f,d | Move f to d | f -> d | Z | 1 | 1, 2 |
| CLRW | Clear W | 0 -> W | Z | 1 | |
| CLRF f | Clear f | 0 -> f | Z | 1 | 2 |
| SWAPF f,d | Swap nibbles in f | f(7:4),(3:0) -> f(3:0),(7:4) | 1 | 1, 2 | |
| Arithmetic-logic Instructions | |||||
| ADDLW k | Add W and constant | W+k -> W | C, DC, Z | 1 | |
| ADDWF f,d | Add W and f | W+f -> d | C, DC ,Z | 1 | 1, 2 |
| SUBLW k | Subtract W from constant | k-W -> W | C, DC, Z | 1 | |
| SUBWF f,d | Subtract W from f | f-W -> d | C, DC, Z | 1 | 1, 2 |
| ANDLW k | Logical AND with W with constant | W AND k -> W | Z | 1 | |
| ANDWF f,d | Logical AND with W with f | W AND f -> d | Z | 1 | 1, 2 |
| IORLW k | Logical OR with W with constant | W OR k -> W | Z | 1 | |
| IORWF f,d | Logical OR with W with f | W OR f -> d | Z | 1 | 1, 2 |
| XORWF f,d | Logical exclusive OR with W with constant | W XOR k -> W | Z | 1 | 1, 2 |
| XORLW k | Logical exclusive OR with W with f | W XOR f -> d | Z | 1 | |
| INCF f,d | Increment f by 1 | f+1 -> f | Z | 1 | 1, 2 |
| DECF f,d | Decrement f by 1 | f-1 -> f | Z | 1 | 1, 2 |
| RLF f,d | Rotate left f through CARRY bit | C | 1 | 1, 2 | |
| RRF f,d | Rotate right f through CARRY bit | C | 1 | 1, 2 | |
| COMF f,d | Complement f | f -> d | Z | 1 | 1, 2 |
| Bit-oriented Instructions | |||||
| BCF f,b | Clear bit b in f | 0 -> f(b) | 1 | 1, 2 | |
| BSF f,b | Clear bit b in f | 1 -> f(b) | 1 | 1, 2 | |
| Program Control Instructions | |||||
| BTFSC f,b | Test bit b of f. Skip the following instruction if clear. | Skip if f(b) = 0 | 1 (2) | 3 | |
| BTFSS f,b | Test bit b of f. Skip the following instruction if set. | Skip if f(b) = 1 | 1 (2) | 3 | |
| DECFSZ f,d | Decrement f. Skip the following instruction if clear. | f-1 -> d skip if Z = 1 | 1 (2) | 1, 2, 3 | |
| INCFSZ f,d | Increment f. Skip the following instruction if set. | f+1 -> d skip if Z = 0 | 1 (2) | 1, 2, 3 | |
| GOTO k | Go to address | k -> PC | 2 | ||
| CALL k | Call subroutine | PC -> TOS, k -> PC | 2 | ||
| RETURN | Return from subroutine | TOS -> PC | 2 | ||
| RETLW k | Return with constant in W | k -> W, TOS -> PC | 2 | ||
| RETFIE | Return from interrupt | TOS -> PC, 1 -> GIE | 2 | ||
| Other instructions | |||||
| NOP | No operation | TOS -> PC, 1 -> GIE | 1 | ||
| CLRWDT | Clear watchdog timer | 0 -> WDT, 1 -> TO, 1 -> PD | TO, PD | 1 | |
| SLEEP | Go into sleep mode | 0 -> WDT, 1 -> TO, 0 -> PD | TO, PD | 1 | |
*1 When an I/O register is modified, the value used will be that value present on the pins themselves.
*2 If the instruction is executed upon the TMR register and if d=1, the prescaler will be cleared.
*3 If the PC is modified or test result is a logic one (1), the instruction requires two cycles. The second cycle is executed as an NOP.

The architecture of 8-bit PIC microcontrollers. Which of these modules are to be built into the microcontroller depends on the type thereof.