4.2 Additional Components
In spite of the fact that the microcontroller is a product of modern technology, it is of no use if not connected to additional components. Simply put, the appearance of voltage on the microcontroller pins means nothing if it is not used for performing certain operations such as turning something on/off, shifting, displaying etc.
This section covers some of the most commonly used additional components in practice such as resistors, transistors, LEDs, LED displays, LCD displays and RS-232 communication modules.
SWITCHES AND PUSH-BUTTONS
Switches and push-buttons are likely the simplest components which provide the simplest way of bringing voltage on a microcontroller input pins. Of course, it is not as simple as that in practice... What makes it complicated is a contact bounce.
The contact bounce is a common problem with mechanical switches. When the contacts collide together, their momentum and elasticity act together to cause a bounce. The result is a rapidly pulsed electrical current instead of a clean transition from zero to full current. It mostly occurs due to vibrations, slight rough spots and dirt between contacts. The bounce happens too fast so that it is not possible to notice it when these components are normally used.
However, it causes problems in some analog and logic circuits that respond fast enough to misinterpret on/off pulses as a data stream. In other words, the whole process doesn’t last long (a few micro- or milliseconds), but long enough to be registered by the microcontroller. When only a push-button is used as a counter signal source, errors occur in almost 100% of cases.
One of possible solutions to this issue is to connect a simple RC circuit to suppress quick voltage changes. Since the bounce period is not defined, the values of components cannot be precisely determined. In most cases it is recommended to use the same values as shown in figure below.
If full stability is required then radical measures should be taken. The output of the logic circuit, as shown in figure below (RS flip-flop), will change its logic state after detecting the first pulse triggered by a contact bounce. This solution is more expensive (SPDT switch), but definitely safer.
In addition to these hardware solutions, there is also a simple software solution. When the program tests the logic state of an input pin and detects a change, the check should be done one more time after a certain delay. The verification of change means that a switch/push button has changed its position. The advantages of such solution are clear: it is free of charge and can be applied to the poorer quality contacts.
RELAYS
A relay is an electrical switch that opens and closes under the control of another electrical circuit. It is therefore connected to output pins of the microcontroller and used to turn on/off power devices such as motors, transformers, heaters, bulbs, etc. These devices are almost always placed away from the on-board sensitive components. There are various types of relays and all operate in the same way. When current flows through the coil, the relay is operated by an electromagnet to open or close one or more sets of contacts. Similar to optocouplers, there is no galvanic connection (electrical contact) between relays input and output. Relays usually require both high voltage and high current to start operation, but there are also miniature ones that can be activated by low current directly supplied from a microcontroller pin.
Figure below shows the most common way of connecting a relay to other mains powered devices.
In order to prevent the high voltage self-induction, caused by a sudden stop of the current flow through the coil, an inverted polarized diode is connected in parallel to the coil. The purpose of this diode is to ‘cut off’ the voltage peak.
LED DIODES
You probably know all you should know about LEDs, but we should also think of the younger generations... Let’s see, how to destroy a LED?! Well...Easily.
Quick Burning
Like any other diode, LEDs have two ends - an anode and a cathode. Connect a diode properly to the power supply voltage and it will emit light happily. Turn the diode upside down and apply the same power supply voltage (even for a moment). It will probably not emit light - EVER AGAIN!
Slow Burning
There is a nominal (consider it maximum) current specified for every LED which must not be exceeded. If it happens, the diode will emit more intensive light, but just for a short period of time.
Something to Remember
Similarly, all you need to do is to remove a current limiting resistor shown below. Depending on the power supply voltage, the effects might be spectacular.
LED DISPLAY
Basically, an LED display is nothing more than several LEDs molded in the same plastic case. There are many types of displays and some of them are composed of several dozens built-in diodes which can display different symbols. Nevertheless, the most commonly used display is a 7-segment display. It is composed of 8 LEDs. Seven segments of a digit are arranged as a rectangle to display symbols, whereas the additional segment is used to display a decimal point. In order to simplify connection, anodes or cathodes of all diodes are connected to one single pin so that there are common anode displays and common cathode displays, respectively. Segments are marked with letters from a to g, plus dp, as shown in figure below. When connecting an LED display, each diode is treated separately, which means that each one must have its own current limiting resistor.
Here are a few things that you should pay attention to when buying LED displays:
- As mentioned above, depending on whether anodes or cathodes are connected to the common pin, there are common anode displays and common cathode displays. There is no difference between them at all in their appearance so you are advised to double check which one is to be used prior to installing it.
- Maximum current that each microcontroller pin can receive or give is limited. Therefore, if several displays are connected to the microcontroller then so called Low current LEDs limited to only 2mA should be used.
- Display segments are usually marked with letters from a to g, but there is no fast rule indicating display pins they are connected to. For this reason, it is very important to check connection prior to start writing a program or designing a device.

LED displays connected to the microcontroller usually occupy a large number of valuable I/O pins, which can be troublesome especially when it is necessary to display multi digit numbers. It is even more complicated if, for example, it is necessary to display two 6-digit numbers. A simple calculation shows that 96 output pins are needed in this case. The solution to this issue is called multiplexing.
Here is how an optical illusion based on the same operating principle as a film camera is made. Only one digit is active at a time, but they change their on/off conditions so quickly creting the impression that all digits of a number are simultaneously active.

Let’s take a look at the figure above. First a byte representing units is loaded to the microcontroller port PORT2 and transistor T1 is activated at the same time. After a while, the transistor T1 is turned off, a byte representing tens is loaded to PORT2 and the transistor T2 is activated. This procedure is repeated cyclically at high speed for all digits and corresponding transistors.
A disappointing fact which indicates that the microcontroller is just a kind of miniature computer designed to understand only the language of zeros and ones is fully expressed when displaying digits. Namely, the microcontroller does not know what units, tens or hundreds are, nor what ten digits we are used to look like. For this reason, each number to be displayed must undergo the following procedure:
First of all, a multi digit number must be split into units, tens etc. in a specialized subroutine. Then each of these digits must be stored in a specific byte. Digits get recognizable appearance for humans by performing a simple procedure called ‘masking’. In other words, a binary number is replaced with a different combination of bits. For example, digit 8 (0000 1000) is replaced with the binary number 0111 1111 in order to activate all LEDs displaying this digit. The only diode remaining inactive here is reserved for the decimal point.
If the microcontroller port is connected to a display so as that bit 0 activates segment ‘a’, bit 1 activates segment ‘b’, bit 2 segment ‘c’ etc., then table below shows appropriate binary mask for each digit.

DIGITS TO DISPLAY |
DISPLAY SEGMENTS |
|
dp |
a |
b |
c |
d |
e |
f |
g |
0 |
0 |
1 |
1 |
1 |
1 |
1 |
1 |
0 |
1 |
0 |
0 |
1 |
1 |
0 |
0 |
0 |
0 |
2 |
0 |
1 |
1 |
0 |
1 |
1 |
0 |
1 |
3 |
0 |
1 |
1 |
1 |
1 |
0 |
0 |
1 |
4 |
0 |
0 |
1 |
1 |
0 |
0 |
1 |
1 |
5 |
0 |
1 |
0 |
1 |
1 |
0 |
1 |
1 |
6 |
0 |
1 |
0 |
1 |
1 |
1 |
1 |
1 |
7 |
0 |
1 |
1 |
1 |
0 |
0 |
0 |
0 |
8 |
0 |
1 |
1 |
1 |
1 |
1 |
1 |
1 |
9 |
0 |
1 |
1 |
1 |
1 |
0 |
1 |
1 |
In addition to digits (0-9), there are some letters of alphabet - A, C, E, J, F, U, H, L, b, c, d, o, r, t- that can also be displayed by masking.
In case that common anode displays are used, all ones contained in the table above should be replaced with zeros and vice versa. Additionally, PNP transistors should be used as drivers.
OPTOCOUPLER
An optocoupler is a component commonly used to galvanically separate microcontroller from any potentially dangerous current or voltage in its surrounding. Optocoupler usually have one, two or four light sources (LEDs) on its input while on its output, opposite to diodes, there is the same number of light-sensitive components (phototransistors, photo-thyristors or phototriacs). The point is that an optocoupler uses a short optical transmission path to transfer a signal between diodes and photo-sensitive components, while keeping them electrically isolated. Such isolation makes sense only if these components are separately powered. This way, the microcontroller and its additional modules are fully protected from high voltage and noises which usually cause them to be damaged or to operate in an unpredictable way. The most frequently used optocouplers are those with phototransistors on their output. When it comes to the optocouplers with internal base-to-pin 6 connection (there are also optocouplers without it), the base can be left unconnected.

The R/C network outlined by a dotted line in figure above is an optional connection which lessens the effects of noise by eliminating very short pulses.
LCD DISPLAY
An LCD display is specifically manufactured for the use with microcontrollers, which means that it cannot be activated by standard IC circuits. It is used to display different messages on a miniature liquid crystal display. The LCD display described here is for its low price and great capabilities most frequently used in practice. It is based on the HD44780 controller (Hitachi) and displays messages in two lines with 16 characters each. Different symbols such as letters of alphabet, Greek letters, punctuation marks, mathematical symbols etc. can be displayed on it. It is also possible to display symbols created by the user. Other useful features include automatic message shift (left and right), cursor appearance, LED backlight etc.
LCD Display Pins
Along one side of the small printed board of the LCD display there are pins which enable it to be connected to the microcontroller. There are in total 14 pins marked with numbers (16, if there is a backlight available). Their functions are described in table bellow:
FUNCTION |
PIN NUMBER |
NAME |
LOGIC STATE |
DESCRIPTION |
Ground |
1 |
Vss |
- |
0V |
Power supply |
2 |
Vdd |
- |
+5V |
Contrast |
3 |
Vee |
- |
0 - Vdd |
Control of operating |
4 |
RS |
0
1 |
D0 – D7 considered as commands
D0 – D7 considered as data |
5 |
R/W |
0
1 |
Write data (from controller to LCD)
Read data (from LCD to controller) |
6 |
E |
0
1
From 1 to 0 |
Access to LCD disabled
Normal operating
Data/commands being transferred to LCD |
Data / commands |
7 |
D0 |
0/1 |
Bit 0 LSB |
8 |
D1 |
0/1 |
Bit 1 |
9 |
D2 |
0/1 |
Bit 2 |
10 |
D3 |
0/1 |
Bit 3 |
11 |
D4 |
0/1 |
Bit 4 |
12 |
D5 |
0/1 |
Bit 5 |
13 |
D6 |
0/1 |
Bit 6 |
14 |
D7 |
0/1 |
Bit 7 MSB |
LCD Screen
An LCD screen is a thin, flat panel used for displaying different contents. It consists of two lines each containing up to 16 characters of 5x8 or 5x11 pixels. The operation of a 5x8 LCD display will be described here as it is more frequently used.
Display contrast depends on the power supply voltage and whether messages are displayed in one or two lines. For this reason, a varying voltage (0-Vdd) is applied to the pin marked as Vee by using a trimmer potentiometer. Some LCD displays have a built-in backlight (blue or green LEDs). When the backlight is used, a current limiting resistor should be serially connected to one of the pins for backlight power supply (similar to LEDs).
If there are no characters displayed or if they are dimmed when the display is switched on, the first thing that should be done is to check the potentiometer for contrast adjustment. Is it properly adjusted? The same applies if the operating mode of display has been changed (write in one or two lines).
LCD Memory
LCD display contains three memory blocks:
- DDRAM Display Data RAM;
- CGRAM Character Generator RAM; and
- CGROM Character Generator ROM.
DDRAM Memory
The DDRAM memory is used for storing characters to be displayed. It is capable of storing up to 80 characters. Some memory locations are directly related to the character fields on the screen.
The principle of DDRAM memory operation is quite simple: it is sufficient to configure a display to increment addresses automatically (shift right) and set the starting address for the message to be displayed (for example 00 hex).
After that, all characters sent through lines D0-D7 will be displayed on the screen as a message we are used to - from left to right. In this case, displaying starts from the first character field in the first line because the starting address is 00 hex. No matter how many characters are sent, only the first sixteen will be visible on the screen, while the rest of them will be saved and displayed afterwards using the shift command. Practically, LCD display is like a window shifting in left-right direction over memory locations containing different characters. This is in fact how the effect of the message shifting over the screen has been created.

If the cursor is enabled, it is always positioned at the currently addressed character field. In other words, as soon as the appropriate character appears at the cursor position, the coursor automatically moves to the next addressed field.
As its name suggests, DDRAM memory is a kind of RAM, which means that data can be written to and read from it, while its content is irretrievably lost when the power goes off.
CGROM Memory
CGROM memory contains a standard character map with all characters that can be displayed on the screen. Each character is assigned one memory location:

Addresses of CGROM memory locations match standard ASCII characters. Let’s see what it acctually means. If the program being executed by the microcontroller encounters a command ‘send character P to port’, binary value 0101 0000 will appear on the port. This value is ASCII equivalent of character P. As a result, the symbol matching the 0101 0000 CGROM memory location, i.e. letter P, will be displayed on the screen. The same applies to all letters of alphabet (capitals and small), but not to numbers.
If you look carefully at the map on the previous page, you will notice that addresses of all digits are shifted forward by 48 relative to their values (digit 0 address is 48, digit 1 address is 49, digit 2 address is 50 etc.). Therefore, in order to display digits correctly it is necessary to add decimal number 48 to each of them prior to sending it to an LCD.

What is ASCII? From their inception till today, computers can recognize only numbers, but not letters. It means that all data a PC swaps with a peripheral device is converted into binary format even though the same is recognized by humans as letters (keyboard is an excellent example). In other words, every character matches a unique combination of zeroes and ones. ASCII is character encoding based on the English alphabet. ASCII code specifies a correspondence between standard character symbols and their numeric equivalents.
CGRAM MEMORY
In addition to standard characters, the LCD display can also display user-defined symbols in size of 5x8 pixels. It is enabled by a special type of RAM called CGRAM (64 bytes).
Memory registers are 8 bits wide, but only 5 lower bits are used. Logic one (1) in every register represents a dimmed field, while 8 locations grouped together represent one character. Refer to figure below:
Symbols are usually defined at the beginnig of the program by simple writing zeros and ones to registers of CGRAM memory so as to form desired shapes. In order to display them, it is sufficient to specify appropriate memory address. Pay attention to the first column of the CGROM map of characters. It doesn't contain RAM memory addresses, but symbols being discussed here. In this example, ‘display 0’ means - display ‘smiley’, ‘display 1’ means - display ‘anchor symbol’ etc.
LCD Basic Commands
All data sent to an LCD through the pins D0-D7 will be interpreted either as a command or a data, which depends on the logic state of the RS pin:
- RS = 1 - Bits D0 - D7 are addresses of the characters to be displayed. A built-in LCD processor addresses one character from the character map and displays it. The DDRAM address specifies location on the screen on which the character is to be displayed. This address is predefined or the address of the previously sent character is automatically incremented.
- RS = 0 - Bits D0 - D7 are commands used for setting the operating mode of display.
Here is a list of commands related to the operation of LCD:
COMMAND |
RS |
RW |
D7 |
D6 |
D5 |
D4 |
D3 |
D2 |
D1 |
D0 |
EXECUTION TIME |
Clear display |
0 |
0 |
0 |
0 |
0 |
0 |
0 |
0 |
0 |
1 |
1.64mS |
Cursor home |
0 |
0 |
0 |
0 |
0 |
0 |
0 |
0 |
1 |
x |
1.64mS |
Entry mode set |
0 |
0 |
0 |
0 |
0 |
0 |
0 |
1 |
I/D |
S |
40uS |
Display on/off control |
0 |
0 |
0 |
0 |
0 |
0 |
1 |
D |
U |
B |
40uS |
Cursor/Display Shift |
0 |
0 |
0 |
0 |
0 |
1 |
D/C |
R/L |
x |
x |
40uS |
Function set |
0 |
0 |
0 |
0 |
1 |
DL |
N |
F |
x |
x |
40uS |
Set CGRAM address |
0 |
0 |
0 |
1 |
CGRAM address |
40uS |
Set DDRAM address |
0 |
0 |
1 |
DDRAM address |
40uS |
Read "BUSY" flag (BF) |
0 |
1 |
BF |
DDRAM address |
- |
Write to CGRAM or DDRAM |
1 |
0 |
D7 |
D6 |
D5 |
D4 |
D3 |
D2 |
D1 |
D0 |
40uS |
Read from CGRAM or DDRAM |
1 |
1 |
D7 |
D6 |
D5 |
D4 |
D3 |
D2 |
D1 |
D0 |
40uS |
I/D 1 = Increment (by 1) R/L 1 = Shift right
0 = Decrement (by 1) 0 = Shift left
S 1 = Display shift on DL 1 = 8-bit interface
0 = Display shift off 0 = 4-bit interface
D 1 = Display on N 1 = Display in two lines
0 = Display off 0 = Display in one line
U 1 = Cursor on F 1 = Character format 5x10 dots
0 = Cursor off 0 = Character format 5x7 dots
B 1 = Cursor blink on D/C 1 = Display shift
0 = Cursor blink off 0 = Cursor shift
WHAT IS A BUSY FLAG?
Compared to the microcontroller, LCD is an extremely slow component. For this reason, it was necessary to provide a signal which would, upon each command execution, indicate that the display is ready to receive next piece of data. This signal is called the busy flag and can be read from the D7 line. LCD display is ready to receive new data when the voltage on this line is 0V (BF=0).
LCD Connecting
Depending on how many lines are used for connecting an LCD to the microcontroller, there are 8-bit and 4-bit operating modes of LCD. The appropriate mode is selected at the beginning of the operation in the process called ‘initialization’. The 8-bit LCD mode uses pins D0-D7 to transfer data as explained on the previous page.
The main purpose of the 4-bit LCD mode is to save valuable I/O pins of the microcontroller. Only 4 higher bits (D4-D7) are used for communication here, while others may be left unconnected. Each piece of data is sent to the LCD in two steps - four higher bits are sent first (normally via lines D4-D7), then four lower bits. As a result of the process of initialization, the LCD is able to link and interpret received bits correctly.

In addition, data is rarely read from the LCD. In most cases the microcontroller sends data to the LCD, which means that it is possible to save an extra I/O pin by simple connecting the R/W pin to Ground. Such saving has its price, of course. Even though the process of displaying data will be normally performed, it will not be possible to read the busy flag as it is not possible to read the display either. Good news is that there is a simple solution to this issue. After sending a character or a command to the LCD it is necessary to give it enough time to get ready for another receive. Owing to the fact that it takes approximately 1.64mS for one command to be executed, it will be sufficient to wait about 2mS.
LCD Initialization
As soon as the power supply goes on, the LCD is automatically cleared. The whole process lasts approximately 15mS. After that, the display is ready for operation and its operating mode is set by default. It means that:
- Display is cleared.
- Mode
DL = 1 - Communication through 8-bit interface
N = 0 - Data is displayed in one line
F = 0 - Character font format is 5 x 8 pixel
- Display/Cursor on/off
D = 0 - Display off
U = 0 - Cursor off
B = 0 - Cursor blink off
- Character entry
ID = 1 Display addresses are automatically incremented by 1
S = 0 Display shift off
In most cases auto-reset normally occurs. Mostly, but not always. If for some reason the power supply voltage doesn’t reach the maximum within 10mS, the display will start to perform completely unpredictably. If the power supply is not able to meet this condition or if it is necessary to provide safe operation, the process of initialization is required. It causes a new reset condition, thus enabling the display to operate normally.
There are two initialization algorithms. Which one is to be performed depends on whether the connection to the microcontroller is established through 4- or 8-bit interface. The process following initialization is the same for both algorithms. You just have to specify a few basic commands and after that, you will be able to send massages to LCD display.
Figure below illustrates the 8-bit initialization of LCD:

It is not a mistake! In this algorithm, the same value is three times successively sent and displayed to the LCD display.
The procedure in the 4-bit initialization is as follows:
Let's do it in mikroBasic...
'In mikroBasic for PIC, it is sufficient to write only one function to perform the
'whole process of LCD initialization. Prior to calling this function it is necessary
'to declare bits LCD_D4-LCD_D7, LCD_RS and LCD_EN.
...
sub procedure Lcd_Init ' Initialize LCD
...
PRACTICAL EXAMPLES
The process of creating a new project is very simple. Select the New Project option from the Project menu, as shown in Figure on the right.
A window called New Project Wizard, which will guide you through the process of creating a new project, appears. The introductory window of this application contains a list of actions to be performed when creating a new project. Click Next.
The process of creating a new project can be broken up into five steps:
- Selecting the microcontroller to write a program for. In this case it is PIC16F887.
- Selecting the device clock. In this case, it is 8 MHz clock.
- Selecting the name and location of the project. In this case, the project name is First _Project and it will be saved in the C:\My projects folder. The compiler automatically appends the .mbppi extension to the project name and a source file having the same name (First_Project .mbas) will be created within it.
- In case the project consists of several source files, it is necessary to specify them all and include into the project by clicking the Add button. In this example, there are no additional source files within the project.
- Finally, it is necessary to approve all selected options by clicking Finish.
After creating the project, a new blank window to write a program in will appear. See Figure below.
When the program is written, it is necessary to compile it into a .hex code, by selecting one of the build options from the Project menu:
- To create a .hex file, select Build (Ctrl+F9) from the Project menu or click the Build icon from the Project toolbar.
- The Build All Projects (Shift+F9) option builds all files within the project, libraries (if there is a source code for them) and def files for the chip in use.
- The Build + Program (Ctrl+F11) option is special as it enables the mikroBasic PRO for PIC compiler to automatically load the program into the microcontroller after compilation. The process of programming is performed by using the PICflash programmer.
All the errors detected during compilation will be shown in the Messages window. If no errors are encountered, the mikroBasic PRO for PIC compiler will generate output files.