Micro Controller 8051
Micro Controller 8051
Introduction
1.1 What are microcontrollers and what are they used for?
1.2 What is what in microcontroller
Introduction
It was electricity in the beginning....The people were happy because they did not know that it was
existing all around them and that it could be utilized. It was fine. And then Faraday came and the
stone has started rolling slowly...
During the time, the first machines using a new sort of energy appeared accompanied with people
who knew something about electricity. A long time has passed since then and just when
civilization got used to this innovation and stopped paying attention to what a new generation of
specialists were doing, someone came up with an idea that electrons could be a very convenient
toy being closed in a glass pipe. At first sight, it was only a good idea, but there was no return,
electonics was born and the stone continued rolling down the hill faster and faster...
A new science - new specialists. The blue coats were replaced with white ones and people who
knew something about electronics appeared on stage. While the rest of the humanity were
passively watching in disbelief what was going on, within plotters two fractions appeared-
“software-oriented” and “hardware-oriented”. A bit younger than their teachers, very enthusiastic
and full of ideas, both of them kept on working but separate ways. While the first group had a
stable development, hardware-oriented people, driven by success, soon threw caution to the wind
and invented transistor.
Up till that moment, the things could be more or less kept under control, but broad publicity was
not aware of seriousness of the situation and it soon led to a fatal mistake! Being naive in belief
that using cheap tricks could slow down technology development as well as developing of the
world, mass market opened its door to the products of Electronics Industry, closing a magic circle
therefore. Components’ prices fell rapidly becoming available for use to younger population. The
stone was falling freely...
The first integrated circuits and processors have soon appeared, which enabled for computers to
drop down in price. The computers have started to develop their own production. The prices
droped down again and Electonics got new adherents. It appeared everywhere. Another circle has
been closed! Ordinary people got hold of computers and computer era has begun...
While this drama was going on, hobbyists and professionals, protected by anonymity, were
working hard on their projects , although split in two big groups. Then, someone has again
remembered: Why should not we make an universal component? It would be a cheap and
universal integrated circuit that could be programmed and used in any field of electronics, device
and wherever needed. Technology has been developed enough, market exists, why not? So it
happened, body and spirit are united, the circuit is created and called MICROCONTROLLER.
1.1 What are microcontrollers and what are they used for?
As all other good things, this powerful component is basically very simple and is obtained by
uniting tested and high- quality "ingredients" (components) as per following receipt:
Three things have had a crucial impact on such a success of the microcontrollers:
Powerful and intelligently chosen electronics embedded in the microcontrollers can via
input/output devices ( switches, push buttons, sensors, LCD displays, relays…) control
various processes and devices such as: industrial automatics, electric current,
temperature, engine performance etc.
A very low price enables them to be embedded in such devices in which, until recent time
it was not worth embedding anything. Thanks to that, the world is overwhelmed today
with cheap automatic devices and various “intelligent” appliences.
Prior knowledge is hardly needed for programming. It is sufficient to have any kind of
PC (software in use is not demanding at all and it is easy to learn to work on it) and one
simple device (programmer) used for “transffering” completed programs into the
microcontroller.
Therefore, if you are infected with a virus called electronics, there is nothing left for you to do but
to learn how to control its power and how to direct it at the right course.
How does microcontroller operate?
Even though there is a great number of various microcontrollers and even greater number of
programs designed for the microcontrollers’ use only, all of them have many things in common.
That means that if you learn to handle one of them you will be able to handle them all. A typical
scenario on whose basis it all functions is as follows:
1. Power supply is turned off and everything is so still…chip is programmed, every thing is
in place and nothing indicates what is to come…
2. Power supply connectors are connected to the power supply source and every thing starts
to happen at high speed! The control logic registers what is going on first. It enables only
quartz oscillator to operate. While the first preparations are in progress and parasite
capacities are being charged, the first milliseconds go by.
3. Power supply connectors are connected to the power supply source and every thing starts
to happen at high speed! The control logic registers what is going on first. It enables only
quartz oscillator to work. While the first preparations are in progress and parasite
capacities are being charged, the first milliseconds go by.
4. Voltage level has reached its full value and frequency of oscillator has became stable. The
bits are being written to the SFRs, showing the state of all periph erals and all pins are
configured as outputs. Everything occurs in harmony to the pulses’ rhythm and the
overall electronis starts operating. Since this moment the time is measured in micro and
nanoseconds.
5. Program Counter is reset to zero address of the program memory. Instruction from that
address is sent to instruction decoder where its meaning is recognised and it is executed
with immediate effect.
6. The value of the Program Counter is being incremented by 1 and the whole process is
being repeated...several million times per second.
1.2 What is what in microcontroller?
Obviously, everything that occurs in the microcontroller occurs at high speed and quite simple,
but it would not be so useful if there are no special interfaces which make it complete. Text below
refers to that (in short).
The Program Memory is a type of memory which permanently stores a program being executed.
Obviously, the maximal length of the program that can be written to depends on the size of the
memory. Program memory can be built in the microcontroller or added from outside as a separate
chip, which depends on type of the microcontroller. Both variants have advantages and
disadvantages: if added from outside, the microcontroller is cheaper and program can be
considerably longer. At the same time, a number of available pins is decremented as the
microcontroller uses its own input/output ports to be connected to the memory. The capacity of
Internal Program Memory is usually smaller and more expensive but such a chip has more
possibilities of connecting to peripheral environment. Program memory size ranges from 512B to
64KB.
Data Memory (RAM)
Data Memory is a type of memory used for temporary storing and keeping different data and
constants created and used during operating process . The content of this memory is erased once
the power is off. For example: when the program performes addition, it is necessary to have a
register presenting what in everyday life is called “a sum” . For that purpose one of the registers
in RAM is named as such and serves for storing results of addition. Data memory size goes up to
a few KBs.
EEPROM Memory
The EEPROM Memory is a special type of memory which not all the types of the
microcontrollers have.Its content can be changed during program execution (similar to RAM ),
but it is permanently saved even after the power goes off (similar to ROM). It is used for storing
different values created and used during operating process and which must be saved upon turning
off the device ( calibration values, codes, values to count up to etc.). A disadvantage of this
memory is that programming is relatively slow- measured in miliseconds.
SFRs ( Special Function Registers )
SFRs are a particular part of memory whose purpose is defined in advance by the producer. Each
of these registers have its name and control some of interfaces within the microcontroller. For
example: by writing zero or one to the SFR controlling some input/output port, each of the port
pins can be configured as input or output (each bit in this register controls the purpose of one
single pin).
Program Counter
Program Counter is an engine which starts the program and indicates the address in memory
where next instruction to execute is found. Immediately after its execution, the value of the
counter is incremented by 1. For this automatic increment, the program executes one instruction
at a time as it is written. However…the program counter value could be changed at any moment,
which will cause “jump” to a new location in the program memory. This is how subroutines or
branch instructions are executed. When finding its new place in the program, the counter resumes
even automatic counting +1, +1, +1…
As its name tells, this is "Big Brother" who monitors and controls all operations being performed
within the microcontroller and the user cannot affect its work. It consists of several smaller units.
The most important are:
Bit - a word invented to confuse people who start handling electronics. In practice ( only in
practice) this word indicates whether the voltage is applied to an electrical conductor or not. In
the first case, a logical one is present on the pin, i.e. the bit’s value is 1. Otherwise, if the voltage
level is 0 V, i.e. a logical zero is present on the pin, the bit’s value is 0. It is more complicated in
theory where the bit is actually a digit in a binary system, whereas, a bit is just a bit whose value
amounts 0 or 1 (in decade system we are used to the digits’ value amounting 0, 1 , 2 , 3 , …..8 or
9).
Input/output ports (I/O Ports)
The microcontroller cannot be of any use without being connected to peripheral devices. For that
reason each microcontroller has one or more registers connected to its pins (called ports in this
case).
Why input/output? Because the user can change pin’s role according to his/her own needs. These
are, in fact, the only registers in the microcontroller whose state can be checked by voltmeter !
Oscillator
The oscillator can be compared with rhythm section of a mini orchestra. Equalized pulses coming
from this circuit enable harmonious and synchronic operating of all other parts of the
microcontroller. It is commonly configured so as to use quartz-crystal or ceramics resonator for
frequency stabilization. Besides, it can often operate without elements for frequency stabilization
( like RC oscillator). It is important to know that instructions are not executed at the rate ordered
by oscillator but several times slower. The reason for this is that each instruction is executed in
several steps (In some microcontrollers execution time of all instructions is equal, while in others
microcontrollers execution time differs for different instructions). Consequently, if your system
uses quartz-crystal of 20MHz, execution time of a program instruction is not 50nS but 200, 400
or even 800 nS!
Timers/Counters
Most programs use in some way these miniature electronic "stopwatches". They are mostly 8- or
16-bit SFRs whose value is automatically incremented with each coming pulse. Once the register
is completely "filled up"- an interrupt is generated !
If the registers use internal oscillator for its operating then it is possible to measure the time
between two events ( if the register value is T1 at the moment measuring has started, and T2 at
the moment measuring has finished, then the time that has passed is equal to the value gained by
their subtruction T2-T1 ). If the registers for its operating use pulses coming from external source
then such a timer is converted to counter.
This is a very simple explanation used to describe the essence of the operating. It’s a bit more
complicated in practice.
Register is another name for a memory cell. Beside 8 bits available to the user, each register has
also addressing part usually not visible to the user. It is important to know:
Its name tells a lot about its purpose. Watchdog Timer is a timer connected to a particular and
totally independent RC oscillator within the microcontroller.
If enabled to operate, every time it "counts up to end", the microcontroller is reset and program
execution starts from the first instruction. The to keep this from happening by using particular
command. The whole idea is based on the fact that every program circulates, in other words, the
program is executed in several longer or shorter loops.
If the instructions which resets the value of the watchdog timer are set at some important program
locations, besides commands being regularly executed, then the operation of the watchdog timer
will not be noticed.
If for any reason (usually electrical disturbances in industry), the program counter "gets stuck" at
memory location from where there is no return, the register’s value being steadily incremented by
the watchdog timer will reach the maximum et voila ! Reset occurs!
Two things within the circuit that take care of the microcontroller power supply are worth
attention :
Brown out is potentially dangerous state coming up at the moment the microcontroller is being
turned off or in situations when due to powerful disturbances, voltage supply comes to the lowest
limit. As the microcontroller consists of several circuits which have different operating voltage
levels, this can cause its "out of control" performance. In order to prevent that, a circuit for brown
out reset is usually embedded. When the voltage level drops below the lower limit then this
circuit immediately resets the whole electronics.
Reset pin is usually identified as MCLR (Master Clear Reset) and serves for "external" reset of
the microcontroller by applying logical zero or one depending on type of the microcontroller. In
case the brown out is not embedded a simple external circuit for brown out reset can be connected
to this pin.
Serial communication
Connection between the microcontroller and peripheral devices established through I/O ports is
an ideal solution for shorter distances- up to several meters. But, when it is needed to enable
communication between two devices on longer distances or when for any other reason it is not
possible to use "parallel" connection ( for example remote control of the aircraft ) it is obvious
that something so simple cannot be taken into account. In such and similar situations,
communication through pulses, called serial communication is the most appropriate to use.
Serial communication problem has been resolved a long time ago and nowadays several different
systems enabling this kind of connection are embedded as a standard equipment into most
microcontroller. Which of them will be used in very situation depends on several factors. The
most important are the following:
One of the most important things concerning the use of serial communication is to strictly
observe the Protocol. It is a set of rules which must be applied in order to enable devices to
recognize the data being exchanged. Fortunately, the microcontrollers automatically take care of
it, which leads to a reduction of the programmer’s work to simple writing and reading data.
Byte - 8 bits next to each other make entity called a program word or a byte. If the bit is a digit
then it is logical that bytes are numbers. All mathematical operations can be performed upon
them, just like with usual decimal numbers and they are performed in the ALU. It is important to
note that byte ( as each number) has “two sides”, i.e. digits a byte consists of are not of equal
significance. The highest value has a digit on the far left called the most significant bit ( MSB). A
digit on the far right has the least value and is called the least significant bit (LSB). As 8 digits
can be combined in 256 different ways, the greatest decimal number that can present one byte is
255 ( zero is also presented with one combination ).
Program
Unlike other integrated circuits which only need to be connected to other components and then
powered on, the microcontrollers need to be programmed too prior to turning the power on. This
is so called "a bitter pill" and the main reason why hardware-oriented electronics engineers
mainly avoid the microcontrollers. It is a trap causing huge losses because the microcontrollers
programming is in fact very simple.
In order to write a program for running microcontrollers, several "low-level" program languages
for programming computers can be used – Assembler , C and Basic ( and their versions ).
Besides, writing program procedure consists of simple giving instructions in order in which they
should be executed. There are also many programs operating in Windows environment used to
facilitate work and provide additional- visual tools.
The use of Assembler is described in this book because it is the simplest language with the fastest
execution allowing entire control on what is going on in the circuit.
Interrupt - electronics is usually more faster than physical process in environment it should keep
under control. That’s why the microcontroller spend the most of its time waiting for something to
happen or execute.In order to avoid continuous checking for logical state on input pins and in
internal registers, the interrupt is generated. It is a signal interrupting regular program
execution. Since several events can cause interrupt, when it occurs, the microcontroller
immediately stops operating and checks for the cause. If it is needed to perform some action, a
current state of the program counter is pushed on the Stack and the appropriate program is
executed (so called interrupt routine ).
Stack is a part of RAM used for storing the current state of the program counter (address).This
address lets the controller know where to return after the subroutine has been executed. Stack can
consist of several levels. This enables subroutines’ nesting, i.e. calling one subroutine from
another.
Chapter 2 : 8051 Microcontroller Architecture
Microcontrollers’ producers have been struggling for a long time for attracting more and more
choosy customers. Every couple of days a new chip with a higher operating frequency, more
memory and more high-quality A/D converters comes on the market.
Nevertheless, by analyzing their structure it is concluded that most of them have the same (or at
least very similar) architecture known in the product catalogs as “8051 compatible”. What is all
this about?
The whole story began in the far 80s when Intel launched its series of the microcontrollers
labelled with MCS 051. Although, several circuits belonging to this series had quite modest
features in comparison to the new ones, they took over the world very fast and became a standard
for what nowadays is ment by a word microcontroller.
The reason for success and such a big popularity is a skillfully chosen configuration which
satisfies needs of a great number of the users allowing at the same time stable expanding ( refers
to the new types of the microcontrollers ). Besides, since a great deal of software has been
developed in the meantime, it simply was not profitable to change anything in the
microcontroller’s basic core. That is the reason for having a great number of various
microcontrollers which actually are solely upgraded versions of the 8051 family. What is it what
makes this microcontroller so special and universal so that almost all the world producers
manufacture it today under different name ?
As shown on the previous picture, the 8051 microcontroller has nothing impressive at first sight:
As it is shown on the previous picture, the 8051 microcontroller have nothing impressive at first
sight:
The whole configuration is obviously envisaged as such to satisfy the needs of most programmers
who work on development of automation devices. One of advantages of this microcontroller is
that nothing is missing and nothing is too much. In other words, it is created exactly in
accordance to the average user‘s taste and needs. The other advantage is the way RAM is
organized, the way Central Processor Unit (CPU) operates and ports which maximally use all
recourses and enable further upgrading.
Pins 1-8: Port 1 Each of these pins can be configured as input or output.
Pin 9: RS Logical one on this pin stops microcontroller’s operating and erases the contents of
most registers. By applying logical zero to this pin, the program starts execution from the
beginning. In other words, a positive voltage pulse on this pin resets the microcontroller.
Pins10-17: Port 3 Similar to port 1, each of these pins can serve as universal input or output .
Besides, all of them have alternative functions:
Pin 10: RXD Serial asynchronous communication input or Serial synchronous communication
output.
Pin 11: TXD Serial asynchronous communication output or Serial synchronous communication
clock output.
Pin 18, 19: X2, X1 Internal oscillator input and output. A quartz crystal which determines
operating frequency is usually connected to these pins. Instead of quartz crystal, the miniature
ceramics resonators can be also used for frequency stabilization. Later versions of the
microcontrollers operate at a frequency of 0 Hz up to over 50 Hz.
Pin 21-28: Port 2 If there is no intention to use external memory then these port pins are
configured as universal inputs/outputs. In case external memory is used then the higher address
byte, i.e. addresses A8-A15 will appear on this port. It is important to know that even memory
with capacity of 64Kb is not used ( i.e. note all bits on port are used for memory addressing) the
rest of bits are not available as inputs or outputs.
Pin 29: PSEN If external ROM is used for storing program then it has a logic-0 value every time
the microcontroller reads a byte from memory.
Pin 30: ALE Prior to each reading from external memory, the microcontroller will set the lower
address byte (A0-A7) on P0 and immediately after that activates the output ALE. Upon receiving
signal from the ALE pin, the external register (74HCT373 or 74HCT375 circuit is usually
embedded ) memorizes the state of P0 and uses it as an address for memory chip. In the second
part of the microcontroller’s machine cycle, a signal on this pin stops being emitted and P0 is
used now for data transmission (Data Bus). In this way, by means of only one additional (and
cheap) integrated circuit, data multiplexing from the port is performed. This port at the same time
used for data and address transmission.
Pin 31: EA By applying logic zero to this pin, P2 and P3 are used for data and address
transmission with no regard to whether there is internal memory or not. That means that even
there is a program written to the microcontroller, it will not be executed, the program written to
external ROM will be used instead. Otherwise, by applying logic one to the EA pin, the
microcontroller will use both memories, first internal and afterwards external (if it exists), up to
end of address space.
Pin 32-39: Port 0 Similar to port 2, if external memory is not used, these pins can be used as
universal inputs or outputs. Otherwise, P0 is configured as address output (A0-A7) when the ALE
pin is at high level (1) and as data output (Data Bus), when logic zero (0) is applied to the ALE
pin.
All 8051 microcontrollers have 4 I/O ports, each consisting of 8 bits which can be configured as
inputs or outputs. This means that the user has on disposal in total of 32 input/output lines
connecting the microcontroller to peripheral devices.
A logic state on a pin determines whether it is configured as input or output: 0=output, 1=input. If
a pin on the microcontroller needs to be configured as output, then a logic zero (0) should be
applied to the appropriate bit on I/O port. In this way, a voltage level on the appropriate pin will
be 0.
Similar to that, if a pin needs to be configured as input, then a logic one (1) should be applied to
the appropriate port. In this way, as a side effect a voltage level on the appropriate pin will be 5V
(as it is case with any TTL input). This may sound a bit confusing but everything becomes clear
after studying a simplified electronic circuit connected to one I/O pin.
Input/Output (I/O) pin
This is a simplified overview of what is connected to a pin inside the microcontroller. It concerns
all pins except those included in P0 which do not have embedded pullup resistor.
Output pin
A logic zero (0) is applied to a bit in the P register. By turning output FE transistor on, the
appropriate pin is directly connected to ground.
Input pin
A logic one (1) is applied to a bit in the P register. Output FE transistor is turned off. The
appropriate pin remains connected to voltage power supply through a pull-up resistor of high
resistance.
A logic state (voltage) on any pin can be changed or read at any moment. A logic zero (0) and
logic one (1) are not equal. A logic one (0) represents almost short circuit to ground. Such a pin is
configured as output.
A logic one (1) is “loosely” connected to voltage power supply through resistors of high
resistance. Since this voltage can be easily “pulled down” by an external signal, such a pin is
configured as input.
Port 0
It is specific to this port to have a double purpose. If external memory is used then the lower
address byte (addresses A0-A7) is applied on it. Otherwise, all bits on this port are configured as
inputs or outputs.
Another characteristic is expressed when it is configured as output. Namely, unlike other ports
consisting of pins with embedded pull-up resistor ( connected by its end to 5 V power supply ),
this resistor is left out here. This, apparently little change has its consequences:
If any pin on this port is configured as input then it performs as if it “floats”. Such input has
unlimited input resistance and has no voltage coming from “inside”.
When the pin is configured as output, it performs as “open drain”, meaning that by writing 0 to
some port’s bit, the appropriate pin will be connected to ground (0V). By writing 1, the external
output will keep on “floating”. In order to apply 1 (5V) on this output, an external pull-up resistor
must be embedded.
Only in case P0 is used for addressing external memory ( only in that case), the microcontroller
will provide internal power supply source in order to establish logical ones on pins. There is no
need to add external pullup resistors.
Port 1
This is a true I/O port, because there are no role assigning as it is the case with P0. Since it has
embedded pull-up resistors it is completely compatible with TTL circuits.
Port 2
Similar to P0, when using external memory, lines on this port occupy addresses intended for
external memory chip. This time it is the higher address byte with addresses A8-A15. When there
is no additional memory, this port can be used as universal input-output port similar by its
features to the port 1.
Port 3
Even though all pins on this port can be used as universal I/O port, they also have an alternative
function. Since each of these functions use inputs, then the appropriate pins have to be configured
like that. In other words, prior to using some of reserve port functions, a logical one (1) must be
written to the appropriate bit in the P3 register. From hardware’s perspective , this port is also
similar to P0, with the difference that its outputs have a pull-up resistor embedded.
When configured as outputs ( logic zero (0) ), single port pins can "receive" current of 10mA. If
all 8 bits on a port are active, total current must be limited to 15mA (port P0: 26mA). If all ports
(32 bits) are active, total maximal current must be limited to 71mA. When configured as inputs
(logic 1), embedded pull-up resistor provides very weak current, but strong enough to activate up
to 4 TTL inputs from LS series.
It may be seen from description of some ports, that even though all pins have more or less similar
internal structure, it is necessary to pay attention to which of them will be used for what and how.
For example: If they are used as outputs with high voltage level (5V), then port 0 should be
avoided because its pins do not have added resistor for connection to +5V. Only low logic level
can be obtained therefore, if another port is used for the same purpose, one should have in mind
that pull-up resistors have a relatively high resistance. Consequentaly it can be counted on only
several hundreds microamperes of current coming out of a pin.
2.4 8051 Microcontroller Memory Organisation
The microcontroller memory is divided into Program Memory and Data Memory. Program
Memory (ROM) is used for permanent saving program being executed, while Data Memory
(RAM) is used for temporarily storing and keeping intermediate results and variables. Depending
on the model in use ( still referring to the whole 8051 microcontroller family) at most a few Kb of
ROM and 128 or 256 bytes of RAM can be used. However…
All 8051 microcontrollers have 16-bit addressing bus and can address 64 kb memory. It is neither
a mistake nor a big ambition of engineers who were working on basic core development. It is a
matter of very clever memory organization which makes these controllers a real “ programmers’
tidbit“ .
Program Memory
The oldest models of the 8051 microcontroller family did not have internal program memory . It
was added from outside as a separate chip. These models are recognizable by their label
beginning with 803 ( for ex. 8031 or 8032). All later models have a few Kbytes ROM embedded,
Even though it is enough for writing most of the programs, there are situations when additional
memory is necessary. A typical example of it is the use of so called lookup tables. They are used
in cases when something is too complicated or when there is no time for solving equations
describing some process. The example of it can be totally exotic (an estimate of self-guided
rockets’ meeting point) or totally common( measuring of temperature using non-linear thermo
element or asynchronous motor speed control). In those cases all needed estimates and
approximates are executed in advance and the final results are put in the tables ( similar to
logarithmic tables ).
How does the microcontroller handle external memory depends on the pin EA logic state:
EA=0 In this case, internal program memory is completely ignored, only a program stored in
external memory is to be executed.
EA=1 In this case, a program from builtin ROM is to be executed first ( to the last location).
Afterwards, the execution is continued by reading additional memory.
in both cases, P0 and P2 are not available to the user because they are used for data nd address
transmission. Besides, the pins ALE and PSEN are used too.
Data Memory
As already mentioned, Data Memory is used for temporarily storing and keeping data and
intermediate results created and used during microcontroller’s operating. Besides, this
microcontroller family includes many other registers such as: hardware counters and timers,
input/output ports, serial data buffers etc. The previous versions have the total memory size of
256 locations, while for later models this number is incremented by additional 128 available
registers. In both cases, these first 256 memory locations (addresses 0-FFh) are the base of the
memory. Common to all types of the 8051 microcontrollers. Locations available to the user
occupy memory space with addresses from 0 to 7Fh. First 128 registers and this part of RAM is
divided in several blocks.
The first block consists of 4 banks each including 8 registers designated as R0 to R7. Prior to
access them, a bank containing that register must be selected. Next memory block ( in the range
of 20h to 2Fh) is bit- addressable, which means that each bit being there has its own address from
0 to 7Fh. Since there are 16 such registers, this block contains in total of 128 bits with separate
addresses (The 0th bit of the 20h byte has the bit address 0 and the 7th bit of th 2Fh byte has the
bit address 7Fh). The third group of registers occupy addresses 2Fh-7Fh ( in total of 80 locations)
and does not have any special purpose or feature.
In order to satisfy the programmers’ permanent hunger for Data Memory, producers have
embedded an additional memory block of 128 locations into the latest versions of the 8051
microcontrollers. Naturally, it’s not so simple…The problem is that electronics performing
addressing has 1 byte (8 bits) on disposal and due to that it can reach only the first 256 locations.
In order to keep already existing 8-bit architecture and compatibility with other existing models a
little trick has been used.
Using trick in this case means that additional memory block shares the same addresses with
existing locations intended for the SFRs (80h- FFh). In order to differentiate between these two
physically separated memory spaces, different ways of addressing are used. A direct addressing is
used for all locations in the SFRs, while the locations from additional RAM are accessible using
indirect addressing.
How to extend memory?
In case on-chip memory is not enough, it is possible to add two external memory chips with
capacity of 64Kb each. I/O ports P2 and P3 are used for their addressing and data transmission.
From the users’ perspective, everything functions quite simple if properly connected because the
most operations are performed by the microcontroller itself. The 8051 microcontroller has two
separate reading signals RD#(P3.7) and PSEN#. The first one is activated byte from external data
memory (RAM) should be read, while another one is activated to read byte from external
program memory (ROM). These both signals are active at logical zero (0) level. A typical
example of such memory extension using special chips for RAM and ROM, is shown on the
previous picture. It is called Hardward architecture.
Even though the additional memory is rarely used with the latest versions of the microcontrollers,
it will be described here in short what happens when memory chips are connected according to
the previous scheme. It is important to know that the whole process is performed automatically,
i.e. with no intervention in the program.
When the program during execution encounters the instruction which resides in exter nal
memory (ROM), the microcontroller will activate its control output ALE and set the first
8 bits of address (A0-A7) on P0. In this way, IC circuit 74HCT573 which "lets in" the
first 8 bits to memory address pins is activated.
A signal on the pin ALE closes the IC circuit 74HCT573 and immediately afterwards 8
higher bits of address (A8-A15) appear on the port. In this way, a desired location in
addtional program memory is completely addressed. The only thing left over is to read its
content.
Pins on P0 are configured as inputs, the pin PSEN is activated and the microcon troller
reads content from memory chip. The same connections are used both for data and lower
address byte.
Similar occurs when it is a needed to read some location from external Data Memory. Now,
addressing is performed in the same way, while reading or writing is performed via signals which
appear on the control outputs RD or WR .
Addressing
While operating, processor processes data according to the program instructions. Each instruction
consists of two parts. One part describes what should be done and another part indicates what to
use to do it. This later part can be data (binary number) or address where the data is stored. All
8051 microcontrollers use two ways of addressing depending on which part of memory should be
accessed:
Direct Addressing
On direct addressing, a value is obtained from a memory location while the address of that
location is specified in instruction. Only after that, the instruction can process data (howdepends
on the type of instruction: addition, subtraction, copy…). Obviously, a number being changed
during operating a variable can reside at that specified address. For example:
Since the address is only one byte in size ( the greatest number is 255), this is how only the first
255 locations in RAM can be accessed in this case the first half of the basic RAM is intended to
be used freely, while another half is reserved for the SFRs.
On indirect addressing, a register which contains address of another register is specified in the
instruction. A value used in operating process resides in that another register. For example:
Only RAM locations available for use are accessed by indirect addressing (never in the SFRs).
For all latest versions of the microcontrollers with additional memory block ( those 128 locations
in Data Memory), this is the only way of accessing them. Simply, when during operating, the
instruction including “@” sign is encountered and if the specified address is higher than 128 ( 7F
hex.), the processor knows that indirect addressing is used and jumps over memory space
reserved for the SFRs.
MOV A,@R0; Means: Store the value from the register whose address is in the R0 register
into accumulator
On indirect addressing, the registers R0, R1 or Stack Pointer are used for specifying 8-bit
addresses. Since only 8 bits are avilable, it is possible to access only registers of internal RAM in
this way (128 locations in former or 256 locations in latest versions of the microcontrollers). If
memory extension in form of additional memory chip is used then the 16-bit DPTR Register
(consisting of the registers DPTRL and DPTRH) is used for specifying addresses. In this way it is
possible to access any location in the range of 64K.
SFRs are a kind of control table used for running and monitoring microcontroller’s operating.
Each of these registers, even each bit they include, has its name, address in the scope of RAM and
clearly defined purpose ( for example: timer control, interrupt, serial connection etc.). Even
though there are 128 free memory locations intended for their storage, the basic core, shared by
all types of 8051 controllers, has only 21 such registers. Rest of locations are intensionally left
free in order to enable the producers to further improved models keeping at the same time
compatibility with the previous versions. It also enables the use of programs written a long time
ago for the microcontrollers which are out of production now.
A Register (Accumulator)
This is a general-purpose register which serves for storing intermediate results during operating.
A number (an operand) should be added to the accumulator prior to execute an instruction upon
it. Once an arithmetical operation is preformed by the ALU, the result is placed into the
accumulator. If a data should be transferred from one register to another, it must go through
accumulator. For such universal purpose, this is the most commonly used register that none
microcontroller can be imagined without (more than a half 8051 microcontroller's instructions
used use the accumulator in some way).
B Register
B register is used during multiply and divide operations which can be performed only upon
numbers stored in the A and B registers. All other instructions in the program can use this register
as a spare accumulator (A).
During programming, each of registers is called by name so that their exact address is not so
important for the user. During compiling into machine code (series of hexadecimal numbers
recognized as instructions by the microcontroller), PC will automatically, instead of registers’
name, write necessary addresses into the microcontroller.
R Registers (R0-R7)
This is a common name for the total 8 generalpurpose registers (R0, R1, R2 ...R7). Even they are
not true SFRs, they deserve to be discussed here because of their purpose. The bank is active
when the R registers it includes are in use. Similar to the accumulator, they are used for
temporary storing variables and intermediate results. Which of the banks will be active depends
on two bits included in the PSW Register. These registers are stored in four banks in the scope of
RAM.
The following example best illustrates the useful purpose of these registers. Suppose that
mathematical operations on numbers previously stored in the R registers should be performed:
(R1+R2) - (R3+R4). Obviously, a register for temporary storing results of addition is needed.
Everything is quite simple and the program is as follows :
This is one of the most important SFRs. The Program Status Word (PSW) contains several status
bits that reflect the current state of the CPU. This register contains: Carry bit, Auxiliary Carry,
two register bank select bits, Overflow flag, parity bit, and user-definable status flag. The ALU
automatically changes some of register’s bits, which is usually used in regulation of the program
performing.
P - Parity bit. If a number in accumulator is even then this bit will be automatically set (1),
otherwise it will be cleared (0). It is mainly used during data transmission and receiving via serial
communication.
- Bit 1. This bit is intended for the future versions of the microcontrollers, so it is not supposed to
be here.
OV Overflow occurs when the result of arithmetical operation is greater than 255 (deci mal), so
that it can not be stored in one register. In that case, this bit will be set (1). If there is no overflow,
this bit will be cleared (0).
RS0, RS1 - Register bank select bits. These two bits are used to select one of the four
register banks in RAM. By writing zeroes and ones to these bits, a group of registers R0-
R7 is stored in one of four banks in RAM.
Space in
RS1 RS2
RAM
Bank0
0 0
00h-07h
Bank1
0 1
08h-0Fh
Bank2
1 0
10h-17h
Bank3
1 1
18h-1Fh
CY - Carry Flag is the (ninth) auxiliary bit used for all arithmetical operations and shift
instructions.
These registers are not true ones because they do not physically exist. They consist of two
separate registers: DPH (Data Pointer High) and (Data Pointer Low). Their 16 bits are used for
external memory addressing. They may be handled as a 16-bit register or as two independet 8-bit
registers.Besides, the DPTR Register is usually used for storing data and intermediate results
which have nothing to do with memory locations.
SP Register (Stack Pointer)
A value of the Stack Pointer ensures that the Stack Pointer will point to valid RAM and permits
Stack availability. By starting each subprogram, the value in the Stack Pointer is incremented by
1. In the same manner, by ending subprogram, this value is decremented by 1. After any reset, the
value 7 is written to the Stack Pointer, which means that the space of RAM reserved for the Stack
starts from this location. If another value is written to this register then the entire Stack is moved
to a new location in the memory.
The state of a port bit, besides being reflected in the pin, determines at the same time whether it
will be configured as input or output. If a bit is cleared (0), the pin will be configured as output.
In the same manner, if a bit is set to 1 the pin will be configured as input. After reset, as well as
when turning the microcontroller on , all bits on these ports are set to one (1). This means that the
appropriate pins will be configured as inputs.
Conditionally said, I/O ports are directly connected to the microcontroller’s pins. This means that
a logic state of these registers can be checked by voltmeter and vice versa-voltage on the pins can
be checked by testing their bits!
As explained in the previous chapter, the main oscillator of the microcontroller uses quartz crystal
for its operating. As the frequency of this oscillator is precisely defined and very stable, these
pulses are the most suitable for time measuring (such oscillators are used in quartz clocks as
well). In order to measure time between two events it is only needed to count up pulses from this
oscillator. That is exactly what the timer is doing. Namely, if the timer is properly programmed,
the value written to the timer register will be incremented or decremented after each coming
pulse, i.e. once per each machine cycle cycle. Taking into account that one instruction lasts 12
quartz oscillator periods (one machine cycle), by embedding quartz with oscillator frequency of
12MHz, a number in the timer register will be changed million times per second, i.e. each
microsecond.
The 8051 microcontrollers have 2 timer counters called T0 and T1. As their names tell, their main
purpose is to measure time and count external events. Besides, they can be used for generating
clock pulses used in serial communication, i.e. Baud Rate.
Timer T0
As it is shown in the picture below, this timer consists of two registers – TH0 and TL0. The
numbers these registers include represent a lower and a higher byte of one 16-digit binary
number.
This means that if the content of the timer 0 is equal to 0 (T0=0) then both registers it includes
will include 0. If the same timer contains for example number 1000 (decimal) then the register
TH0 (higher byte) will contain number 3, while TL0 (lower byte) will contain decimal number
232.
This register selects mode of the timers T0 and T1. As illustrated in the following picture, the
lower 4 bits (bit0 - bit3) refer to the timer 0, while the higher 4 bits (bit4 - bit7) refer to the timer
1. There are in total of 4 modes and each of them is described here in this book.
GATE1 starts and stops Timer 1 by means of a signal provided to the pin INT1 (P3.3):
o 1 - Timer 1 operates only if the bit INT1 is set
o 0 - Timer 1 operates regardless of the state of the bit INT 1
C/T1 selects which pulses are to be counted up by the timer/counter 1:
o 1 - Timer counts pulses provided to the pin T1 (P3.5)
o 0 - Timer counts pulses from internal oscillator
T1M1,T1M0 These two bits selects the Timer 1 operating mode.
T1M1 T1M0 Mode Description
0 0 0 13-bit timer
0 1 1 16-bit timer
8-bit auto-
1 0 2
reload
1 1 3 Split mode
GATE0 starts and stops Timer 1, using a signal provided to the pin INT0 (P3.2):
o 1 - Timer 0 operates only if the bit INT0 is set
o 0 - Timer 0 operates regardless of the state of the bit INT0
C/T0 selects which pulses are to be counted up by the timer/counter 0:
o 1 - Timer counts pulses provided to the pin T0(P3.4)
o 0 - Timer counts pulses from internal oscillator
T0M1,T0M0 These two bits select the Timer 0 operating mode.
This is one of the rarities being kept only for compatibility with the previuos versions of the
microcontrollers. When using this mode, the higher byte TH0 and only the first 5 bits of the lower
byte TL0 are in use. Being configured in this way, the Timer 0 uses only 13 of all 16 bits. How
does it operate? With each new pulse coming, the state of the lower register (that one with 5 bits)
is changed. After 32 pulses received it becomes full and automatically is reset, while the higher
byte TH0 is incremented by 1. This action will be repeated until registers count up 8192 pulses.
After that, both registers are reset and counting starts from 0.
Timer 0 in mode 1 (16-bit timer)
All bits from the registers TH0 and TL0 are used in this mode. That is why for this mode is being
more commonly used. Counting is performed in the same way as in mode 0, with difference that
the timer counts up to 65 536, i.e. as far as the use of 16 bits allows.
Timer 0 in mode 2 (Auto-Reload Timer)
What does auto-reload mean? Simply, it means that such timer uses only one 8-bit register for
counting, but it never counts from 0 but from an arbitrary chosen value (0- 255) saved in another
register.
The advantages of this way of counting are described in the following example: suppose that for
any reason it is continuously needed to count up 55 pulses at a time from the clock generator.
When using mode 1 or mode 0, It is needed to write number 200 to the timer registers and check
constantly afterwards whether overflow occured, i.e. whether the value 255 is reached by
counting . When it has occurred, it is needed to rewrite number 200 and repeat the whole
procedure. The microcontroller performs the same procedure in mode 2 automatically. Namely, in
this mode it is only register TL0 operating as a timer ( normally 8-bit), while the value from
which counting should start is saved in the TH0 register. Referring to the previous example, in
order to register each 55th pulse, it is needed to write the number 200 to the register and
configure the timer to operate in mode 2.
Timer 0 in Mode 3 (Split Timer)
By configuring Timer 0 to operate in Mode 3, the 16-bit counter consisting of two registers TH0
and TL0 is split into two independent 8-bit timers. In addition, all control bits which belonged to
the initial Timer 1 (consisting of the registers TH1 and TL1), now control newly created Timer 1.
This means that even though the initial Timer 1 still can be configured to operate in any mode
( mode 1, 2 or 3 ), it is no longer able to stop, simply because there is no bit to do that. Therefore,
in this mode, it will uninterruptedly “operate in the background “.
The only application of this mode is in case two independent 'quick' timers are used and the initial
Timer 1 whose operating is out of control is used as baud rate generator.
This is also one of the registers whose bits directly control timer operating.
Only 4 of all 8 bits this register has are used for timer control, while others are used for interrupt
control which will be discussed later.
TF1 This bit is automatically set with the Timer 1 overflow
TR1 This bit turns the Timer 1 on
o 1 - Timer 1 is turned on
o 0 - Timer 1 is turned off
TF0 This bit is automatically set with the Timer 0 overflow.
TR0 This bit turns the timer 0 on
o 1 - Timer 0 is turned on
o 0 - Timer 0 is turned off
Normally, first this timer and afterwards its mode should be selected. Bits which control that are
resided in the register TMOD:
This means that timer 0 operates in mode 1 and counts pulses from internal source whose
frequency is equal to 1/12 the quartz frequency.
In order to enable the timer, turn it on:
Immediately upon the bit TR0 is set, the timer starts operating. Assuming that a quartz crystal
with frequency of 12MHz is embedded, a number it contains will be incremented every
microsecond. By counting up to 65.536 microseconds, the both registers that timer consists of
will be set. The microcontroller automatically reset them and the timer keeps on repeating
counting from the beginning as far as the bit’s value is logic one (1).
Depending on the timer’s application, it is needed to read a number in the timer registers or to
register a moment they have been reset.
- Everything is extremely simple when it is needed to read a value of the timer which uses only
one register for counting (mode 2 or Mode 3) . It is sufficient to read its state at any moment and
it is it!
- It is a bit complicated to read a timer’s value when it operates in mode 2. Assuming that the
state of the lower byte is read first (TL0) and the state of the higher byte (TH0) afterwards, the
result is:
Everything seems to be in order at first sight, but the current state of register at the moment of
reading was:
There is another solution too. It is sufficient to simply turn timer off while reading ( the bit TR0
in the register TCON should be 0), and turn it on after that.
Usually, there is no need to continuously read timer registers’ contents. It is sufficient to register
the moment they are reset, i.e. when counting starts from 0. It is called overflow. When this has
occurred, the bit TF0 from the register TCON will be automatically set. The microcontroller is
waiting for that moment in a way that program will constantly check the state of this bit.
Furthermore, an interrupt to stop the main program execution can be enabled. Assuming that it is
needed to provide a program pause ( time the program appeared to be stopped) in duration of for
example 0.05 seconds ( 50 000 machine cycles ):
First, it is needed to calculate a number that should be written to the timer registers:
This number should be written to the timer registers TH0 and TL0:
Once the timer is started it will continue counting from the written number. Program instruction
checks if the bit TF0 is set, which happens at the moment of overflow, i.e. after exactly 50.000
machine cycles and 0.05 seconds respectively.
Suppose it is needed to measure the duration of an event, for example how long some device has
been turned on? Look at the picture of the timer and pay attention to the purpose of the bit
GATE0 ( which resides in the TMOD register ). If this bit is cleared then the state on the pin P3.2
does not affect the timer operating. If GATE0 = 1 the timer will operate as far as the pin P3.2 has
logic one (1) value. If this pin is supplied with 5V through some external switch at the moment
the device is being turned on, the timer will measure duration of its operating, which actually was
the aim.
How to count up pulses?
This time, the answer lies in the register TCON, and bit C/T0 respectively. Similar to the previous
example, this bit brings into an external signal. If the bit is cleared everything occurs in the same
way as in the previous examples and the timer counts pulses from oscillator of defined frequency,
i.e. measures the time that went by. If the bit is set, the timer input is provided with pulses from
the pin P3.4 (T0). Since these pulses do not have some definite time or order, it is not possible to
measure time by counting them. For that reason, this timer is turned into the counter. The highest
frequency that could be measured by such a counter is 1/24 frequency of used quartz-crystal.
Timer 1
Referring to its characteristics, this timer is “ a twin brother “ to the Timer 0. This means that they
have the same purpose, their operating is controlled by the same registers TMOD and TCON and
both of them can operate in one of 4 different modes.
One of the features that makes this microcontroller so powerful is an integrated UART, better
known as a serial port. It is a duplex port, which means that it can transmit and receive data
simultaneously. Without it, serial data sending and receiving would be endlessly complicated part
of the program where the pin state continuously is being changed and checked according to
strictly determined rhythm. Naturally, it does not happen here because the UART resolves it in a
very elegant manner. All the programmer needs to do is to simply select serial port mode and
baud rate. When the programmer is such configured, serial data sending is done by writing to the
register SBUF while data receiving is done by reading the same register. The microcontroller
takes care of all issues necessary for not making any error during data exchange.
Serial port should be configured prior to being used. That determines how many bits one serial
“word” contains, what the baud rate is and what the pulse source for synchronization is. All bits
controlling this are stored in the SFR Register SCON (Serial Control).
As seen, serial port mode is selected by combining the bits SM0 and SM2 :
TRANSMIT - Data transmission in form of pulse train automatically starts on the pin RXD at
the moment the data has been written to the SBUF register.In fact, this process starts after any
instruction being performed on this register. Upon all 8 bits have been sent, the bit TI in the
SCON register is automatically set.
RECEIVE - Starts data receiving through the pin RXD once two necessary conditions are met:
bit REN=1 and RI=0 (both bits reside in the SCON register). Upon 8 bits have been received, the
bit RI (register SCON) is automatically set, which indicates that one byte is received.
Since, there are no START and STOP bits or any other bit except data from the SBUF register,
this mode is mainly used on shorter distance where the noise level is minimal and where
operating rate is important. A typical example for this is I/O port extension by adding cheap IC
circuit ( shift registers 74HC595, 74HC597 and similar).
Mode 1
In Mode1 10 bits are transmitted through TXD or received through RXD in the following
manner: a START bit (always 0), 8 data bits (LSB first) and a STOP bit (always 1) last. The
START bit is not registered in this pulse train. Its purpose is to start data receiving mechanism.
On receive the STOP bit is automatically written to the RB8 bit in the SCON register.
The Baud rate in this mode is determined by the timer 1 overflow time.
Mode 2
In mode 2, 11 bits are sent through TXD or received through RXD: a START bit (always 0), 8
data bits (LSB first), additional 9th data bit and a STOP bit (always 1) last. On transmit, the 9th
data bit is actually the TB8 bit from the SCON register. This bit commonly has the purpose of
parity bit. Upon transmission, the 9th data bit is copied to the RB8 bit in the same register
( SCON).The baud rate is either 1/32 or 1/64 the quartz oscillator frequency.
TRANSMIT - A sequence for data transmission via serial communication is automatically
started upon the data has been written to the SBUF register. End of 1 byte transmission is
indicated by setting the TI bit in the SCON register.
RECEIVE - Receiving starts as soon as the START bit (logic zero (0)) appears on the pin RXD.
The condition is that bit REN=1and bit RI=0. Both of them are stored in the SCON register. The
RI bit is automatically set upon receiving has been completed.
Mode 3
Mode 3 is the same as Mode 2 except the baud rate. In Mode 3 is variable and can be selected.
The parity bit is the bit P in the PSW register. The simplest way to check correctness of the
received byte is to add this parity bit to the transmit side as additional bit. Simply, immediately
before transmit, the message is stored in the accumulator and the bit P goes into the TB8 bit in
order to be “a part of the message”. On the receive side is the opposite : received byte is stored in
the accumulator and the bit P is compared with the bit RB8 ( additional bit in the message). If
they are the same- everything is OK!
Baud Rate
Baud Rate is defined as a number of send/received bits per second. In case the UART is used,
baud rate depends on: selected mode, oscillator frequency and in some cases on the state of the
bit SMOD stored in the SCON register. All necessary formulas are specified in the table :
Timer 1 is usually used as a baud rate generator because it is easy to adjust various baud rate by
the means of this timer. The whole procedure is simple:
As described in the previous text, modes 2 and 3 enable the additional 9th data bit to be part of
message. It can be used for checking data via parity bit. Another useful application of this bit is in
communication between two microcontrollers, i.e. multiprocessor communication. This feature is
enabled by setting the SM2 bit in the SCON register. The consequence is the following: when the
STOP bit is ready, indicating end of message, the serial port interrupt will be requested only in
case the bit RB8 = 1 (the 9th bit).
Suppose that there are several connected microcontrollers having to exchange data. That means
that each of them must have its address. The point is that each address sent via serial
communication has the 9th bit set (1), while data has it cleared (0). If the microcontroller A
should send data to the microcontroller C then it at will place first send address of C and the 9th
bit set to 1. That will generate interrupt and all microcontrollers will check whether they are
called.
Of course, only one of them will recognize this address and immediately clear the bit SM2 in the
SCON register. All following data will be normally received by that microcontroller and ignored
by other microcontrollers.
There are five interrupt sources for the 8051, which means that they can recognize 5 different
event that can interrupt regular program execution. Each interrupt can be enabled or disabled by
setting bits in the IE register. Also, as seen from the picture below the whole interrupt system can
be disabled by clearing bit EA from the same register.
Now, one detail should be explained which is not completely obvious but refers to external
interrupts- INT0 and INT1. Namely, if the bits IT0 and IT1 stored in the TCON register are set,
program interrupt will occur on changing logic state from 1 to 0, (only at the moment). If these
bits are cleared, the same signal will generate interrupt request and it will be continuously
executed as far as the pins are held low.
IE
Register (Interrupt Enable)
Interrupt Priorities
It is not possible to predict when an interrupt will be required. For that reason, if several
interrupts are enabled. It can easily occur that while one of them is in progress, another one is
requested. In such situation, there is a priority list making the microcontroller know whether to
continue operating or meet a new interrupt request.
Which one of these existing interrupt sources have higher and which one has lower priority is
defined in the IP Register ( Interrupt Priority Register). It is usually done at the beginning of the
program. According to that, there are several possibilities:
Once an interrupt service begins. It cannot be interrupted by another inter rupt at the same
or lower priority level, but only by a higher priority interrupt.
If two interrupt requests, at different priority levels, arrive at the same time then the
higher priority interrupt is serviced first.
If the both interrupt requests, at the same priority level, occur one after another , the one
who came later has to wait until routine being in progress ends.
If two interrupts of equal priority requests arrive at the same time then the interrupt to be
serviced is selected according to the following priority list :
The IP register bits specify the priority level of each interrupt (high or low priority).
Handling Interrupt
Once some of interrupt requests arrives, everything occurs according to the following order:
From the moment an interrupt is enabled, the microcontroller is on alert all the time. When
interrupt request arrives, the program execution is interrupted, electronics recognizes the cause
and the program “jumps” to the appropriate address (see the table above ). Usually, there is a
jump instruction already prepared subroutine prepared in advance. The subroutine is executed
which exactly the aim- to do something when something else has happened. After that, the
program continues operating from where it left off…
Reset
Reset occurs when the RS pin is supplied with a positive pulse in duration of at least 2 machine
cycles ( 24 clock cycles of crystal oscillator). After that, the microcontroller generates internal
reset signal during which all SFRs, excluding SBUF registers, Stack Pointer and ports are reset
( the state of the first two ports is indefinite while FF value is being written to the ports
configuring all pins as inputs). Depending on device purpose and environment it is in, on power-
on reset it is usually push button or circuit or both connected to the RS pin. One of the most
simple circuit providing secure reset at the moment of turning power on is shown on the picture.
Everything functions rather simply: upon the power is on, electrical condenser is being charged
for several milliseconds through resistor connected to the ground and during this process the pin
voltage supply is on. When the condenser is charged, power supply voltage is stable and the pin
keeps being connected to the ground providing normal operating in that way. If later on, during
the operation, manual reset button is pushed, the condenser is being temporarily discharged and
the microcontroller is being reset. Upon the button release, the whole process is repeated…
The microcontrollers normally operate at very high speed. The use of 12 Mhz quartz crystal
enables 1.000.000 instructions per second to be executed! In principle, there is no need for higher
operating rate. In case it is needed, it is easy to built-in crystal for high frequency. The problem
comes up when it is necessary to slow down. For example, when during testing in real operating
environment, several instructions should be executed step by step in order to check for logic state
of I/O pins.
Interrupt system applied on the 8051 microcontrollers practically stops operating and enables
instructions to be executed one at a time by pushing button. Two interrupt features enable that:
Interrupt request is ignored if an interrupt of the same priority level is being in progress.
Upon interrupt routine has been executed, a new interrupt is not executed until at least
one instruction from the main program is executed.
In order to apply this in practice, the following steps should be done:
1. External interrupt sensitive to the signal level should be enabled (for example INT0).
2. Three following instructions should be entered into the program (start from address
03hex.):
What is going on? Once the pin P3.2 is set to “0” (for example, by pushing button), the
microcontroller will interrupt program execution jump to the address 03hex, will be executed a
mini-interrupt routine consisting of 3 instructions is located at that address.
The first instruction is being executed until the push button is pressed ( logic one (1) on the pin
P3.2). The second instruction is being executed until the push button is released. Immediately
after that, the instruction RETI is executed and processor continues executing the main program.
After each executed instruction, the interrupt INT0 is generated and the whole procedure is
repeated ( push button is still pressed). Button Press = One Instruction.
Conditionally said microcontroller is the most part of its “lifetime” is inactive for some external
signal in order to takes its role in a show. It can make a great problem in case batteries are used
for power supply. In extremely cases, the only solution is to put the whole electronics to sleep in
order to reduce consumption to the minimum. A typical example of this is remote TV controller:
it can be out of use for months but when used again it takes less than a second to send a command
to TV receiver. While normally operating, the AT89S53 uses current of approximately 25mA,
which shows that it is not too sparing microcontroller. Anyway, it doesn’t have to be always like
this, it can easily switch the operation mode in order to reduce its total consumption to
approximately 40uA. Actually, there are two power-saving modes of operation: Idle and Power
Down.
Idle mode
Immediately upon instruction which sets the bit IDL in the PCON register, the microcontroller
turns off the greatest power consumer- CPU unit while peripheral units serial port, timers and
interrupt system continue operating normally consuming 6.5mA. In Idle mode, the state of all
registers and I/O ports is remains unchanged.
In order to terminate the Idle mode and make the microcontroller operate normally, it is necessary
to enable and execute any interrupt or reset.Then, the IDL bit is automatically cleared and the
program continues executing from instruction following that instruction which has set the IDL
bit. It is recommended that three first following one which set NOP instructions. They do not
perform any operation but keep the microcontroller from undesired changes on the I/O ports.
When the bit PD in the register PCON is set from within the program, the microcontroller is set to
Powerdown mode. It and turns off its internal oscillator reducing drastically consumption in that
way. In power- down mode the microcontroller can operate using only 2V power supply while the
total power consumption is less than 40uA. The only way to get the microcontroller back to
normal mode is reset.
During Power Down mode, the state of all SFR registers and I/O ports remains unchanged, and
after the microcontroller is put get into the normal mode, the content of the SFR register is lost,
but the content of internal RAM is saved. Reset signal must be long enough approximately 10mS
in order to stabilize quartz oscillator operating.
PCON register
Writing program for the microcontroller mainly consists of giving instructions (commands) in
that order in which they should be executed later in order to carry out specific task. As electronics
can not “understand” what for example instruction “if the push button is pressed- turn the light
on” means, then a certain number of more simpler and precisely defined orders that decoder can
recognise must be used. All commands are known as INSTRUCTION SET. All microcontrollers
compatibile with the 8051 have in total of 255 instructions, i.e. 255 different words available for
program writing.
At first sight, it is imposing number of odd signs that must be known by heart. However, It is not
so complicated as it looks like. Many instructions are considered to be “different”, even though
they perform the same operation, so there are only 111 truly different commands. For example:
ADD A,R0, ADD A,R1, ... ADD A,R7 are instructions that perform the same operation (additon
of the accumulator and register) but since there are 8 such registers, each instruction is counted
separately! Taking into account that all instructions perform only 53 operations ( addition,
subtraction, copy etc.) and most of them are rarely used in practice, there are actually 20-30
shortened forms needed to be known, which is acceptable.
Depending on operation they perform, all instructions are divided in several groups:
Arithmetic Instructions
Branch Instructions
Data Transfer Instructions
Logical Instructions
Logical Instructions with bits
The first part of each instruction, called MNEMONIC refers to the operation an instruction
performs (copying, addition, logical operation etc.). Mnemonics commonly are shortened form of
name of operation being executed.
For example:
Another part of instruction, called OPERAND is separated from mnemonic at least by one empty
space and defines data being processed by instructions. Some instructions have no operand, some
have one, two or three. If there is more than one operand in instruction, they are separated by
comma. For example:
Arithmetic instructions
ADD A,R1 - The result of addition (A+R1) will be stored in the accumulator.
Arithmetical Instructions
Byte Oscillator
Mnemonic Description
Number Period
ADD A,Rn Add R Register to accumulator 1 1
Add directly addressed Rx Register to
ADD A,Rx 2 2
accumulator
ADD Add indirectly addressed Register to 1 1
A,@Ri accumulator
ADD A,#X Add number X to accumulator 2 2
ADDC Add R Register with Carry bit to
1 1
A,Rn accumulator
ADDC Add directly addressed Rx Register with
2 2
A,Rx Carry bit to accumulator
ADDC Add indirectly addressed Register with
1 1
A,@Ri Carry bit to accumulator
ADDC Add number X with Carry bit to
2 2
A,#X accumulator
SUBB Subtruct R Register with borrow from
1 1
A,Rn accumulator
SUBB Subtruct directly addressed Rx Register
2 2
A,Rx with borrow from accumulator
SUBB Subtruct indirectly addressed Register with
1 1
A,@Ri borrow from accumulator
SUBB Subtruct number X with borrow from
2 2
A,#X accumulator
INC A Increment accumulator by 1 1 1
INC Rn Increment R Register by 1 1 1
Increment directly addressed Rx Register by
INC Rx 2 2
1
Increment indirectly addressed Register by
INC @Ri 1 1
1
DEC A Decrement accumulator by 1 1 1
DEC Rn Decrement R Register by 1 1 1
Decrement directly addressed Rx Register
DEC Rx 2 2
by 1
Decrement indirectly addressed Register by
DEC @Ri 1 1
1
INC DPTR Increment Data Pointer by 1 1 3
Multiply number in accumulator by B
MUL AB 1 5
register
DIV AB Divide number in accumulator by B register 1 5
Decimal adjustment of accumulator
DA A 1 1
according to BCD code
Branch Instructions
Unconditional jump instructions: after their execution a jump to a new location from where the
program continues execution is executed.
Conditional jump instructions: if some condition is met - a jump is executed. Otherwise, the
program normally proceeds with the next instruction.
Branch Instruction
Byte Oscillator
Mnemonic Description
Number Period
ACALL Call subroutine located at addreess within 2
2 3
adr11 K byte Program Memory space
LCALL Call subroutine located at any address
3 4
adr16 within 64 K byte Program Memory space
RET Return from subroutine 1 4
RETI Return from interrupt routine 1 4
AJMP Jump to address located within 2 K byte
2 3
adr11 Program Memory space
LJMP Jump to any address located within 64 K
3 4
adr16 byte Program Memory space
Short jump (from –128 to +127 locations in
SJMP rel 2 3
relation to first next instruction).
JC rel Jump if Carry bit is set. Short jump. 2 3
JNC rel Jump if Carry bit is cleared. Short jump. 2 3
JB bit,rel Jump if addressed bit is set. Short jump. 3 4
Jump if addressed bit is set and clear it.
JBC bit,rel 3 4
Short jump.
JMP Indirect jump. Jump address is obtained by
1 3
@A+DPTR addition of accumulator and DPTR Register
JZ rel Jump if accumulator is 0. Short jump. 2 3
JNZ rel Jump if accumulator is not 0. Short jump. 2 3
Compare accumulator and directly
CJNE
addressed Register Rx. Jump if they are 3 4
A,Rx,rel
different. Short jump.
CJNE Compare accumulator with number X. Jump
3 4
A,#X,rel if they are different. Short jump.
CJNE Compare Register R with number X. Jump
3 4
Rn,#X,rel if they are different. Short jump.
Compare indirectly addressed register with
CJNE
number X. Jump if they are different. Short 3 4
@Ri,#X,rel
jump.
DJNZ Decrement R Register by 1. Jump if the
2 3
Rn,rel result is not 0. Short jump.
DJNZ Decrement directly addressed Register Rx
3 4
Rx,rel by 1. Jump if the result is not 0. Short jump.
NOP No operation 1 1
Data Transfer Instructions
These instructions move the content of one register to another one. The register which
content is moved remains unchanged. If they have the suffix “X” (MOVX), the data is
exchanged with external memory.
Logical Instruction
Logical Instructions
Byte Cycle
Mnemonic Description
Number Number
Logical AND between accumulator and R
ANL A,Rn 1 1
register
Logical AND between accumulator and
ANL A,Rx 2 2
directly addressed register Rx
ANL Logical AND between accumulator and
1 1
A,@Ri indirectly addressed register
Logical AND between accumulator and
ANL A,#X 2 2
number X
Logical AND between accumulator and
ANL Rx,A 2 2
directly addressed register Rx
ANL Logical AND between directly addressed
3 3
Rx,#X register Rx and number X
Logical OR between accumulator and R
ORL A,Rn 1 1
register
Logical OR between accumulator and
ORL A,Rx 2 2
directly addressed register Rx
ORL Logical OR between accumulator and
2 2
A,@Ri indirectly addressed register
Logical OR between accumulator and
ORL Rx,A 2 2
directly addressed register Rx
ORL Logical OR between directly addressed
3 3
Rx,#X register Rx and number X
XORL Logical exclusive OR between accumulator
1 1
A,Rn and R register
XORL Logical exclusive OR between accumulator
2 2
A,Rx and directly addressed register Rx
XORL Logical exclusive OR between accumulator
1 1
A,@Ri and indirectly addressed register
XORL Logical exclusive OR between accumulator
2 2
A,#X and number X
XORL Logical exclusive OR between accumulator
2 2
Rx,A and directly addressed register Rx
Logical exclusive OR between accumulator
XORL
and directly addressed register Rx and 3 3
Rx,#X
number X
CLR A Clear accumulator 1 1
CPL A Complement accumulator (1=0, 0=1) 1 1
Swap nibbles in accumulator (left and right
SWAP A 1 1
half of one byte)
RL A Rotate bits in accumulator left by 1 place 1 1
Rotate bits in accumulator left by 1 place
RLC A 1 1
through Carry
RR A Rotate bits in accumulator right by 1 place 1 1
RRC A Rotate bits In accumulator right by 1 place 1 1
through Carry
Logical Operations on Bits
Similar to logical instructions, these instructions perform logical operations. The difference is that
these operations are performed on single bits.
The operands listed below are written in shortened forms having the following meaning :
A - accumulator
Rn - Rn is one of R registers (R0-R7) in the currently active bank in RAM.
Rx - Rx is any register in RAM with 8-bit address. It can be a general-purpose register or SFR
Register (I/O port, control register etc.)
@Ri - Ri is R0 or R1 register in the currently active bank. It contains register.
address - the instruction is referring to.
#X - X is any 8-bit number (0-255).
#X16 - X is any 16-bit number (0-65535).
adr16 - 16-bit address is specified
adr11 - 11-bit address is specified
rel - The address of a close memory location is specified (-128 do +127 rela tive to the current
one). Basing on that address,
Asembler computes the value which is added or subtructed to the number which currently stored
in the program counter.
bit - Bit address is specified.
C - Carry bit in the status register (register PSW)
EXAMPLE:
Before execution: PC=0123h
After execution: PC=0345h
A: accumulator
Rn: Any R register (R0-R7)
Description: Instruction adds the number in the accumulator and the number in register Rn (R0-
R7). After addition, the result is stored in the accumulator.
EXAMPLE:
Before execution: A=2Eh (46 dec.) R4=12h (18 dec.)
After execution: A=40h (64 dec.) R4=12h
A: accumulator
Ri: Register R0 or R1
Description: Instruction adds number in the accumulator and number in Rx. The register Rx
address is in the Ri register (R0 or R1). After addition, the result is stored in the accumulator.
EXAMPLE:
Register address: SUM = 4Fh R0=4Fh
Before execution: A= 16h (22 dec.) SUM= 33h (51 dec.)
After execution : A= 49h (73 dec.)
A: accumulator
Rx: Arbitrary register with address 0 - 255 (0 - FFh)
Description: Instruction adds the accumulator and Rx register. As it is direct addressing, Rx can
be some of SFRs or general-purpose register with address 0-7 Fh. The result is stored in the
accumulator.
EXAMPLE:
A: accumulator
Rn: any R register (R0-R7)
Description: Instruction adds the accumulator, Carry bit and value in Rn register (R0-R7). After
addition, the result is stored in the accumulator.
Syntax: ADDC A,Rn
Byte: 1 (Instruction Code)
STATUS register flags: C, OV i AC
EXAMPLE:
Before execution: A= C3h (195 dec.) R0= AAh (170 dec.) C=1
After execution: A= 6Eh (110 dec.) AC=0, C=1, OV=1
A: accumulator
X: Constant within 0 - 255 (0-FFh)
Description: Instruction adds the accumulator and number X (0-255). After addition, the result is
stored in the accumulator.
EXAMPLE:
ADDC A,Rx - Add accumulator, directly addressed register Rx and Carry bit
A: accumulator
Rx: Arbitrary register with address 0 - 255 (0 - FFh)
Description: Instruction adds value in the accumulator and Rx register including the Carry bit as
well. As it is direct addressing, Rx can be some of SFRs or general purpose register with address
0-7Fh (0-127dec.). The result is stored in the accumulator.
EXAMPLE:
Before execution: A= C3h (195 dec.) TEMP = AAh (170 dec.) C=1
After execution: A= 6Eh (110 dec.) AC=0, C=1, OV=1
ADDC A,@Ri - Add Carry bit, accumulator and indirectly addressed register Rx
A: accumulator
Ri: Register R0 or R1
Description: Instruction adds value in the accumulator and number in the Rx register. The Carry
bit is also added. Register Rx address is in the Ri register (R0 or R1). After addition, the result is
stored in the accumulator.
EXAMPLE:
Register address: SUM = 4Fh R0=4Fh
Before execution: A= C3h (195 dec.) SUM = AAh (170 dec.) C=1
After execution: A= 6Eh (110 dec.) AC=0, C=1, OV=1
A: accumulator
X: Constant within 0 - 255 (0-FFh)
Description: Instruction adds number in the accumulator and number X (0- 255). The Carry bit is
also added. After addition, the result is stored in the accumulator.
EXAMPLE:
Description : Program continues execution upon a jump to the specified address has been
executed. Similar to the ACALL instruction , this jump must be executed within the same 2K byte
block of program memory (starting from the first byte of the instruction following AJMP).
EXAMPLE:
Before execution: PC=0345h SP=07h
After execution: PC=0123h SP=09h
A: accumulator
Rn: Any R register (R0-R7)
Description: Instruction performs the logical-AND operation between the accumulator and Rn
register. The result of this logical operation is stored in the accumulator.
EXAMPLE:
ANL A,Rx - Logical-AND operation between accumulator and directly addressed register
A: accumulator
Rx: Arbitrary register with address 0 - 255 (0 - FFh)
Description: Instruction performs logical-AND operation between the accumulator and Rx
register. As it is direct addressing, Rx can be some of SFRs or general purpose register with
address 0-7Fh (o-127 dec.). The result is stored in the accumulator.
EXAMPLE:
ANL A,@Ri - Logical-AND operation between accumulator and indirectly addressed register
A: accumulator
Ri: Register R0 or R1
A: accumulator
X: Constant in the range of 0 - 255 (0-FFh)
Description: Instruction performs logical-AND operation between the accumulator and number
X. The result is stored in the accumulator.
EXAMPLE:
ANL Rx,A - Logical-AND operation between directly addressed register Rx and accumulator
EXAMPLE:
ANL Rx,#X - Logical-AND operation between number X and directly addressed register Rx
Description: Instruction performs logical-AND operation between the register Rx and number X.
As it is direct addressing, Rx can be some of SFRs or general-purpose register with address 0-7Fh
(0-127 dec.). The result of this logical operation is stored in the Rx register.
Before execution: X= C3h (11000011 Bin.) MASK= 55h (01010101 Bin.) After execution:
MASK= 41h (01000001 Bin.)
C: Carry
bit: Any bit in RAM
Description: Instruction performs logical-AND operation between the addressed bit and
Carry bit.
C AND
bit C
bit
0 0 0
0 1 0
1 0 0
1 1 1
EXAMPLE:
Before execution: ACC= 43h (01000011 Bin.)
C=1
After execution: ACC= 43h (01000011 Bin.)
C=0
ANL C,/bit - Logical-AND opertaion between complement of bit and Carry bit
C: Carry
bit: Any bit in RAM
C AND
bit bit C
bit
0 1 0 0
0 1 1 1
1 0 0 0
1 0 1 0
EXAMPLE:
Before execution: ACC= 43h (01000011 Bin.)
C=1
After execution: ACC= 43h (01000011 Bin.)
C=1
CJNE A,Rx,rel - Compare directly addessed byte with accumulator and jump if they are not equal
A: accumulator
Rx: Arbitrary register with address 0 - 255 (0 - FFh)
adr. Jump Address
Description: Instruction first compares the number in the accumulator with the number in Rx
register. If they are equal, the program continues execution. Otherwise, a jump to the indicated
address in the program will be executed. This is a short jump instruction, which means that the
address of a new location must be relatively near the current position in the program (-128 to
+127 locations relative to the first following instruction).
EXAMPLE:
Before execution: PC=0145h A=27h
After execution: if MAX≠27: PC=0123h
If MAX=27: PC=0146h
CJNE A,#X,rel - Compare number X with accumulator and jump if they are not equal
A: accumulator
X: Constant in the range of 0 - 255 (0-FFh)
Description: Instruction first compares the number in the accumulator with number X. If they are
equal, the program continues execution. Otherwise, a jump to the specified address in the
program will be executed. This is a short jump instruction, which means that the address of a new
location must be relatively near the current position in the program (-128 to +127 locations
relative to the first following instruction)
CJNE Rn,#X,rel - Compare number X with register Rn and jump if they are not equal
Description: Instruction first compares number in the Rx register with number X. If they are
equal, the program continues execution. Otherwise, a jump to the specified address in the
program will be executed. This is a short jump instruction, which means that the address of a new
location must be relatively near the current position in the program ( -128 to + 127 locations
relative to the first following instruction).
CJNE @Ri,#X,rel - Compare indirectly addressed register with number X and jump if they are
not equal
Ri: Register R0 or R1
X: Constant in the range of 0 - 255 (0-FFh)
Description: Register Rx address is stored in the Ri register (R0 or R1). This instruction first
compares the number in Rx register with number X. If they are equal, the program continues
execution. Otherwise, a jump to the indicated address in the program will be executed.This is a
short jump instruction, which means that the address of a new location must be relatively near the
current position in the program (-128 to +127 locations relative to the next instruction).
EXAMPLE:
Before execution: Register Address SUM=F3h
PC=0345h R0=F3h
After execution : If SUM≠44h: PC=0323h
If SUM=44h: PC=0346h
A: accumulator
Syntax: CLR A
Byte: 1 (Instruction Code)
STATUS register flags: No flags are affected.
EXAMPLE:
C: Carry Bit
Description: Instruction writes 0 to the Carry bit.
Syntax: CLR C
Byte: 1 (Instruction Code)
STATUS register flags: C
EXAMPLE:
EXAMPLE:
Before execution: P0.3=1 (input pin)
After execution: P0.3=0 (output pin)
A: accumulator
Syntax: CPL A
Bytes: 1 (Instruction Code)
STATUS register flags: No flags are affected.
EXAMPLE:
EXAMPLE:
C: Carry bit
Syntax: CPL C
Byte: 1 (Instruction Code)
STATUS register flags: C
EXAMPLE:
A: accumulator
Description: This instruction corrects the value after binary addition in order to fit BCD format.
Prior to addition, both numbers have to be in BCD format, which means that it is not just a simple
coversion of hexadecimal numbers into BCD numbers.The result of this operation in form of two
4-digit BCD numbers is stored in the Accumaulator.
Syntax: DA A
Byte: 1 (Instruction Code)
STATUS register flags: C
EXAMPLE:
A: accumulator
Syntax: DEC A
Byte: 1 (Instruction Code)
STATUS register flags: No flags are affected.
EXAMPLE:
EXAMPLE:
EXAMPLE:
A: accumulator
B: Register B
Description: Instruction divides value in the accumulator by the value in the B register. After
division the integer part of result is stored in the accumulator while the register contains the
remainder. In case of dividing by 1, the flag OV is set and the result of division is unpredictable.
The 8-bit quotient is stored in the accumulator and the 8-bit remainder is stored in the B register.
Syntax: DIV AB
Byte: 1 (Instruction Code)
STATUS register flags: C, OV
EXAMPLE:
Ri: Register R0 or R1
EXAMPLE:
Description: This instruction first decrements value in the register. If the result is 0, the program
continues execution. Otherwise, a jump to the specified address in the program will be executed.
As it is direct addressing, Rx must be within the first 255 locations in RAM. This is a short jump
instruction, which means that the address of a new location must be relatively near the current
position in the program ( -128 to +127 locations relative to the first following instruction).
Syntax: DJNZ Rx,[jump address]
Bytes: 3 (Instruction Code, Address Rx, Jump Value)
STATUS register flags: No flags are affected.
EXAMPLE:
Description: This instruction first decrements value in the Rn register. If the result is 0, the
program continues execution. Otherwise, a jump to the specified address in the program will be
executed. This is a short jump instruction, which means that the address of a new location must
be realtively near the current position in the program (- 128 to +127 locations relative to the first
following instruction).
EXAMPLE:
Before execution: PC=0445h
After execution: If R1≠0: PC=0423h
If R1=0: PC=0446h
Description: This instruction increments value in the Rn register by 1. If the register includes the
number 255, the result of the operation will be 0.
Syntax: INC Rn
Byte: 1 (Instruction Code)
STATUS register flags: No flags are affected.
EXAMPLE:
Syntax: INC A
Byte: 1 (Instruction Code)
STATUS register flags: No flags are affected.
EXAMPLE:
Ri: Register R0 or R1
EXAMPLE:
Syntax: INC Rx
Bytes: 2 (Instruction Code, Address Rx)
STATUS register flags: No flags are affected.
EXAMPLE:
Description: If the bit is set, a jump to the specified address will be executed. Otherwise, if the
value of bit is 0, the program proceeds with the next instruction. This is a short jump instruction,
which means that the address of a new location must be relatively near the current position in the
program (-128 to + 127 locations relative to the first following instruction).
EXAMPLE:
Description: This instruction increments value of the 16-bit data pointer by 1. This is a single 16-
bit register on which this operation can be performed.
EXAMPLE:
Description: This instruction first check if the Carry bit is set. If it is set, a jump to the indicated
address is executed. Otherwise, the program proceeds with the next instruction. This is a short
jump instruction, which means that the address of a new location must be relatively near the
current position in the program (-129 to + 127 locations relative to the first following instruction).
EXAMPLE:
Description: This instruction first checks if the bit is set. If it is set, a jump to the specified
address is executed and afterwards the bit is cleared. Otherwise, the program proceeds with the
first next instruction. This is a short jump instruction, which means that the address of a new
location must be relatively near the current position in the program (-129 to + 127 locations
relative to the first following instruction).
EXAMPLE:
Description: If the bit is cleared, a jump to the specified address will be executed. Otherwise, if
the bit value is 1, the program proceeds with the first next instruction. This is a short jump
instruction, which means that the address of a new location must be relatively near the current
position in the program (-129 to + 127 locations relative to the first following instruction).
EXAMPLE:
Before execution: PC=0323h
After execution: If P0.5=1: PC=0324h
If P0.5=0: PC=0345h
A: accumulator
DPTR: Data Pointer
Description: This instruction causes a jump to address which is calculated by adding value in the
accumulator and 16-bit number in the DPTR Register. It is used with complex program branching
where the accumulator affects jump address, for example when reading table. Neither
accumulator nor DPTR register are affected.
EXAMPLE:
Note:
As instructions AJMP LABELS occupy two locations each, the values in the accumulator
indicating them must be mutually different from each other by 2.
Description: This instruction checks if value in the accumulator is 0. If it is not 0, a jump to the
specified address will be executed. Otherwise, the program proceeds with the first next
instruction. This is a short jump instruction, which means that the address of a new location must
be relatively near the current position in the program (-129 to + 127 locations relative to the first
following instruction).
EXAMPLE:
Description: This instruction first checks if the bit is set. If it is not set, a jump to the specified
address will be executed. Otherwise, the program proceeds with the first next instruction.This is a
short jump instruction, which means that the address of a new location must be relatively near the
current position in the program (-129 to + 127 locations relative to the first following instruction).
EXAMPLE:
Description: This instruction unconditionally calls a subroutine located at the specified address.
The current address and the start of the called subroutine can be located anywhere within the
memory space of 64K.
EXAMPLE:
Description: The instruction checks if the value in the accumulator is 0. If it is 0, a jump to the
specified address will be executed. Otherwise, the program proceeds with the next
instruction.This is a short jump instruction, which means that the address of a new location must
be relatively near the current position in the program (-129 to + 127 locations relative to the first
following instruction).
EXAMPLE:
Before execution: PC=0323h
After execution: If A0: PC=324h
If A=0: PC=283h
Description: The instruction moves the Rn register to the accumulator. The Rn register is not
affected.
EXAMPLE:
EXAMPLE:
Description: Instruction moves the Rx register to the accumulator. Rx register address is stored
in the Ri register (R0 or R1). After instruction execution, the result is stored in the accumulator.
The Rx Register is not affected.
EXAMPLE:
EXAMPLE:
Desription: Instruction moves the accumulator to Rn register. The accumulator is not affected.
EXAMPLE:
A: accumulator
X: Constant in the range of 0 - 255 (0-FFh)
EXAMPLE:
EXAMPLE:
EXAMPLE:
EXAMPLE:
EXAMPLE:
Description: Instruction moves the Ry register to Rx register. Ry register address is stored in the
Ri register (R0 or R1). The Ry register is not affected .
Syntax: MOV Rx,@Ri
Bytes: 2 (Instruction Code, Address Rx)
STATUS register flags: No flags are affected.
EXAMPLE:
EXAMPLE:
A: accumulator
Ri: Register R0 or R1
Description: Instruction moves the accumulator to the Rx register. The Rx register address is
stored in the Ri register (R0 or R1). After instruction execution, the accumulator is not affected.
Syntax: MOV @Ri,A
Byte: 1 (Instruction Code)
STATUS register flags: No flags are affected.
EXAMPLE:
EXAMPLE:
Ri: Register R0 or R1
X: Constant in the range of 0 - 255 (0-FFh)
Description: Instruction moves number X to the idirectly addressed register Rx. The Register Rx
address is stored in the Ri register ( R0 or R1).
Syntax: MOV @Ri,#X
Bytes: 2 (Instruction Code, Constant X)
STATUS register flags: No flags are affected.
EXAMPLE:
Description: Instruction moves the Rx register to Ry register. The register Ry address is stored in
the Ri register ( R0 or R1). After instruction execution, the Rx register is not affected.
EXAMPLE:
C: Carry bit
bit: Any bit in RAM
Description: Instruction moves the value of the Carry bit to the specified bit. After this operation,
the Carry bit is not affected.
Syntax: MOV bit,C
Bytes: 2 (Instruction Code, Address bit)
STATUS register flags: No flags are affected.
EXAMPLE:
C: Carry bit
bit: Any bit in RAM
Description: Instruction moves value of the specified bit to the Carry bit. After this operation, the
bit is not affected.
EXAMPLE:
MOVC A,@A+DPTR - Move relatively addressed byte from program memory to accumulator
A: accumulator
DPTR: Data Pointer
Description: Instruction first adds the 16-bit DPTR Register and the accumulator. The result of
addition is afterwards used as address in the program memory indicating from which the 8-bit
content is moved to the accumulator.
Syntax: MOVC A,@A+DPTR
Byte: 1 (Instruction Code)
STATUS register flags: No flags affected.
EXAMPLE:
Before execution :
DPTR=1000:
A=0
A=1
A=2
A=3
After execution:
A=66h
A=77h
A=88h
A=99h
Description: Instruction writes 16-bit number into the DPTR register. The 8 high bits of this
number are stored in the DPH register while the 8 low bits are stored in the DPL register.
Ri: Register R0 or R1
A: accumulator
Description: Instruction reads the content of the Rx register in external RAM and moves it to the
accumulator. The register Rx address is stored in the Ri register (R0 or R1).
EXAMPLE:
Note:
SUMA Register is stored in external RAM in size of 256 bytes.
MOVC A,@A+PC - Move relatively addressed byte from program memory to accumulator
A: accumulator
PC: Program Counter
Description: Instruction first adds the 16-bit PC register with the content of the accumulator (the
current address in the program is stored in the PC register). The result of addition is afterwards
used as address in the program memory from which the 8-bit content is moved to the
accumulator.
EXAMPLE:
After the subroutine "Tabela" has been executed, one of four values is stored in the accumulator:
Before execution:
A=0
A=1
A=2
A=3
After execution:
A=66h
A=77h
A=88h
A=99h
MOVX @Ri,A - Write the content of accumulator into byte of external memory (8-bit address)
Ri: Register R0 or R1
A: accumulator
Description: Instruction reads the content of the accumulator and moves it to the Rx register
which is stored in external RAM. The Rx register address is located in the Ri register.
Syntax: MOVX @Ri,A
Byte: 1 (Instruction Code)
STATUS register flags: No flags affected.
EXAMPLE:
NOTE:
Register SUM is located in external RAM in size of 256 byte.
MOVX A,@DPTR - Write the content of accumulator into byte of external memory (8-bit
address)
A: accumulator
DPRTR: Data Pointer
Description: Instruction reads the content of the Rx register in external memory and moves it to
the accumulator. The 16-bit address of the Rx register is stored in the DPTR register (DPH and
DPL).
EXAMPLE:
Note:
Register SUM is located in external RAM in size of up to 64K.
MUL AB - Multiply value in accumulator with value in B register
A: accumulator
B: Register B
Description: Instruction multiplies the value in the accumulator with the value in the B register .
The low-order byte of the 16-bit result is stored in the accumulator , and the high byte is left in
the B register. If the result is greater than 255, the overflow flag is set. The Carry bit (C flag) is
not affected.
Syntax: MUL AB
Byte: 1 (Instruction Code)
STATUS register flags: No flags affected.
EXAMPLE:
MOVX @DPTR,A - Write value in accumulator to byte of external memory (16-bit address)
A: accumulator
DPTR: Data Pointer
Description: Instruction reads value in the accumulator and moves it to the Rx register which is
stored in external RAM. 16-bit address of the Rx register is stored in the DPTR register (DPH
and DPL).
EXAMPLE:
Register address SUM=1234h
Before execution: A=58 DPTR=1234h
After execution: SUM=58h
Note:
Register SUM is located in RAM in size of up to 64K.
Description: Instruction performs logical-OR operation between the accumulator and Rn register.
The result of this logical operation is stored in the accumulator.
EXAMPLE:
NOP - No operation
Description: Instruction doesn’t perform any operation and is used when additional time delays
are needed.
Syntax: NOP
Byte: 1 (Instruction Code)
STATUS register flags: No flags affected.
EXAMPLE:
Sequence like this one provides on the P2.3 a negative pulse which lasts exactly 5 machine
cycles. If a 12 MHz quartz crystal is used then 1 cycle lasts 1uS, which means that this output
will be a low-going output pulse for 5 uS.
ORL A,@Ri - Logical-OR operation between accumulator and indirectly addressed register
Ri: Register R0 or R1
A: accumulator
Description: Instruction performs logical-OR operation between the accumulator and Rx register.
As it is indirect addressing, register Rx address is stored in the Ri register ( R0 or R1). The result
of this logical operation is stored in the accumulator.
EXAMPLE:
Description: Instruction performs logical-OR operation between the accumulator and Rx register.
As it is direct addressing, Rx can be some of SFRs or general-purpose register with address 0-7Fh
(0-127 dec.). The result of this logical operation is stored in the accumulator.
Syntax: ORL A,Rx
Bytes: 2 (Instruction Code, Address Rx)
STATUS register flags: No flags affected.
EXAMPLE:
ORL Rx,A - Logical-OR operation between directly addressed register Rx and accumulator
Description: Instruction performs logical-OR operation between the Rx register and accumulator.
As it is direct addressing, the Rx register can be some of SFRs or general- purpose register with
address 0-7Fh (0-127 dec.) . The result of this logical operation is stored in the Rx register.
EXAMPLE:
Syntax: ORL A, #X
Bytes: 2 (Instruction Code, Constant X)
STATUS register flags: No flags affected.
EXAMPLE:
C: Carry bit
bit: Any bit in RAM
Description: Instruction performs logical-OR operation (logical OR) between the addressed bit
and Carry bit. The result is stored in the Carry bit.
EXAMPLE:
ORL Rx,#X - Logical-OR operation between directly addressed register Rx and number X
EXAMPLE:
Description: Instruction first reads data from the location the Stack Pointer is currently ponting
to. Afterwards, the data is copied to the register Rx and the value of the Stack Pointer is
decremented by 1. As it is direct addressing, Rx can be some of SFRs or general-purpose register
with address 0-7Fh. (0-127 dec.)
Syntax: POP Rx
Bytes: 2 (Instruction Code, Address Rx)
STATUS register flags: No flags affected.
EXAMPLE:
ORL C,/bit - Logical-OR operation between complement bit and Carry bit
C: Carry bit
bit: Any bit in RAM
C AND
bit bit C
bit
0 1 0 0
0 1 1 1
1 0 0 0
1 0 1 0
EXAMPLE:
Description: This instruction ends every subroutine. After execution, the program proceeds with
the instruction currently following an ACALL or LCALL.
Syntax: RET
Byte: 1 (Instruction Code)
STATUS register flags: No flags affected.
EXAMPLE:
Description: Address currently pointed to by the Stack Pointer is first incremented by 1 and
afterwards the data from the register Rx are copied to it. As it is direct addressing, Rx can be
some of SFRs or general-purpose register with address 0-7Fh. (0-127 dec.)
Syntax: PUSH Rx
Bytes: 2 (Instruction Code, Address Rx)
STATUS register flags: No flags affected.
EXAMPLE:
A: accumulator
Description: Eight bits in the accumulator are rotated one bit left, so that the bit 7 is rotated into
the bit 0 position.
Syntax: RL A
Byte: 1 (Instruction Code)
STATUS register flags: No flags affected.
EXAMPLE:
Description: This instruction ends every interrupt routine and informs processor that interrupt
routine is no longer in progress. After instruction execution, the execution of the interrupted
program continues from where it left off. The PSW is not autotomatically restored to its pre-
interrupt status.
Syntax: RETI
Byte: 1 (Instruction Code)
STATUS register flags: No flags affected.
A: accumulator
Description: All eight bits in the accumulator are rotaded one bit right so that the bit 0 is rotated
into the bit 7 position.
Syntax: RR A
Byte: 1 (Instruction Code)
STATUS register flags: No flags affected.
EXAMPLE:
A: accumulator
Description: All eight bits in the accumulator and Carry bit are rotated one bit left. After this
operation, the bit 7 is rotated into the Carry bit position and the Carry bit is rotated into the bit 0
position.
Syntax: RLC A
Byte: 1 (Instruction Code)
STATUS register flags: C
EXAMPLE:
C: Carry bit
Syntax: SETB C
Byte: 1 (Instruction Code)
STATUS register flags: C
EXAMPLE:
A: accumulator
Description: All eight bits in the accumulator and Carry bit are rotated one bit right. After this
operation, the Carry bit is rotated into the bit 7 position and the bit 0 is rotated into the Carry
position.
Syntax: RRC A
Byte: 1 (Instruction Code)
STATUS register flags: C
EXAMPLE:
Before execution: A= C2h (11000010 Bin.)
C=0
After execution: A= 61h (01100001 Bin.)
C=0
Description: Instruction enables jump to the new address that address should be in the range of
-128 to +127 locations relative to the first following instruction.
EXAMPLE:
Description: Instruction sets the specified bit. The register including that bit must belong to the
group of so called bit addressable registers.
Syntax: SETB [bit address]
Bytes: 2 (Instruction Code, Bit Address)
STATUS register flags: No flags are affected.
EXAMPLE:
Description: Instruction performs subtract operation: A-Rx including the Carry bit as well which
acts as borrow. If the higher bit is subtracted from the lower bit then the Carry bit is set. As it is
direct addressing, Rx can be some of SFRs or general-purpose register with address 0-7Fh. (0-
127 dec.). The result is stored in the accumulator.
EXAMPLE:
EXAMPLE:
Note:
The result is different (C9 - 54=75!) because the Carry bit has been set (C=1)before instruction
execution.
A: accumulator
X: Constant in the range of 0 - 255 (0-FFh)
Description: Instruction performs subtract operation: A-X including the Carry bit as well which
acts as borrow. If the higher bit is subtracted from the lower bit then the Carry bit is set. The
result is stored in the accumulator.
EXAMPLE:
Ri: Register R0 or R1
A: accumulator
Description: Instruction performs subtract operation: A-Rx including the Carry bit as well which
acts as borrow. If the higher bit is subtracted from the lower bit then the Carry bit is set. As it is
indirect addressing, register Rx address is located in the Ri register (R0 or R1) . The result of the
operation is stored in the accumulator.
EXAMPLE:
Description: Instruction causes the accumulator and Rn registers to exchange data. The content
of the accumulator is set in the register Rn. At the same time, the content of the Rn register is set
in the accumulator.
Syntax: XCH A,Rn
Byte: 1 (Instruction Code)
STATUS register flags: No flags are affected.
EXAMPLE:
A: accumulator
Description: A word “nibble” designates a group of 4 adjacent bits within one register (bit0-bit3
and bit4-bit7).This instruction interchanges the high and low nibbles of the accumulator.
Syntax: SWAP A
Byte: 1 (Instruction Code)
STATUS register flags: No flags are affected.
EXAMPLE:
Ri: Register R0 or R1
A: accumulator
Description: Instruction sets the contents of accumulator into register Rx. At the same time, the
content of register Rx is set into the accumulator. As it is indirect addressing, register Rx address
is located in the register Ri (R0 or R1).
XCH A,Rx - Exchange the content of registers Rx with the content of accumulator
Description: Instruction sets the contents of the accumulator into the register Rx. At the same
time, the content of the Rx register is set into the accumulator. As it is direct addressing, the
register Rx can be some of SFRs or general-purpose register with address 0-7Fh (0-127 dec.).
EXAMPLE:
XCHD A,@Ri - Exchange the content of low nibbles accumulator with indirectly addressed
register Rx
Ri: Register R0 or R1
A: accumulator
Description: This instruction interchanges the low nibbles (bits 0-3) of the accumulator with the
low nibbles of indirectly addressed register Rx. High nibbles of the accumulator and Rx register
are not affected. This instruction is mainly used in operating with BCD values. As it is indirect
addressing, the regiter Rx address is stored in the register Ri (R0 or R1).
EXAMPLE:
XRL A,@Ri - Exclusive-OR operation between accumulator and indirectly addressed register
Ri: Register R0 or R1
A: accumulator
EXAMPLE:
EXAMPLE:
Before execution: A= C2h (11000010 Bin.)
LOG= 54h (01010100 Bin.)
After execution: A= 96h (10010110 Bin.)
XRL Rx,A - Exclusive-OR operation between directly addressed register Rx and accumulator
EXAMPLE:
Description: Instruction performs exclusive-OR operation between the accumulator and number
X. The result of this logical operation is stored in the accumulator.
EXAMPLE:
Before execution: A= C2h (11000010 Bin.)
X= 11h (00010001 Bin.)
After execution: A= D3h (11010011 Bin.)
XRL Rx,# - Exclusive-OR operation between directly addressed register Rx and number X
Description: Instruction performs exclusive-OR operation between the Rx Register and number
X. As it is direct addressing, the Rx register can be some of SFRs or general-purpose register with
address 0-7Fh (0-127 dec.). The result of this logical operation is stored in the Rx register.
EXAMPLE:
Chapter 4 : Examples
Chapter 6 : Examples
6.1 Basic connecting of the microcontroller
6.2 Additional components
6.3 Examples
Introduction
The purpose of this chapter is to inform you about basic issues on microcontrollers that
one should know in order to use them successfully in practice. That is why you will not
find here some ultra interesting program or device scheme with amazing solutions.
Instead of that, examples described in this chapter are more proof that program writing is
neither privilege nor talent issue but ability of simple putting puzzle pieces together using
directives. Device development mainly comes to the method “test-correct-repeat”. Of
course, the more you are into it, the issues become more complicated as the puzzle pieces
are put together by both children and first-class architects...
Power supply
Reset signal
Clock signal
Obviously, all this is about very simple circuits, but it does not have to be always like
that. If device is used for handling expensive machines or for maintaining vital functions,
everything becomes more and more complicated! This kind of solution is quite enough
for the time being...
Power supply
Although this circuit can operate with different power supply voltage, why to test
“Marphy’s low”?! Voltage of 5V is so common that it imposes itself. The circuit, shown
on the figure, uses cheap voltage stabilisator LM7805 and provides high-quality voltage
level and guite enough current to enable microcontroller and “peripheral electronics” to
operate ( sufficient current in this case amounts to 1A)!
Reset signal
In order to operate properly, the microcontroller must “see” logic 0 (0V) on reset pin RS
(It explains connection pin-resistor 10K-ground). Pushbutton which connects reset pin
RS to power supply VCC is not necessary but it is almost always built in because it
enables microcontroller safe return to normal operating conditions when the things go
wrong. By activating this pin, 5V is brought to it, the microcontroller is reset and
program starts execution from the beginning.
Clock signal
Although the microcontroller has built in oscillator, it cannot operate without two
external condensators and quartz crystal which stabilize its frequency (microcontroller’s
operating speed).
Regardless of the fact that microcontrollers are the product of modern technology, they
are not so useful without being connected to additional components. Simply, the
appearance of voltage on its pin means nothing if it does not perform certain operations
(turn on/off, shift, display and similar).
There is nothing simpler than this! This is the simplest way of controlling appearance of
some voltage on microcontroller’s input pin. There is also no need for additional
explanation of how these components operate.
Nevertheless, it is not so simple in practice... This is about something commonly
unnoticeable when using these components in everyday life. It is about contact bounce- a
common problem with m e c h a n i c a l switches. If contact switching does not happen
so quickly, several consecutive bounces can be noticed prior to maintain stable state. The
reasons for this are: vibrations, slight rough spots and dirt. Anyway, whole this process
does not last long (a few micro- or miliseconds), but long enough to be registered by the
microcontroller. Concerning pulse counter, error occurs in almost 100% of cases!
The simplest solution is to connect simple RC circuit which will “suppress” each quick
voltage change. Since the bouncing time is not defined, the values of elements are not
strictly determined. In the most cases, the values shown on figure are sufficient.
If complete safety is needed, radical measures should be taken! The circuit, shown on the
figure (RS flip-flop), changes logic state on its output with the first pulse triggered by
contact bounce. Even though this is more expensive solution (SPDT switch), the problem
is definitely resolved! Besides, since the condensator is not used, very short pulses can be
also registered in this way.
In addition to these hardware solutions, a simple software solution is commonly applied
too: when a program tests the state of some input pin and finds changes, the check should
be done one more time after certain time delay. If the change is confirmed it means that
switch (or pushbutton) has changed its position. The advantages of such solution are
obvious: it is free of charge, effects of disturbances are eliminated too and it can be
adjusted to the worst-quality contacts. Disadvantage is the same as in case of using RC
filter-pulses shorter than program delay cannot be registered.
Optocouplers
Relays
Relays are elements connected to ouput pins of the microcontroller and used to turn
on/off all that being out of board which has sensitive components: motors,
transformators, heaters, bulbs, high-voltage components, antenna systems etc. There are
various types of relays but all have the same operating principle: when a current flows
through the coil, it makes or brakes machanical connection between one or more pairs of
contacts. As it is case with optocouplers, there is no galvanically connection (electrical
contact) between input and output circuits. Relays usually demand both higher voltage
and current to start operating but there are also miniature versions which can be activated
with a low current directly obtained from the microcontroller’s pin.
Below figure presents one solution specific to the 8051 microcontrollers. In this very
case, darlington transistor is used to activate relays because of its high current gain. This
is not in accordance with “rules”, but it is necessary in case of logic one activation since
the current is then very low (pin acts as input)!
In order to be prevented from appearance of high voltage of self-induction caused by a
sudden stop of 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.
Light-emitting diodes are elements for light signalization in electronics. They are
manufactured in different shapes, colors and sizes. For their low price, low consumption
and simple use, they have almost completely pushed aside other light sources- bulbs at
first place. They perform similar to common diodes with the difference that they emit
light when current flows through them.
It is important to know that each diode will be immediately destroyed unless its current is
limited. This means that a conductor must be connected in parallel to a diode. In order to
correctly determine value of this conductor, it is necessary to know diode’s voltage drop
in forward direction, which depends on what material a diode is made of and what colour
it is. Values typical for the most frequently used diodes are shown in table below: As
seen, there are three main types of LEDs. Standard ones get ful brightness at current of
20mA. Low Current diodes get ful brightness at ten times lower current while Super
Bright diodes produce more intensive light than Standard ones.
Typical Maximal
Voltage
Color Type current Id current If
drop Ud (V)
(mA) (mA)
Infrared - 30 50 1.4
Red Standard 20 30 1.7
Red Super Bright 20 30 1.85
Red Low Current 2 30 1.7
Orange - 10 30 2.0
Green Low Current 2 20 2.1
Yellow - 20 30 2.1
Blue - 20 30 4.5
White - 25 35 4.4
Since the 8051 microcontrollers can provide only low input current and since their pins
are configured as outputs when voltage level on them is equal to 0, direct connectining to
LEDs is carried out as it is shown on figure (Low current LED, cathode is connected to
output pin).
LED displays
Basically, LED displays are nothing else but several LEDs moulded in the same plastic
case. Diodes are arranged so that different marks-commonly digits: 0, 1, 2,...9 are
displayed by activating them. There are many types of displays composed of several
dozens of built in diodes which can display different symbols.
The most commonly used are so called 7-segment displays. They are composed of 8
LEDs, 7 segments are arranged as a rectangle for symbol displaying and there is
additional segment for decimal point displaying. In order to simplify connecting, anodes
and catodes of all diodes are connected to the common pin so that there are common
cathode displays and common anode displays. Segments are marked with the latters Ato
G as shown on the figure on the left. When connecting, each diode is treated
independently, which means that each must have its own conductor for current limitation.
When connecting displays to the microcontroller, the greatest problem is a great deal of
valuable I/O pins which they “occupy”, especially if it is needed to display several-digit
numbers. Problem is more than obvious if for example it is needed to display two 6-digit
numbers (a simple calculation shows that 96 output pins are needed)!The solution on this
problem is called MULTIPLEXING. This is how optical illusion based on the same
operating principle as filmcamera occurs. The principle is that only one digit is active but
by quick changing one gets impression that all digits of a number are active at the same
time.
Referring to the previous example it would mean that firstly one byte representing units is
applied on a microcontroller’s port and only transistor T1 is activated at the same time.
After a while, the transistor T1 is turned off, a byte representing tens is applied on a port
and transistor T2 is activated. This process is being cyclicly repeated at high speed for all
digits and corresponding transistors.
When displaying any digit, a defeating fact that microcontroller is nevertheless only a
machine made to understand only language of units and zeros is fully expressed. Namely,
it “does not know” what units, tens or hundreds are, nor it knows how ten digits we are
used to look like. Therefore, each number intended to be shown on display must be
prepared in the following way:
In special subroutine, a several digit number must be first separated in units, tens etc.
Afterwards, each of these digits must be stored in specific byte. In order to make these
digits familiar to us, “masking” is carried out. Basically, it is a simple subroutine by
which binary format of each number is replaced by different combination of bits. For
example, the digit 8 (0000 1000) is replaced by binary digit 0111 111 in order to activate
all LEDs which represent digit 8 on display. The only diode, inactive in this case is
reserved for decimal point. If a microcontroller’s port is connected to display in a way
that bit 0 activates segment “a”, bit 1 activates segment “b”, bit 2 segment “c” etc., the
table below shows “mask” for each digit.
Digits to
Display Segments
display
dp a b c d e f g
0 1 0 0 0 0 0 0 1
1 1 0 0 1 1 1 1 1
2 1 0 0 1 0 0 1 0
3 1 0 0 0 0 1 1 0
4 1 1 0 0 1 1 0 0
5 1 0 1 0 0 1 0 0
6 1 0 1 0 0 0 0 0
7 1 0 0 0 1 1 1 1
8 1 0 0 0 0 0 0 0
9 1 0 0 0 0 1 0 0
These components are “specialized” for being used with the microcontrollers, which
means that they cannot be activated by standard IC circuits. They are used for writing
different messages on a miniature LCD.
Amodel described here is for its low price and great possibilities most frequently used in
practice. It is based on the HD44780 microcontroller (Hitachi) and can display messages
in two lines with 16 characters each . It displays all letters of alphabet, greek letters,
punctuation marks, mathematical symbols etc. In addition, it is possible to display
symbols that user makes up on its own. Automatic shifting message on display (shift left
and right), appearance of the pointer, backlight etc. are considered as useful
characteristics.
Pins Functions
There are pins along one side of the small printed board used for connection to the
microcontroller. There are total of 14 pins marked with numbers (16 in case the
background light is built in). Their function is described in the table bellow:
Pin Logic
Function Name Description
Number State
Ground 1 Vss - 0V
Power
2 Vdd - +5V
supply
Contrast 3 Vee - 0 - Vdd
D0 – D7 are interpreted as
0 commands
4 RS
1 D0 – D7 are interpreted as
data
Write data (from
Control of 0 controller to LCD)
5 R/W
operating 1 Read data (from LCD to
controller)
0 Access to LCD disabled
1 Normal operating
6 E
From 1 Data/commands are
to 0 transferred to LCD
7 D0 0/1 Bit 0 LSB
8 D1 0/1 Bit 1
9 D2 0/1 Bit 2
Data / 10 D3 0/1 Bit 3
commands 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
LCD screen consists of two lines with 16 characters each. Each character consists of 5x8
or 5x11 dot matrix. This book covers 5x8 character display because it is commonly used.
Contrast on display depends on the power supply voltage and whether messages are
displayed in one or two lines. For that reason, variable voltage 0-Vdd is applied on pin
marked as Vee. Trimmer potentiometer is usually used for that purpose. Some versions of
displays have built in backlight (blue or green diodes). When used during operating, a
resistor for current limitation should be used (like with any LE diode).
If there are no characters on display or all of them are dimmed upon the display is on, the
first thing that should be done is to check the potentiometer for contrast regulation. Is it
properly adjusted? Same applies in case the operation mode is changed (writing in one or
two lines).
LCD Basic Commands
All data transferred to LCD through outputs D0-D7 will be interpreted as commands or
as data, which depends on logic state on pin RS:
LCD Connection
Depending on how many lines are used for connection to the microcontroller, there are 8-
bit and 4-bit LCD modes. The appropriate mode is determined at the beginning of the
process in a phase called “initialization”. In the first case, the data are transferred through
outputs D0-D7 as it has been already explained. In case of 4-bit LED mode, for the sake
of saving valuable I/O pins of the microcontroller, there are only 4 higher bits (D4-D7)
used for communication, while other may be left unconnected. Consequently, each data is
sent to LCD in two steps: four higher bits are sent first (that normally would be sent
through lines D4-D7), four lower bits are sent afterwards. With the help of initialization,
LCD will correctly connect and interprete each data received. Besides, with regards to the
fact that data are rarely read from LCD (data mainly are transferred from microcontroller
to LCD) one more I/O pin may be saved by simpleconnecting R/W pin to the Ground.
Such saving has its price. Even though message displaying will be normally performed, it
will not be possible to read from busy flag since it is not possible to read from display.
Luckily, solution is simple. It is sufficient to give LCD enough time to perform its task
upon sending every character or command. Since execution of the slowest command is
approximately 1.64mS, it will be quite enough to wait for approximately 2mS.
LCD Initialization
Once the power supply is turned on, LCD is automatically cleared. This process lasts for
approximately 15mS. After that, display is ready to operate. The mode of operating is set
by default. This means that:
1. Display is cleared
2. Mode
o DL = 1 Communication through 8-bit interface
o N = 0 Messages are displayed in one line
o F = 0 Character font 5 x 8 dots
3. Display/Cursor on/off
o D = 0 Display off
o U = 0 Cursor off
o B = 0 Cursor blink off
4. Character entry
o ID = 1 Addresses on display are automatically incremented by 1
o S = 0 Display shift off
Automatic reset is mainly performed without any problems. Mainly but not always! If for
any reason power supply voltage does not reach ful value in the course of 10mS, display
will start perform completely unpredictably. If voltage supply unit can not meet this
condition or if it is needed to provide completely safe operating, the process of
initialization by which a new reset enabling display to operate normally must be applied.