Architecture and Programming of 8051 MCU's For Reverse Engineering
Architecture and Programming of 8051 MCU's For Reverse Engineering
Introduction
It was electricity in the beginning....The people were happy because they did not know that it was all
around them and could be utilized. That was good. Then Faraday came and a stone has started to roll
slowly...
The first machines using a new sort of energy appeared soon. A long time has passed since then and just
when the people finally got used to them and stopped paying attention to what a new generation of
specialists were doing, someone came to an idea that electrons could be a very convenient toy being
closed in a glass pipe. It was just a good idea at first, but there was no return. Electonics was born and the
stone kept on rolling down the hill faster and faster...
A new science - new specialists. Blue coats were replaced with white ones and people who knew
something about electronics appeared on the stage. While the rest of humanity were passively watching in
disbelief what was going on, the plotters split in two groups - software-oriented and hardwareoriented. Somewhat younger than their teachers, very enthusiastic and full of ideas, both of them kept on
working but separate ways. While the first group was developing constantly and gradually, the hardwareoriented people, driven by success, threw caution to the wind and invented transistors.
Up till that moment, the things could be more or less kept under control, but a broad publicity was not
aware of what was going on, which soon led to a fatal mistake! Being naive in belief that cheap tricks
could slow down technology development and development of the world and retrieve the good all days,
mass market opened its doors for the products of Electronics Industry, thus closing a magic circle. A rapid
drop in prices made these components available for a great variety of people. The stone was falling
freely...
The first integrated circuits and processors appeared soon, which caused computers and other products of
electronics to drop down in price even more. They could be bought everywhere. Another circle was
closed! Ordinary people got hold of computers and computer era has begun...
While this drama was going on, hobbyists and professionals, also split in two groups and protected by
anonymity, were working hard on their projects. Then, someone suddenly put a question: Why should not
we make a universal component? A cheap, universal integrated circuit that could be programmed and
used in any field of electronics, device or wherever needed? Technology has been developed enough as
well as the market. Why not? So it happened, body and spirit were united and the first integrated circuit
was designed and called the MICROCONTROLLER.
1.1 What are microcontrollers and what are they used for?
Like all good things, this powerful component is basically very simple. It is made by mixing tested and
high- quality "ingredients" (components) as per following receipt:
1. The simplest computer processor is used as the "brain" of the future system.
2. Depending on the taste of the manufacturer, a bit of memory, a few A/D converters, timers,
input/output lines etc. are added
3. All that is placed in some of the standard packages.
4. A simple software able to control it all and which everyone can easily learn about has been
developed.
On the basis of these rules, numerous types of microcontrollers were designed and they quickly became
man's invisible companion. Their incredible simplicity and flexibility conquered us a long time ago and if
you try to invent something about them, you should know that you are probably late, someone before you
has either done it or at least has tried to do it.
The following things have had a crucial influence on development and success of the microcontrollers:
Powerful and carefully chosen electronics embedded in the microcontrollers can independetly or
via input/output devices (switches, push buttons, sensors, LCD displays, relays etc.), control
various processes and devices such as industrial automation, electric current, temperature, engine
performance etc.
Very low prices enable them to be embedded in such devices in which, until recent time it was not
worthwhile to embed anything. Thanks to that, the world is overwhelmed today with cheap
automatic devices and various smart appliences.
Prior knowledge is hardly needed for programming. It is sufficient to have a PC (software in use is
not demanding at all and is easy to learn) and a simple device (called the programmer) used for
loading raedy-to-use programs into the microcontroller.
So, if you are infected with a virus called electronics, there is nothing left for you to do but to learn how to
use and control its power.
How does the microcontroller operate?
Even though there is a large number of different types of microcontrollers and even more programs
created for their use only, all of them have many things in common. Thus, if you learn to handle one of
them you will be able to handle them all. A typical scenario on the basis of which it all functions is as
follows:
1. Power supply is turned off and everything is stillthe program is loaded into the microcontroller,
nothing indicates what is about to come
2. Power supply is turned on and everything starts to happen at high speed! The control logic unit
keeps everything under control. It disables all other circuits except quartz crystal to operate. While
the preparations are in progress, the first milliseconds go by.
3. Power supply voltage reaches its maximum and oscillator frequency becomes stable. SFRs are
being filled with bits reflecting the state of all circuits within the microcontroller. All pins are
configured as inputs. The overall electronis starts operation in rhythm with pulse sequence. From
now on the time is measured in micro and nanoseconds.
4. Program Counter is set to zero. Instruction from that address is sent to instruction decoder which
recognizes it, after which it is executed with immediate effect.
5. The value of the Program Counter is incremented by 1 and the whole process is repeated...several
million times per second.
miliseconds.
are:
Instruction decoder is a part of the electronics which recognizes program instructions and runs
other circuits on the basis of that. The abilities of this circuit are expressed in the "instruction set"
which is different for each microcontroller family.
Arithmetical Logical Unit (ALU) performs all mathematical and logical operations upon data.
Accumulator is an SFR closely related to the operation of ALU. It is a kind of working desk used
for storing all data upon which some operations should be executed (addition, shift etc.). It also
stores the results ready for use in further processing. One of the SFRs, called the Status Register, is
closely related to the accumulator, showing at any given time the "status" of a number stored in
the accumulator (the number is greater or less than zero etc.).
A bit is just a word invented to confuse novices at electronics. Joking aside, this word in practice
indicates whether the voltage is present on a conductor or not. If it is present, the approprite pin is set to
logic one (1), i.e. the bits value is 1. Otherwise, if the voltage is 0 V, the appropriate pin is cleared (0),
i.e. the bits value is 0. It is more complicated in theory where a bit is referred to as a binary digit, but
even in this case, its value can be either 0 or 1.
Input/output ports (I/O Ports)
In order to make the microcontroller useful, it is necessary to connect it to peripheral devices. Each
microcontroller has one or more registers (called a port) connected to the microcontroller pins.
Why do we call them input/output ports? Because it is possible to change a pin function according to the
user's needs. These registers are the only registers in the microcontroller the state of which can be checked
by voltmeter!
Oscillator
Even pulses generated by the oscillator enable harmonic and synchronous operation of all circuits within
the microcontroller. It is usually configured as to use quartz-crystal or ceramics resonator for frequency
stabilization. It can also operate without elements for frequency stabilization (like RC oscillator). It is
important to say that program instructions are not executed at the rate imposed by the oscillator itself, but
several times slower. It happens because each instruction is executed in several steps. For some
microcontrollers, the same number of cycles is needed to execute any instruction, while it's different for
other microcontrollers. Accordingly, if the system uses quartz crystal with a frequency of 20MHz, the
execution time of an instruction is not expected 50nS, but 200, 400 or even 800 nS, depending on the type
of the microcontroller!
Timers/Counters
Most programs use these miniature electronic "stopwatches" in their operation. These are commonly 8- or
16-bit SFRs the contents of which is automatically incremented by each coming pulse. Once the register
is completely loaded, an interrupt is generated!
If these registers use an internal quartz oscillator as a clock source, then it is possible to measure the time
between two events (if the register value is T1 at the moment measurement has started, and T2 at the
moment it has finished, then the elapsed time is equal to the result of subtraction T2-T1 ). If the registers
use pulses coming from external source, then such a timer is turned into a counter.
This is only a simple explanation of the operation itself. Its somehow more complicated in practice.
A register or a memory cell is an electronic circuit which can memorize the state of one byte. Besides 8
bits available to the user, each register has also a number of addressing bits. It is important to remember
that:
All registers of ROM as well as those of RAM referred to as general-purpose registers are
mutually equal and nameless. During programming, each of them can be assigned a name, which
makes the whole operation much easier.
All SFRs are assigned names which are different for different types of the microcontrollers and
each of them has a special function as their name suggests.
Watchdog timer
The Watchdog Timer is a timer connected to a completely separate RC oscillator within the
microcontroller.
If the watchdog timer is enabled, every time it counts up to the program end, the microcontroller reset
occurs and program execution starts from the first instruction. The point is to prevent this from happening
by using a special command. The whole idea is based on the fact that every program is executed in several
longer or shorter loops.
If instructions resetting the watchdog timer are set at the appropriate program locations, besides
commands being regularly executed, then the operation of the watchdog timer will not affect the program
execution.
If for any reason (usually electrical noise in industry), the program counter "gets stuck" at some memory
location from which there is no return, the watchdog will not be cleared, so the registers value being
constantly incremented will reach the maximum et voila! Reset occurs!
Brown out is a potentially dangerous state which occurs at the moment the microcontroller is being
turned off or when power supply voltage drops to the lowest level due to electric noise. 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 it, the microcontroller usually has a circuit for brown out
reset built-in. This circuit immediately resets the whole electronics when the voltage level drops below the
lower limit.
Reset pin is usually referred to as Master Clear Reset (MCLR) and serves for external reset of the
microcontroller by applying logic zero (0) or one (1) depending on the type of the microcontroller. In case
the brown out is not built in the microcontroller, a simple external circuit for brown out reset can be
connected to this pin.
Serial communication
Parallel connections between the microcontroller and peripherals established over I/O ports are the ideal
solution for shorter distances up to several meters. However, in other cases, when it is necessary to
establish communication between two devices on longer distances it is obviously not possible to use
parallel connections. Then, serial communication is the best solution.
Today, most microcontrollers have several different systems for serial communication built in as a
standard equipment. Which of them will be used depends on many factors of which the most important
are:
How many devices the microcontroller has to exchange data with?
How fast the data exchange has to be?
A byte consists of 8 bits grouped together. If a bit is a digit then it is logical that bytes are numbers. All
mathematical operations can be performed upon them, just like upon common decimal numbers, which is
carried out in the ALU. It is important to remember that byte digits are not of equal significance. The
largest value has the leftmost bit called the most significant bit (MSB). The rightmost bit has the least
value and is therefore called the least significant bit (LSB). Since 8 digits (zeros and ones) of one byte can
be combined in 256 different ways, the largest decimal number which can be represented by one byte is
255 (one combination represents zero).
Program
Unlike other integrated circuits which only need to be connected to other components and turn the power
supply on, the microcontrollers need to be programmed first. This is a so called "bitter pill" and the main
reason why hardware-oriented electronics engineers stay away from microcontrollers. It is a trap causing
huge losses because the process of programming the microcontroller is basically very simple.
In order to write a program for the microcontroller, several "low-level" programming languages can be
used such as Assembly, C and Basic (and their versions as well). Writing program procedure consists of
simple writing instructions in the order in which they should be executed. There are also many programs
running in Windows environment used to facilitate the work providing additional visual tools.
This book describes the use of Assembly 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 processes it should keep under control. This is
why the microcontroller spends most of its time waiting for something to happen or execute. In other
words, when some event takes place, the microcontroller does something. In order to prevent the
microcontroller from spending most of its time endlessly checking for logic state on input pins and
registers, an interrupt is generated. It is the signal which informs the central processor that something
attention worthy has happened. As its name suggests, it interrupts regular program execution. It can be
generated by different sources so when it occurs, the microcontroller immediately stops operation and
checks for the cause. If it is needed to perform some operations, a current state of the program counter is
pushed onto the Stack and the appropriate program is executed. It's the so called interrupt routine.
Stack is a part of RAM used for storing the current state of the program counter (address) when an
interrupt occurs. In this way, after a subroutine or an interrupt execution, the microcontroller knows from
where to continue regular program execution. This address is cleared after returning to the program
because there is no need to save it any longer, and one location of the stack is automatically availale for
further use. In addition, the stack can consist of several levels. This enables subroutines nesting, i.e.
calling one subroutine from another.
As seen in figure above, the 8051 microcontroller has nothing impressive in appearance:
4 Kb of ROM is not much at all.
128b of RAM (including SFRs) satisfies the user's basic needs.
4 ports having in total of 32 input/output lines are in most cases sufficient to make all necessary
connections to peripheral environment.
The whole configuration is obviously thought of as to satisfy the needs of most programmers working on
development of automation devices. One of its advantages is that nothing is missing and nothing is too
much. In other words, it is created exactly in accordance to the average users taste and needs. Another
advantages are RAM organization, the operation of Central Processor Unit (CPU) and ports which
completely use all recourses and enable further upgrade.
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. It means that even there is a program written to the
microcontroller, it will not be executed. Instead, the program written to external ROM will be executed.
By applying logic one to the EA pin, the microcontroller will use both memories, first internal then
external (if exists).
Pin 32-39: Port 0 Similar to P2, if external memory is not used, these pins can be used as general
inputs/outputs. Otherwise, P0 is configured as address output (A0-A7) when the ALE pin is driven high
(1) or as data output (Data Bus) when the ALE pin is driven low (0).
Pin 40: VCC +5V power supply.
Output pin
A logic zero (0) is applied to a bit of the P register. The output FE transistor is turned on, thus connecting
the appropriate pin to ground.
Input pin
A logic one (1) is applied to a bit of the P register. The output FE transistor is turned off and the
appropriate pin remains connected to the power supply voltage over a pull-up resistor of high resistance.
Logic state (voltage) of 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 a short circuit to ground. Such a pin acts as an output.
A logic one (1) is loosely connected to the power supply voltage over a resistor of high resistance.
Since this voltage can be easily reduced by an external signal, such a pin acts as an input.
Port 0
The P0 port is characterized by two functions. If external memory is used then the lower address byte
(addresses A0-A7) is applied on it. Otherwise, all bits of this port are configured as inputs/outputs.
The other function is expressed when it is configured as an output. Unlike other ports consisting of pins
with built-in pull-up resistor connected by its end to 5 V power supply, pins of this port have this resistor
left out. This apparently small difference has its consequences:
If any pin of this port is configured as an input then it acts as if it floats. Such an input has unlimited
input resistance and indetermined potential.
When the pin is configured as an output, it acts as an open drain. By applying logic 0 to a port bit, the
appropriate pin will be connected to ground (0V). By applying logic 1, the external output will keep on
floating. In order to apply logic 1 (5V) on this output pin, it is necessary to built in an external pull-up
resistor.
Only in case P0 is used for addressing external memory, the microcontroller will provide internal power
supply source in order to supply its pins with logic one. There is no need to add external pull-up resistors.
Port 1
P1 is a true I/O port, because it doesn't have any alternative functions as is the case with P0, but can be
cofigured as general I/O only. It has a pull-up resistor built-in and is completely compatible with TTL
circuits.
Port 2
P2 acts similarly to P0 when external memory is used. Pins of this port occupy addresses intended for
external memory chip. This time it is about the higher address byte with addresses A8-A15. When no
memory is added, this port can be used as a general input/output port showing features similar to P1.
Port 3
All port pins can be used as general I/O, but they also have an alternative function. In order to use these
alternative functions, a logic one (1) must be applied to appropriate bit of the P3 register. In tems of
hardware, this port is similar to P0, with the difference that its pins have a pull-up resistor built-in.
Pin's Current limitations
When configured as outputs (logic zero (0)), single port pins can receive a current of 10mA. If all 8 bits of
a port are active, a total current must be limited to 15mA (port P0: 26mA). If all ports (32 bits) are active,
total maximum current must be limited to 71mA. When these pins are configured as inputs (logic 1),
built-in pull-up resistors provide very weak current, but strong enough to activate up to 4 TTL inputs of
LS series.
As seen from description of some ports, even though all of them have more or less similar architecture, it
is necessary to pay attention to which of them is to be used for what and how.
For example, if they shall be used as outputs with high voltage level (5V), then P0 should be avoided
because its pins do not have pull-up resistors, thus giving low logic level only. When using other ports,
one should have in mind that pull-up resistors have a relatively high resistance, so that their pins can give
a current of several hundreds microamperes only.
How does the microcontroller handle external memory depends on the EA pin logic state:
EA=0 In this case, the microcontroller completely ignores internal program memory and executes only
the program stored in external memory.
EA=1 In this case, the microcontroller executes first the program from built-in ROM, then the program
stored in external memory.
In both cases, P0 and P2 are not available for use since being used for data and address transmission.
Besides, the ALE and PSEN pins are also used.
Data Memory
As already mentioned, Data Memory is used for temporarily storing data and intermediate results created
and used during the operation of the microcontroller. Besides, RAM memory built in the 8051 family
includes many registers such as hardware counters and timers, input/output ports, serial data buffers etc.
The previous models had 256 RAM locations, while for the later models this number was incremented by
additional 128 registers. However, the first 256 memory locations (addresses 0-FFh) are the heart of
memory common to all the models belonging to the 8051 family. Locations available to the user occupy
memory space with addresses 0-7Fh, i.e. first 128 registers. This part of RAM is divided in several blocks.
The first block consists of 4 banks each including 8 registers denoted by R0-R7. Prior to accessing any of
these registers, it is necessary to select the bank containing it. The next memory block (address 20h-2Fh)
is bit- addressable, which means that each bit has its own address (0-7Fh). Since there are 16 such
registers, this block contains in total of 128 bits with separate addresses (address of bit 0 of the 20h byte is
0, while address of bit 7 of the 2Fh byte is 7Fh). The third group of registers occupy addresses 2Fh-7Fh,
i.e. 80 locations, and does not have any special functions or features.
Additional RAM
In order to satisfy the programmers constant hunger for Data Memory, the manufacturers decided to
embed an additional memory block of 128 locations into the latest versions of the 8051 microcontrollers.
However, its not as simple as it seems to be The problem is that electronics performing addressing has
1 byte (8 bits) on disposal and is capable of reaching only the first 256 locations, therefore. In order to
keep already existing 8-bit architecture and compatibility with other existing models a small trick was
done.
What does it mean? It means that additional memory block shares the same addresses with locations
intended for the SFRs (80h- FFh). In order to differentiate between these two physically separated
memory spaces, different ways of addressing are used. The SFRs memory locations are accessed by direct
addressing, while additional RAM memory locations are accessed by indirect addressing.
Memory expansion
In case memory (RAM or ROM) built in the microcontroller is not sufficient, it is possible to add two
external memory chips with capacity of 64Kb each. P2 and P3 I/O ports are used for their addressing and
data transmission.
From the users point of view, everything works quite simply when properly connected because most
operations are performed by the microcontroller itself. The 8051 microcontroller has two pins for data
read RD#(P3.7) and PSEN#. The first one is used for reading data from external data memory (RAM),
while the other is used for reading data from external program memory (ROM). Both pins are active low.
A typical example of memory expansion by adding RAM and ROM chips (Hardward architecture), is
shown in figure above.
Even though additional memory is rarely used with the latest versions of the microcontrollers, we will
describe in short what happens when memory chips are connected according to the previous schematic.
The whole process described below is performed automatically.
When the program during execution encounters an instruction which resides in external memory
(ROM), the microcontroller will activate its control output ALE and set the first 8 bits of address
(A0-A7) on P0. IC circuit 74HCT573 passes the first 8 bits to memory address pins.
A signal on the ALE pin latches the IC circuit 74HCT573 and immediately afterwards 8 higher
bits of address (A8-A15) appear on the port. In this way, a desired location of additional program
memory is addressed. It is left over to read its content.
Port P0 pins are configured as inputs, the PSEN pin is activated and the microcontroller reads
from memory chip.
Similar occurs when it is necessary to read location from external RAM. Addressing is performed in the
same way, while read and write are performed via signals appearing on the control outputs RD (is short
for read) or WR (is short for write).
Addressing
While operating, the processor processes data as per program instructions. Each instruction consists of
two parts. One part describes WHAT should be done, while the other explains HOW to do it. The latter
part can be a data (binary number) or the address at which the data is stored. Two ways of addressing are
used for all 8051 microcontrollers depending on which part of memory should be accessed:
Direct Addressing
On direct addressing, the address of memory location containing data to be read is specified in instruction.
The address may contain a number being changed during operation (variable). For example:
Since the address is only one byte in size (the largest number is 255), only the first 255 locations of RAM
can be accessed this way. The first half of RAM is available for use, while another half is reserved for
SFRs.
MOV A,33h; Means: move a number from address 33 hex. to accumulator
Indirect Addressing
On indirect addressing, a register containing the address of another register is specified in instruction.
Data to be used in the program is stored in the letter register. For example:
Indirect addressing is only used for accessing RAM locations available for use (never for accessing
SFRs). This is the only way of accessing all the latest versions of the microcontrollers with additional
memory block (128 locations of RAM). Simply put, when the program encounters instruction including
@ sign and if the specified address is higher than 128 ( 7F hex.), the processor knows that indirect
addressing is used and skips memory space reserved for SFRs.
MOV A,@R0; Means: Store the value from the register whose address is in the R0
register
into accumulator
On indirect addressing, 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 this way (128 locations
when speaking of previous models or 256 locations when speaking of latest models of microcontrollers).
If an extra memory chip is added then the 16-bit DPTR Register (consisting of the registers DPTRL and
DPTRH) is used for specifying address. In this way it is possible to access any location in the range of
64K.
A Register (Accumulator)
A register is a general-purpose register used for storing intermediate results obtained during operation.
Prior to executing an instruction upon any number or operand it is necessary to store it in the accumulator
first. All results obtained from arithmetical operations performed by the ALU are stored in the
accumulator. Data to be moved from one register to another must go through the accumulator. In other
words, the A register is the most commonly used register and it is impossible to imagine a microcontroller
without it. More than half instructions used by the 8051 microcontroller use somehow the accumulator.
B Register
Multiplication and division 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 the process of writing a program, each register is called by its name so that their exact addresses
are not of importance for the user. During compilation, their names will be automatically replaced by
appropriate addresses.
R Registers (R0-R7)
This is a common name for 8 general-purpose registers (R0, R1, R2 ...R7). Even though they are not true
SFRs, they deserve to be discussed here because of their purpose. They occupy 4 banks within RAM.
Similar to the accumulator, they are used for temporary storing variables and intermediate results during
operation. Which one of these banks is to be active depends on two bits of the PSW Register. Active bank
is a bank the registers of which are currently used.
The following example best illustrates the purpose of these registers. Suppose it is necessary to perform
some arithmetical operations upon numbers previously stored in the R registers: (R1+R2) - (R3+R4).
Obviously, a register for temporary storing results of addition is needed. This is how it looks in the
program:
MOV A,R3; Means: move number from R3 into accumulator
ADD A,R4; Means: add number from R4 to accumulator (result remains in accumulator)
MOV R5,A; Means: temporarily move the result from accumulator into R5
MOV A,R1; Means: move number from R1 to accumulator
ADD A,R2; Means: add number from R2 to accumulator
SUBB A,R5; Means: subtract number from R5 (there are R3+R4)
PSW register is one of the most important SFRs. It contains several status bits that reflect the current state
of the CPU. Besides, this register contains Carry bit, Auxiliary Carry, two register bank select bits,
Overflow flag, parity bit and user-definable status flag.
P - Parity bit. If a number stored in the accumulator is even then this bit will be automatically set (1),
otherwise it will be cleared (0). It is mainly used during data transmit and receive via serial
communication.
- Bit 1. This bit is intended to be used in the future versions of microcontrollers.
OV Overflow occurs when the result of an arithmetical operation is larger than 255 and cannot be stored
in one register. Overflow condition causes the OV bit to be set (1). Otherwise, it will be cleared (0).
RS0, RS1 - Register bank select bits. These two bits are used to select one of four register banks of
RAM. By setting and clearing these bits, registers R0-R7 are stored in one of four banks of RAM.
RS1 RS2 Space in RAM
0
0
Bank0 00h-07h
0
1
Bank1 08h-0Fh
1
0
Bank2 10h-17h
1
1
Bank3 18h-1Fh
F0 - Flag 0. This is a general-purpose bit available for use.
AC - Auxiliary Carry Flag is used for BCD operations only.
CY - Carry Flag is the (ninth) auxiliary bit used for all arithmetical operations and shift instructions.
Data Pointer Register (DPTR)
DPTR register is not a true one because it doesn't physically exist. It consists of two separate registers:
DPH (Data Pointer High) and (Data Pointer Low). For this reason it may be treated as a 16-bit register or
as two independent 8-bit registers. Their 16 bits are primarly used for external memory addressing.
Besides, the DPTR Register is usually used for storing data and intermediate results.
A value stored in the Stack Pointer points to the first free stack address and permits stack availability.
Stack pushes increment the value in the Stack Pointer by 1. Likewise, stack pops decrement its value by 1.
Upon any reset and power-on, the value 7 is stored in the Stack Pointer, which means that the space of
RAM reserved for the stack starts at this location. If another value is written to this register, the entire
Stack is moved to the new memory location.
If neither external memory nor serial communication system are used then 4 ports with in total of 32
input/output pins are available for connection to peripheral environment. Each bit within these ports
affects the state and performance of appropriate pin of the microcontroller. Thus, bit logic state is
reflected on appropriate pin as a voltage (0 or 5 V) and vice versa, voltage on a pin reflects the state of
appropriate port bit.
As mentioned, port bit state affects performance of port pins, i.e. whether they will be configured as
inputs or outputs. If a bit is cleared (0), the appropriate pin will be configured as an output, while if it is
set (1), the appropriate pin will be configured as an input. Upon reset and power-on, all port bits are set
(1), which means that all appropriate pins will be configured as inputs.
I/O ports are directly connected to the microcontroller pins. Accordingly, logic state of these registers can
be checked by voltmeter and vice versa, voltage on the pins can be checked by inspecting their bits!
Accordingly, if the content of the timer T0 is equal to 0 (T0=0) then both registers it consists of will
contain 0. If the timer contains for example number 1000 (decimal), then the TH0 register (high byte) will
contain the number 3, while the TL0 register (low byte) will contain decimal number 232.
Since the timer T0 is virtually 16-bit register, the largest value it can store is 65 535. In case of exceeding
this value, the timer will be automatically cleared and counting starts from 0. This condition is called an
overflow. Two registers TMOD and TCON are closely connected to this timer and control its operation.
TMOD Register (Timer Mode)
The TMOD register selects the operational mode of the timers T0 and T1. As seen in figure below, the
low 4 bits (bit0 - bit3) refer to the timer 0, while the high 4 bits (bit4 - bit7) refer to the timer 1. There are
4 operational modes and each of them is described herein.
o
o
The only application of this mode is when two timers are used and the 16-bit Timer 1 the operation of
Referring to figure above, the timer 0 operates in mode 1 and counts pulses generated by internal clock
the frequency of which is equal to 1/12 the quartz frequency.
Turn on the timer:
The TR0 bit is set and the timer starts operation. If the quartz crystal with frequency of 12MHz is
embedded then its contents will be incremented every microsecond. After 65.536 microseconds, the both
registers the timer consists of will be loaded. The microcontroller automatically clears them and the timer
keeps on repeating procedure from the beginning until the TR0 bit value is logic zero (0).
How to 'read' a timer?
Depending on application, it is necessary either to read a number stored in the timer registers or to register
the moment they have been cleared.
- It is extremely simple to read a timer by using only one register configured in mode 2 or 3. It is
sufficient to read its state at any moment. That's all!
- It is somehow complicated to read a timer configured to operate in mode 2. Suppose the lower byte is
read first (TL0), then the higher byte (TH0). The result is:
TH0 = 15 TL0 = 255
Everything seems to be ok, but the current state of the register at the moment of reading was:
TH0 = 14 TL0 = 255
In case of negligence, such an error in counting (255 pulses) may occur for not so obvious but quite
logical reason. The lower byte is correctly read (255), but at the moment the program counter was about
to read the higher byte TH0, an overflow occurred and the contents of both registers have been changed
(TH0: 1415, TL0: 2550). This problem has a simple solution. The higher byte should be read first,
then the lower byte and once again the higher byte. If the number stored in the higher byte is different
then this sequence should be repeated. It's about a short loop consisting of only 3 instructions in the
program.
There is another solution as well. It is sufficient to simply turn the timer off while reading is going on (the
TR0 bit of the TCON register should be cleared), and turn it on again after reading is finished.
Timer 0 Overflow Detection
Usually, there is no need to constantly read timer registers. It is sufficient to register the moment they are
cleared, i.e. when counting starts from 0. This condition is called an overflow. When it occurrs, the TF0
bit of the TCON register will be automatically set. The state of this bit can be constantly checked from
within the program or by enabling an interrupt which will stop the main program execution when this bit
is set. Suppose it is necessary to provide a program delay of 0.05 seconds (50 000 machine cycles), i.e.
When enabled, the timer will resume counting from this number. The state of the TF0 bit, i.e. whether it is
set, is checked from within the program. It happens at the moment of overflow, i.e. after exactly 50.000
machine cycles or 0.05 seconds.
How to measure pulse duration?
Suppose it is necessary to measure the duration of an operation, for example how long a device has been
turned on? Look again at the figure illustrating the timer and pay attention to the function of the GATE0
bit of the TMOD register. If it is cleared then the state of the P3.2 pin doesn't affect timer operation. If
GATE0 = 1 the timer will operate until the pin P3.2 is cleared. Accordingly, 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 operation, which actually was the objective.
How to count up pulses?
Similarly to the previous example, the answer to this question again lies in the TCON register. This time
it's about the C/T0 bit. If the bit is cleared the timer counts pulses generated by the internal oscillator, i.e.
measures the time passed. If the bit is set, the timer input is provided with pulses from the P3.4 pin (T0).
Since these pulses are not always of the same width, the timer cannot be used for time measurement and is
turned into a counter, therefore. The highest frequency that could be measured by such a counter is 1/24
frequency of used quartz-crystal.
Timer 1
Timer 1 is identical to timer 0, except for mode 3 which is a hold-count mode. It means that they have the
same function, their operation is controlled by the same registers TMOD and TCON and both of them can
operate in one out of 4 different modes.
Serial port must be configured prior to being used. In other words, it is necessary to determine how many
bits is contained in one serial word, baud rate and synchronization clock source. The whole process is in
control of the bits of the SCON register (Serial Control).
Serial Port Control (SCON) Register
SM0 - Serial port mode bit 0 is used for serial port mode selection.
SM1 - Serial port mode bit 1.
SM2 - Serial port mode 2 bit, also known as multiprocessor communication enable bit. When set,
it enables multiprocessor communication in mode 2 and 3, and eventually mode 1. It should be
cleared in mode 0.
REN - Reception Enable bit enables serial reception when set. When cleared, serial reception is
disabled.
TB8 - Transmitter bit 8. Since all registers are 8-bit wide, this bit solves the problem of
transmiting the 9th bit in modes 2 and 3. It is set to transmit a logic 1 in the 9th bit.
RB8 - Receiver bit 8 or the 9th bit received in modes 2 and 3. Cleared by hardware if 9th bit
received is a logic 0. Set by hardware if 9th bit received is a logic 1.
TI - Transmit Interrupt flag is automatically set at the moment the last bit of one byte is sent. It's a
signal to the processor that the line is available for a new byte transmite. It must be cleared from
within the software.
RI - Receive Interrupt flag is automatically set upon one byte receive. It signals that byte is
received and should be read quickly prior to being replaced by a new data. This bit is also cleared
from within the software.
As seen, serial port mode is selected by combining the SM0 and SM2 bits:
SM0 SM1 Mode
Description
Baud Rate
0
0
0
8-bit Shift Register 1/12 the quartz frequency
0
1
1
1
0
1
1
2
3
8-bit UART
9-bit UART
9-bit UART
In mode 0, serial data are transmitted and received through the RXD pin, while the TXD pin output
clocks. The bout rate is fixed at 1/12 the oscillator frequency. On transmit, the least significant bit (LSB
bit) is sent/received first.
TRANSMIT - Data transmit is initiated by writing data to the SBUF register. In fact, this process starts
after any instruction being performed upon this register. When all 8 bits have been sent, the TI bit of the
SCON register is automatically set.
RECEIVE - Data receive through the RXD pin starts upon the two following conditions are met: bit
REN=1 and RI=0 (both of them are stored in the SCON register). When all 8 bits have been received, the
RI bit of the SCON register is automatically set indicating that one byte receive is complete.
Since there are no START and STOP bits or any other bit except data sent from the SBUF register in the
pulse sequence, this mode is mainly used when the distance between devices is short, noise is minimized
and operating speed is of importance. A typical example is I/O port expansion by adding a cheap IC (shift
In mode 1, 10 bits are transmitted through the TXD pin or received through the RXD pin in the following
manner: a START bit (always 0), 8 data bits (LSB first) and a STOP bit (always 1). The START bit is
only used to initiate data receive, while the STOP bit is automatically written to the RB8 bit of the SCON
register.
TRANSMIT - Data transmit is initiated by writing data to the SBUF register. End of data transmission is
indicated by setting the TI bit of the SCON register.
RECEIVE - The START bit (logic zero (0)) on the RXD pin initiates data receive. The following two
conditions must be met: bit REN=1 and bit RI=0. Both of them are stored in the SCON register. The RI
bit is automatically set upon data reception is complete.
Mode 2
In mode 2, 11 bits are transmitted through the TXD pin or received through the RXD pin: a START bit
(always 0), 8 data bits (LSB first), a programmable 9th data bit and a STOP bit (always 1). On transmit,
the 9th data bit is actually the TB8 bit of the SCON register. This bit usually has a function of parity bit.
On receive, the 9th data bit goes into the RB8 bit of the same register (SCON).The baud rate is either 1/32
or 1/64 the oscillator frequency.
TRANSMIT - Data transmit is initiated by writing data to the SBUF register. End of data transmission is
indicated by setting the TI bit of the SCON register.
RECEIVE - The START bit (logic zero (0)) on the RXD pin initiates data receive. The following two
conditions must be met: bit REN=1 and bit RI=0. Both of them are stored in the SCON register. The RI
bit is automatically set upon data reception is complete.
Mode 3
Mode 3 is the same as Mode 2 in all respects except the baud rate. The baud rate in Mode 3 is variable.
The parity bit is the P bit of the PSW register. The simplest way to check correctness of the received byte
is to add a parity bit to it. Simply, before initiating data transmit, the byte to transmit is stored in the
accumulator and the P bit goes into the TB8 bit in order to be a part of the message. The procedure is
opposite on receive, received byte is stored in the accumulator and the P bit is compared with the RB8 bit.
If they are the same- everything is OK!
Baud Rate
Baud Rate is a number of sent/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 SMOD bit of the SCON register.
All the necessary formulas are specified in the table:
Baud Rate BitSMOD
Mode 0 Fosc. / 12
1 Fosc.
Mode 1
BitSMOD
16 12 (256-TH1)
Fosc. / 32
1
Mode 2
Fosc. / 64
0
1 Fosc.
Mode 3
16 12 (256-TH1)
Timer 1 as a clock generator
Timer 1 is usually used as a clock generator as it enables various baud rates to be easily set. The whole
procedure is simple and is as follows:
First, enable Timer 1 overflow interrupt.
Configure Timer T1 to operate in auto-reload mode.
Depending on needs, select one of the standard values from the table and write it to the TH1
register. That's all.
Baud Rate
150
300
600
1200
2400
4800
4800
9600
9600
19200
38400
76800
Fosc. (MHz)
Bit SMOD
11.0592 12 14.7456 16 20
40 h
30 h 00 h
0
A0 h
98 h 80 h
75 h 52 h 0
D0 h
CC h C0 h
BB h A9 h 0
E8 h
E6 h E0 h
DE h D5 h 0
F4 h
F3 h F0 h
EF h EA h 0
F3 h EF h
EF h
1
FA h
F8 h
F5 h 0
FD h
FC h
0
F5 h 1
FD h
FC h
1
FE h
1
FF h
1
Multiprocessor Communication
As you may know, additional 9th data bit is a part of message in mode 2 and 3. It can be used for
checking data via parity bit. Another useful application of this bit is in communication between two or
more microcontrollers, i.e. multiprocessor communication. This feature is enabled by setting the SM2 bit
of the SCON register. As a result, after receiving the STOP bit, indicating end of the message, the serial
port interrupt will be generated only if the bit RB8 = 1 (the 9th bit).
Of course, only one of them will match the address and immediately clear the SM2 bit of the SCON
register and prepare to receive the data byte to come. Other slaves not being addressed leave their SM2 bit
set ignoring the coming data bytes.
From the moment an interrupt is enabled, the microcontroller is on alert all the time. When an interrupt
request arrives, the program execution is stopped, electronics recognizes the source and the program
jumps to the appropriate address (see the table above). This address usually stores a jump instruction
specifying the start of appropriate subroutine. Upon its execution, the program resumes operation 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 an internal reset signal which
clears all SFRs, except SBUF registers, Stack Pointer and ports (the state of the first two ports is not
defined, while FF value is written to the ports configuring all their pins as inputs). Depending on
surrounding and purpose of device, the RS pin is usually connected to a power-on reset push button or
circuit or to both of them. Figure below illustrates one of the simplest circuit providing safe power-on
reset.
Basically, everything is very simple: after turning the power on, electrical capacitor is being charged for
several milliseconds throgh a resistor connected to the ground. The pin is driven high during this process.
When the capacitor is charged, power supply voltage is already stable and the pin remains connected to
the ground, thus providing normal operation of the microcontroller. Pressing the reset button causes the
capacitor to be temporarily discharged and the microcontroller is reset. When released, the whole process
is repeated
Through the program- step by step...
Microcontrollers normally operate at very high speed. The use of 12 Mhz quartz crystal enables 1.000.000
instructions to be executed per second. Basically, there is no need for higher operating rate. In case it is
needed, it is easy to built in a crystal for high frequency. The problem arises when it is necessary to slow
down the operation of the microcontroller. For example during testing in real environment when it is
necessary to execute several instructions step by step in order to check I/O pins' logic state.
Interrupt system of the 8051 microcontroller practically stops operation of the microcontroller and enables
instructions to be executed one after another by pressing the button. Two interrupt features enable that:
Interrupt request is ignored if an interrupt of the same priority level is in progress.
Upon interrupt routine execution, a new interrupt is not executed until at least one instruction from
the main program is executed.
In order to use 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 inserted into the program (at the 03hex. address):
What is going on? As soon as the P3.2 pin is cleared (for example, by pressing the button), the
microcontroller will stop program execution and jump to the 03hex address will be executed. This address
stores a short interrupt routine consisting of 3 instructions.
The first instruction is executed until the push button is realised (logic one (1) on the P3.2 pin). The
second instruction is executed until the push button is pressed again. Immediately after that, the RETI
instruction is executed and the processor resumes operation of the main program. Upon execution of any
program instruction, the interrupt INT0 is generated and the whole procedure is repeated (push button is
still pressed). In other words, one button press - one instruction.
Idle mode
Upon the IDL bit of the PCON register is set, the microcontroller turns off the greatest power consumerCPU unit while peripheral units such as serial port, timers and interrupt system continue operating
normally consuming 6.5mA. In Idle mode, the state of all registers and I/O ports remains unchanged.
In order to exit the Idle mode and make the microcontroller operate normally, it is necessary to enable and
execute any interrupt or reset. It will cause the IDL bit to be automatically cleared and the program
resumes operation from instruction having set the IDL bit. It is recommended that first three instructions
to execute now are NOP instructions. They don't perform any operation but provide some time for the
microcontroller to stabilize and prevents undesired changes on the I/O ports.
Power Down mode
By setting the PD bit of the PCON register from within the program, the microcontroller is set to Power
down mode, thus turning off its internal oscillator and reduces power consumption enormously. The
microcontroller can operate using only 2V power supply in power- down mode, while a total power
consumption is less than 40uA. The only way to get the microcontroller back to normal mode is by reset.
While the microcontroller is in Power Down mode, the state of all SFR registers and I/O ports remains
unchanged. By setting it back into the normal mode, the contents of the SFR register is lost, but the
content of internal RAM is saved. Reset signal must be long enough, approximately 10mS, to enable
stable operation of the quartz oscillator.
PCON register
Introduction
The process of writing program for the microcontroller mainly consists of giving instructions
(commands) in the specific order in which they should be executed in order to carry out a specific task.
As electronics cannot understand what for example an instruction if the push button is pressed- turn
the light on means, then a certain number of 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). 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 abbreviations to be learned, which is acceptable.
The other part of instruction, called OPERAND is separated from mnemonic by at least one whitespace
and defines data being processed by instructions. Some of the instructions have no operand, while some
of them have one, two or three. If there is more than one operand in an instruction, they are separated by a
comma. For example:
RET - return from a subroutine;
JZ TEMP - if the number in the accumulator is not 0, jump to the address marked as TEMP;
ADD A,R3 - add R3 and accumulator;
CJNE A,#20,LOOP - compare accumulator with 20. If they are not equal, jump to the address
marked as LOOP;
Arithmetic instructions
Arithmetic instructions perform several basic operations such as addition, subtraction, division,
multiplication etc. After execution, the result is stored in the first operand. For example:
ADD A,R1 - The result of addition (A+R1) will be stored in the accumulator.
Arithmetic Instructions
Mnemonic
Description
Byte Cycle
ADD A,Rn
Adds the register to the accumulator
1
1
ADD A,direct Adds the direct byte to the accumulator
2
2
ADD A,@Ri Adds the indirect RAM to the accumulator
1
2
ADD A,#data Adds the immediate data to the accumulator
2
2
ADDC A,Rn Adds the register to the accumulator with a carry flag
1
1
ADDC A,direct Adds the direct byte to the accumulator with a carry flag
2
2
ADDC A,@Ri Adds the indirect RAM to the accumulator with a carry flag
1
2
ADDC A,#data Adds the immediate data to the accumulator with a carry flag
2
2
SUBB A,Rn
Subtracts the register from the accumulator with a borrow
1
1
SUBB A,direct Subtracts the direct byte from the accumulator with a borrow
2
2
SUBB A,@Ri Subtracts the indirect RAM from the accumulator with a borrow 1
2
SUBB A,#data Subtracts the immediate data from the accumulator with a borrow 2
2
INC A
Increments the accumulator by 1
1
1
INC Rn
Increments the register by 1
1
2
INC Rx
Increments the direct byte by 1
2
3
INC @Ri
Increments the indirect RAM by 1
1
3
DEC A
Decrements the accumulator by 1
1
1
DEC Rn
Decrements the register by 1
1
1
DEC Rx
Decrements the direct byte by 1
1
2
DEC @Ri
Decrements the indirect RAM by 1
2
3
INC DPTR
Increments the Data Pointer by 1
1
3
MUL AB
Multiplies A and B
1
5
DIV AB
Divides A by B
1
5
DA A
Decimal adjustment of the accumulator according to BCD code 1
1
Branch Instructions
There are two kinds of branch instructions:
Unconditional jump instructions: upon their execution a jump to a new location from where the program
Description
Absolute subroutine call
Long subroutine call
Returns from subroutine
Returns from interrupt subroutine
Absolute jump
Long jump
Short jump (from 128 to +127 locations relative to the following
SJMP rel
instruction)
JC rel
Jump if carry flag is set. Short jump.
JNC rel
Jump if carry flag is not set. Short jump.
JB bit,rel
Jump if direct bit is set. Short jump.
JBC bit,rel
Jump if direct bit is set and clears bit. Short jump.
JMP @A+DPTR Jump indirect relative to the DPTR
JZ rel
Jump if the accumulator is zero. Short jump.
JNZ rel
Jump if the accumulator is not zero. Short jump.
Compares direct byte to the accumulator and jumps if not equal. Short
CJNE A,direct,rel
jump.
Compares immediate data to the accumulator and jumps if not equal.
CJNE A,#data,rel
Short jump.
Compares immediate data to the register and jumps if not equal. Short
CJNE Rn,#data,rel
jump.
CJNE
Compares immediate data to indirect register and jumps if not equal.
@Ri,#data,rel
Short jump.
DJNZ Rn,rel
Decrements register and jumps if not 0. Short jump.
DJNZ Rx,rel
Decrements direct byte and jump if not 0. Short jump.
NOP
No operation
Byte Cycle
2
6
3
6
1
4
1
4
2
3
3
4
2
2
2
3
3
1
2
2
3
3
4
4
2
3
3
2
3
1
3
4
1
Description
Moves the register to the accumulator
Moves the direct byte to the accumulator
Moves the indirect RAM to the accumulator
Moves the immediate data to the accumulator
Moves the accumulator to the register
Moves the direct byte to the register
Moves the immediate data to the register
Byte Cycle
1
1
2
2
1
2
2
2
1
2
2
4
2
2
MOV direct,A
MOV direct,Rn
MOV direct,direct
MOV direct,@Ri
MOV direct,#data
MOV @Ri,A
MOV @Ri,direct
MOV @Ri,#data
MOV DPTR,#data
MOVC
A,@A+DPTR
2
2
3
2
3
1
2
2
3
3
3
4
4
3
3
5
3
3
1
1
1
1
2
2
1
2
1
1
3-10
3-10
4-11
4-11
4
3
2
3
3
3
Logic Instructions
Logic instructions perform logic operations upon corresponding bits of two registers. After execution, the
result is stored in the first operand.
Logic Instructions
Mnemonic
Description
ANL A,Rn
AND register to accumulator
ANL A,direct
AND direct byte to accumulator
ANL A,@Ri
AND indirect RAM to accumulator
ANL A,#data
AND immediate data to accumulator
ANL direct,A
AND accumulator to direct byte
ANL direct,#data AND immediae data to direct register
ORL A,Rn
OR register to accumulator
ORL A,direct
OR direct byte to accumulator
ORL A,@Ri
OR indirect RAM to accumulator
ORL direct,A
OR accumulator to direct byte
ORL direct,#data OR immediate data to direct byte
XRL A,Rn
Exclusive OR register to accumulator
XRL A,direct
Exclusive OR direct byte to accumulator
XRL A,@Ri
Exclusive OR indirect RAM to accumulator
XRL A,#data
Exclusive OR immediate data to accumulator
XRL direct,A
Exclusive OR accumulator to direct byte
XORL direct,#data Exclusive OR immediate data to direct byte
Byte Cycle
1
1
2
2
1
2
2
2
2
3
3
4
1
1
2
2
1
2
2
3
3
4
1
1
2
2
1
2
2
2
2
3
3
4
CLR A
CPL A
SWAP A
RL A
RLC A
RR A
RRC A
1
1
1
1
1
1
1
Bit-oriented Instructions
Similar to logic instructions, bit-oriented instructions perform logic operations. The difference is that
these are performed upon single bits.
Bit-oriented Instructions
Mnemonic Description
CLR C
Clears the carry flag
CLR bit
Clears the direct bit
SETB C Sets the carry flag
SETB bit Sets the direct bit
CPL C
Complements the carry flag
CPL bit
Complements the direct bit
ANL C,bit AND direct bit to the carry flag
ANL C,/bit AND complements of direct bit to the carry flag
ORL C,bit OR direct bit to the carry flag
ORL C,/bit OR complements of direct bit to the carry flag
MOV C,bit Moves the direct bit to the carry flag
MOV bit,C Moves the carry flag to the direct bit
Byte Cycle
1
1
2
3
1
1
2
3
1
1
2
3
2
2
2
2
2
2
2
2
2
2
2
3
Description: Instruction unconditionally calls a subroutine located at the specified code address.
Therefore, the current address and the address of called subroutine must be within the same 2K byte block
of the program memory, starting from the first byte of the instruction following ACALL.
Syntax: ACALL [subroutine name];
Bytes: 2 (instruction code, subroutine address);
STATUS register flags: No flags are affected.
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
ADD A,#data - Adds the immediate data to the accumulator
A: accumulator
Data: constant within 0-255 (0-FFh)
Description: Instruction adds data (0-255) to the accumulator. After addition, the result is stored in the
accumulator.
Syntax: ADD A,#data;
Bytes: 2 (instruction code, data);
STATUS register flags: C, OV and AC;
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 - Adds the indirect RAM to the accumulator with a carry flag
A: accumulator
Ri: Register R0 or R1
Description: Instruction adds the indirect RAM to the accumulator with a carry flag. RAM address is
stored in the Ri register (R0 or R1). After addition, the result is stored in the accumulator.
Syntax: ADDC A,@Ri;
Byte: 1 (instruction code);
STATUS register flags: C, OV and AC;
EXAMPLE:
Description: Instruction performs logic AND operation between the accumulator and data. The result is
stored in the accumulator.
Syntax: ANL A,#data;
Bytes: 2 (instruction code, data);
STATUS register flags: No flags are affected;
EXAMPLE:
Description: Instruction performs logic AND operation between direct byte and data. As it is direct
addressing, the register can be any SFRs or general-purpose register with address 0-7Fh (0-127 dec.). The
result is stored in the direct byte.
Syntax: ANL register address ,#data;
Bytes: 3 (instruction code, direct byte address, data);
STATUS register flags: No flags are affected;
EXAMPLE:
Before execution: X= C3h (11000011 Bin.) MASK= 55h (01010101 Bin.) After execution: MASK= 41h
(01000001 Bin.)
ANL C,bit - AND direct bit to the carry flag
C: Carry flag
Bit: any bit of RAM
Description: Instruction performs logic AND operation between the direct bit and the carry flag.
bit C C AND bit
0 0 0
0 1 0
1 0 0
1 1 1
Syntax: ANL C, bit address;
Bytes: 2 (instruction code, bit address);
STATUS register flags: C;
EXAMPLE:
two BCD numbers have been added by the ADD and ADDC instructions. The result in form of two 4digit BCD numbers is stored in the accumulator.
Syntax: DA A;
Byte: 1 (instruction code);
STATUS register flags: C;
EXAMPLE:
EXAMPLE:
If R1=0: PC=0446h
INC Rn - Increments the Rn register by 1
Rn: any R register (R0-R7)
Description: Instruction increments the 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:
Ri: Register R0 or R1
Description: This instruction increments the value in the directly addressed register of RAM by 1. The
register address is stored in the Ri Register (R0 or R1). If the register includes the number 255, the result
of the operation will be 0.
Syntax: INC @Ri;
Byte: 1 (instruction code);
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 one (-128 to + 127 locations relative to
the first following instruction).
Syntax: JB bit, [jump address];
Bytes: 3 (instruction code, bit address, jump address);
STATUS register flags: No flags are affected;
EXAMPLE:
64K.
Syntax: LCALL [subroutine name];
Bytes: 3 (instruction code, address (15-8), address (7-0));
STATUS register flags: No flags are affected;
EXAMPLE:
Description: The instruction moves the Rn register to the accumulator. The Rn register is not affected.
Syntax: MOV A,Rn;
Byte: 1 (instruction code);
STATUS register flags: No flags are affected;
EXAMPLE:
EXAMPLE:
Description: Instruction moves the accumulator to the direct byte. As it is direct addressing, the register
can be any SFRs or general-purpose register with address 0-7Fh. (0-127 dec.). After executing the
instruction, the register is not affected.
Syntax: MOV direct,A;
Bytes: 2 (instruction code, direct byte address);
STATUS register flags: No flags are affected;
EXAMPLE:
Before execution:
DPTR=1000:
A=0
A=1
A=2
A=3
After execution:
A=66h
A=77h
A=88h
A=99h
Note: DB (Define Byte) is a directive in assembly language used to define constant.
MOV DPTR,#data16 - Loads the data pointer with a 16-bit constant
Data: constant in the range of 0-65535 (0-FFFFh)
DPTR: Data Pointer
Description: Instruction stores a 16-bit constant to the DPTR register. The 8 high bits of the constant are
stored in the DPH register, while the 8 low bits are stored in the DPL register.
Syntax: MOV DPTR,#data;
Bytes: 3 (instruction code, constant (15-8), constant (7-0));
STATUS register flags: No flags affected;
EXAMPLE:
After the subroutine "Table" 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
Note: DB (Define Byte) is a directive in assembly language used to define constant.
MOVX @Ri,A - Moves the accumulator to the external RAM (8-bit address)
Ri: register R0 or R1
A: accumulator
Description: Instruction moves the accumulator to a register stored in external RAM. Its address is stored
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 which is 256 bytes in size.
MOVX A,@DPTR - Moves the external memory (16-bit address) to the accumulator
A: accumulator
DPRTR: Data Pointer
Description: Instruction moves the content of a register in external memory to the accumulator. The 16bit address of the register is stored in the DPTR register (DPH and DPL).
Syntax: MOVX A,@DPTR;
Byte: 1 (instruction code);
STATUS register flags: No flags affected;
EXAMPLE:
AB=80160=12800 (3200h)
MOVX @DPTR,A - Moves the accumulator to the external RAM (16-bit address)
A: accumulator
DPTR: Data Pointer
Description: Instruction moves the accumulator to a register stored in external RAM. The 16-bit address
of the register is stored in the DPTR register (DPH and DPL).
Syntax: MOVX @DPTR,A;
Byte: 1 (instruction code);
STATUS register flags: No flags affected;
EXAMPLE:
NOP - No operation
Description: Instruction doesnt 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:
Such a sequence provides a negative pulse which lasts exactly 5 machine cycles on the P2.3. 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 - OR indirect RAM to the accumulator
Ri: register R0 or R1
A: accumulator
Description: Instruction performs logic OR operation between the accumulator and a register. As it is
indirect addressing, the register address is stored in the Ri register (R0 or R1). The result is stored in the
accumulator.
Syntax: ANL A,@Ri;
Byte: 1 (instruction code);
STATUS register flags: No flags affected;
EXAMPLE:
A: accumulator
Description: Instruction performs logic OR operation between the accumulator and the immediate data.
The result is stored in the accumulator.
Syntax: ORL A, #data;
Bytes: 2 (instruction code, data);
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:
RLC A - Rotates the accumulator one bit left through the carry flag
A: accumulator
Description: All eight bits in the accumulator and carry flag are rotated one bit left. After this operation,
the bit 7 is rotated into the carry flag position and the carry flag is rotated into the bit 0 position.
Syntax: RLC A;
Byte: 1 (instruction code);
STATUS register flags: C;
EXAMPLE:
EXAMPLE:
Introduction
It has been more than 20 years since the first version of the 8051 microcontroller was launched. During
that time it has undergone various upgrades and improvements. Today, the 8051 microcontroller is being
manufactured across the globe by many manufacturers and under different names. Of course, the latest
versions are by far more advanced than the original one. Many of them has the label 8051 compatible,
8051 compliantor 8051 family in order to emphasize their noble heritage. These tags imply that
microcontrollers have similar architecture and are programmed in a similar way using the same
instruction set. Practically, if you know how to handle one microcontroller belonging to this family, you
will be able to handle any of them. In other words, several hundreds of different models are at your
disposal.
This book covers one of them called the AT89S8253, manufactured by Atmel. Why this particular one?
Because it is widely used, cheap and uses Flash memory for storing programs. The last feature mentioned
makes it ideal for experimentation due to the fact that program can be loaded and erased from it for many
times. Besides, thanks to the built-in SPI System (Serial Programing Interface), the program can be
loaded to the microcontroller even after embedding the chip in the target device.
relative to ground, i.e. they are floating. If additional (external) memory is used, these pins are used for
accessing it. Signal on the ALE pin determines what and when will be transferred to this port.
Port 1 (P1.0-P1.7) If configured as outputs, each of these pins can be connected to up to 4 TTL inputs.
When configured as inputs, these pins act as standard TTL inputs, that is, each of them is internally
connected to the positive supply voltage via a resistor of relatively high impedance. Power supply voltage
provided on these inputs is 5V. Also, the Port 1 pins have alternate functions as shown in the table below:
Port Pin
Alternate Function
P1.0
T2 (Timer 2 input)
P1.1
T2EX (Timer 2 control input)
P1.4
SS (SPI system control input)
P1.5
MOSI (SPI system I/O)
P1.6
MISO (SPI system I/O)
P1.7
SCK (SPI system clock signal)
Port 2 (P2.0-P2.7) Whether configured as an input or an output, this port acts the same as Port 1. If
external memory is used, the high byte of the address (A8-A15) comes out on the Port 2 which is thus
used for addressing it.
Port 3 (P3.0-P3.7) Similar to P1, Port 3 pins can be used as general inputs or outputs. They also have
additional functions to be explained later in the chapter.
Port Pin
Alternate Function
P3.0
RXD (serial input)
P3.1
TXD (serial output)
P3.2
INT0 (external interrupt 0)
P3.3
INT1 (external interrupt 1)
P3.4
T0 (Timer 0 external input)
P3.5
T1 (Timer 1 external input)
P3.6
WR (External data memory write signal)
P3.7
RD (External data memory read signal)
RST Logic one (1) on this pin causes the microcontroller to be reset.
ALE/PROG In normal operation, the ALE pin is activated at a constant rate of 1/16 the oscillator
frequency and can be used for external clocking and timing purposes. When external memory is used, a
signal from this pin is used to latch the low byte of an address (A0-A7) from P0. During the process of
writing a program to the microcontroller, this pin also serves as a control input.
PSEN This pin provides a signal used for accessing external program memory (ROM).
EA/VPP When this pin is connected to ground, the microcontroller reads program instructions from
external program memory. If internal program memory is used, which is the common case, this pin
should be connected to the positive power supply voltage (VCC). During the process of programming
internal Flash mamory, this pin is supplied with +12V.
XTAL 1 This is internal oscillator input. It is used for the purpose of synchronizing the operation of the
microcontroller with some other circuit or for connecting external oscillator when used.
XTAL 2 This pin is connected to internal oscillator output. Therefore, it is out of use when using external
oscillator.
EEPROM Memory
EEPROM is a special type of memory having features of both RAM and ROM. The contents of the
EEPROM may be changed during operation, but remains permanently saved even after the loss of power.
The AT89S8253 microcontroller has in total of 2K of EEPROM, that is 2048 locations.
Memory Expansion
All mentioned above about ROM and RAM memory expansion remains in force when it comes to the
AT89S8253 microcontroller as it is based on the 8051 core. In other words, both memories can be added
as external chips with the capacity of up to 64Kb. The process of addressing is also the same as in the
8051 standard.
Types of addressing
Similar to all microcontrollers compatible with the 8051, there are two ways of addressing:
Direct addressing (for example: MOV A,30h); and
Indirect addressing (for example: MOV A,@R0).
As shown in the table above, each of these registers has its name and specific address in RAM.
Unoccupied locations are intended for the future upgraded versions of the microcontroller and shouldnt
be used. As their name suggests, these registers are mostly in control of one specific circuit within the
microcontroller such as timers or SPI etc. and they will be discussed later in the book. This chapter covers
only those SFRs controlling more than one circuit within the microcontroller.
Accumulator (ACC)
The accumulator, otherwise marked as ACC or A, belongs to the core registers of the 8051
microcontroller. Its contents is not modified.
B register
The B register also belongs to the core registers of the 8051 microcontroller. Bits of this register are not
modified. It is used during multiply and divide operations (MUL and DIV instructions) to store the
They belong to the core registers of the 8051 microcontroller. Their bits are not modified.
DISALE
o 0 - ALE is activated at a constant rate of 1/6 the oscillator frequency.
o 1 - ALE is active only during execution of MOVX or MOVC instructions.
Intel_Pwd_Exit
o 0 - When the microcontroller is in Power Down mode, the program proceeds with
execution on high-to-low transition (1-0).
o 1 - When the microcontroller is in Power Down mode, the program proceeds with
execution on low-to-high transition (0-1).
CLKREG register (Clock Register) X2
0 - The oscillator frequency (the XTAL1 pin) is divided by 2 before used as a clock (machine
cycle lasts for 6 such periods).
1 - Quartz oscillator is used as a clock generator. This enables the quartz crystal of two times
lower frequency (for example 6MHz instead of 12MHz) to be used for the same operating rate of
the microcontroller.
Data Pointers
Data Pointers are not true registers as they dont physically exist. They consist of two separate registers:
DPH (Data Pointer High) and DPL (Data Pointer Low). All 16 bits are used for addressing external and
internal EEPROM memory. The DPS bit of the EECON register determines the registers to be used as
data pointers:
DPS=0 -> Data pointer consists of DP0L and DP0H registers and is marked as DPTR0.
DPS=1 -> Data pointer consists of DP1L and DP1H registers and is marked as DPTR1.
EECON register
Bits of the EECON register controls the operation of EEPROM memory:
WRTINH
The WRTINH bit is read-only. When the power supply voltage is too low for programming EEPROM,
hardware automatically clears this bit, which means that write to EEPROM cannot be completed or is
aborted if in progress.
RDY/BSY
The RDY/BSY bit is read-only.
0 - Write in progress (takes approximately 4mS).
1 - Write complete (data is written to EEPROM).
DPS
0 - Address for EEPROM write/read is stored in the DP0H and DP0L registers.
1 - Address for EEPROM write/read is stored in the DP1H and DP1L registers.
EEMEN
0 - Instruction MOVX is used for accessing external memory chip.
1 - Instruction MOVX is used for accessing internal EEPROM memory. If the register address is
larger than 2K, the microcontroller will access external memory chip.
EEMWE
When set, the EEMWE bit enables write to EEPROM using the MOVX instruction. After completing
EEPROM write, the bit must be cleared from within the program.
EELD
When set, the EELD bit enables up to 32 bytes to be written simultaneously. The bit is set and the MOVX
instruction writes data to EEPROM (buffer is loaded). The bit is cleared before writing the last data.
When the last MOVX is executed, the entire buffer is automatically loaded to EEPROM for 4mS.
PS2,PS1,PS0
These three bits are in control of the prescaler and determine the nominal time of the watchdog timer. If
the program doesnt clear the WSWRST bit during that time, the watchdog timer will reset the
microcontroller. When all three bits are cleared to 0, the watchdog timer has a nominal period of 16K
machine cycles. When all three bits are set to 1, the nominal period is 2048K machine cycles.
WDIDLE
The WDIDLE bit enables/disables the watchdog timer in Idle mode:
0 - Watchdog timer is enabled in Idle mode (low-consumption mode).
1 - Watchdog timer is disabled in Idle mode.
DISRTO
The DISRTO bit enables/disables reset of peripheral circuits connected to the RST pin:
0 - Watchdog controls the state of the input reset pin. At the moment of reset, this pin acts for a
moment as an output and generates a logic one (1). It causes the microcontroller and all other
circuits connected to the RST pin to be reset.
1 - Reset triggered by the watchdog timer doesnt affect the state of the reset pin. At the moment
the watchdog timer resets the microcontroller, the reset pin remains configured as an input.
HWDT
The HWDT bit selects hardware or software mode for the watchdog timer:
0 - Watchdog is in software mode and can be enabled or disabled by the WDTEN bit.
1 - Watchdog is in hardware mode. To enable it, the sequence 1E/E1(hex) should be written to the
WDTRST register. Only reset condition can disable the watchdog timer. In order to prevent the
WCDT from resetting the microcontroller when the nominal time expires, the same sequence
1E/E1hex must be constantly repeated.
WSWRST
When set, this bit resets the watchdog timer in software mode (bit HWDT=0). In order to enable the
microcontroller to operate without being interrupted, this bit must regularly be cleared from within the
program. After being set, the watchdog timer is cleared by hardware, counting starts from zero and the bit
is automatically cleared.
If the watchdog timer is in hardware mode, setting this bit has no effect on the watchdog timer operation.
WDTEN
The WDTEN bit enables/disables the watchdog timer in software mode (HWDT=0):
0 - Watchdog disabled.
1 - Watchdog enabled.
When the watchdog timer is in hardware mode (HWDT=1), this bit is read-only and reflects the status of
the watchdog timer (whether it is enabled or disabled).
The WDTEN bit doesnt clear the watchdog timer, it only enables/disables it. This means that the current
state of the counter remains unchanged as long as WDTEN=0.
4.6 Interrupts
The AT89S8253 has in total of six interrupt sources, which means that it can recognize up to 6 different
events that can interrupt regular program execution. Each of these interrupts can be individually enabled
or disabled by setting bits of the IE register, whereas the whole interrupt system can be disabled by
clearing the EA bit of the same register.
Since this microcontroller has embedded Timer T2 and SPI (they don't fall under the 8051 Standard)
which can generate an interrupt, it was necessary to make some changes in registers controlling interrupt
system. Besides, there is a new interrupt vector (address 2B), i.e. program memory address from which
the program proceeds with execution when the Timer T2 generates an interrupt. All these changes are
made on the previously unused bits. This enables all programs written for the previous versions of the
microcontrollers to be used in this one too without being modified. This is why the 8051-based
microcontrollers are so popular.
0 - Priority 0
1 - Priority 1
PT1 Timer T1 interrupt priority:
0 - Priority 0
1 - Priority 1
PX1 External interrupt INT1 priority:
0 - Priority 0
1 - Priority 1
PT0 Timer T0 interrupt priority:
0 - Priority 0
1 - Priority 1
PX0 External interrupt INT0 priority:
0 - Priority 0
1 - Priority 1
IPH Register (Interrupt Priority High)
following occurs:
1. Instruction in progress is ended;
2. The address of the next instruction to execute is pushed onto the stack;
3. Depending on which interrupt is requested, one of five vectors (addresses) is written to the
program counter according to the table below:
Interrupt Source Jump Address
IE0
3h
TF0
Bh
IE1
13h
TF1
1Bh
RI, TI, SPIF
23h
TF2, EXF2
2Bh
All addresses are in hex format
Appropriate subroutines processing interrupts are stored at these addresses. Instead of them, there are
usually jump instructions specifying locations at which these subroutines reside.
4. When an interrupt routine is executed, the address of the next instruction to be executed is popped from
the stack to the program counter and the program proceeds from where it left off.
0 - Timer 2 disabled.
C/T2 is timer/counter 2 select bit used to select pulses to be counted by counter/timer 2:
1 - 16-bit register (T2H and T2L) counts pulses on the C/T2 pin (counter).
0 - 16-bit register (T2H and T2L) counts pulses from the oscillator (timer).
CP/RL2 is timer 2 capture/reload bit used to define transfer direction:
1 - If EXEN=1, pulse on the T2EX pin will cause a number to be transferred from counter to
capture register.
0 - Under the same condition, signal on the T2EX pin will cause a number to be transferred from
capture to counter register.
Timer T2 in Capture mode
If the CP/RL2 bit of the T2CON register is set, timer 2 operates according to the figure below. This is so
called Capture mode in which the value of the counter register (consisting of RCAP2H and RCAP2L)
can be captured and copied to the capture register (consisting of RCAP2H and RCAP2L), thus not
affecting the counting process. This is how it operates:
1. First, it is necessary to write a number from which the counting starts to a 16-bit register
(TH2+TL2).
2. Timer 2 is enabled by setting the TR2 bit of the TCON register. Each coming pulse increments the
number stored in the 16-bit register by 1. When both registers are loaded (decimal number 65536),
the first next pulse causes an overflow, reset occurs and counting starts from zero.
Settings:
As seen in figure above, unlike Capture mode, the contents of the capture register (RCAP2H, RCAP2L)
is now copied in the opposite direction upon an overflow occurs, from capture (RCAP2H, RCAP2L) to
counter register (TH2, TL2).
Settings of Auto Reload mode are shown in the table below:
All previously mentioned about timer 2 is in force only if the T2MOD register hasn't been changed, i.e. if
DCEN = 0. Otherwise, timer/counter is enabled to count in either direction, which depends on the T2EX
pin:
T2EX = 0 Timer 2 counts down
T2EX = 1 Timer 2 counts up
On counting up, the whole procedure is similar to the previous mode with one exception referring to the
function of the EXF2 bit.
On counting down, an overflow occurs when values stored in the counter and capture registers match. It
causes the TF2 bit as well as all bits of registers T2H and T2L to be set while the counter keeps on
counting down: 65535, 65534,65533...
In either case, the EXF2 bit is assigned a new function. When an overflow occurs, this bit inverts the
signal and cannot be used for generating an interrupt anymore. Instead, it serves as supplementary bit (the
17th bit) of the counter register, making this counter virtually a 17-bit register.
Timer T2 as a baud rate generator
The Timer T2 can be used as a baud rate generator and a clock generator simultaneously. If the RCLK or
TCLK bit of the register TCON is set, timer T2 turns into a clock generator, so called Baud Rate
generator). This mode is very similar to auto-reload mode. The baud rate is computed using the following
formula:
Multiprocessor Communication
Multiprocessor communication (the SM2 bit of the SCON register is set) enables automatic address
recognition by allowing the serial port to examine the adress of each incoming command. The process of
writing a program is much easier therefore as the microcontrollers sharing the same interface don't have
to check each address received via the serial port. Let's make it clear.
Two special function registers, SADDR and SADEN, enable multiprocessor communication. Each device
has an individual address that is specified in the SADDR register, while the so called mask address is
written to the SADEN register. The mask address contains don't care bits which provide the flexibility to
address one or more slaves at a time. In other words, it defines which bits of the SADDR register are to
be used and which are to be ignored.
When the master wants to transmit data to one of several slaves, it first sends out an address byte which
identifies the target device. An address byte differs from a data byte in that the 9th bit is 1 in an address
byte and 0 in a data byte. After receiving the address byte, all slaves check whether it matches their
address. The adressed slave clears its SM2 bit and prepares to receive the data bytes to come. The slaves
that weren't addressed leave their SM2 bits set and ignores the coming data bytes.
The most simple example is a mini-network comprising only 3 microcontrollers:
Microcontroller A is the master and communicates with devices B and C.
Microcontroller B: SADDR = 1100 0000
SADEN = 1111 1101
Address = 1100 00X0
Microcontroller C: SADDR = 1100 0000
SADEN = 1111 1110
Address = 1100 000X
Although both microcontrollers B and C are assigned the same address (1100 0000), the mask in register
SADEN is used to differentiate between them. It enables the master to communicate with both of them
separately or at the same time:
If transmit address is 1100 0010, the data will be sent to slave device B.
If transmit address is 1100 0001 the data will be sent to slave device C.
If transmit address is 1100 0000 the data will be sent to both slave devices.
doesnt fall into the 8051 Standard. It is SPI system which provides a high-speed synchronous data
transfer between the microcontroller and one or more peripheral devices or between multiple
microcontrollers. Here, one microcontroller is always considered main and is called master therefore. It
defines rate, transfer direction (whether data is to be transferred or received) and data format. The other is
slave device which is in subordinated position, which further means that it cannot start data transfer, but
has to adjust to conditions set by the master device.
The data are transferred via full duplex connection using 3 conductors connected to pins MISO (P1.6),
MOSI (P1.5) and SCK (P1.7). The forth pin-control pin SS- is not used on the master side and may be
used as a general-purpose input/output therefore, while on the slave side it must have voltage level 0.
When the SS pin on the slave side is set, its SPI system is deactivated and the MOSI pin can be used as a
general-purpose input.
As shown on the schematic, pins MISO and MOSI are configured differently in the master and slave
device (as inputs or outputs), which is determined by the MSTR bit of the SPCR register.
After sending one byte, the SPI clock generator stops, the SPIF bit (flag) is set, the received byte is
transferred to the SPDR register and, if enabled, an interrupt is generated.
Any attempt to write another byte to the SPDR register while byte transmit is in progress will cause the
WCOL bit to be set. It indicates that an error has occured. However, the byte will be succesfully
transmitted, while the new byte will be ignored, i.e. it will not be transmitted.
Enhanced SPI mode (buffer in use)
Enhanced mode is similar to normal except that this time data goes through one more register while being
transmitted. It makes no sense at first sight, but communication is really faster. Look at the figure below...
Data written to the SPI data register SPDR is automatically transferred to the capture register (buffer),
which causes the WCOL bit to be set. It means that the buffer is full and any further write will cause an
overflow. Control electronics (hardware) cleares this bit after transmitting data from buffer to the shift
register and after commencing serial data transmit. If the byte sent is the first, the data is immediately
transmitted to the shift register (still empty), thus clearing the WCOL bit (buffer is empty).
While one byte transmit is in progress, the next byte to transmit may be written to the SPDR register. It
will be immediately moved to buffer. In order to check whether data transmit is in progress, it is sufficient
to check the logic state of the LDEN bit of the SPSR register. If this bit is set (Load Enable) and the
WCOL bit is cleared, data transmit is in progress and buffer is empty so the next byte can be written to
the SPDR register.
How to select the right mode? If individual bytes are sent occasionally then there is no need to
complicate- the best solution is the normal mode. If it is necessary to send a great amounts of data, it is
better to use enhanced mode in which the clock oscillator is enabled as far as buffer is regularly loaded
and the WCOL bit is set. In addition, no time is needed for synchronization and data is easily and
efficiently transferred.
The SPI system is under control of 3 special function registers. These are SPDR, SPSR and SPCR.
SPDR (SPI Data Register)
The SPDR register is used for storing data to be transferred via SPI (in serial format). It is also used for
storing received data.
SPIF Interrupt flag. Upon data transfer, this bit is automatically set and an interrupt is generated if
SPIE=1 and ES=1. The SPIF bit is cleared by reading SPSR followed by reading/writing SPDR register.
WCOL This bit is set in normal mode (ENH=0) if the SPDR register is written during data transfer is in
progress. The write is premature and has no effect. It is called Write Collision. This bit is cleared in the
same manner as the SPIF bit.
The bit is set in enhanced mode (ENH=1) when buffer is full. It is indication that a new data is ready to
be transmitted to the shift register.
In enhanced mode, a new data can be written to buffer when the WCOL bit is set. In addition, the
WCOL bit must be cleared.
DISSO When set, this bit causes the MISO pin to float, thus enabling several slave microcontrollers to
share the same interface. Normally, the first byte, called address byte, is received by all of them, but only
one should clear its DISSO bit.
ENH
0 SPI system operates in normal mode (without buffer).
1 SPI system operates in enhanced mode.
SPCR (SPI Control Register)
SPIE When this bit is set, the SPI system can generate an interrupt.
SPE This bit enables SPI communication. When set, pins SS, MOSI, MISO and SCK are connected to
the microcontroller pins P1.4, P1.5, P1.6 and P1.7.
DORD Bit determines which bytes in serial communication are to be sent first:
0 - MSB bit is sent first.
1 - LSB bit is sent first.
If we neglect this detail, there is a risk that the program suddenly starts to perform unpredictably. In
order to prevent it, it is necessary to take care of the following:
If only registers R0-R7 from bank 0 are in use, everything is easily kept under control and program
memory locations from 08h to 1Fh are available for use. If registers, otherwise having the same names,
from some other bank are in use, you should be careful when using locations whose addresses are less
than 20h because it can cause R registers to be erased.
If bit-variables are not used in the program, program memory locations 20h-2Fh are available for use. If
the program contains bit-variables, you should be careful when using these location in order not to change
them accidentaly.
By default, the data pushed onto stack occupy program memory locations starting from 08h. If the banks
1, 2 or 3 are in use, their contents will be certainly erased. For this reason, it is recommended to set the
Stack Pointer value to be greater than 20h or even greater at the beginning of the program.
SFRs are used for controlling the microcontroller operation. Each of them has its specific purpose and it
should be observed. It means that they cannot be used as general purpose registers even in the event that
some of their locations is not occupied.
Instruction set, recognized by the microcontroller, contains instructions which can be used for controlling
individual bits of registers at program memory location 20h-7Fh. Besides, individual bits of some SFRs
(not all of them) can also be directly accessed. Addresses of these registers are divisible by 8.
If memory is expanded by adding external RAM or ROM memory chip, ports P0 and P2 are not available
for use regardless of how many pins are actually used for memory expansion.
The DPTR register is a 16-bit register comprised of registers DPH and DPL which are 8-bit wide each.
The DPTR register should be considered like that practically. For example, when pushing it onto the
Stack, DPL should be pushed first, then DPH.
When used, serial communication is under control of the SCON register. Besides, registers TCON and
TMOD should be configured for this purpose as well since the timer T1 is mostly used for boud rate
generation.
When some of the interrupts is enabled, you should be careful because there is a risk that program starts
to perform unexpectedly. When an interrupt request arrives, the microcontroller will execute instruction
in progress, push the address of the first following location onto the stack (in order to know from where to
continue) and jump to the specified interrupt routine address. When the routine has been executed, the
microcontroller will pop the address from the stack and continue from where it left off. However...
The microcontroller saves only the address to continue from after routine execution. What is usually
neglected is the fact that the contents of many registers can be changed during routine execution. The
program normally procedees with execution considering the changed registers correct if their original
vaules haven't been saved, thus causing a total chaos. The worst thing is that this problem can be
manifested anytime: at the moment or several days later (depending on the moment an interrupt occurs).
Obviously, the only solution is to save the state of all important registers at the beginning of interrupt
routine and to update these values before returning to the program. We are actually talking about the
following registers:
PSW
DPTR (DPH, DPL)
ACC
B
Registers R0 - R7
Note: Contents of registers are usually saved by being pushed onto the Stack using the PUSH instruction.
However, instructions such as PUSH R0 cannot be used here because the microcontroller doesnt
know which register is concerned as there are 4 banks with registers haing the same names R0-R7. For
this reason, it is necessary to save addresses of these registers instead of their names using the PUSH 00h
instruction.
When some of the instructions for indirect addressing is used, you should be careful not to use them for
accessing SFRs as the microcontroller ignores their addresses and accesses free RAM locations having
the same addresses as SFRs.
When UART system for serial communication is used, setting bits RI and TI of the SCON register
generated the same interrupt. If such an interrupt is generated, it is first necessary to detect interrupt
source (byte is sent, received or both). It is important to remember that the microcontroller only sets these
bits so that they must be cleared from within the program. Otherwise, the program gets stuck and
executes the same interrupt routine over and over again.
A list of bit-addressable registers
Accumulator (Address: E0)
AC After reset 0 0 0 0 0 0 0 0
C Bit name - - - - - - - Bit address E7 E6 E5 E4 E3 E2 E1 E0
B register (Address: F0)
After reset 0 0 0 0 0 0 0 0
Bit name - - - - - - - Bit address F7 F6 F5 F4 F3 F2 F1 F0
P After reset X X 0
0 0
0
0
0
Bit name - - PT2 PS PT1 PX1 PT0 PX0
Bit address BF BE BD BC BB BA B9 B8
Interrupt Enable register (Address: A8)
0 0
0
0
0
I After reset 0 X 0
E Bit name EA - ET2 ES ET1 EX1 ET0 EX0
Bit address AF AE AD AC AB AA A9 A8
Port 0 (Address: 80)
P After reset 1 1 1 1 1 1 1 1
0 Bit name - - - - - - - Bit address 87 86 85 84 83 82 81 80
Port 1 (Address: 90)
P After reset 1 1 1 1 1 1 1 1
1 Bit name - - - - - - - Bit address 97 96 95 94 93 92 91 90
Port 2 (Address: A0)
P After reset 1 1 1 1 1 1 1 1
2 Bit name - - - - - - - Bit address A7 A6 A5 A4 A3 A2 A1 A0
Port 3 (Address: B0)
P After reset 1 1 1 1 1 1 1 1
3 Bit name - - - - - - - Bit address B7 B6 B5 B4 B3 B2 B1 B0
Program Status Word (Address: D0)
0
0 0 0
PS After reset 0 0 0 0
W Bit name CY AC F0 RS1 RS0 OV - P
Bit address D7 D6 D5 D4 D3 D2 D1 D0
Serial Port Control register (Address: 98)
SCO
After reset 0
0
0
0
0
0
0 0
Bit name SM0 SM1 SM2 REN TB8 RB8 TI RI
Bit address 9F 9E 9D 9C 9B 9A 99 98
0
0
0
0 0 0 0
TCO After reset 0
N Bit name TF1 TR1 TF0 TR0 IF1 IT1 IF0 IT0
Bit address 8F 8E 8D 8C 8B 8A 89 88
Timer/Counter 2 Control register (Address: C8)
0
0
0
0
0
0
0
T2CO After reset 0
N
Bit name TF2 EXF2 RCLK TCLK EXEN2 TR2 C/T2 CP/RL2
Bit address CF CE CD
CC
CB
CA C9 C8
A list of non bit-addressable registers
Auxiliary register (Address: 8E)
AUX
After reset X X X X X X X
0
R
Bit name - - - - - - Intel_Pwd_Exit DISALE
Clock register (Address: 8F)
CLKRE
After reset X X X X X X X 0
G
Bit name - - - - - - - X2
Data Pointer 0 High (Address: 83)
DP0
After reset 0 0 0 0 0 0 0 0
H
Bit name - - - - - - - Data Pointer 0 Low (Address: 82)
DP0
After reset 0 0 0 0 0 0 0 0
L
Bit name - - - - - - - Data Pointer 1 High Byte (Address: 85)
DP1
After reset 0 0 0 0 0 0 0 0
H
Bit name - - - - - - - -
SPC
After reset 0
0
0
0
0
1
0
0
R
Bit name SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0
SPI Data register (Address: 86)
SPD
After reset - - - - - - - R
Bit name - - - - - - - SPI Status register (Address: AA)
SPS
After reset 0
0
0
---0
0
R
Bit name SPIF WCOL LDEN - - - DISSO ENH
Timer 2 Reload Capture High (Address: CB)
RCAP2
After reset 0 0 0 0 0 0 0 0
H
Bit name - - - - - - - Timer 2 Reload Capture Low (Address: CA)
RCAP2
After reset 0 0 0 0 0 0 0 0
L
Bit name - - - - - - - Timer 0 Low (Address: 8A)
TL
After reset 0 0 0 0 0 0 0 0
0
Bit name - - - - - - - Timer 1 Low (Address: 8B)
TL
After reset 0 0 0 0 0 0 0 0
1
Bit name - - - - - - - Timer 2 Low (Address: CC)
TL
After reset 0 0 0 0 0 0 0 0
2
Bit name - - - - - - - Timer 0 High Byte (Address: 8C)
TH
0 After reset 0 0 0 0 0 0 0 0
Parameter
VIL
Input Low-voltage
VIL1
VIH
Input High-voltage
VIH1
VOL
Output High-voltage
Condition
Min.
Max.
0.2Vcc All pins except EA
-0.5 V
0.1V
0.2Vcc -0.5 V
0.3V
All pins except XTAL1 0.2 Vcc Vcc +
and RST
+ 0.9V 0.5 V
Vcc +
0.7 Vcc
0.5 V
Iol = 10mA, Vcc =
0.4 V
IIL
Power-supply current
ICC
Power-down mode
4.0V, Ta = 85C
Ioh = -40mA, Ta =
85C
Ioh = -25mA, Ta =
85C
Ioh = -10mA, Ta =
85C
Vin = 0.45V, Vcc =
5.5V, Ta = -40C
0.45V < Vin < Vcc
2.4 V
0.75
Vcc
0.9 Vcc
- 50 A
50 K
f = 1Mhz, Ta = 25C
Normal mode: f =
12Mhz, Vcc = 5.5V Ta
= -40C
Idlle mode f = 12Mhz,
Vcc = 5.5V Ta = -40C
Vcc = 5.5V Ta = -40C
Vcc = 4V Ta = -40C
10 A
150 K
10 pF
25 mA
6.5 mA
100 A
40 A
Introduction
It was time that hardware-oriented to the core made compromise if they wanted to stay in the game.
Namely, unlike other circuits which only need to be connected to other components and powered in order to
be of any use, microcontrollers require to be programmed as well. Fortunately, they still didn't progress so far
in their evolution, so that all microcontroller families understand only one language - machine language.
That's a good thing. The bad one is that, even primitive, this language of zeros and ones can only be
understood by microcontrollers and some of the experts working on its development. In order to bridge this
gap between machine and humans, the first high-level programming language called Assembly language was
created.
The main problem of remembering codes recognized as instructions by electronics was solved therefore, but
another one, equally complicated to both us and them(microcontrollers) arose. This problem was also
easily solved by means of the program for a PC called assembler and a simple device called programmer.
This program enables the PC to receive commands in the form of abbreviations and convert them unerringly
into so called executable file. The moment of compiling a program into machine language is crucial as this
file, called HEX file, represents a series of binary numbers understandable to microcontrollers only. The
program written in assembly language cannot be executed practically unless this file is loaded into the
microcontroller memory. This is the moment when the last link in the chain - the programmer - appears on
the scene. It is a small device connected to a PC via some of the ports and has a socket for placing chip in.
Directives; and
Comments.
Numbers
If octal number system, otherwise considered as obsolite, is disregarded, assembly laguage allows numbers
to be used in one out of three number systems:
Decimal Numbers
If not stated otherwise, the assembly language considers all the numbers as decimal. All ten digits are used
(0,1,2,3,4,5,6,7,8,9). Since at most 2 bytes are used for saving them in the microcontroller, the largest
decimal number that can be written in assembly language is 65535. If it is necessary to specify that some of
the numbers is in decimal format, then it has to be followed by the letter D. For example 1234D.
Hexadecimal Numbers
Hexadecimal numbers are commonly used in programming. There are 16 digits in hexadecimal number
system (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F). The largest hexadecimal number that can be written in
assembly language is FFFF. It corresponds to decimal number 65535. In order to distinguish hexadecimal
numbers from decimal, they are followed by the letter h(either in upper- or lowercase). For example 54h.
Binary Numbers
Binary numbers are often used when the value of each individual bit of some of the registers is important,
since each binary digit represents one bit. There are only two digits in use (0 and 1). The largest binary
number written in assembly language is 1111111111111111. In order to distinguish binary numbers from
other numbers, they are followed by the letter b (either in upper- or lowercase). For example 01100101B.
Operators
Some of the assembly-used commands use logical and mathematical expessions instead of symbols having
specific values. For example:
IF (VERSION>1)
LCALL Table_2
USING VERSION+1
ENDIF
...
As seen, the assembly language is capable of computing some values and including them in a program code,
thus using the following mathematical and logical operations:
Name
Operation
Example
Result
+
Addition
10+5
15
Subtraction
25-17
8
*
Multiplication
7*4
28
/
Division (with no remainder)
7/4
1
MOD Remainder of division
7 MOD 4
3
SHR Shift register bits to the right
1000B SHR 2
0010B
SHL Shift register bits to the left
1010B SHL 2
101000B
NOT Negation (first complement of number) NOT 1
1111111111111110B
AND Logical AND
1101B AND 0101B 0101B
OR
Logical OR
1101B OR 0101B 1101B
XOR Exclusive OR
1101B XOR 0101B 1000B
LOW 8 low significant bits
LOW(0AADDH) 0DDH
HIGH 8 high significant bits
HIGH(0AADDH) 0AAH
EQ, = Equal
7 EQ 4 or 7=4
0 (false)
NE,<> Not equal
7 NE 4 or 7<>4
0FFFFH (true)
GT, > Greater than
7 GT 4 or 7>4
0FFFFH (true)
GE, >= Greater or equal
7 GE 4 or 7>=4
0FFFFH (true)
LT, < Less than
7 LT 4 or 7<4
0 (false)
LE,<= Less or equal
7 LE 4 or 7<=4
0 (false)
Symbols
Every register, constant, address or subroutine can be assigned a specific symbol in assembly language,
which considerably facilitates the process of writing a program. For example, if the P0.3 input pin is
connected to a push button used to stop some process manually (push button STOP), the process of writing a
program will be much simpler if the P0.3 bit is assigned the same name as the push button, i.e.
pushbutton_STOP. Of course, like in any other language, there are specific rules to be observed as well:
For the purpose of writing symbols in assembly language, all letters from alphabet (A-Z, a-z),
decimal numbers (0-9) and two special characters ("?" and "_") can be used. Assembly language is
not case sensitive.
For example, the following symbols will be considered identical:
Serial_Port_Buffer
SERIAL_PORT_BUFFER
In order to distinguish symbols from constants (numbers), every symbol starts with a letter or one of
two special characters (? or _).
The symbol may consist of maximum of 255 characters, but only first 32 are taken into account. In
the following example, the first two symbols will be considered duplicate (error), while the third and
forth symbols will be considered different:
START_ADDRESS_OF_TABLE_AND_CONSTANTS_1
START_ADDRESS_OF_TABLE_AND_CONSTANTS_2
TABLE_OF_CONSTANTS_1_START_ADDRESS
TABLE_OF_CONSTANTC_2_START_ADDRESS
Some of the symbols cannot be used when writing a program in assembly language because they are
already part of instructions or assembly directives. Thus, for example, a register or subroutine cannot
be assigned name A or DPTR because there are registers having the same name.
Here is a list of symbols not allowed to be used during programming in assembly language:
A
ADDC
AR0
AR4
BIT
CJNE
CSEG
DBIT
DPTR
END
GT
ISEG
JMP
JZ
LOW
MOVC
NOP
ORL
R0
R4
RET
RR
AB
ACALL ADD
AJMP AND ANL
AR1
AR2
AR3
AR5
AR6
AR7
BSEG C
CALL
CLR
CODE CPL
DA
DATA DB
DEC DIV
DJNZ
DS
DSEG DW
EQ
EQU
GE
HIGH IDATA INC
JB
JBC
JC
JNB
JNC
JNZ
LCALL LE
LJMP
LT
MOD MOV
MOVX MUL NE
NOT OR
ORG
PC
POP
PUSH
R1
R2
R3
R5
R6
R7
RETI RL
RLC
RRC SET
SETB
SHL
SHR
SJMP
SWAP USING XCH
XDATA XOR XRL
SUBB
XCHD
XSEG
Labels
A label is a special type of symbols used to represent a textual version of an address in ROM or RAM
memory. They are always placed at the beginning of a program line. It is very complicated to call a
subroutine or execute some of the jump or branch instructions without them. They are easily used:
A symbol (label) with some easily recognizable name should be written at the beginning of a program
line from which a subroutine starts or where jump should be executed.
It is sufficient to enter the name of label instead of address in the form of 16-bit number in
instructions calling a subroutine or jump.
During the process of compiling, the assembler automatically replaces such symbols with appropriate
addresses.
Directives
Unlike instructions being compiled and written to chip program memory, directives are commands of
assembly language itself and have no influence on the operation of the microcontroller. Some of them are
obligatory part of every program while some are used only to facilitate or speed up the operation.
Directives are written in the column reserved for instructions. There is a rule allowing only one directive per
program line.
EQU directive
The EQU directive is used to replace a number by a symbol. For example:
MAXIMUM EQU 99
After using this directive, every appearance of the label MAXIMUM in the program will be interpreted by
the assembler as the number 99 (MAXIMUM = 99). Symbols may be defined this way only once in the
program. The EQU directive is mostly used at the beginning of the program therefore.
SET directive
The SET directive is also used to replace a number by a symbol. The significant difference compared to the
EQU directive is that the SET directive can be used an unlimited number of times:
SPEED SET 45
SPEED SET 46
SPEED SET 57
BIT directive
The BIT directive is used to replace a bit address by a symbol. The bit address must be in the range of 0 to
255. For example:
TRANSMIT BIT PSW.7 ;Transmit bit (the seventh bit in PSW register)
;is assigned the name "TRANSMIT"
OUTPUT BIT 6 ;Bit at address 06 is assigned the name "OUTPUT"
RELAY BIT 81 ;Bit at address 81 (Port 0)is assigned the name ;"RELAY"
CODE directive
The CODE directive is used to assign a symbol to a program memory address. Since the maximum capacity
of program memory is 64K, the address must be in the range of 0 to 65535. For example:
RESET CODE 0 ;Memory location 00h called "RESET"
TABLE CODE 1024 ;Memory location 1024h called "TABLE"
DATA directive
The DATA directive is used to assign a symbol to an address within internal RAM. The address must be in
the range of 0 to 255. It is possible to change or assign a new name to any register. For example:
TEMP12 DATA 32 ;Register at address 32 is named ;as "TEMP12"
STATUS_R DATA D0h ;PSW register is assigned the name ;"STATUS_R"
IDATA directive
The IDATA directive is used to change or assign a new name to an indirectly addressed register. For
example:
TEMP22 IDATA 32 ;Register whose address is in register ;at address 32 is named as
"TEMP22"
TEMP33 IDATA T_ADR ;Register whose address is in ;register T_ADR is named as "TEMP33"
XDATA directive
The XDATA directive is used to assign a name to registers within external (additional) RAM memory. The
addresses of these registers cannot be larger than 65535. For example:
TABLE_1 XDATA 2048 ;Register stored in external
;memory at address 2048 is named
;as "TABLE_1"
ORG directive
The ORG directive is used to specify a location in program memory where the program following directive is
to be placed. For example:
BEGINNING ORG 100
...
...
ORG 1000h
TABLE
...
...
This program starts at location 100. The table containing data is to be stored at location 1024 (1000h).
USING directive
The USING directive is used to define which register bank (registers R0-R7) is to be used in the program.
USING
USING
USING
USING
0
1
2
3
;Bank
;Bank
,Bank
;Bank
0
1
2
3
is
is
is
is
used
used
used
used
(registers
(registers
(registers
(registers
R0-R7
R0-R7
R0-R7
R0-R7
at
at
at
at
RAM-addresses
RAM-addresses
RAM-addresses
RAM-addresses
0-7)
8-15)
16-23)
24-31)
END directive
The END directive is used at the end of every program. The assembler will stop compiling once the program
encounters this directive. For example:
...
END ;End of program
The CSEG segment is activated by default after enabling the assembler and remains active until a new
directive is specified. Each of these memory segments has its internal address counter which is cleared every
time the assembler is activated. Its value can be changed by specifying value after the mark AT. It can be a
number, an arithmetical operation or a symbol. For example:
DSEG
;Next segment refers to directly accessed registers; and
BSEG AT 32 ;Selects bit-addressable part of memory with address counter
;moved by 32 bit locations relative to the beginning of that
;memory segment.
A dollar symbol "$" denotes current value of address counter in the currently active segment. The following
two examples illustrate how this value can be used practically:
Example 1:
JNB FLEG,$ ;Program will constantly execute this
;instruction (jump instruction),until
;the flag is cleared.
Example 2:
MESSAGE DB ALARM turn off engine
LENGTH EQU $-MESSAGE-1
These two program lines can be used for computing exact number of characters in the message ALARM
turn off engine which is defined at the address assigned the name MESSAGE.
DS directive
The DS directive is used to reserve memory space expressed in bytes. It is used if some of the following
segments ISEG, DSEG or XSEG is currently active. For example:
Example 1:
DSEG
;Select directly addressed part of RAM
DS 32
;Current value of address counter is incremented by 32
SP_BUFF DS 16 ;Reserve space for serial port buffer
;(16 bytes)
IO_BUFF DS 8 ;Reserve space for I/O buffer in size of 8 bytes
Example 2:
ORG 100
;Start at address 100
DS 8
;8 bytes are reserved
LAB ......... ;Program proceeds with execution (address of this location is 108)
DBIT directive
The DBIT directive is used to reserve space within bit-addressable part of RAM. The memory size is
expressed in bits. It can be used only if the BSEG segment is active. For example:
BSEG ;Bit-addressable part of RAM is selected
IO_MAP DBIT 32 ;First 32 bits occupy space intended for I/O buffer
DB directive
The DB directive is used for writing specified value into program memory. If several values are specified,
then they are separated by a comma. If ASCII array is specified, it should be enclosed within single quotation
marks. This directive can be used only if the CSEG segment is active. For example:
CSEG
DB 22,33,Alarm,44
If this directive is preceeded by a lable, then the label will point to the first element of the array. It is the
number 22 in this example.
DW directive
The DW directive is similar to the DB directive. It is used for writing a two-byte value into program
memory. The higher byte is written first, then the lower one.
IF, ENDIF and ELSE directives
These directives are used to create so called conditional blocks in the program. Each of these blocks starts
with directive IF and ends with directive ENDIF or ELSE. The statement or symbol (in parentheses)
following the IF directive represents a condition which specifies the part of the program to be compiled:
If the statement is correct or if the symbol is equal to one, the program will include all instructions up
to directive ELSE or ENDIF.
If the statement is not correct or if the symbol value is equal to zero, all instructions are ignored, i.e.
not compiled, and the program continues with instructions following directives ELSE or ENDIF.
Example 1:
IF (VERSION>3)
LCALL Table_2
LCALL Addition
ENDIF
...
If the program is of later date than version 3 (statement is correct), subroutines Table 2 and Addition will
be executed. If the statement in parentheses is not correct (VERSION<3), two instructions calling
subroutines will not be compiled.
Example 2:
If the value of the symbol called Model is equal to one, the first two instructions following directive IF will
be compiled and the program continues with instructions following directive ENDIF (all instructions
between ELSE and ENDIF are ignored). Otherwise, if Model=0, instructions between IF and ELSE are
ignored and the assembler compiles only instructions following directive ELSE.
IF (Model)
MOV R0,#BUFFER
MOV A,@R0
ELSE
MOV R0,#EXT_BUFFER
MOVX A,@R0
ENDIF
...
Control directives
Control directives start with a dollar symbol $. They are used to determine which files are to be used by the
assembler during compilation, where the executable file is to be stored as well as the final layout of the
compiled program called Listing. There are many control directives, but only few of them is of importance:
\$INCLUDE directive
This directive enables the assembler to use data stored in other files during compilation. For example:
\$INCLUDE(TABLE.ASM)
\$MOD8253 directive
This $MOD8253 directive is a file containing names and addresses of all SFRs of 8253 microcontrollers. By
means of this file and directive having the same name, the assembler can compile the program on the basis of
register names. If they are not used, it is necessary to specify name and address of every SFRs to be used at
the beginning of the program.
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 provide basic information about microcontrollers that one needs to know in
order to be able to use them successfully in practice. This is why this chapter doesn't contain any super
interesting program or device schematic with amazing solutions. Instead, the following examples are better
proof that program writing is neither a privilege nor a talent issue, but the ability of simply putting puzzle
pieces together using directives. Rest assured that design and development of devices mainly consists of the
following method test-correct-repeat. Of course, the more you are in it, the more complicated it becomes
since the puzzle pieces are put together by both children and first-class architects...
As seen in the figure above, in order to enable the microcontroller to operate properly it is necessary to
provide:
Power supply:
Reset signal: and
Clock signal.
Clearly, it is about very simple circuits, but it does not have to be always like that. If the target device is used
for controlling expensive machines or maintaining vital functions, everything gets increasingly complicated.
However, this solution is sufficient for the time being...
Power supply
Even though this microcontroller can operate at different power supply voltages, why to test Murphys
low?! A 5V DC is most commonly used. The circuit, shown in the figure, uses a cheap integrated threeterminal positive regulator LM7805, and provides high-quality voltage stability and quite enough current to
enable the microcontroller and peripheral electronics to operate normally (enough current in this case means
1Amp).
Reset signal
In order that the mucrocontroller can operate properly, a logic 0 (0V) must be applied to the reset pin RS.
The push button connecting the reset pin RS to power supply VCC is not necessary. However, it is almost
always provided because it enables the microcontroller safe return to normal operating conditions if
something goes wrong. 5V is brought to this pin, the microcontroller is reset and program starts execution
from the beginning.
Clock signal
Even though the microcontroller has a built-in oscillator, it cannot operate without two external capacitors
and quartz crystal which stabilize its operation and determines its frequency (operating speed of the
microcontroller).
Of course, it is not always possible to apply this solution so that there are always alternative ones. One of
them is to provide clock signal from a special source through invertor. See the figure on the left.
Nevertheless, it is not so simple in practice... It is about contact bounce- a common problem with m e c h a n
i c a l switches. When the contacts strike together, their momentum and elasticity act together to cause
bounce. The result is a rapidly pulsed electrical current instead of a clean transition from zero to full current.
It mostly occurs due to vibrations, slight rough spots and dirt between contacts. This effect is usually
unnoticeable when using these components in everyday life because the bounce happens too quickly. In other
words, the whole this process does not last long (a few micro- or miliseconds), but it is long enough to be
registered by the microcontroller. When using only a push-button as a pulse counter, errors occur in almost
100% of cases!
The simplest solution to this problem is to connect a simple RC circuit to suppress quick voltage changes.
Since the bounce period is not defined, the values of components are not precisely determined. In most cases,
it is recomended to use the values shown in figure below.
If complete stability is needed then radical measures should be taken. The output of the circuit, shown in
figure (RS flip-flop), will change its logic state only after detecting the first pulse triggered by contact
bounce. This solution is expensive (SPDT switch), but effecient, the problem is definitely solved. Since the
capacitor is not used, very short pulses can also be registered in this way.
In addition to these hardware solutions, there is also a simple software solution. When a program tests the
state of an input pin and detects a change, the check should be done one more time after a certain delay. If the
change is confirmed, it means that a switch or push button has changed its position. The advantages of such
solution are obvious: it is free of charge, effects of noises are eliminated and it can be applied to the poorer
quality contacts as well. Disadvantage is the same as when using RC filter, i.e. pulses shorter than program
delay cannot be registered.
Optocoupler
An optocoupler is a device commonly used to galvanically separate microcontrollers electronics from any
potentially dangerous current or voltage in its surroundings. Optocouplers usually have one, two or four light
sources (LED diodes) on their input while on their output, opposite to diodes, there is the same number of
elements sensitive to light (phototransistors, photo-thyristors or photo-triacs). The point is that an
optocoupler uses a short optical transmission path to transfer a signal between the elements of circuit, while
keeping them electrically isolated. This isolation makes sense only if diodes and photo-sensitive elements are
separately powered. In this way, the microcontroller and expensive additional electronics are completely
protected from high voltage and noises which are the most common cause of destroying, damaging or
unstable operation of electronic devices in practice. The most frequently used optocouplers are those with
phototransistors on their outputs. When using the optocoupler with internal base-to-pin 6 connection (there
are also optocouplers without it), the base can be left unconnected. An optional connection which lessens the
effects of noises by eliminating very short pulses is presented by the broken line in the figure.
Relay
A relays is an electrical switch that opens and closes under control of another electrical circuit. It is therefore
connected to ouput pins of the microcontroller and used to turn on/off high-power devices such as motors,
transformers, heaters, bulbs, antenna systems etc. These are almost always placed away from the board
sensitive components. There are various types of relays but all of them operate in the same way. When a
current flows through the coil, the relay is operated by an electromagnet to open or close one or many sets of
contacts. Similar to optocouplers, there is no galvanic connection (electrical contact) between input and
output circuits. Relays usually demand both higher voltage and current to start operation, but there are also
miniature ones which can be activated by a low current directly obtained from a microcontroller pin.
The figure shows the solution specific to the 8051 microcontroller. A darlington transistor is used here to
activate relays because of its high current gain. This is not in accordance with rules, but is necessary in the
event that logic one activation is applied since the output current is then very low (pin acts as an input).
In order to prevent the appearance of self-induction high voltage, 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 diode (LED)
Light-emitting diodes are elements for light signalization in electronics. They are manufactured in different
shapes, colors and sizes. For their low price, low power 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 limit their current, otherwise they will be permanently destroyed. For this reason, a
conductor must be connected in parallel to an LED. In order to determine value of this conductor, it is
necessary to know diodes voltage drop in forward direction, which depends on what material a diode is
made from and what colour it is. Typical values of 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.
Color
Type
Typical current Id (mA) Maximal current If (mA) Voltage drop Ud (V)
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 microcontroller can provide only low output current and since its pins are configured as
outputs when voltage provided on them is 0V, direct connecting to LEDs is performed as shown in figure on
the right (Low current LED, cathode is connected to the output pin).
LED displays
Basically, an LED display is nothing more than several LEDs moulded in the same plastic case. There are
many types of displays composed of several dozens of built in diodes which can display different symbols.
Most commonly used is a so called 7-segment display. It is composed of 8 LEDs, 7 segments are arranged as
a rectangle for symbol displaying and there is an 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 anode displays and common catode displays, respectively. Segments are marked with the latters
from A to G, plus dp, as shown in the figure on the left. On connecting, each diode is treated separtely, which
means that each must have its own current limiting resistor.
Displays connected to the microcontroller usually occupy a large number of valuable I/O pins, which can be
a big problem especially if it is needed to display multy digit numbers. The 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 in this case). The solution to this problem is called MULTIPLEXING. This is how an optical illusion
based on the same operating principle as a film camera is made. Only one digit is active at a time, but they
change their state so quickly making impression that all digits of a number are simultaneously active.
Here is an explanation on the figure above. First a byte representing units is applied on a microcontroller port
and a 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 a transistor T2 is activated. This process is being cyclically
repeated at high speed for all digits and corresponding transistors.
The fact that the microcontroller is just a kind of miniature computer designed to understand only the
language of zeros and ones is fully expressed when displaying any digit. Namely, the microcontroller doesn't
know what units, tens or hundreds are, nor what ten digits we are used to look like. Therefore, each number
to be displayed must be prepared in the following way:
First of all, a multy digit number must be split into units, tens etc. in a particular subroutine. Then each of
these digits must be stored in special bytes. Digits get familiar format by performing masking. In other
words, a binary format of each digit is replaced by a different combination of bits in a simple subroutine. For
example, the digit 8 (0000 1000) is replaced by the binary number 0111 111 in order to activate all LEDs
displaying digit 8. The only diode remaining inactive in this case is reserved for the decimal point. If a
microcontroller port is connected to the display in such a way that bit 0 activates segment a, bit 1 activates
segment b, bit 2 segment c etc., then the table below shows the mask for each digit.
The model described here is for its low price and great capabilities 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 the letters of alphabet, Greek letters, punctuation marks, mathematical symbols etc. In
addition, it is possible to display symbols made up by the user. Other useful features include automatic
message shift (left and right), cursor appearance, LED backlight etc.
LCD Pins
There are pins along one side of a small printed board. These are used for connecting to the microcontroller.
There are in total of 14 pins marked with numbers (16 if it has backlight). Their function is described in the
table bellow:
Function
Ground
Power supply
Contrast
An LCD screen consists of two lines each containing 16 characters. Each character consists of 5x8 or 5x11
dot matrix. This book covers the most commonly used display, i.e. the 5x8 character display.
Display contrast depends on the power supply voltage and whether messages are displayed in one or two
lines. For this reason, varying voltage 0-Vdd is applied on the pin marked as Vee. Trimmer potentiometer is
usually used for that purpose. Some LCD displays have built-in backlight (blue or green LEDs). When used
during operation, a current limiting resistor should be serially connected to one of the pins for backlight
power supply (similar to LEDs).
If there are no characters displayed or if all of them are dimmed when the display is on, the first thing that
should be done is to check the potentiometer for contrast regulation. Is it properly adjusted? The same
applies if the mode of operation has been changed (writing in one or two lines).
LCD Memory
The LCD display contains three memory blocks:
DDRAM Display Data RAM;
CGRAM Character Generator RAM; and
CGROM Character Generator ROM.
DDRAM Memory
DDRAM memory is used for storing characters to be displayed. The size of this memory is sufficient for
storing 80 characters. Some memory locations are directly connected to the characters on display.
It works quite simply: it is sufficient to configure the display so as to increment addresses automatically
(shift right) and set the starting address for the message that should be displayed (for example 00 hex).
After that, all characters sent through lines D0-D7 will be displayed in the message format we are used tofrom left to right. In this case, displaying starts from the first field of the first line since the address is 00 hex.
If more than 16 characters are sent, then all of them will be memorized, but only the first sixteen characters
will be visible. In order to display the rest of them, a shift command should be used. Virtually, everything
looks as if the LCD display is a window which moves left-right over memory locations containing
different characters. This is how the effect of message moving on the screen is made.
If the cursor is on, it appears at the location which is currently addressed. In other words, when a character
appears at the cursor position, it will automatically move to the next addressed location.
Since this is a sort of RAM memory, data can be written to and read from it, but its contents is irretrievably
lost when the power goes off.
CGROM Memory
CGROM memory contains the default chracter map with all characters that can be displayed on the screen.
Each character is assigned to one memory location.
The addresses of CGROM memory locations match the characters of ASCII. If the program being currently
executed encounters a command send character P to port, then the binary value 0101 0000 appears on the
port. This value is the ASCII equivalent to the character P. It is then written to LCD, which results in
displaying the symbol from 0101 0000 location of CGROM. In other words, the character P is displayed.
This applies to all letters of alphabet (capitals and small), but not to numbers.
As seen on the previous map, addresses of all digits are pushed forward by 48 relative to their values (digit
0 address is 48, digit 1 address is 49, digit 2 address is 50 etc.). Accordingly, in order to display digits
correctly, each of them needs to be added a decimal number 48 prior to be sent to LCD.
From their inception till today, computers can recognize only numbers, but not letters. It means that all data a
computer swaps with a peripheral device has a binary format, even though the same is recognized by the man
as letters (keyboard is an excellent example). Every character matches the unique combination of zeroes and
ones. ASCII is character encoding based on the English alphabet. ASCII code specifies correspondance
between standard character symbols and their numerical equivalents.
CGRAM memory
Apart from standard characters, the LCD display can also display symbols defined by the user itself. It can be
any symbol in the size of 5x8 pixels. RAM memory called CGRAM in the size of 64 bytes enables it.
Memory registers are 8 bits wide, but only 5 lower bits are used. Logic one (1) in every register represents a
dimmed dot, while 8 locations grouped together represent one character. It is best illustrated in figure below:
Symbols are usually defined at the beginnig of the program by simply writing zeros and ones to registers of
CGRAM memory so that they form desired shapes. In order to display them it is sufficient to specify their
address. Pay attention to the first coloumn in the CGROM map of characters. It doesn't contain RAM
memory addresses, but symbols being discussed here. In this example, display 0 means - display ,
display 1 means - display etc.
LCD Basic Commands
All data transferred to LCD through the outputs D0-D7 will be interpreted as a command or a data, which
depends on the pin RS logic state:
RS = 1 - Bits D0-D7 are addresses of the characters to be displayed. LCD processor addresses one character
from the character map and displays it. The DDRAM address specifies the location on which the character is
to be displayed. This address is defined before the character is transferred or the address of previously
transferred character is automatically incremented.
RS = 0 - Bits D0 - D7 are commands which determine the display mode. The commands recognized by the
LCD are given in the table below:
Command
Clear display
RS RW D7 D6 D5 D4 D3 D2 D1 D0 Execution Time
0 0 0 0 0 0 0 0 0 1 1.64mS
Cursor home
0
Entry mode set
0
Display on/off control
0
Cursor/Display Shift
0
Function set
0
Set CGRAM address
0
Set DDRAM address
0
Read BUSY flag (BF)
0
Write to CGRAM or DDRAM 1
Read from CGRAM or DDRAM 1
0
0
0
0
0
0
0
1
0
1
0 0 0 0 0 0 1 x 1.64mS
0 0 0 0 0 1 I/D S 40uS
0 0 0 0 1 D U B 40uS
0 0 0 1 D/C R/L x x 40uS
0 0 1 DL N F x x 40uS
0 1 CGRAM address
40uS
1 DDRAM address
40uS
BF DDRAM address
D7 D6 D5 D4 D3 D2 D1 D0 40uS
D7 D6 D5 D4 D3 D2 D1 D0 40uS
S 1 = Display shift on
0 = Display shift off
DL 1 = 8-bit interface
0 = 4-bit interface
D 1 = Display on
0 = Display off
U 1 = Cursor on
0 = Cursor off
B 1 = Cursor blink on
0 = Cursor blink off
Fortunately, there is a simple solution. After sending a character or a command it is important to give the
LCD enough time to do its job. Owing to the fact that execution of the slowest command lasts for
approximately 1.64mS, it will be sufficient to wait approximately 2mS for LCD.
LCD Initialization
The LCD is automatically cleared when powered up. It lasts for approximately 15mS. After that, the display
is ready for operation. The mode of operation is set by default. It 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 Displayed addresses are automatically incremented by 1
o S = 0 Display shift off
Automatic reset is in most cases performed without any problems. In most cases, but not always! If for any
reason the power supply voltage does not reach ful value within 10mS, the display will start to perform
completely unpredictably. If the voltage supply unit is not able to meet this condition or if it is needed to
provide completely safe operation, the process of initialization is applied. Initialization, among other things,
causes a new reset enabling display to operate normally.
Refer to the figure below for the procedure on 8-bit initialization:
It is not a mistake!
In this algorithm, the same value is transferred three times in a row.
In case of 4-bit initialization, the procedure is as follows:
6.3 Examples
The schematic below is used in the several following examples:
Apart from components necessary for the operation of the microcontroller such as oscillator with capacitors
and the simplest reset circuit, there are also several LEDs and one push button. These are used to indicate the
operation of the program.
All LEDs are polarized in such a way that they are activated by driving a microcontroller pin low (logic 0).
LED Blinking
The purpose of this example is not to demonstrate the operation of LEDs, but the operating speed of the
microcontroller. Simply put, in order to enable LED blinking to be visible, it is necessary to provide
sufficient amount of time to pass between on/off states of LEDs. In this example time delay is provided by
executing a subroutine called Delay. It is a triple loop in which the program remains for approximately 0.5
seconds and decrements values stored in registers R0, R1 or R2. After returning from the subroutine, the pin
state is inverted and the same procedure is repeated...
;************************************************************************
;* PROGRAM NAME : Delay.ASM
;* DESCRIPTION: Program turns on/off LED on the pin P1.0
;* Software delay is used (Delay).
;************************************************************************
;BASIC DIRECTIVES
$MOD53
$TITLE(DELAY.ASM)
$PAGEWIDTH(132)
$DEBUG
$OBJECT
$NOPAGING
;STACK
DSEG
STACK_START:
AT
DS
;RESET VECTORS
CSEG
JMP
AT
0
XRESET
ORG
XRESET: MOV
MOV
03FH
040H
;Reset vector
100H
SP,#STACK_START
P1,#0FFh
CPL
LCALL
SJMP
P1.0
Delay
LOOP
MOV
MOV
MOV
DJNZ
DJNZ
DJNZ
R2,#20
R1,#50
R0,#230
R0,$
R1,F01
R2,F02
LOOP:
Delay:
F02:
F01:
END
;End of program
DATA
EQU
EQU
96H
00000001B
11000000B
;RESET
VECTOR
CSEG
JMP
AT
XRESET
; Reset vector
CSEG
ORG
100H
ORL
ORL
WMCON,#PERIOD
WMCON,#WDTEN
MOV
A,R3
; R3 is moved to port 1
XRESET:
LAB:
MOV
INC
P1,A
R3
; Register R3 is incremented by 1
SJMP
LAB
END
; End of program
Timer T0 in mode 1
This program spends most of its time in an endless loop waiting for timer T0 to count up a full cycle. When it
happens, an interrupt is generated, routine TIM0_ISR is executed and logic zero (0) on port P1 is shifted right
by one bit. This is another way of demonstrating the operating speed of the microcontroller since each shift
means that counter T0 has counted up 216 pulses!
;************************************************************************
;* PROGRAM NAME : Tim0Mod1.ASM
;* DESCRIPTION: Program rotates "0" on port 1. Timer T0 in mode 1 is
;* used
;************************************************************************
;BASIC DIRECTIVES
$MOD53
$TITLE(TIM0MOD1.ASM)
$PAGEWIDTH(132)
$DEBUG
$OBJECT
$NOPAGING
;DECLARATION OF VARIABLES
;STACK
DSEG
STACK_START:
AT
DS
03FH
040H
;RESET VECTORS
CSEG
JMP
AT 0
XRESET
; Reset vector
ORG
JMP
00BH
TIM0_ISR
ORG
100H
XRESET: MOV
MOV
MOV
MOV
SETB
MOV
CLR
SP,#STACK_START
TMOD,#01H
A,#0FFH
P1,#0FFH
TR0
IE,#082H
C
LOOP1: SJMP
LOOP1
; Remain here
TIM0_ISR:
RRC
MOV
RETI
END
A
P1,A
; Timer T0 is enabled
; Interrupt enabled
The first interrupt is generated after timer T0 reset. Routine TIM0_ISR in which logic zero (0) bit on port P1
rotates is executed. Outside looking, it seems that LEDs move.
Another interrupt is generated upon Timer T1 reset. Routine TIM1_ISR in which the bit state DIRECTION
inverts is executed. Since this bit determines direction of bit rotation then the moving direction of LED is
also changed.
If you press a push button T1 at some point, a logic zero (0) on the P3.2 output will disable Timer T1.
;************************************************************************
;* PROGRAM NAME : Split.ASM
;* DESCRIPTION: Timer TL0 rotates bit on port P1, while TL1 determines
;* the rotation direction. Both timers operate in mode
;* 3. Logic zero (0) on output P3.2 disables rotation on port P1.
;************************************************************************
;BASIC DIRECTIVES
$MOD53
$TITLE(SPLIT.ASM)
$PAGEWIDTH(132)
$DEBUG
$OBJECT
$NOPAGING
;DECLARATION OF VARIABLES
BSEG
AT
;DECLARATION OF BIT-VARIABLES
SEMAPHORE:
DIRECTION
DBIT
BIT
8
SEMAPHORE
;STACK
DSEG
STACK_START:
AT
DS
03FH
040H
;RESET VECTORS
CSEG
JMP
ORG
AT
0
XRESET
00BH
; Reset vector
JMP
TIM0_ISR
ORG
JMP
01BH
TIM1_ISR
ORG
XRESET: MOV
MOV
MOV
MOV
MOV
SETB
SETB
MOV
CLR
CLR
100H
SP,#STACK_START
TMOD,#00001011B
A,#0FFH
P1,#0FFH
R0,#30D
TR0
TR1
IE,#08AH
C
DIRECTION
LOOP1:
LOOP1
; Remain here
R0,LAB3
DIRECTION,LAB1
A
SJMP
TIM0_ISR:
DJNZ
JB
RRC
through
; TL0 is turned on
; TL1 is turned on
; Interrupt enabled
; Rotate to the right
; Carry flag
SJMP
LAB1:
RLC
through
LAB2
A
LAB2:
LAB3:
P1,A
; Carry flag
; Contents of Accumulator is moved to port P1
; Return from interrupt
R1,LAB4
R2,LAB4
MOV
RETI
TIM1_ISR:
DJNZ
times
DJNZ
direction
CPL
MOV
LAB4:
RETI
SMER
R2,#30D
END
; End of program
AT
;DECLARATION OF BIT-VARIABLES
SEMAPHORE:
DIRECTION
DBIT
BIT
8
SEMAPHORE
;STACK
DSEG
STACK_START:
AT
DS
03FH
040H
;RESET VECTORS
CSEG
AT
0
JMP
XRESET
; Reset vector
ORG
JMP
00BH
TIM0_ISR
ORG
JMP
01BH
TIM1_ISR
ORG
100H
XRESET: MOV
MOV
MOV
MOV
MOV
SETB
SETB
MOV
CLR
CLR
SP,#STACK_START
TMOD,#11H
A,#0FFH
P1,#0FFH
R0,#30D
TR0
TR1
IE,#08AH
C
DIRECTION
LOOP1:
LOOP1
; Remain here
SJMP
TIM0_ISR:
JB
RRC A
through
;
;
;
;
R0 is initialized
TIMER0 is turned on
TIMER1 is turned on
Timer0 and Timer1 Interrupt enabled
DIRECTION,LAB1
; Rotate contents of accumulator to the right
; Carry flag
LAB1:
through
LAB2:
SJMP
RLC
LAB2
A
MOV
RETI
P1,A
; Carry flag
; Contents of Accumulator is moved to port P1
; Return from interrupt
R0,LAB3
DIRECTION
R0,#30D
; Initialize R0
TIM1_ISR:
DJNZ
direction
CPL
MOV
LAB3:
RETI
END
; End of program
Using Timer T2
This example describes the use of Timer T2 configured to operate in Auto-Reload mode. In this very case,
LEDs are connected to port P3 while the push button used for forced timer reset (T2EX) is connected to the
P1.1 pin.
Program execution is similar to the previous examples. When timer ends counting, an interrupt is enabled
and subroutine TIM2_ISR is executed, thus rotating a logic zero (0) in accumulator and moving the contents
of accumulator to the P3 pin. At last, flags which caused an interrupt are cleared and program returns to the
loop LOOP1 where it remains until a new interrupt request arrives...
If push button T2EX is pressed, timer is temporarily reset. This push button resets timer, while push button
RESET resets the microcontroller.
;************************************************************************
;* PROGRAM NAME : Timer2.ASM
;* DESCRIPTION: Program rotates log. "0" on port P3. Timer2 determines
;* the speed of rotation and operates in auto-reload mode
;************************************************************************
;BASIC DIRECTIVES
$MOD53
$TITLE(TIMER2.ASM)
$PAGEWIDTH(132)
$DEBUG
$OBJECT
$NOPAGING
;DEFINITION OF VARIABLES
T2MOD
DATA
0C9H
DSEG
STACK_START:
AT
DS
03FH
040H
;RESET VECTORS
CSEG
JMP
AT
XRESET
;STACK
ORG
JMP
02BH
TIM2_ISR
ORG
100H
; Reset vector
; Timer T2 Reset vector
XRESET: MOV
MOV
MOV
MOV
MOV
CLR
SETB
SETB
MOV
CLR
SP,#STACK_START
A,#0FFH
P3,#0FFH
RCAP2L,#0FH
RCAP2L,#01H
CAP2
EXEN2
TR2
IE,#0A0H
C
LOOP1:
LOOP1
; Remain here
SJMP
TIM2_ISR:
RRC
through
MOV
CLR
CLR
RETI
END
P3,A
TF2
EXF2
;
;
;
;
;
Carry flag
Move the contents of Accumulator A to PORT3
Clear timer T2 flag TF2
Clear timer T2 flag EXF2
Return from interrupt
; End of program
;************************************************************************
;* PROGRAM NAME : Int.ASM
;* DESCRIPTION : Program counts interrupts INT0 generated by appearance of high-to-low
;* transition signal on pin P3.2 Result appears on port P0. Interrupts INT1 are also
;* counted up at the same time. They are generated byappearing high-to-low transition
;* signal on pin P3. The result appears on port P1.
;************************************************************************
;BASIC DIRECTIVES
$MOD53
$TITLE(INT.ASM)
$PAGEWIDTH(132)
$DEBUG
$OBJECT
$NOPAGING
;RESET VECTORS
CSEG
JMP
AT
0
XRESET
ORG
003H
JMP
Isr_Int0
ORG 013H
JMP
Isr_Int1
ORG
100H
MOV
TCON,#00000101B
MOV
MOV
MOV
MOV
MOV
IE,#10000101B
R0,#00H
R1,#00H
P0,#00H
P1,#00H
SJMP
LOOP
; Reset vector
; Interrupt routine address for INT0
; Interrupt routine address for INT1
XRESET:
LOOP:
Isr_Int0:
INC R0
MOV P0,R0
RETI
Isr_Int1:
INC R1
MOV P1,R1
RETI
END
;
;
;
;
;
;
; Reset port P0
; Reset port P1
; Remain here
; Increment value of interrupt INT0 counter
AT
DS
03FH
040H
;RESET VECTORS
CSEG
JMP
XRESET:
AT
0
XRESET
; Reset vector
ORG
100H
MOV
MOV
MOV
SP,#STACK_START
P1,#0
P3,#20h
MOV
LCALL
MOV
SJMP
A,#03
Disp
P1,A
LOOP
INC
MOVC
RET
DB
DB
DB
DB
DB
DB
DB
DB
DB
DB
END
A
A,@A+PC
LOOP:
Disp:
3FH
06H
5BH
4FH
66H
6DH
7DH
07H
7FH
6FH
;
;
;
;
;
;
;
;
;
;
;
Digit 0 mask
Digit 1 mask
Digit 2 mask
Digit 3 mask
Digit 4 mask
Digit 5 mask
Digit 6 mask
Digit 7 mask
Digit 8 mask
Digit 9 mask
End of program
AT
DS
03FH
040H
;RESET VECTORS
CSEG
JMP
XRESET:
AT
0
XRESET
ORG
100H
MOV
MOV
MOV
MOV
SP,#STACK_START
R3,#0
P1,#0
P3,#20h
MOV
LCALL
A,R3
Disp
MOV
INC
CJNE
MOV
P1,A
R3
R3,#10,L2
R3,#0
MOV
MOV
MOV
DJNZ
DJNZ
DJNZ
SJMP
R2,#20
R1,#50
R0,#230
R0,$
R1,F01
R2,F02
LOOP
INC
MOVC
RET
DB
DB
DB
DB
DB
DB
DB
DB
DB
DB
A
A,@A+PC
; Reset vector
;
;
;
;
LOOP:
; Perform appropriate masking for number in
; Accumulator
; Increment number in register by 1
; Check whether the number 10 is in R3
; If it is, reset counter
L2:
F02:
F01:
Disp:
3FH
06H
5BH
4FH
66H
6DH
7DH
07H
7FH
6FH
END
;
;
;
;
;
;
;
;
;
;
Digit
Digit
Digit
Digit
Digit
Digit
Digit
Digit
Digit
Digit
0
1
2
3
4
5
6
7
8
9
mask
mask
mask
mask
mask
mask
mask
mask
mask
mask
; End of program
$OBJECT
$NOPAGING
;STACK
DSEG
STACK_START:
AT
DS
03FH
040H
;RESET VECTORS
CSEG
JMP
AT
XRESET
XRESET:
LOOP:
; Reset vector
ORG
MOV
100H
SP,#STACK_START
MOV
MOV
MOV
LCALL
MOV
MOV
MOV
MOV
LCALL
MOV
SJMP
P1,#0
P3,#20h
A,#03
Disp
P1,A
P1,#0
P3,#10h
A,#02
Disp
P1,A
LOOP
;
;
;
;
;
;
;
;
;
;
;
INC
MOVC
RET
DB
DB
DB
DB
DB
DB
DB
DB
DB
DB
A
A,@A+PC
Disp:
3FH
06H
5BH
4FH
66H
6DH
7DH
07H
7FH
6FH
;
;
;
;
;
;
;
;
;
;
END
Digit
Digit
Digit
Digit
Digit
Digit
Digit
Digit
Digit
Digit
0
1
2
3
4
5
6
7
8
9
mask
mask
mask
mask
mask
mask
mask
mask
mask
mask
; End of program
AT
DS
03FH
040H
;RESET VECTORS
CSEG
JMP
AT
0
XRESET
; Reset vector
ORG
100H
XRESET:
MOV
SP,#STACK_START
LOOP:
MOV
MOV
MOV
LCALL
MOV
MOV
MOV
MOV
LCALL
MOV
MOV
MOV
MOV
LCALL
MOV
MOV
MOV
MOV
LCALL
MOV
SJMP
P1,#0
P3,#20h
A,#04
Disp
P1,A
P1,#0
P3,#10h
A,#03
Disp
P1,A
P1,#0
P3,#08h
A,#02
Disp
P1,A
P1,#0
P3,#04h
A,#01
Disp
P1,A
LOOP
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
;
INC
MOVC
RET
DB
DB
DB
DB
DB
DB
DB
DB
DB
DB
A
A,@A+PC
Disp:
3FH
06H
5BH
4FH
66H
6DH
7DH
07H
7FH
6FH
;
;
;
;
;
;
;
;
;
;
Digit
Digit
Digit
Digit
Digit
Digit
Digit
Digit
Digit
Digit
0
1
2
3
4
5
6
7
8
9
mask
mask
mask
mask
mask
mask
mask
mask
mask
mask
$MOD53
$TITLE(7SEG4.ASM)
$PAGEWIDTH(132)
$DEBUG
$OBJECT
$NOPAGING
;STACK
DSEG
STACK_START:
AT
DS
03FH
040H
;RESET VECTORS
CSEG
JMP
AT
XRESET
0
; Reset vector
ORG
100H
XRESET:
MOV
MOV
MOV
MOV
SP,#STACK_START
R2,#0
R3,#0
R4,#0
LOOP:
times
INC
R4
CJNE
MOV
MOV
INC
CJNE
MOV
INC
CJNE
MOV
R4,#20d,LAB1
R4,#0
P1,#0
R2
R2,#10d,LAB1
R2,#0
R3
R3,#10d,LAB1
R3,#0
MOV
MOV
LCALL
MOV
LCALL
MOV
MOV
MOV
LCALL
MOV
LCALL
SJMP
P3,#20h
A,R2
Disp
P1,A
Delay
P1,#0
P3,#10h
A,R3
Disp
P1,A
Delay
LOOP
;
;
;
;
;
;
;
;
;
;
;
MOV
MOV
DJNZ
DJNZ
RET
R1,#50
R0,#250
R0,$
R1,F01
; 5 ms delay
INC
MOVC
RET
DB
DB
DB
DB
DB
DB
DB
DB
DB
DB
A
A,@A+PC
LAB1:
Activate display D4
Copy Register containing units to A
Call mask for that digit
Write units on display D4
25ms delay
Turn off all display segments
Activate display D3
Copy Register contaning tens to A
Call mask for that digit
Write tens on display D3
25ms delay
Delay:
F01:
Disp:
3FH
06H
5BH
4FH
66H
6DH
7DH
07H
7FH
6FH
;
;
;
;
;
;
;
;
;
;
Digit
Digit
Digit
Digit
Digit
Digit
Digit
Digit
Digit
Digit
0
1
2
3
4
5
6
7
8
9
mask
mask
mask
mask
mask
mask
mask
mask
mask
mask
END
; End of program
Handling EEPROM
This program writes data to on-chip EEPROM memory. In this case, the data is a hexadecimal number 23
which is to be written to the location with address 00.
To make sure that this number is correctly written, the same location of EEPROM is read 10mS later in order
to compare these two numbers. If they match, F will be displayed. Otherwise, E will be displayed on the
LED display (Error).
;************************************************************************
;* PROGRAM NAME: EEProm1.ASM
;* DESCRIPTION: Programming EEPROM at address 0000hex and displaying message
;* on LED display.
;************************************************************************
;BASIC DIRECTIVES
$MOD53
$TITLE(EEPROM1.ASM)
$PAGEWIDTH(132)
$DEBUG
$OBJECT
$NOPAGING
WMCON
EEMEN
EEMWE
TEMP
DATA
EQU
EQU
DATA
96H
00001000B
00010000B
030H
THE END
ERROR
EQU
EQU
071H
033H
; Display "F"
; Display "E"
;STACK
DSEG
STACK_START:
AT
DS
;RESET VECTORS
CSEG
JMP
AT
0
XRESET
XRESET:
LOOP1:
ERROR:
LOOP2:
03FH
040H
; Reset vector
ORG
100H
MOV
MOV
IE,#00
SP,#STACK_START
MOV
ORL
ORL
MOV
MOV
MOVX
CALL
MOVX
CJNE
MOV
MOV
XRL
XRL
SJMP
DPTR,#0000H
WMCON,#EEMEN
WMCON,#EEMWE
TEMP,#23H
A,TEMP
@DPTR,A
DELAY
A,@DPTR
A,TEMP,ERROR
A,#KRAJ
P1,A
WMCON,#EEMWE
WMCON,#EEMEN
LOOP1
;
;
;
;
;
;
;
;
;
;
MOV
MOV
SJMP
A,#ERROR
P1,A
LOOP2
; Display E (error)
DELAY:
LOOP3:
LOOP4:
LOOP5:
MOV
MOV
NOP
DJNZ
DJNZ
DJNZ
RET
A,#0AH
R3,A
; Delay
B,LOOP4
B,LOOP5
R3,LOOP3
END
; End of program
;************************************************************************
;* PROGRAM NAME : UartR.ASM
;* DESCRIPTION: Each data received from PC via UART appears on the port
;* P1.
;*
;************************************************************************
;BASIC DIRECTIVES
$MOD53
$TITLE(UARTR.ASM)
$PAGEWIDTH(132)
$DEBUG
$OBJECT
$NOPAGING
;STACK
DSEG
STACK_START:
AT
DS
03FH
040H
;RESET VECTORS
CSEG
JMP
ORG
JMP
AT
0
XRESET
023H
IR_SER
; Reset vector
; Starting address of UART interrupt routine
ORG
100H
MOV
MOV
MOV
MOV
IE,#00
SP,#STACK_START
TMOD,#20H
TH1,#0FDH
MOV
MOV
CLR
CLR
SETB
SCON,#50H
IE,#10010000B
TI
RI
TR1
;
;
;
;
;
;
;
;
;
;
LOOP:
SJMP
LOOP
; Remain here
IR_SER:
JNB
RI,OUTPUT
A,SBUF
P1,A
RI
OUTPUT
MOV
MOV
CLR
RETI
XRESET:
END
; End of program
AT
DS
;RESET VECTORS
CSEG
JMP
AT
0
XRESET
XRESET:
03FH
040H
ORG
100H
MOV
MOV
MOV
MOV
IE,#00
SP,#STACK_START
TMOD,#20H
TH1,#0FDH
; Reset vector
;
;
;
;
All interrupts
Initialization
Timer1 in mode
9600 baud rate
are disabled
of Stack pointer
2
at the frequency of
START:
LOOP1:
LOOP:
;
;
;
;
;
;
11.0592MHz
8-bit UART
Clear transmit bit
Clear receive flag
Reset caunter
Start Timer 1
;
;
;
;
;
MOV
CLR
CLR
MOV
SETB
SCON,#40H
TI
RI
R3,#00H
TR1
MOV
JNB
SBUF,R3
TI,LOOP1
CLR
INC
TI
R3
CJNE
R3,#00H,START
SJMP
LOOP
; Remain here
END
; End of program
*************************************************************************
;* PROGRAM NAME : Lcd.ASM
;* DESCRIPRTION : Program for testing LCD display. 4-bit communication
;* is used. Program does not check BUSY flag but uses program delay
;* between 2 commands. PORT1 is used for connection
;* to the microcontroller.
;************************************************************************
;BASIC DIRECTIVES
$MOD53
$TITLE(LCD.ASM)
$PAGEWIDTH(132)
$DEBUG
$OBJECT
$NOPAGING
;Stack
DSEG
Stack_Start:
AT
DS
0E0h
020h
Start_address
EQU
0000h
;Reset vectors
Inic:
CSEG
ORG
JMP
AT
0
Start_address
Inic
ORG
Start_address+100h
MOV
MOV
IE,#00
SP,#Stack_Start
CALL
LCD_inic
; Initialize LCD
;*************************************************
;* MAIN PROGRAM
;*************************************************
START:
MOV
CALL
A,#80h
LCD_status
A,#'M'
LCD_putc
; Display character M.
; Call subroutine for character
A,#'i'
LCD_putc
A,#'k'
LCD_putc
A,#'r'
LCD_putc
A,#'o'
LCD_putc
A,#'e'
LCD_putc
A,#'l'
LCD_putc
A,#'e'
LCD_putc
A,#'k'
LCD_putc
A,#'t'
LCD_putc
A,#'r'
LCD_putc
A,#'o'
LCD_putc
A,#'n'
LCD_putc
A,#'i'
LCD_putc
A,#'k'
LCD_putc
A,#'a'
LCD_putc
; Display character i.
A,#0c0h
LCD_status
A,#'R'
LCD_putc
; Display character R.
; Call subroutine for character
A,#'a'
LCD_putc
; Display character a.
display.
MOV
CALL
transmission.
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
; Display character k.
; Display character r.
; Display character o.
; Display character e.
; Display character l.
; Display character e.
; Display character k.
; Display character t.
; Display character r.
; Display character o.
; Display character n.
; Display character i.
; Display character k.
; Display character a.
display.
MOV
CALL
transmission.
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
MOV
CALL
A,#'z'
LCD_putc
A,#'v'
LCD_putc
A,#'o'
LCD_putc
A,#'j'
LCD_putc
A,#'n'
LCD_putc
A,#'i'
LCD_putc
A,#' '
LCD_putc
A,#'s'
LCD_putc
A,#'i'
LCD_putc
A,#'s'
LCD_putc
A,#'t'
LCD_putc
A,#'e'
LCD_putc
A,#'m'
LCD_putc
A,#'i'
LCD_putc
; Display character z.
MOV
CALL
MOV
MOV
CALL
MOV
CALL
JMP
R0,#20d
Delay_10ms
DPTR,#LCD_DB
A,#6d
LCD_inic_status
R0,#10d
Delay_10ms
START
; Display character v.
; Display character o.
; Display character j.
; Display character n.
; Display character i.
; Display character .
; Display character s.
; Display character i.
; Display character s.
; Display character t.
; Display character e.
; Display character m.
; Display character i.
;*********************************************
;* Subroutine for wait time (T= r0 x 10ms)
;*********************************************
Delay_10ms:
MOV
MOV
MOV
DJNZ
DJNZ
DJNZ
RET
R5,00h
R6,#100d
R7,#100d
R7,$
R6,$-4
R5,$-6
;
;
;
;
1+(1+(1+2*r7+2)*r6+2)*r5 approximately
(if r7>10)
2*r5*r6*r7
$ indicates current instruction.
;**************************************************************************************
;* SUBROUTINE: LCD_inic
;* DESCRIPTION: Subroutine for LCD initialization.
;*
;* (is used with 4-bit interface, under condition that pins DB4-7 on LCD
;* are connected to pins PX.4-7 on microcontrollers ports, i.e. four higher
;* bits on the port are used).
;*
;* NOTE: It is necessary to define port pins for controlling LCD operation:
;* LCD_enable, LCD_read_write, LCD_reg_select,similar to port for connection to LCD.
;* It is also necessary to define addresses for the first character in each
;* line.
;**************************************************************************************
LCD_enable
LCD_read_write
LCD_reg_select
LCD_port
Busy
BIT
BIT
BIT
SET
BIT
P1.3
P1.1
P1.2
P1
P1.7
;
;
;
;
;
E on LCD.
RW on LCD.
RS on LCD.
LCD.
flag appears.
LCD_Start_I_red
EQU
00h
LCD_Start_II_red EQU
40h
LCD_DB:
;
;
;
;
DB
DB
DB
DB
00111100b
00101100b
00011000b
00001100b
;
;
;
;
0
1
2
3
DB
DB
DB
DB
00000110b
00000010b
00000001b
00001000b
;
;
;
;
4
5
6
7
off
off
LCD_inic:
;*****************************************
MOV
DPTR,#LCD_DB
MOV
CALL
MOV
CALL
MOV
lcall
A,#00d
LCD_inic_status_8
A,#00d
LCD_inic_status_8
A,#00d
LCD_inic_status_8
;
;
;
;
MOV
CALL
MOV
CALL
A,#1d
LCD_inic_status_8
A,#1d
LCD_inic_status
MOV
A,#3d
CALL
MOV
CALL
MOV
CALL
LCD_inic_status
A,#6d
LCD_inic_status
A,#4d
LCD_inic_status
in
;4-bit mode
RET
LCD_inic_status_8:
;******************************************
PUSH B
MOVC
CLR
CLR
A,@A+DPTR
LCD_reg_select
LCD_read_write
MOV
ORL
ORL
ANL
B,LCD_port
B,#11110000b
A,#00001111b
A,B
MOV
SETB
LCD_port,A
LCD_enable
CLR
LCD_enable
MOV
B,#255d
DJNZ B,$
DJNZ B,$
DJNZ B,$
POP B
RET
LCD_inic_status:
;****************************************************************************
MOVC A,@A+DPTR
CALL LCD_status
RET
;****************************************************************************
;* SUBROUTINE: LCD_status
;* DESCRIPTION: Subroutine for defining LCD status.
;****************************************************************************
LCD_status:
PUSH
MOV
DJNZ
DJNZ
DJNZ
CLR
CALL
B
B,#255d
B,$
B,$
B,$
LCD_reg_select
LCD_port_out
SWAP
DJNZ
DJNZ
DJNZ
CLR
CALL
B,$
B,$
B,$
LCD_reg_select
LCD_port_out
POP
RET
;****************************************************************************
;* SUBROUTINE: LCD_putc
;* DESCRIPTION: Sending character to be displayed on LCD.
;****************************************************************************
LCD_putc:
PUSH
MOV
DJNZ
SETB
CALL
B
B,#255d
B,$
LCD_reg_select
LCD_port_out
SWAP
DJNZ
SETB
B,$
LCD_reg_select
CALL
POP
RET
LCD_port_out
B
;****************************************************************************
;* SUBROUTINE: LCD_port_out
;* DESCRIPTION: Sending commands or characters on LCD display
;****************************************************************************
LCD_port_out:
PUSH
PUSH
MOV
ORL
ORL
ANL
ACC
B
B,LCD_port
B,#11110000b
A,#00001111b
A,B
MOV
LCD_port,A
SETB
LCD_enable
CLR
LCD_enable
POP
POP
RET
B
ACC
END
; End of program
MOV
DIV
MOV
MOV
DIV
MOV
MOV
DIV
MOV
RET
B,#10d
AB
R3,B
B,#10d
AB
R2,B
B,#10d
AB
A,B
;
;
;
;
;
;
;
;
;
;
may be used. It may, but it does not have to... When using such a software, there are numerous tools
which facilitate the operation (simulator tool comes first), which is an obvious advantage. But there is
also another ways to write a program. Basically, text is the only thing that matters. Any program for text
processing can be used for this purpose. The point is to write all instructions in such an order they should
be executed by the microcontroller, observe the rules of assembly language and write instructions exactly
as they are defined. In other words, you just have to follow the program idea. Thats all!
;RESET
XRESET:
VECTOR
CSEG
JMP
AT
XRESET
CSEG
ORG
100H
ORL
ORL
WMCON,#PERIOD
WMCON,#WDTEN
0
; Reset vector
To enable the compiler to operate successfully, it is necessary that a document containing this program
has the extension, .asm in its name, for example: Program asm.
When a specialized program (mplab) is used, this extension will be automatically added. If any other
program for text processing (Notepad) is used then the document should be saved and renamed. For
example: Program.txt -> Program.asm. This procedure is not necessarily performed. The document may
be saved in original format while its text may be copied to the programmer for further use.
Compiling a program
The microcontroller does not undrestand assembly language as such. That is why it is necessary to
compile the program into machine language. It is more than simple when a specialized program (mplab)
is used because a compiler is a part of the software. Just one click on the appropriate icon solves the
problem and a new document with .hex extension appears. It is actually the same program, only compiled
into machine language which the microcontroller perfectly understands. Such documentation is
commonly named hex code and seemingly represents a meaningless sequence of numbers in
hexadecimal number system.
:03000000020100FA1001000075813F
7590FFB29012010D80F97A1479D40
90110003278589EAF3698E8EB25B
A585FEA2569AD96E6D8FED9FAD
AF6DD00000001FF255AFED589EA
F3698E8EB25BA585FEA2569AD96
DAC59700D00000278E6D8FED9FA
DAF6DD00000001FF255AFED8FED
9FADAF6DD000F7590FFB29013278
E6D8FED9FADAF6DD00000001FF2
55AFED589EAF3698E8EB25BA585
FEA2569AD96DAC59D9FADAF6D
D00000001FF255AFED8FED9FADA
F6DD000F7590FFB29013278E6D82
78E6D8FED9FA589EAF3698E8EB2
5BA585FEA2569AD96DAF6DD000
00001FF2DAF6DD00000001FF255A
ADAF6DD00000001FF255AFED8FE
D9FA
In the event that other software for program writing in assembly language is used, a special software for
compiling the program must be installed and used as follows - set up the compiler, open the document
with .asm extension and compile. The result is the same- a new document with extension .hex. The only
problem now is that it is stored in your PC.
Programming a microcontroller
In order to transfer a hex code to the microcontroller, it is necessary to provide a cable for serial
communication and a special device, called programmer, with software. There are several ways to do it.
A large number of programs and electronic circuits having this purpose can be found on the Internet. Do
as follows: open hex code document, set a few parameters and click the icon for compiling. After a while,
a sequence of zeros and ones will be programmed into the microcontroller through the serial connection
cable and programmer hardware. What's left is to place the programmed chip into the taget device. In the
event that it is necessary to make some changes in the program, the previous procedure may be repeated
an unlimited number of times.
The program is written and successfully compiled. All that's left is to dump the program to the
microcontroller. For this purpose it is necessary to have a software that takes the written and compiled
program and passes it to the microcontroller.
Start the program 8051 Flash_setup.exe...
Thats all! The microcontroller is programmed and everything is ready for operation. If you are not
satisfied, make some changes in the program and repeat the procedure. Until when? Until you feel
satisfied...
Development systems
A device which in the testing program phase can simulate any environment is called a development
system. Apart from the programmer, the power supply unit and the microcontrollers socket, the
development system contains elements for input pin activation and output pin monitoring. The simplest
version has every pin connected to one push button and one LED as well. A high quality version has LED
displays, LCD displays, temperature sensors and all other elements which can be supplied with the target
device. These peripherals can be connected to the MCU via miniature jumpers. In this way, the whole
program may be tested in practice during its development stage, because the microcontroller doesn't know
or care whether its input is activated by a push button or a sensor built in a real device.
All microcontrollers manufactured by Atmel appear in a few standard DIP packages. In order to enable
their programming using one device, corresponding pins (having the same name) on sockets are
connected in parallel. As a result, by being placed in the appropriate socket, each microcontroller is
automatically properly connected. Figure on the right shows a microcontroller in 40-pin package and
connection of one of its I/O pins (P1.5). As seen, the pin can be connected to an external device
(connector PORT1), LED (microswitch SW2), push button or resistor through connectors. In the last two
cases, polarity of voltage is selected using on-board jumpers.
Programmer
The purpose of the programmer is to transfer HEX code from PC to appropriate pins and provide regular
voltage levels during chip programming as well. For this development system, the programmer is built in
it and should be connected to PC via USB cable. When the process of programming is completed, pins
There is a connector on the development board enabling commection to external power supply source
(AC/DC, 8-16V). Besides, voltage necessary for device operation can also be obtained from PC via USB
cable. Jumper J5 is used for power supply selection.
8MHz Oscillator
The EASY8051A development system has built-in oscillator used as a clock signal generator. The
frequency of this oscillator is stabilized by 8Hz quartz crystal. Besides, it is also possible to select internal
RC oscillator during chip programming,.
Each I/O port pin is connected to one LED which enables visual indication of its logic state. In the event
that the presence of directly polarized LEDs and serial resistors is not acceptable in some applications,
DIP switch SW2 enables them to be disconnected from the port.
Similar to LEDs, each I/O port pin is connected to one push button on the development board. It enables
simple activation of input pins. Jumper J6 is used for selecting voltage polarity (+ or -) brought to pins by
pressing appropriate push button.
Being often applied in the industry, four high-performance LED displays set in multiplex mode belong to
the development system. Display segments are connected to the port P0 via resistors. Transistor drivers
used for activating individual digits are connected to the first four port P1 pins. It enables programs using
7-segment displays to be tested with minimum use of I/O ports. Similar to LEDs, DIP switch SW2
enables transistor drivers to be disconnected from microcontroller pins.
LCD displays
The EASY8051A development system provides connection to eather graphic or alphanumeric LCD
display. Both types of displays are connected by being placed into appropriate connector and by
switching position of the jumper J8. If displays are not in use, all pins used for their operation are
available for other applications. Apart from connectors, there is also a potentiometer for contrast
regulation on the board.
In order to enable programs using serial communication to be tested, the development system has built in
standard 9-pin SUB-D connector. The MAX232 is used as a voltage regulator.
Similar to other built-in circuits, electronics supporting serial communication can be enabled or disabled
by using jumpers J9 and J10.
Temperature measurement is one of the most common tasks of devices which operate in the industry. For
this reason, there is a circuit DS1820 on the EASY8051A development system which measures
temperature in the range of -55 to +125oC with accuracy greater than 0.50. Results of measurement are
transferred via serial communication to the pins P3.3 or P2.7. Jumper J7 is used for selecting pins for data
reception. In the event that no jumper is installed, port pins are available for other applications.
A built-in 12-bit AD Converter MCP3204 has four input channels connected to on-board connectors.
Data are interchanged with the microcontroller via SPI serial communication system using pins P1.5,
P1.6, P1.7 and P3.5. If A/D converter is not in use, these pins can be used for other applications (DIP
switch SW1). In order to check operation, there is a potentiometer on the development board used as a
variable voltage source. It can be brought to the converters input pins using one of four jumpers J12. As
a special convenience, a reference voltage source MCP1541 (4,096V) is built in. Jumper J11 is used to
select whether converter will use this voltage or 5V.
Digital to analog conversion (D/A) is another operation ofen performed by the microcontroller in
practice. For this reason, there is a special on-board chip which interchanges data with the microcontroller
via SPI communication system. It can also generate analog voltage in 12-bit resolution on its output pin.
When it is not in use, all microcontroller pins are available for other applications using DIP switch SW1.
Similar to A/D converter, jumper J11 is used for selecting reference voltage.
In order to enable microcontroller ports to be directly connected to additional components, each of them
is connected to one on-board connector. Besides, two pins of each connector are connected to power
supply voltage while each pin can be connected to + or - polarity of voltage via resistors (pull up or pull
down resistors). Presence and connection of these resistors are determined by jumpers. Jumper J3 which
controls port P3 is shown in figure on the right.