8051 Microcontrollers

Size: px
Start display at page:

Download "8051 Microcontrollers"

Transcription

1 8051 Microcontrollers Author: Milan Verle compilation with Meisam Fanoody 1

2 Chapter 1: Introduction to Microcontrollers Chapter 2: 8051 Microcontroller Architecture Chapter 3: The 8051 Instruction Set Chapter 4: The AT89S8253 Microcontroller Chapter 5: Program Language Assembler Chapter 6: Examples Chapter 7: Development Tools 2

3 Chapter1: Introduction to Microcontrollers Introduction 1.1 What are microcontrollers and what are they used for? 1.2 What is what in microcontroller? Introduction It was electricity in the beginning...the people were happy because they didn t know that it was existing all around them and that it could be utilized. It was fine. And then Faraday came and the stone has started rolling slowly... During the time, the first machines using a new sort of energy appeared accompanied with people who knew something about electricity. A long time has passed since then and just when civilization got used to this innovation and stopped paying attention to what a new generation of specialists were doing, someone came up with an idea that electrons could be a very convenient toy being closed in a glass pipe. At first sight, it was only a good idea, but there was no return, electonics was born and the stone continued rolling down the hill faster and faster... A new science - new specialists. The blue coats were replaced with white ones and people who knew something about electronics appeared on stage. While the rest of the humanity were passively watching in disbelief what was going on, within plotters two fractions appeared- software-oriented and hardware-oriented. A bit younger than their teachers, very enthusiastic and full of ideas, both of them kept on working but separate ways. While the first group had a stable development, hardware-oriented people, driven by success, soon threw caution to the wind and invented transistor. Up till that moment, the things could be more or less kept under control, but broad publicity wasn t aware of seriousness of the situation and it soon led to a fatal mistake! Being naive in belief that using cheap tricks could slow down technology development as well as developing of the world, mass market opened its door to the products of Electronics Industry, closing a magic circle therefore. Components prices fell rapidly becoming available for use to younger population. The stone was falling freely... The first integrated circuits and processors have soon appeared, which enabled for computers to drop down in price. The computers have started to develop their own production. The prices droped down again and Electonics got new adherents. It appeared everywhere. Another circle has been closed! Ordinary people got hold of computers and computer era has begun... While this drama was going on, hobbyists and professionals, protected by anonymity, were working hard on their projects, although split in two big groups. Then, someone has again remembered: Why shouldn t we make an universal component? It would be a cheap and universal integrated circuit that could be programmed and used in any field of electronics, device and wherever needed. Technology has been developed enough, market exists, why not? So it happened, body and spirit are united, the circuit is created and called MICROCONTROLLER. 3

4 1.1 What are microcontrollers and what are they used for? As all other good things, this powerful component is in its essence very simple and is obtained by uniting tested and high- quality "ingredients" (components) as per following receipt: 1. The simplest computer s processor is used as a "brain" of the future system. 2. Depending on the taste of the producer, it is added : a bit of memory, a few A/D converters, timers, input/output lines etc. 3. It is all placed in one of standard packages. 4. A simple software that will be able to control it all and about which everyone will be able to learn has been developed. Three things have had a crucial impact on such a success of the microcontrollers: Powerful and intelligently chosen electronics embedded in the microcontrollers can via input/output devices ( switches, push buttons, sensors, LCD displays, relays ) control various processes and devices such as: industrial automatics, electric current, temperature, engine performance etc. A very low price enables them to be embedded in such devices in which, until recent time it wasn t worth embedding anything. Thanks to that, the world is overwhelmed today with cheap automatic devices and various intelligent appliences. Prior knowledge is hardly needed for programming. It is sufficient to have any kind of PC (software in use is not demanding at all and it is easy to learn to work on it) and one simple device (programmer) used for transffering completed programs into the microcontroller. Therefore, if you are infected with a virus called electronics, there is nothing left for you to do but to learn how to control its power and how to direct it at the right course. How does microcontroller work? Even though there is a great number of various microcontrollers and even greater number of programs designed for the microcontrollers use only, all of them have many things in common. That means that if you learn to handle one of them you will be able to handle them all. A typical scenario on whose basis it all functions is as follows: 1. Power supply is turned off and everything is so still chip is programmed, every thing is in place, nothing indicates what is to come 2. Power supply connectors are connected to the power supply source and every thing starts to happen at high speed! The control logic registers what is going on first. It enables only quartz oscillator to work. While the first preparations are in progress and parasite capacities are being charged, the first milliseconds go by. 3. Power supply connectors are connected to the power supply source and every thing starts to happen at high speed! The control logic registers what is going on first. It enables only quartz oscillator to work. While the first preparations 4

5 are in progress and parasite capacities are being charged, the first milliseconds go by. 4. Voltage level has reached its full value and frequency of oscillator has became stable. The bits are being written to the SFRs, showing the state of all periph erals and all pins are configured as outputs. Everything occurs in harmony to the pulses rhythm and the overall electronis starts working. Since this moment the time is measured in micro and nanoseconds. 5. Program Counter is reset to zero address of the program memory. Instruction from that address is sent to instruction decoder where its meaning is recognised and it is executed with immediate effect. 6. The value of the Program Counter is being incremented by 1 and the whole process is being repeated...several million times per second. 1.2 What is what in microcontroller? Obviously, everything that occurs in the microcontroller occurs at high speed and rather simple, but it wouldn t be so useful if there are no special interfaces which make it complete. Text below refers to that (in short). Program Memory (ROM) The Program Memory is a kind of memory which permanently stores a program being executed. Obviously, the maximal length of the program that can be written to depends on the size of the memory. The program memory can be built in the microcontroller or added from outside as a separate chip, which depends on type of the microcontroller. Both variants have advantages and disadvantages: if added from outside, the microcontroller is cheaper and program can be considerably longer. At the same time, a number of available pins is decremented as the microcontroller uses 5

6 its own input/output ports to be connected to the memory. The capacity of Internal Program Memory is usually smaller and more expensive but such a chip has more possibilities of connecting to peripheral environment. The size of the program memory ranges from 512Kb to 64Kb. Data Memory (RAM) The Data Memory is a kind of memory which serves for temporary storing and keeping different data and constants created and used during operating process. The content of this memory is erased when the power is off. For example: when the program performes addition, it is necessary to have a register presenting what in everyday life is called a sum. For that purpose one of the registers in RAM is named as such and serves for storing results of addition. The size of data memory size goes up to a few Kbs. EEPROM Memory The EEPROM Memory is a special kind of memory which not all the types of microcontrollers have.its content can be changed during program execution (similar to RAM ), but it is permanently saved even after the power goes off (similar to ROM). It serves for storing different values created and used during operating process and which must be saved upon turning off the device ( calibration values, codes, values to number up to etc.). A disadvantage of this memory is that writing process is relatively slow- measured in miliseconds. 6

7 SFRs ( Special Function Registers ) The SFRs are a particular part of memory whose purpose is defined in advance by the producer. Each of these registers have its name and control some of interfaces within the microcontroller. For example: by writing 0 or 1 to the SFR controlling some input/output port, each of these pins can be configured as input or output (each bit in this register controls the purpose of one single pin). Program Counter The Program Counter is an engine which starts the program and indicates the address in memory where next instruction to execute is found. Immediately after its execution, the value of the counter is incremented by 1. For this automatic increment, the program executes an instruction at a time as it is written. However the program counter value could be changed at any moment, which will cause jump to a new location in the program memory. This is how subroutines or branch instructions are executed. Finding its new place in the program, the counter resumes even automatic counting +1, +1, +1 CPU (Central Processor Unit) As its name says, this is the "Big Brother" who monitors and controls all operations being performed within the microcontroller and the user cannot affect its work. It consists of several smaller units. The most important are: Instruction decoder - a part of electronics which recognizes program instructions and on the basis of which runs other circuits. Arithmetical Logical Unit (ALU) - performs all mathematical and logical operations with data. The features of this circuit are described in the "instruction set" which differs for each type of the microcontroller.. Accumulator - is a special kind of the SFR closely related to operating mode of the ALU. It s a kind of desk on which all data needed to perform some operation on are set (addition, shift etc.). It contains the result, too, ready to be used further in operation. One of the SFRs, called the Status Register, is closely related to the accumulator, showing at any time the "status" of a number being in the accumulator (the number is greater than or less than zero etc.). Bit - a word invented to confuse people who start handling electronics. In practice ( only in practice) this word indicates whether the voltage is applied to an electrical conductor or not. In the first case, it is said that a logical 1 is set on the pin, i.e. the bit s value is 1. Otherwise, if the voltage level is 0 V, i.e. a logical 0 is present on the pin, the bit s value is 0. It is more complicated in theory where the bit is actually a digit in a binary system, whereas, a bit is just a bit whose value amounts 0 or 1 (in decade system we are used to the digits value amounting 0, 1, 2, 3,..8 or 9). Input/output ports (I/O Ports) 7

8 The microcontroller cannot be of any use without being connected to peripheral devices. For that reason each microcontroller has one or more registers ( called ports in this case) connected to its pins. Why input/output? Because the user can change pin s role according to his/her own needs. These are, in fact, the only registers in the microcontroller whose state can be measured by voltmeter! Oscillator 8

9 The oscillator can be compared with rhythm section of a mini orchestra. Equalized pulses coming from this circuit enable harmonious and synchronic operating of all other parts of the microcontroller. It is commonly configured so as to use quartzcrystal or ceramics resonator for frequency stabilization. Besides, it often can work without elements for frequency stabilization ( like RC oscillator). It is important to know that instructions are not executed at the rate directed by oscillator but several times slower. Behind this is that each instruction is executed in several steps (In some microcontrollers execution time of all instructions is equal, while in others microcontrollers execution time differs for different instructions). Because of that, if your system uses quartz-crystal of 20MHz, execution time of a program instruction is not 50nS but 200, 400 or even 800 ns! Timers/Counters Most programs are somehow using these miniature electronic "stopwatches". They are mostly 8- or 16-bit SFRs whose value is automatically incremented with each coming pulse. Once the register is completely "filled up"- an interrupt is generated! If the registers use internal oscillator for its operating then it is possible to measure the time between two events ( if the register value is T1 at the moment measuring has started, and T2 at the moment measuring has finished, then the time that has passed is equal to the value gained by their subtruction T2-T1 ). If the registers for its work use pulses coming from external source then such a timer is converted to counter. This is a very simple explanation used to describe the essence of the operating. It s a bit more complicated in practice. 9

10 Register is another name for a memory cell. Beside 8 bits available to the user, each register has addressing part usually not visible to the user. It is important to know: All registers in both ROM and RAM memory identified as general-purpose registers are mutually equal and nameless. During programming, each register can be assigned a name, which makes process much easier. All SFRs have their own names which are different for different types of the microcontrollers and each of them has a particular role. Watchdog timer Its name says a lot about its purpose. Watchdog Timer is a timer connected to a particular and totally independent RC oscillator within the microcontroller. If enabled to operate, every time it "counts up to end", the microcontroller is reset and program execution starts from the first instruction. The point is that the use of particular command doesn t allow that to happen. The whole idea is based on the fact that every program circulates, in other words, the program is executed in several longer or shorter loops. If the instructions which resets the value of the watchdog timer are added at some important program locations, besides commands being regularly executed, then its operation will not be noticed. If for any reason (usually electrical disturbances in industry), the program counter "gets stuck" at memory location with no return, the register s value being steadily incremented by the watchdog timer will reach the maximum et voila! Reset occurs! Power Supply Circuit Two things within circuit that take care of the microcontroller power supply are worth attention : 10

11 Brown out is potentially dangerous state coming up while the microcontroller is being turned off or in those situations when due to powerful disturbances, voltage supply comes to the lower limit. As the microcontroller consists of several circuits which have different power supply voltage levels, this can cause its "out of control" performance. In order to prevent that, a circuit for brown out reset is usually embedded. When the voltage level drops below the lower limit then this circuit immediately resets the whole electronics. Reset pin is usually identified as MCLR (Master Clear Reset) and serves for "external" reset of the microcontroller by applying logical 0 or 1 (depending on type of the microcontroller). In case the circuit is not embedded then a simple external circuit for brown out reset can be connected to this pin. Serial communication Connection between the microcontroller and peripheral devices enabled through I/O ports is an ideal solution for shorter distances- up to several meters. But, when it is needed to enable communication between two devices on longer distances or when for any other reason it is not possible to use "parallel" connection ( for example remote control of the aircraft ) it is obvious that something simple like that is not 11

12 considered. In such or similar situations, communication through pulses, called serial communication is the most appropriate to use. Serial communication problem has been solved a long time ago and nowadays several different systems enabling this kind of connection are embedded as a standard equipment into the microcontroller. Which of them will be used in concrete situation depends on several factors. The most important are the following: With how many devices the microcontroller must exchange data? How fast the serial communication must be? What is the distance between devices? Is there any need to transmit and receive data simultaneously? One of the most important things concerning use of serial communication is to strictly observe the Protocol. It is a set of rules which must be applied in order to enable devices to recognize exchanging data. Fortunately, the microcontrollers automatically take care of it, which leads to a reduction of the user s work to simple writing and reading data. Byte - 8 bits next to each other make entity called a program word or a byte. If the bit is a digit then it is logical that bytes are numbers. All mathematical operations can be performed with them, just as with usual decimal numbers and it occurs in the ALU. It is important to note that a byte ( as each number) has two sides, i.e. digits a byte consists of are not of equal significance. The highest value has a digit on the far left called most significant bit ( MSB). A digit on the far right has the least value and is called the least significant bit (LSB). As 8 digits can be combined in 256 different ways, the greatest decimal number that can make one byte is 255 ( zero is also presented with one combination ). Program Unlike other integrated circuits which only need to be connected to other components and then powered on, the microcontrollers need to be programmed prior to turning the power on. This is so called "a bitter pill" and the main reason why hardware-oriented electricians mainly avoid the microcontrollers. It is a trap causing huge losses because the microcontrollers programming is in fact very simple. In order to write a program for running microcontrollers, several "lower" program languages can be used Assembler, C and Basic ( and their variants ). Besides, writing program procedure consists of simple giving instructions in order they should be executed. There are also many programs operating in Windows environment used to facilitate work and provide additional- visual tools. Use of Assembler is described in this book because it is the most simple language with the fastest execution allowing entire control on what is going on in circuit. 12

13 Interrupt - electronics is usually more faster than physical process in environment it should control. That s why the microcontroller spend the most of its time waiting for something to happen or execute.in order to avoid continuous checking for logical state on input pins and in internal registers, the interrupt is generated. It is a signal interrupting regular program execution. Since several events can cause interrupt, when it occurs, the microcontroller immediately stops operating and checks for the cause. If it is needed to perform some action, a temporary state of the program counter is pushed on the Stack and the appropriate program is executed (so called interrupt routine ). Stack is a part of RAM used for storing the acctual state of the program counter (address).this address lets the controller know where to return after the subroutine has been executed. Stack can consist of several levels. This enables subroutines nesting, i.e. calling one subroutine from another. Programming for the beginners: 13

14 14

15 Chapter 2 : 8051 Microcontroller Architecture 2.1 What is 8051 Standard? Microcontroller's pins 2.3 Input/Output Ports (I/O Ports) Microcontroller Memory Organisation 2.5 SFRs (Special Function Registers) 2.6 Counters and Timers 2.7 UART (Universal Asynchronous Receiver and Transmitter) Microcontroller Interrupts Microcontroller Power Consumption Control 2.1 What is 8051 Standard? Microcontrollers producers have been struggling for a long time for attracting more and more choosy customers. Every couple of days a new chip with a higher operating frequency, more memory and more high-quality A/D converters comes on the market. Nevertheless, by analyzing their structure it is concluded that most of them have the same (or at least very similar) architecture known in the product catalogs as The 8051 compatibility. What is this all about? The whole story began in the far 80s when Intel launched its series of the microcontrollers labelled with MCS 051. Although, several circuits belonging to this series had rather modest features in comparison to the new ones, they took over the world and became a standard for what nowadays is ment by a word microcontroller. The reason for success and such a big popularity is a skillfully chosen configuration which satisfies needs of a great number of the users allowing at the same time stable expanding ( refers to the new types of the microcontrollers ). Besides, since a great deal of software has been developed in the meantime, it simply wasn t profitable to change anything in the microcontroller s basic core. That s the reason for having a great number of various microcontrollers which actually are solely upgraded versions of the 8051 family. What is it what makes this microcontroller so special and universal so that almost all the world producers manufacture it today under different name? 15

16 As it is shown on the previous picture, the 8051 microcontroller have nothing impressive at first sight: 4 Kb program memory is not much at all. 128Kb RAM (including SFRs as well) satisfies basic needs, but it s not imposing amount. 4 ports having in total of 32 input/output lines are enough to make connection to peripheral environment and are not luxury at all. As it is shown on the previous picture, the 8051 microcontroller have nothing impressive at first sight: The whole configuration is obviously envisaged as such to satisfy the needs of most programmers who work on the development of automation devices. One of advantages of this microcontroller is that nothing is missing and nothing is too much. In other words, it is created exactly in accordance to the average user s taste and needs. The other advantages are the way RAM is organized, the way Central Processor Unit (CPU) operates and ports which maximally are using all recourses and enabling further upgrading Microcontroller's pins Pins 1-8: Port 1 Each of these pins can be configured as input or output. Pin 9: RS Logical 1 on this pin stops microcontroller s work and erases the contents of most registers. By applying logical 0 to this pin, the program starts execution from the beginning. In other words, a positive voltage pulse on this pin resets the microcontroller. Pins10-17: Port 3 Similar to port 1, each of these pins can serve as universal input or output. Besides, all of them have alternative functions: 16

17 Pin 10: RXD Serial asynchronous communication input or Serial synchronous communication output. Pin 11: TXD Serial asynchronous communication output or Serial synchronous communication clock output. Pin 12: INT0 Interrupt 0 input Pin 13: INT1 Interrupt 1 input Pin 14: T0 Counter 0 clock input Pin 15: T1 Counter 1 clock input Pin 16: WR Signal for writing to external (additional) RAM Pin 17: RD Signal for reading from external RAM Pin 18, 19: X2, X1 Internal oscillator input and output. A quartz crystal which determines operating frequency is usually connected to these pins. Instead of quartz crystal, the miniature ceramics resonators can be also used for frequency stabilization. Later versions of the microcontrollers operates at a frequency of 0 Hz up to over 50 Hz. Pin 20: GND Ground Pin 21-28: Port 2 If there is no intention to use external memory then these port pins are configured as universal inputs/outputs. In case external memory is used then the higher address byte, i.e. addresses A8-A15 will appear on this port. It is important to know that even memory with capacity of 64Kb is not used ( meaning that all bits on port are not used for memory addressing) the rest of bits are not available as inputs or outputs. Pin 29: PSEN If external ROM is used for storing program then it has a logic-0 value every time the microcontroller reads a byte from memory. Pin 30: ALE Prior to every reading from external memory, the microcontroller sets the lower address byte (A0-A7) on P0 and immediately after that activates the output ALE. Upon receiving signal from the ALE pin, the external register (74HCT373 or 74HCT375 circuit is usually embedded ) remembers the state of P0 and uses it as an address for memory chip. In the second part of the microcontroller s machine cycle, a signal on this pin stops being emitted and P0 is used now for data transmission (Data Bus). In this way, by means of only one additional (and cheap) integrated circuit, data multiplexing from the port is performed. It is at the same time used for data and address transmission. Pin 31: EA By applying logical 0 to this pin, P2 and P3 are used for data and address transmission regardless if there is internal memory or not. That means that even there 17

18 is a program written to the microcontroller, it will not be executed, the program written to external ROM is used instead. Otherwise, by applying logical 1 to the EA pin, the microcontroller will use both memories, first internal and afterwards external (if it exists), up to end of address space. Pin 32-39: Port 0 Similar to port 2, if external memory is not used, these pins can be used as universal inputs or outputs. Otherwise, P0 is configured as address output (A0-A7) when the ALE pin is at high level and as data output (Data Bus), when logical 0 is applied to the ALE pin. Pin 40: VCC Power supply +5V 2.3 Input/Output Ports (I/O Ports) All 8051 microcontrollers have 4 I/O ports, each consisting of 8 bits which can be configured as inputs or outputs. This means that the user has on disposal in total of 32 input/output lines connecting the microcontroller to peripheral devices. A logical state on a pin determines whether it is configured as input or output: 0=output, 1=input. If a pin on the microcontroller needs to be configured as output, then a logical 0 should be applied to the appropriate bit on I/O port. In this way, a voltage level on the appropriate pin will be 0. Similar to that, if a pin needs to be configured as input, then a logical 1 should be applied to the appropriate port. In this way, as a side effect a voltage level on the appropriate pin will be 5V (as it is case with any TTL input). This maybe sounds a bit confusing but everything becomes clear after studying a simplified electronic circuit connected to one I/O pin. 18

19 19

20 Input/Output (I/O) pin This is a simplified overview of what is connected to a pin inside the microcontroller. It concerns all pins except those included in P0 which do not have embedded pullup resistor. Output pin A logical 0 is applied to a bit in the P register. By turning output FE transistor on, the appropriate pin is directly connected to ground. Input pin A logical 1 is applied to a bit in the P register. Output FE transistor is turned off. The appropriate pin remains connected to voltage supply through a pullup resistor of high resistance. 20

21 A logical state (voltage) at any pin can be changed or read at any moment. A logical 0 and logical 1 are not equal. A logical 0 represents almost short circuit to ground. Such a pin is configured as output. A logical 1 is loosely connected to voltage supply through resistors of high resistance. Since this voltage can be easily pulled down by an external signal, such a pin is configured as input. Port 0 Having a double role is very common for this port. If external memory is used then the lower address byte (addresses A0-A7) is applied on it. Otherwise, all bits on this port are configured as inputs or outputs. Another characteristic is expressed when it is configured as output. Namely, unlike other ports consisting of pins with embedded pullup resistor ( connected by its end to 5 V power supply ), this resistor is left out here. This, roughly estimated, a little exchange has its consequences: If any pin on this port is configured as input means that it performs as if it hangs in the air. Such input has unlimited input resistance and has no voltage coming from inside. When the pin is configured as output, it performs as open drain, meaning that by writing 0 to some port s bit, the appropriate pin will be connected to ground (0V). By 21

22 writing 1, the external output will keep on hang-ing. In order to apply 1 (5V) on this output, an external pullup resistor must be embedded. If P0 is used for addressing external memory ( only in that case), the microcontroller will provide internal power supply source in order to establish logical ones on pins. There is no need to add external pullup resistors. Port 1 This is an actual I/O port, because there are no roles assigned as it is the case with P0. Since it has embedded pullup resistors it is completely compatible with TTL circuits. Port 2 Similar to P0, when using external memory, lines on this port occupy addresses intended for external memory chip (this time it is the higher address byte with addresses A8-A15). When there is no additional memory, it can be used as universal input-output port similar by its features to the port 1. Port 3 Besides all these port pins can be used as universal I/O port, they also have an alternative function. Since each of these functions operate as input, the appropriate pin has to be configured equally. In other words, prior to using some of reserve port functions, a logical 1 must be written to the appropriate bit in the P3 register. From hardware s perspective, this port is also similar to P0, with the difference that its outputs have a pullup resistor embedded. Current limitations on pins When configured as outputs ( logical 0 ), single port pins can receive current of 10mA. If all 8 bits on a port are active, total current must be limited to 15mA (port P0: 26mA). If all ports (32 bits) are active, total maximal current must be limited to 71mA. When configured as inputs (logic 1), embedded pullup resistor provides a very weak current, but strong enough to activate up to 4 TTL inputs from LS series. As it is seen from description of some ports, even though all pins have more or less similar internal structure, it is necessary to pay attention to which of them will be used for what and how. For example: If they are used as outputs with high voltage level (5V), then port 0 should be avoided because on its pins which have no added resistor connecting them to +5V, only low logical level can be obtained. If another port is used for the same purpose, you should have in mind that factory build in resistor has a relatively high 22

23 resistance, so that it can be counted on only several hundreds microamperes of current coming out of a pin Microcontroller Memory Organisation The microcontroller memory is divided into Program Memory and Data Memory. Program Memory (ROM) is used for permanent saving program being executed, while Data Memory (RAM) is used for temporarily storing and keeping intermediate results and variables. Depending on the model in use ( still referring to the whole 8051 microcontroller family) at most a few Kb of ROM and 128 or 256 bytes of RAM can be used. However All 8051 microcontrollers have 16-bit addressing bus and can address 64 kb memory. It is neither a mistake nor a big ambition of engineers who were working on basic core developing. It s a matter of very clever memory organization which makes these controllers a real programmers tidbit. Program Memory The oldest models of the 8051 microcontroller family didn t have internal program memory. It was added from outside as a separate chip. These models are recognized by their label which begins with 803 ( for ex or 8032). All later models have a few Kbytes ROM embedded, which is enough for writing most of the programs, but there are situations when additional memory is necessary. A typical example of it is the use of so called look- up tables. They are used in cases when something is too complicated or when there is no time for solving equations describing some process. The example of it can be completely exotic (an estimate of self-guided rockets meeting point) or completely usual( measuring of temperature using non-linear thermo element or asynchronous motor speed control). In those cases all needed estimates and approximates are executed in advance and the final results are put in the tables ( similar to logarithmic tables ). How does the microcontroller handle external memory depends on the pin EA logical state: 23

24 EA=0 In this case, internal program memory is completely stored in external memory is to be executed. EA=1 In this case, a program from built-in ROM is to be executed first ( to the last location). Afterwards, the execution is continued by reading additional memory. in both cases, P0 and P2 are not available to the user because they are used for data nd address transmission. Besides, the pins ALE and PSEN are used too. Data Memory As it has been already said, Data Memory is used for temporarily storing and keeping data and intermediate results created and used during microcontroller s operating. Besides, this microcontroller family includes many other registers such as: hardware counters and timers, input/output ports, serial data buffers etc. The previous versions have total memory size of 256 locations, while for later models this number is incremented by additional 128 available registers. In both cases, these first 256 memory locations (addresses 0-FFh) are the base of the memory. This part is the same for all types of the 8051 microcontrollers. Locations available to the user occupy addressing space from 0 to 7Fh, i.e. first 128 registers and this part of RAM is divided in several blocks. 24

25 The first block consists of 4 banks each including 8 registers designated as R0 to R7. Prior to access them, a bank containing that register must be selected. Next memory block ( in the range of 20h to 2Fh) is bit- addressable, which means that each bit being there has its own address from 0 to 7Fh. Since there are 16 such registers, this block contains in total of 128 bits with separate addresses ( Bit 0 of byte 20h has the bit address 0, and bit 7 of byte 2Fh has the bit address 7Fh). The third group of registers occupy addresses 2Fh-7Fh ( in total of 80 locations) and doesn t have any special purpose or feature. Additional Memory Block of Data Memory In order to satisfy the programmers permanent hunger for Data Memory, producers have embedded an additional memory block of 128 locations into the latest versions of the 8051 microcontrollers. Naturally, it s not so simple The problem is that electronics performing addressing has 1 byte (8 bits) available and due to that it can reach only the first 256 locations. In order to keep already existing 8-bit architecture and compatibility with other existing models a little trick has been used. Using trick in this case means that additional memory block shares the same addresses with existing locations intended for the SFRs (80h- FFh). In order to differentiate these two physically separated memory spaces, different ways of addressing are used. A direct addressing is used for all locations from the SFRs, while the locations from additional RAM are accessible through indirect addressing. Ne 25

26 How to expand memory? In case that memory embedded in the microcontroller is not enough, it is possible to add two external memory chips with capacity of 64Kb each. For their addressing and data transmission I/O ports P2 and P3 are used. Kj 26

27 From the users perspective, everything functions rather simple if it is properly connected because the most operations are performed by the microcontroller itself. The 8051 microcontroller has two separate reading signals RD#(P3.7) and PSEN#. The first one is activated when there is a need to read byte from external data memory (RAM), while another one is activated to read byte from external program memory (ROM). These both signals are active at logical 0 level. A typical example of such memory extension using special chips for RAM and ROM, is shown on the previous picture. It is called Hardward architecture. Even though the additional memory is rarely used with the latest versions of the microcontrollers, it will be described here in short what is going on when memory chips are connected according to the previous scheme. It is important to know that the whole process is performed automatically, i.e. with no interference in the program. 27

28 When the program during execution reaches the instruction which resides in exter nal memory (ROM), the microcontroller will activate its control output ALE and set the first 8 bits of address (A0-A7) on P0. In this way, IC circuit 74HCT573 which passes on the first 8 bits to memory address pins is activated. A signal on the pin ALE closes the IC circuit 74HCT573 and immediately afterwards 8 higher bits of address (A8-A15) are set on the port. In this way, a desired location in addtional program memory is completely addressed and reading content is the only thing left over. Pins on P0 are configured as inputs, the pin PSEN is activated and the microcon troller reads content from memory chip (the same connections are used both for data and lower address byte). The similar occurs when there is a need to read some location from external Data Memory. Now, addressing is performed in the same way, while reading or writing to is performed via signals which appear on the control outputs RD or WR. Addressing While operating, processor processes data according to the program instructions. Each instruction consists of two parts: one part describes what should be done and another part indicates what to use to do it. This another part can be data (binary number) or address where the data is stored. All 8051 microcontrollers use two ways of addressing depending on which part of memory should be accessed: Direct Addressing On direct addressing, a value is obtained from a memory location while the address of that location is specified in instruction. Only after that, the instruction can process data (howdepends on the type of instruction: addition, subtraction, copy ). Obviously, a number being changed during operating (a variable) can resides in the given address. For example: Since an address is only one byte in size ( the greatest number is 255), this is how only the first 255 locations in RAM can be accessed ( the first half of the basic RAM is intended to be used freely, while another half is reserved for the SFRs). MOV A,33h; Means: move a number from address 33 hex. to accumulator Indirect Addressing On indirect addressing, a register which contains another register s address is specified in the instruction. A value used in operating process resides in that another register. For example: By indirect addressing, only locations in RAM available for use are accessed (never in the SFRs). For all latest versions of the microcontrollers with additional memory block ( 128 locations in Data Memory), this is the only way of accessing them. Simply, when during operating, the instruction sign is encountered and if the specified address is higher than 128 ( 7F hex.), then processor knows that 28

29 indirect addressing should be used and jumps over memory space reserved for the SFRs. MOV Means: Store the value from the register whose address is in the R0 register into accumulator On indirect addressing, the registers R0, R1 or Stack Pointer are used for specifying 8-bit addresses. Since only 8 bits are avilable, it is possible to access only registers of internal RAM in this way (128 locations in previous or 256 locations in latest versions of microcontrollers). If memory expansion in form of additional memory chip is used then the 16-bit DPTR Register (consisting of the registers DPTRL and DPTRH) is used for specifying addresses. In this way it is possible to access any location in the range of 64K. 2.5 SFRs (Special Function Registers) The SFRs are a kind of control table used for running and monitoring microcontroller s operating. Each of these registers, even each bit they include, has its name, address in the scope of RAM and clearly defined purpose ( for example: control of timers, interrupt, serial connection etc.). Even though there are 128 free memory locations intended for their storage, the basic core, shared by all types of the 8051 controllers, has only 21 such registers. Rest of locations are with the intention left free in order to enable the producers to make more perfect model keeping at the same time compatibility with the previous versions. It also enables the programs written a long time ago for the microcontrollers which are no longer produced to be still in use. 29

30 A Register (Accumulator) This is a general-purpose register which serves for storing intermediate results while operating. Prior to perform an instruction on a number (operand), it first should be added to the accumulator. Once the ALU performed an arithmetical operation, the result is added to the accumulator. Prior to be transferred from one register to another, the data must go through the accumulator. For such universal purpose, this is the most commonly used register that none microcontroller can be imagined without (more than a half instructions used by the 8051 microcontrollers use the accumulator in some way). B Register The B register is used during multiply and divide operations which can be performed only on numbers stored in the A and B registers. All other instructions in the program can use this register as a spare accumulator (A). While programming, each of registers are called by name so that their exact address is not so important for the user. During the process of compiling into machine code (series of hexadecimal numbers recognized as instructions by the microcontroller), PC will automatically, instead of registers name, write necessary addresses into the microcontroller. R Registers (R0-R7) 30

31 This is a common name for the total 8 generalpurpose registers (R0, R1, R2...R7). Even they are not actual SFRs, they should be discussed here because of their purpose. Four banks in RAM consist of these registers. Similar to the accumulator, they are used for temporary storing variables and intermediate results. Which of the banks will be active depends on two bits included in the PSW Register, i.e. in order to use the R registers, a bank must be active. The following example best illustrates the useful purpose of these registers. Assuming that mathematical operations on numbers previously stored in the R registers should be performed: (R1+R2) - (R3+R4). Obviously, a register for temporary storing results of addition is needed. Everything is rather simple and the program looks like this : MOV A,R3; Means: move a number from R3 into accumulator ADD A,R4; Means: add a 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 a number from R1 into accumulator ADD A,R2; Means: add a number from R2 to accumulator SUBB A,R5; Means: subtract a number from R5 ( there are R3+R4 ) PSW Register (Program Status Word) This is one of the most important SFRs. The Program Status Word (PSW) contains several status bits that reflect the current state of the CPU. It contains the Carry bit, Auxiliary Carry, two register bank select bits, Overflow flag, parity bit, and userdefinable status flag. The ALU automatically changes some of register s bits, which is usually used in regulation of the program performing. 31

32 P - Parity bit. If a number in accumulator is even then this bit will be automatically set (1), otherwise it will be cleared (0). It is mainly used during data transmission and receiving via serial communication. - Bit 1. This bit is reserved for the future versions of the microcontrollers, so it won t be used here. OV Overflow is when the result of arithmetical operation is greater than 255 (deci mal), so that it can not be stored in one register. In that case, this bit will be set (1). If there is no overflow, this bit will be cleared (0). RS0, RS1 - Register bank select bits. These two bits are used to select one of the four register banks in RAM. By setting these bits to 0 and 1, a group of registers R0- R7 is stored in one of four banks in RAM. RS1 RS Space RAM in Bank0 00h- 07h Bank1 08h- 0Fh Bank2 10h- 17h Bank3 18h- 1Fh F0 - Fleg 0. This is a general-purpose bit available to the user. 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. DPTR Register (Data Pointer) These are actually not registers because they don t physically exist. They consist of two separate registers: DPH (Data Pointer High) and (Data Pointer Low). Their intended function is to hold a 16-bits address for external memory addressing. They may be handled as a 16-bit register or as two independet 8-bit registers.besides, the DPTR Register is usually used for storing data and intermediate results which have nothing to do with memory locations. 32

33 SP Register (Stack Pointer) A value of the Stack Pointer ensures that the Stack Pointer will point to valid RAM and permits Stack availability. By starting each subprogram, the value in the Stack Pointer is incremented by 1. In the same manner, by ending subprogram, this value is decremented by 1. After any reset, the value 7 is written to the Stack Pointer, which means that the space of RAM reserved for the Stack starts from this location. If another value is written to this register then the entire Stack is moved to a new location in the memory. P0, P1, P2, P3 - Input/Output Registers In case that external memory and serial communication system are not in use then, 4 ports with in total of 32 input-output lines are available to the user for connection to peripheral environment. Each bit inside these ports matches appropriate pin on the microcontroller. This means that logical state to be written to them appeares as a voltage on the pin ( 0 or 5 V). Naturally, while reading, the opposite occurs voltage on some input pins is reflected in the appropriate port bit. The state of a port bit, besides being reflected in the pin,simultaneously determines whether it will be configured as input or output: if a bit is cleared (0), the pin will be configured as output. In the same manner, if a bit is set to 1 the same pin will be configured as input. After reset, as well as while turning the microcontroller on, all bits on these ports are set to 1. This means that the appropriate pins will be configured as inputs. 33

34 Conditionally said, I/O ports are directly connected to the microcontroller s pins. This means that a logical state of these registers can be checked by voltmeter and vice versa-voltage on the pins can be checked by testing their bits! 2.6 Counters and Timers It is explained in the previous chapter that the main oscillator of the microcontroller uses quartz crystal for its operating. As the frequency of this oscillator is precisely defined and very stable, these pulses are the most suitable for time measuring (such oscillators are used in quartz clocks as well). In order to measure time between two events it is only needed to count up pulses from this oscillator. That is exactly what the timer is doing. Namely, if the timer is properly programmed, then the value written to the timer register will be incremented ( or decremented ) after each coming pulse, i.e. one at a time during each machine cycle. Since one instruction lasts 12 quartz oscillator periods (one machine cycle), then by embedding quartz with oscillator frequency of 12MHz, a number in the timer register will be changed million times per second, i.e. each microsecond. The 8051 microcontrollers have 2 timer-counters called T0 and T1. As the name says, their main purpose is to measure time and count external events. Besides, they can be used for generating clock pulses used in serial communication, i.e. Baud Rate. Timer T0 As it is shown in the picture below, this timer consists of two registers TH0 and TL0 while numbers they include represent a lower and a higher byte of one 16-digit binary number. This means that if the content of the timer 0 is equal to 0 (T0=0) then both registers it includes will include 0. If the same timer contains for example number 1000 (decimal) then the register TH0 (higher byte) will contain number 3, while TL0 (lower byte) will contain decimal number

35 Formula used to calculate values in registers is very simple: TH TL0 = T Matching the previous example it would be as follows : = 1000 Since the timers are virtually 16-bit registers, the greatest value that could be written to them is In case of exceeding this value, the timer will be automatically reset and after that counting starts from 0. This is called overflow. Two registers TMOD and TCON are closely connected to this timer and control how it operates. TMOD Register (Timer Mode) This register selects mode of the timers T0 and T1. As it is illustrated in the following picture, the lower 4 bits (bit0 - bit3) refer to the timer 0, while the higher 4 bits (bit4 - bit7) refer to the timer 1. There are in total of 4 modes and each of them is described here in detail. Bits of this register have the following purpose: 35

36 GATE1 starts and stops Timer 1 by means of a signal provided to the pin INT1 (P3.3): o 1 - Timer 1 operates only if the bit INT1 is set o 0 - Timer 1 operates regardless of the state of the bit INT 1 C/T1 selects which pulses are to be counted up by the timer/counter 1: o 1 - Timer counts pulses provided to the pin T1 (P3.5) o 0 - Timer counts pulses from internal oscillator T1M1,T1M0 These two bits selects the Timer 1 operating mode. T1M1 T1M0 Mode Description bit timer bit timer Split mode GATE0 starts and stops Timer 1, using a signal provided to the pin INT0 (P3.2): o 1 - Timer 0 operates only if the bit INT0 is set o 0 - Timer 0 operates regardless of the state of the bit INT0 C/T0 selects which pulses are to be counted up by the timer/counter 0: o 1 - Timer counts pulses provided to the pin T0(P3.4) o 0 - Timer counts pulses from internal oscillator T0M1,T0M0 These two bits select the Timer 0 operating mode. T0M1 T0M0 Mode Description bit timer bit timer auto- 8-bit reload Split mode Timer 0 in mode 0 (13-bit timer) auto- 8-bit reload This is one of the rarities being kept only for compatibility with the previuos versions of the microcontrollers. When using this mode, the higher byte TH0 and only the first 5 bits of the lower byte TL0 are in use. Being configured in this way, the Timer 0 uses only 13 of all 16 bits. How does it operate? With each new pulse coming, the state of the lower register (that one with 5 bits) is changed. After 32 pulses received it becomes full and automatically is reset, while the higher byte TH0 is incremented by 1. This action will be repeated until registers count up 8192 pulses. After that, both registers are reset and start counting from 0. 36

37 Timer 0 in mode 1 (16-bit timer) All bits from the registers TH0 and TL0 are used in this mode. That is the reason for this mode being more commonly used. Counting is performed in the same way as in mode 0, with difference that the timer counts up to , i.e. as much as the use of 16 bits allows. Timer 0 in mode 2 (Auto-Reload Timer) What does auto-reload mean? Simply, it means that timer uses only one 8-bit register for counting, but it doesn t have to start counting from 0 but from an arbitrary chosen 37

38 value (0-255) which is saved in another register. The advantages of this kind of counting are described in the following example: assuming that for any reason it is continuously needed to count up 55 pulses at a time from the clock generator. When using mode 1 or mode 0, It is needed to write number 200 to the timer registers and afterwards constantly check whether it has come to overflow, i.e. whether the value 255 is reached by counting. When it has occurred, it is needed to write to number 200 one more time and repeat the whole procedure. The microcontroller performs the same procedure in mode 2 automatically. Namely, in this mode it is only register TL0 operating as a timer ( normally 8-bit), while the value from which counting should start is saved in the TH0 register. Referring to the previous example, in order to register each 55th pulse, it is needed to write the number 200 to the register and configure the timer to operate in mode 2. Timer 0 in Mode 3 (Split Timer) By configuring Timer 0 to operate in Mode 3, it becomes two separate 8-bit timers. TL0 becomes Timer 0, while TH0 becomes Timer 1. In addition, all control bits which initially belonged to the Timer 1 (consisting of the registers TH1 and TL1), now control newly created Timer 1. This means that even though the initial Timer 1 still can be configured to operate in any mode ( mode 1, 2 or 3 ), it is no longer able to stop, simply because there is no bit to do that. Therefore, in this mode, it will uninterruptedly operate in the background. 38

39 The only application of this mode is when it is needed to have two separate timers and, additionally, a baud rate generator. In such case, TH0 and TL0 are used as two separate timers and the initial Timer 1 (whose operating is out of control) is used as baud rate generator. TCON - Timer Control Register This is also one of the registers whose bits directly control timer operating. Only 4 of all 8 bits this register has are used for timer control, while others are used for interrupt control which will be discussed later. TF1 This bit is automatically set with the Timer 1 overflow TR1 This bit turns the Timer 1 on o 1 - Timer 1 is turned on o 0 - Timer 1 is turned off TF0 This bit is automatically set with the Timer 0 overflow. TR0 This bit turns the timer 0 on 39

40 o o 1 - Timer 0 is turned on 0 - Timer 0 is turned off How to start Timer 0? As it is usual, first select this timer and afterwards its mode. Bits which control that are resided in the register TMOD: This means that timer 0 operates in mode 1 and counts pulses from internal source whose frequency is equal to 1/12 the quartz frequency. In order to enable the timer, turn it on: 40

41 Immediately upon the bit TR0 is set, the timer starts operating. Assuming that a quartz crystal with frequency of 12MHz is embedded, then a number in it will be incremented every microsecond. By counting up to microseconds, the both registers that timer consists of will be set. The microcontroller automatically reset them and the timer keeps on repeating counting from the beginning as far as the bit s value is logical 1. Depending on the timer s application, it is needed to read a number in the timer registers or to register a moment it has been reset. - Everything is extremely simple when it is needed to read a value of the timer which uses only one register for counting (mode 2 or Mode 3). It is sufficient to read its state at any moment and it is it! - It is a bit complicated to read a timer s value when it operates in mode 2. Assuming that the state of the lower byte is read first (TL0) and the state of the higher byte (TH0) afterwards, the result is: TH0 = 15 TL0 = 255 Everything seems to be in order at first sight, but actual state of register at the moment of reading was: TH0 = 14 TL0 = 255 In case of negligence, this error in counting ( 255 pulses ) can occur for not so obvious but rather logical reason. Reading the lower byte is correct ( 255 ), but at the same time the program counter was taking a new instruction for the TH0 state reading, an overflow occurred and both registers have changed their contents ( TH0: 14 15, TL0: 255 0). The problem has simple solution: the state of the higher byte should be read first, then the state of the lower byte and once again the state of the higher byte. If the number which resides in the higher byte is not the same both times it has been read then this sequence should be repeated ( this is a mini- loop consisting of only 3 instructions in a program). There is another solution too. It is sufficient to simply turn timer off while reading ( the bit TR0 in the register TCON should be 0), and turn it on after that. Detecting Timer 0 Overflow Usually, there is no need to continuously read timer registers contents. It is sufficient to register the moment they are being reset, i.e. when counting starts from 0. It is called overflow. When this has occurred, the bit TF0 from the register TCON will be automatically set. The microcontroller is waiting for that moment in a way that program will constantly check the state of this bit. Furthermore, an interrupt to stop the main program execution can be enabled. Assuming that it is needed to provide a program pause ( time the program appeared to be stopped) in duration of for example 0.05 seconds ( machine cycles ): First, it is needed to calculate a number that should be written to the timer registers: 41

42 This number should be written to the timer registers TH0 and TL0: Once the timer is started it will continue counting from the written number. Program 42

43 instruction checks if the bit TF0 is set, which happens at the moment of overflow, i.e. after exactly machine cycles and 0.05 seconds respectively. How to measure pulses? Suppose it is needed to measure the duration of an event, for example how long some device has been turned on? Look at the picture of the timer and pay attention to the purpose of the bit GATE0 ( resides in the TMOD register ). If this bit is reset then the state on the pin P3.2 does not affect the timer operating. If GATE0 = 1 then the timer will operate only as far as the pin P3.2 has logical 1 value. This means that if this pin is supplied with 5V through some external switch at the same time the device is being turned on, the timer will measure duration of its operating, which actually was the aim. How to count up pulses? This time, the answer lies in the register TCON, actually in the bit C/T0. Similar to the previous example, this bit brings into an external signal. If the bit is cleared everything occurs in the same way as in the previous examples and the timer counts pulses from oscillator of known frequency, i.e. measures the time that went by. If the bit is set, the timer input is provided with pulses from the pin P3.4 (T0). Since these pulses do not have some definite time or order, it is not possible to measure time by counting them. For that reason, this timer converts into the counter. The highest frequency that could be measured by such a counter is 1/24 of used quartz-crystal frequency. Timer 1 Referring to its characteristics, this timer is a twin brother to the timer 0. This means that they have the same purpose, their operating is controlled by the same registers TMOD and TCON and both of them can operate in one of 4 different modes. 43

44 2.7 UART (Universal Asynchronous Receiver and Transmitter) One of the features that makes this microcontroller so powerful is an integrated UART, better known as a serial port. It is a duplex port, meaning it can transmit and receive data simultaneously. Without it, serial data sending and receiving would be endlessly complicated part of the program where the pin state continuously is being changed and checked according to strictly determined rhythm. Naturally, nothing similar happens here because the UART solves it in a very elegant manner: All the programmer needs to do is to simply select serial port mode and transfer rate. When configured like this, serial data sending means writing to the register SBUF while data receiving is done by reading the same register. The microcontroller is taking care of all details necessary for making no error while data transferring. The first thing that should be done prior to use serial port is to configure it. This determines how many bits does one serial word contain, what is the transmission rate and what is the pulse source for synchronization. All bits controlling this are placed in the SFR Register SCON (Serial Control). SCON Register (Serial Port Control Register) SM0 - bit selects mode SM1 - bit selects mode SM2 - this bit is used in case that several microcontrollers exchange data through the same line. In normal circumstances this bit must be cleared in order to enable connection to function normally. 44

45 REN - bit enables data receiving. It is simply used and must be set in case of data receiving via serial communication. TB8 - the 9th bit in case of data sending. Since all registers in microcontroller are 8-bit registers, this bit solves the problem of sending the 9th bit in modes 2 and 3 where 9-bit format is used. Simply, its content is sent as the 9th bit. RB8 - the 9th bit in case of data receiving in modes 2 and 3. It has the same purpose as the bit TB8 but this time on the receiver side. This means that on receiving data in 9-bit format, the value of the last ( ninth) bit is being appeared on its place. TI - this bit is automatically set at the moment the last bit of one byte is passed on to the transmitter side. In that way processor knows that the line is available for sending a new bit. Bit must be program cleared! RI - this bit is automatically set when one byte has been received. Everything functions in the similar way as in the previous case but on the receivier side. This is doorbell which announces that a byte is received via serial communication and it should be read quickly prior to a new data takes its place. This bit must also be program cleared! As it can be seen, serial port mode is selected by combining the bits SM0 and SM2 : SM0 SM1 Mode Description Baud Rate bit Shift Register bit UART bit UART bit UART 1/12 the quartz frequency Determined by the timer 1 1/32 the quartz frequency (1/64 the quartz frequency) Determined by the timer 1 45

46 In mode 0, the data are transmitted and received through the RXD pin, while TXD pin is fed with clock pulses. The bout rate is fixed at 1/12 the quartz oscillator frequency. On transmit, the lowest significant bit (LSB bit) is being first sent (received). TRANSMIT - At the moment the data has beenwritten to the SBUF register, automatically starts data sending in form of pulses on the pin RXD ( more accurately said, this process starts after any instruction being performed on this register). Upon all 8 bits have been sent, the bit TI in the SCON register is automatically set. RECEIVE - Once two necessary conditions are met: bit REN=1 and RI=0 (both bits reside in the SCON register), starts data receiving through the pin RXD. Upon 8 bits have been received, the bit RI (register SCON) is automatically set, which indicates that one byte is received. Since within these bits, there are no start and stop bit or any other bit except data from the SBUF register, this mode is mainly used on shorter distance where the noise level is minimal and where operation rate is important. A typical example for this is expansion of I/O ports by adding cheap IC circuit ( shift registers 74HC595, 74HC597 and so on). Mode 1 46

47 In this mode 10 bits are transmitted through TXD or received through RXD in the following order: a start bit (always 0), 8 data bits (LSB first) and a stop bit (always 1) at last. In this oulse train, the start bit is not registered anywhere and has the role to start data receiving mechanism while the stop bit during receiving automatically goes into the RB8 bit in the SCON register. TRANSMIT - Once data are written to the SBUF register, a sequence for its serial transmission is automatically started. End of message is indicated by setting the TI bit in the SCON register. RECEIVING - Receiving starts as soon as the start bit (logical 0) is on the pin RXD. The condition is that bit REN=1and bit RI=0 ( both in the SCON register). Once receiving is terminated, the bit RI is automatically set. 47

48 The Baud rate in this mode is variable determined by the timer 1 overflow time. Mode 2 In this mode 11 bits are transmitted through TXD or received through RXD: a start bit (always 0), 8 data bits (LSB first), the additional 9th data bit and a stop bit (always 1) at last. On transmit, the 9th data bit is actually the TB8 bit in the SCON register ) commonly has the role of parity bit. On receive, the 9th data bit goes into RB8 in the same register ( SCON).The baud rate is programmable to either 1/32 or 1/64 the quartz oscillator frequency. TRANSMIT - Once data are written to the SBUF register, a sequence for its serial transmission is automatically started. End of message is indicated by setting the TI bit in the SCON register. 48

49 RECEIVE - Receive starts as soon as the start bit (logical 0) is on the pin RXD. The condition is that the bit REN=1and the bit RI=0 ( both in the SCON register). Once receiving is terminated, the bit RI is automatically set. 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 and can be selected. The parity bit is the bit P in the PSW register. The most simple way to check validity of the received message is to add this bit to the transmit side as additional bit. Simply, immediately before transmit, the message is stored in the accumulator and the bit P goes into the TB8 bit in order to be a part of the message. On the receive side is the opposite : received byte is stored in the accumulator and the bit P is compared with the bit RB8 ( additional bit in the message). If they are the same- everything is OK! Baud Rate Baud Rate is defined as a number of bits per second. In case the UART is used, baud rate depends on: chosen mode, the main oscillator frequency and in some cases the bit SMOD state in the 0 SCON register. All needed formulas are listed in the table : Baud Rate Mode 0 Fosc. / 12 Mode 1 BitSMOD 1 Fosc (256- BitSMOD 49

50 Mode 2 TH1) Fosc. / 32 Fosc. / Fosc. Mode (256- TH1) Timer 1 as a baud rate generator This timer is usually used as a baud rate generator because it is easy to adjust its various baud rate. Process itself is simple: First, Timer 1 overflow interrupt should be disabled T1 should be configured as a timer which operates in auto-reload mode Depending on baud rate needed, one value should be selected from the table in order to obtain some of the standard values. This value should be written to the TH1 register and that s all! Fosc. (MHz) Baud Rate Bit SMOD h 30 h 00 h A0 h 98 h 80 h 75 h 52 h D0 h CC h C0 h BB h A9 h E8 h E6 h E0 h DE h D5 h F4 h F3 h F0 h EF h EA h F3 h EF h EF h FA h F8 h F5 h FD h FC h F5 h FD h FC h FE h FF h 1 Multiprocessor Communication As it is described in the text above, modes 2 and 3 provide the additional 9th data bit. It can be used for checking data via parity bit. Another useful application of this bit is in communication between two microcontrollers, i.e. multiprocessor communication. This feature is enabled by setting the SM2 bit in the SCON register. The consequence of this is as follows: when the stop bit, indicating end of message is received, the serial port interrupt will be requested only if the bit RB8 ( the 9th bit)=1. The whole process will be performed as follows: Suppose that there are several connected microcontrollers having to exchange data. That means that each of them must have an address. The point is that the 9th bit is set 50

51 to 1 for address bytes and to 0 for data bytes, respectively. If the microcontroller A should transmit data to the microcontroller C then it will first send address C and logical 1 as the 9th bit. It generates interrupt and all microcontrollers will check whether they are called. Of course, only one of them will recognize this address and immediately clear the bit SM2 in the SCON register. All following data will be normally received and ignored by other microcontrollers Microcontroller Interrupts There are five interrupt sources for the 8051, which means that they can recognize 5 different event that can interrupt regular program execution. Each interrupt can be enabled or disabled by setting bits in the IE register. Also, as it can be seen from the picture below the whole interrupt system can be disabled by clearing bit EA in the same register. Now, it will be explained one detail which is not completely obvious and refers to external interrupts- INT0 and INT1. Namely, if the bits IT0 and IT1 (in the TCON register) are set, program interrupt will occur by changing logical state from 1 to 0, 51

52 i.e. only on the falling edge. If these bits are cleared, the same signal will generate interrupt request and it will be continuously executed as far as the pins are held low. IE Register (Interrupt Enable) EA - bit enables or disables all other interrupt sources (globally) o 0 - (when cleared) any interrupt request is ignored (even if it is enabled) o 1 - (when set to 1) enables all interrupts requests which are individually enabled ES - bit enables or disables serial communication interrupt (UART) o 0 - UART System can not generate interrupt o 1 - UART system enables interrupt ET1 - bit enables or disables timer 1 interrupt o 0 - Timer 1 can not generate interrupt o 1 - Timer 1 enables interrupt EX1 - bit enables or disables INT 0 pin external interrupt o 0 - changing of the pin INT0 logical state can not generate interrupt o 1 - enables external interrupt at the moment of changing the pin INT0 state ET0 - bit enables or disables timer 0 interrupt 52

53 o 0 - Timer 0 can not generate interrupt o 1 - enables timer 0 interrupt EX0 - bit enables or disables INT1 pin external interrupt o 0 - changing INT1 pin logical state can not cause interrupt o 1 - enables external interrupt at the moment of changing the pin INT1 state Interrupt Priorities It is not possible to predict when the interrupt will be required. For that reason, if several interrupts are being enabled it can easily occur that while one of them is being in progress, another one is requested. In such situation, there is priority list making the microcontroller know whether to continue operation or to meet a new priority request. The priority list cosists of 3 levels: 1. Reset! The apsolute master of the situation. If there is an request for Reset, everything is being stopped and the microcontroller starts operating from the beginning. 2. Interrupt priority. It can be stopped by Reset only. 3. Interrupt priority 0. It can be stopped by both Reset and interrupt priority 1. In the IP Register ( Interrupt Priority Register) is defined which one of these existing interrupt sources have higher and which one has lower priority and it is usually done at the beginning of the program. After that, there are several possibilities: Once an interrupt service begins it cannot be interrupted by another inter rupt at the same or lower priority level, but only by a higher priority interrupt. If two interrupt requests, at different priority levels, arrive at the same time then the higher priority interrupt is serviced first. If the both interrupt requests, at the same priority level, occur one after another, the one who came later has to wait until routine being in progress ends. If two interrupts of equal priority requests arrive at the same time then the interrupt to be serviced is selected according to the following priority list : 1. External interrupt INT0 2. Timer 0 interrupt 3. External Interrupt INT1 4. Timer 1 interrupt 5. Serial Communication Interrupt IP Register (Interrupt Priority) The IP register bits specify the relative priority (high or low priority ) of each interrupt. 53

54 PS - Serial Port Interrupt priority bit o Priority 0 o Priority 1 PT1 - Timer 1 interrupt priority o Priority 0 o Priority 1 PX1 - External Interrupt INT1 priority o Priority 0 o Priority 1 PT0 - Timer 0 Interrupt Priority o Priority 0 o Priority 1 PX0 - External Interrupt INT0 Priority o Priority 0 o Priority 1 Handling Interrupt Once some of interrupt requests arrives, everything occurs according to the following order: 1. Instruction in progress is being ended 2. The next program instruction address is pushed on the stack 3. Depending on which interrupt is requested, one of 5 vectors (addresses) are written to the Program Counter according to the following table: Interrupt Source IE0 TF0 TF1 RI, TI Vector (address) 3 h B h 1B h 23 h All addresses are in hexadecimal format 4. The appropriate sub-routines processing interrupts have to be at these addresses. Instead of them, there are usually instructions indicating the place where the sub-routines reside ( jump instruction). 5. When interrupt routine is executed, address is poped from the stack to program counter and the interrupted program resumes operating from where it left off. 54

55 From the moment an interrupt is enabled, the microcontroller is on alert all the time. When interrupt request arrives, the program execution is interrupted, electronics recognizes the cause and the program jumps to the appropriate address (see the table above ). Usually, there is a jump instruction which leads to the subroutine prepared in advance. The subroutine is being executed ( it is exactly the aim- to do something when something else has happened). After that, the program continues operating from where it left off Reset Reset occurs when the RS pin is supplied with a positive pulse in duration of at least 2 machine cycles ( 24 clock cycles of crystal oscillator). After that, the microcontroller generates internal reset signal during which all SFRs, excluding SBUF registers, Stack Pointer and ports are reset ( the state of the first two ports is indefinite while FF value is being written to the ports configuring all pins as inputs). Depending on device purpose and environment it is in, on power-on reset it is usually push button or circuit or both connected to the RS pin. One of the most simple circuit providing secure reset at the moment of turning power on is shown on the picture. Everything functions rather simply: upon the power is on, electrical condenser is being charged for several milliseconds through resistor connected to the ground and during this process the pin voltage supply is on. When the condenser is charged, power supply voltage is stable and the pin keeps being connected to the ground providing normal operating in that way. If later on, during the operation, manual reset button is pushed, the condenser is being temporarily discharged and the microcontroller is being reset. Upon the button release, the whole process is repeated 55

56 Through the program- step by step... In normal environment the microcontrollers operate at very high speed. The use of crystal quartz for 12Mhz means that instructions per second will be executed! In principle, there is no need for higher operating rate ( in case it is needed, it is easy to embed crystal for higher frequency). But, the problem arises when it is needed to slow down. For example: when during the testing in real operating environment, several instructions should be executed step by step in order to check logical state of I/O pins. Interrupt system applied on the 8051 microcontrollers practically stops operating and enables that instructions are executed one at the time by pushing button. Two interrupt features enables that: Interrupt request is ignored if an interrupt of the same priority level is being exe cuted. Upon interrupt routine has been executed, a new interrupt is not executed as far as at least one instruction of the main program is not executed. In order to use it 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 added to the program (at address 03hex.): What s going on? As soon as the pin P3.2 is set to 0 (for example, by pushing button), the microcontroller will interrupt program execution and jump to the address 03hex. where mini-interrupt routine consisting of 3 instructions is shown. The first instruction is being executed as far as the push button is pressed ( logic 1 on the pin P3.2). The second instruction is being executed as far as the push button is released. Immediately after that, the instruction RETI is executed and processor executes the main program again. After each executed instruction, interrupt INT0 is activated ( push button is still pressed) and the whole process is repeated. Each button press=one instruction. 56

57 Microcontroller Power Consumption Control The microcontroller is the most part of its lifetime inactive ( conditionally said ), and waits for some external signal in order to do its part of job. The use of battery for power supply can be a big problem. In extremely cases, the only solution is to put the whole electronics to sleep in order to reduce consumption to the minimum. A typical example of this is remote TV controller: it can be out of use for months but when used again it takes less than a second to send a command to TV receiver. While normally operating, the AT89S53 uses current of approximately 25mA, which shows that it is not too sparing microcontroller. Anyway, it doesn t have to be always like this, it can easily switch the operation mode in order to reduce its total consumption to approximately 40uA. Actually, there are two power-saving modes of operation: Idle and Power Down. Idle mode 57

58 Immediately upon instruction set the bit IDL in the PCON register, the microcontroller turns off the greatest power consumer- CPU unit while peripheral units ( serial port, timers and interrupt system ) continue operating normally using 6.5mA. In Idle mode, the state of all registers and I/O ports is unchanged. In order to terminate the Idle mode and make the microcontroller continue normal operating, it is needed to enable any interrupt or reset When it has been occurred, the IDL bit is automatically erased and the program continues executing the first instruction following that instruction which has set the IDL bit. It is recommended that three first following instructions are NOP instructions, for these instructions do not perform any operation but keeps the microcontroller from undesired changes on the I/O ports. Power Down mode By program setting the bit PD in the register PCON, the microcontroller goes into Powerdown mode and turns off its internal oscillator reducing drastically consumption in that way. In power- down mode the microcontroller can operate using only 2V power supply while the total power consumption is less than 40nA. The only way to put the microcontroller back to normal mode is reset. During Power Down mode, the state of all SFR registers and I/O ports remains unchanged, and after the microcontroller is put back into the normal mode, the content of the SFR register is lost, but the content of internal RAM is saved. Reset signal must be long enough ( approximately 10mS ) in order to stabilize quartz oscillator operating. PCON register The purpose of the Register PCON bits : SMOD By setting this bit baud rate is doubled. GF1 General-purpose bit (available to use). GF1 General-purpose bit (available to use). GF0 General-purpose bit (available to use). PD By setting this bit the microcontroller is put into Power Down mode. IDL By setting this bit the microcontroller is put into Idle mode. 58

59 Chapter 3 : The 8051 Instruction Set 3.1 Types of instructions 3.2 Description of the 8051 instructions Introduction Writing program for the microcontroller mainly consists of giving instructions (commands) in that order in which they should be performed later in order to carry out specific task. As electronics can not understand what for example instruction if the push button is pressed- turn on the light means, then a certain number of more simple and precisely defined orders that decoder can recognise must be used. All commands are known as THE INSTRUCTION SET. All microcontrollers compatibile with the 8051 have in total 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 s not so complicated as it looks like. Since many instructions are considered to be different, even though they perform the same operation, there are as a matter of fact only 111 truly different commands. For example: ADD A,R0, ADD A,R1,... ADD A,R7 are instructions that perform the same operation (additon of the Accumulator and Register) but since there are 8 such registers, each instruction is counted separately! Taking into account that all instructions perform only 53 operations ( addition, subtraction, copy etc.) and that most of them are rarely used in practice, there are actually shortened forms needed to be known, which is actually acceptable. 3.1 Types of instructions Depending on operation they perform, all instructions are divided in several groups: Arithmetic Instructions Branch Instructions Data Transfer Instructions Logical Instructions Logical Instructions with bits The first part of each instruction, called MNEMONIC refers to the operation an instruction performs (copying, addition, a logical operation etc.). Mnemonics are most commonly shortened names of operation being executed. For example: INC R1 - Means: Increment R1 (increment register R1) LJMP LAB5 - Means: Long Jump LAB5 (long jump to address specified as LAB5) JNZ LOOP - Means: Jump if Not Zero LOOP (if the number in the Accumulator is not 0, jump to address specified as LOOP) Another part of instruction, called OPERAND is separated from mnemonic at least by one empty space and defines data being processed by instructions. Some instructions 59

60 have no operand, some have one, two or three. If there is more than one operand in instruction, they are separated by comma. For example: RET - (return from sub-routine) JZ TEMP - (if the number in the Accumulator is not 0, jump to address specified as TEMP) ADD A,R3 - (add R3 and Accumulator) CJNE A,#20,LOOP - (compare Accumulator with 20. If they are not equal, jump to address specified as LOOP) Arithmetic instructions These instructions perform several basic operations ( 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. Arithmetical Instructions Mnemonic Description Byte Number ADD A,Rn Add R Register to Accumulator 1 1 ADD A,Rx ADD A,@Ri Add directly addressed Rx Register to Accumulator Add indirectly addressed Register to Accumulator ADD A,#X Add number X to Accumulator 2 2 ADDC A,Rn ADDC A,Rx ADDC A,@Ri ADDC A,#X SUBB A,Rn SUBB A,Rx SUBB A,@Ri SUBB A,#X Add R Register with Carry bit to Accumulator Add directly addressed Rx Register with Carry bit to Accumulator Add indirectly addressed Register with Carry bit to Accumulator Add number X with Carry bit to Accumulator Subtruct R Register with borrow from Accumulator Subtruct directly addressed Rx Register with borrow from Accumulator Subtruct indirectly addressed Register with borrow from Accumulator Subtruct number X with borrow from Accumulator INC A Increment Accumulator by INC Rn Increment R Register by Oscillator Period 60

61 INC Rx Increment directly addressed Rx Register by 1 Increment indirectly addressed Register by DEC A Decrement Accumulator by DEC Rn Decrement R Register by DEC Rx Decrement directly addressed Rx Register by 1 Decrement indirectly addressed Register by INC DPTR Increment Data Pointer by MUL AB DIV AB Multiply number in Accumulator by B register Divide number in Accumulator by B register Decimal adjust Accumulator according to DA A BCD code Branching Instructions There are two kinds of these instructions: Unconditional jump instructions: after their execution a jump to a new location from where the program continues execution is executed. Conditional jump instructions: if some condition is met - a jump is executed. Otherwise, the program normally proceeds with the next instruction. Branching Instruction Mnemonic ACALL adr11 LCALL adr16 Description Call subroutine located at addreess within the 2 K byte Program Memory space Byte Number 2 3 Call subroutine located at any address within the 64 K byte Program Memory 3 4 space RET Return from subroutine 1 4 RETI Return from interrupt routine 1 4 AJMP adr11 LJMP adr16 SJMP rel Jump to address located within the 2 K byte Program Memory space Jump to any address located within the 64 K byte Program Memory space Short jump (from 128 to +127 locations in relation to the first next instruction) Oscillator Period 61

62 JC rel Jump if Carry bit is set. Short jump. 2 3 JNC rel Jump if Carry bit is cleared. Short jump. 2 3 JB bit,rel Jump if addressed bit is set. Short jump. 3 4 JBC bit,rel Jump if addressed bit is set and clear it. Short jump. Indirect jump. Jump address is obtained by addition of Accumulator and DPTR Register JZ rel Jump if Accumulator is 0. Short jump. 2 3 JNZ rel Jump if Accumulator is not 0. Short jump. 2 3 CJNE A,Rx,rel CJNE A,#X,rel CJNE Rn,#X,rel DJNZ Rn,rel DJNZ Rx,rel Compare Accumulator and directly addressed Register Rx. Jump if they are different. Short jump. Compare Accumulator with number X. Jump if they are different. Short jump. Compare Register R with number X. Jump if they are different. Short jump. Compare indirectly addressed register with number X. Jump if they are different. Short jump. Decrement R Register by 1. Jump if the result is not 0. Short jump Decrement directly addressed Register Rx by 1. Jump if the result is not 0. Short jump. 3 4 NOP No operation 1 1 Data Transfer Instruction These instructions move the content of one register to another one (the register which content is moved is not altered). If they have the suffix X (MOVX), the data is exchanged with external memory. Data Transfer Instruction Mnemonic Description Byte Number MOV A,Rn Move R register to Accumulator 1 1 MOV A,Rx MOV A,@Ri Move directly addressed Rx register to Accumulator Move indirectly addressed register to Accumulator MOV A,#X Store number X in accumulator 2 2 MOV Rn,A Move Accumulator to R register 1 1 MOV Rn,Rx Move directly addressed Rx register to R register 2 2 Cycle Number 62

63 MOV Rn,#X Move number X to R register 2 2 MOV Rx,A MOV Rx,Rn MOV Rx,Ry MOV Rx,@Ri MOV Rx,#X MOV DPTR,#X MOVC A,@A+DPTR MOVC A,@A+PC MOVX A,@Ri MOVX A,@DPTR PUSH Rx POP Rx Move Accumulator to directly addressed Rx register Move R register to directly addressed Rx register Move directly addressed register Ry to directly addressed Rx register Move indirectly addressed register to directly addressed Rx register Store number X in directly addressed Rx register Move Accumulator to indirectly addressed register Move directly addressed Rx register to indirectly addressed register Store number X in indirectly addressed register Store number X in Data Pointer 3 3 Move register from Program Memory (address= A+DPTR) to Accumulator Move register from Program Memory (address= A+PC) to Accumulator Move data from external memory (8-bit address) to Accumulator Move data from external memory (16- bit address) to Accumulator Move Accumulator to external memory register (8-bit address) Move Accumulator to external memory register (16-bit address) Push directly addressed Rx register in the part of RAM provided for Stack Pop data from Stack part of RAM. Store it in directly addressed Rx register XCH A,Rn Exchange Accumulator with R register 1 1 XCH A,Rx XCH A,@Ri XCHD A,@Ri Logical Instruction Exchange Accumulator with directly addressed Rx register Exchange accumulator with indirectly addressed register Exchange 4 lower bits in accumulator with indirectly addressed register

64 These instructions perform logical operations between corresponding bits of two registers. After execution, the result is stored in the first operand. Logical Instructions Mnemonic ANL A,Rn ANL A,Rx ANL ANL A,#X ANL Rx,A ANL Rx,#X ORL A,Rn ORL A,Rx ORL ORL Rx,A ORL Rx,#X XORL A,Rn XORL A,Rx XORL XORL A,#X XORL Rx,A XORL Rx,#X Description Logical AND between Accumulator and R register Logical AND between Accumulator and directly addressed register Rx Logical AND between Accumulator and indirectly addressed register Logical AND between Accumulator and number X Logical AND between Accumulator and directly addressed register Rx Logical AND between directly addressed register Rx and number X Logical OR between Accumulator and R register Logical OR between Accumulator and directly addressed register Rx Logical OR between Accumulator and indirectly addressed register Logical OR between Accumulator and directly addressed register Rx Logical OR between directly addressed register Rx and number X Logical exclusive OR between Accumulator and R register Logical exclusive OR between Accumulator and directly addressed register Rx Logical exclusive OR between Accumulator and indirectly addressed register Logical exclusive OR between Accumulator and number X Logical exclusive OR between Accumulator and directly addressed register Rx Logical exclusive OR between Accumulator and directly addressed register Rx and number X Byte Number CLR A Clear Accumulator 1 1 CPL A Complement Accumulator (1=0, 0=1) 1 1 Cycle Number 64

65 SWAP A Swap nibbles in Accumulator (left and right half of one byte) 1 1 RL A Rotate bits in Accumulator left by 1 place 1 1 RLC A Rotate bits in Accumulator left by 1 place through Carry 1 1 RR A Rotate bits in Accumulator right by 1 place 1 1 Rotate bits In Accumulator right by 1 place RRC A through Carry Logical Operations with Bits 1 1 Similar to logical instructions, these instructions perform logical operations. The difference is that these operations are performed on single bits. Logical operations on bits Mnemonic Description Byte Number CLR C Clear Carry bit 1 1 CLR bit Clear directly addressed bit 2 2 SETB C Set Carry bit 1 1 SETB bit Set directly addressed bit 2 2 CPL C Complement Carry bit 1 1 CPL bit Complement directly addressed bit 2 2 ANL C,bit ANL C,/bit ORL C,bit ORL C,/bit Logical AND between Carry bit and directly addressed bit Logical AND between Carry bit and inverted directly addressed bit Logical OR between Carry bit and directly addressed bit Logical OR between Carry bit and inverted directly addressed bit MOV C,bit Move directly addressed bit to Carry bit 2 2 MOV bit,c Move Carry bit to directly addressed bit 2 2 Cycle Number 3.2 Descriptiion of all 8051 instructiions The operands listed below are written in shortened forms with the following meaning : A - Accumulator Rn - Rn is one of R registers (R0-R7) in the currently active bank in RAM. Rx - Rx is any register in RAM with 8-bit address. It can be a general-purpose register or SFR Register (I/O port, control register - Ri is R0 or R1 register in the currently active bank. It contains register. 65

66 address - the instruction is referring to. #X - X is any 8-bit number (0-255). #X16 - X is any 16-bit number ( ). adr16-16-bit address is specified adr11-11-bit address is specified rel - The address of a close memory location is specified (-128 do +127 rela tive to the current one). Basing on that address, Asembler computes the value which is added (or subtructed) to the number which currently resides in the program counter. bit - Bit address is specified. C - Carry bit in the status register (register PSW) ACALL adr11 - Call subroutine adr11: - Subroutine address Description: Instruction unconditionally calls a subroutine located at the indicated address. Therefore, the immediate address and the subroutine called must start 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, Address of the subroutine called) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: PC=0123h After execution: PC=0345h 66

67 ADD A,Rn - Add register Rn and Accumulator A: Accumulator Rn: Any R register (R0-R7) Description: Instruction adds the number in the Accumulator and the number in register Rn (R0-R7). After addition, the result is stored in the Accumulator. Syntax: ADD A,Rn Byte: 1 (Instruction Code) Effect on STATUS register flags: C, OV i ACy EXAMPLE: Before execution: A=2Eh (46 dec.) R4=12h (18 dec.) After execution: A=40h (64 dec.) R4=12h ADD A,@Ri - Add indirectly addressed register and Accumulator A: Accumulator Ri: Register R0 or R1 Description: Instruction adds the number in the Accumulator and the number in Rx. Register Rx address is in the Ri Register (R0 or R1). After addition, the result is stored in the Accumulator. Syntax: ADD A,@Ri Byte: 1 (Instruction Code) Effect on STATUS register flags: C, OV and AC EXAMPLE: 67

68 Register address: SUM = 4Fh R0=4Fh Before execution: A= 16h (22 dec.) SUM= 33h (51 dec.) After execution : A= 49h (73 dec.) ADD A,Rx - Add directly addressed register Rx and Accumulator A: Accumulator Rx: Arbitrary register with address (0 - FFh) Description: Instruction adds the Accumulator and Rx register. As it is direct addressing, Rx can be some of SFRs or general-purpose register with address 0-7 Fh. The result is stored in the Accumulator. Syntax: ADD A, Register s name Bytes: 2 (Instruction Code, Rx Address) Effect on STATUS register flags: C, OV and AC EXAMPLE: Before execution: SUM= 33h (51 dec.) A= 16h (22 dec.) After execution: SUM= 33h (73 dec.) A= 49h (73 dec.) ADDC A,Rn - Add register Rn, Accumulator and Carry bit 68

69 A: Accumulator Rn: any R register (R0-R7) Description: Instruction adds the Accumulator, Carry bit and the value in Rn register (R0-R7). After addition, the result is stored in the Accumulator. Syntax: ADDC A,Rn Byte: 1 (Instruction Code) Effect on STATUS register flags: C, OV i AC EXAMPLE: Before execution: A= C3h (195 dec.) R0= AAh (170 dec.) C=1 After execution: A= 6Eh (110 dec.) AC=0, C=1, OV=1 ADD A,#X - Add Accumulator and number X A: Accumulator X: Constant within (0-FFh) Description: Instruction adds the Accumulator and number X (0-255). After addition, the result is stored in the Accumulator. Syntax: ADD A,#X Bytes: 2 (Instruction Code, Constant X) Effect on STATUS register flags: C, OV i AC EXAMPLE: 69

70 Before execution: A= 16h (22 dec.) After execution: A= 49h (73 dec.) ADDC A,Rx - Add Accumulator, directly addressed register Rx and Carry bit A: Accumulator Rx: Arbitrary register with address (0 - FFh) Description: Instruction adds the value in the Accumulator and Rx Register including the Carry bit as well. As it is direct addressing, Rx can be some of SFRs or general purpose register with address 0-7Fh (0-127dec.). The result is stored in the Accumulator. Syntax: ADDC A, register address Bytes: 2 (Instruction Code, Address Rx) Effect on STATUS register flags: C, OV i 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 - Add Carry bit, Accumulator and indirectly addressed register Rx A: Accumulator Ri: Register R0 or R1 Description: Instruction adds value in the Accumulator and number in the Rx register. The Carry bit is also added. Register Rx address is in the Ri register (R0 or R1). After addition, the result is stored in the Accumulator. Syntax: ADDC A,@Ri Byte: 1 (Instruction Code) Effect on STATUS register flags: C, OV i AC EXAMPLE: 70

71 Register address: SUM = 4Fh R0=4Fh Before execution: A= C3h (195 dec.) SUM = AAh (170 dec.) C=1 After execution: A= 6Eh (110 dec.) AC=0, C=1, OV=1 ADDC A,#X - Add Accumulator, number X and Carry bit A: Accumulator X: Constant within (0-FFh) Description: Instruction adds number in the Accumulator and number X (0-255). The Carry bit is also added. After addition, the result is stored in the Accumulator. Syntax: ADDC A,#X Bytes: 2 (Instruction Code, Constant X) Effect on STATUS register flags: C, OV i AC EXAMPLE: Before execution: A= C3h (195 dec.) C=1 After execution: A= 6Dh (109 dec.) AC=0, C=1, OV=1 AJMP adr11 - Jump to address adr11: Jump address Description : Instruction transfers program execution to the indicated address. Similar to the ACALL instruction, this jump must be executed within the same 2K 71

72 byte block of program memory (starting from the first byte of the instruction following AJMP). Syntax: AJMP address (label) Bytes: 2 (Instruction Code, Jump Address) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: PC=0345h SP=07h After execution: PC=0123h SP=09h ANL A,Rn - Logical-AND operation between Accumulator and Register Rn A: Accumulator Rn: Any R register (R0-R7) Description: Instruction performs the logical-and operation between the Accumulator and Rn register. The result of this logical operation is stored in the Accumulator. Syntax: ANL A,Rn Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: 72

73 Before execution: A= C3h ( Bin.) R5= 55h ( Bin.) After execution: A= 41h ( Bin.) ANL A,Rx - Logical-AND operation between Accumulator and directly addressed register A: Accumulator Rx: Arbitrary register with address (0 - FFh) Description: Instruction performs logical-and operation between the Accumulator and Rx register. As it is direct addressing, Rx can be some of SFRs or general purpose register with address 0-7Fh (o-127 dec.). The result is stored in the Accumulator. Syntax: ANL A,Rx Byte: 2 (Instruction Code, Constant X) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: A= C3h ( Bin.) MASK= 55h ( Bin.) After execution: A= 41h ( Bin.) 73

74 ANL - Logical-AND operation between Accumulator and indirectly addressed register A: Accumulator Ri: Register R0 or R1 Description: Instruction performs logical-and operation between the Accumulator and Rx register. As it is indirect addressing, register Rx address is in the Ri register (R0 or R1). The result is stored in the Accumulator. Syntax: ANL Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: Register address ZBIR = 4Fh R0=4Fh Before execution: A= C3h ( Bin.) R0= 55h ( Bin.) After execution: A= 41h ( Bin.) ANL A,#X - Logical-AND operation between Accumulator and number X A: Accumulator X: Constant in the range of (0-FFh) Description: Instruction performs logical-and operation between the Accumulator and number X. The result is stored in the Accumulator. Syntax: ANL A,#X Bytes: 2 (Instruction Code, Constant X) Effect on STATUS register flags: No flags are affected. EXAMPLE: 74

75 Before execution: A= C3h ( Bin.) After execution: A= 41h ( Bin.) ANL Rx,A - Logical-AND operation between directly addressed register Rx and Accumulator Rx: Arbitrary register with address (0 - FFh) A: Accumulator Description: Instruction performs logical-and operation between the Rx register and Accumulator. As it is direct addressing, Rx can be some of SFRs or generalpurpose register with address 0-7Fh (0-127 dec.). The result of this logical operation is stored in the register Rx. Syntax: ANL register address,a Bytes: 2 (Instruction Code, Address Rx) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: A= C3h ( Bin.) MASK= 55h ( Bin.) After execution: MASK= 41h ( Bin.) 75

76 ANL Rx,#X - Logical-AND operation between number X and directly addressed register Rx Rx: Arbitrary register with address (0 - FFh) X: Constant within (0-FFh) Description: Instruction performs logical-and operation between the register Rx and number X. As it is direct addressing, Rx can be some of SFRs or general-purpose register with address 0-7Fh (0-127 dec.). The result of this logical operation is stored in the Rx register. Syntax: ANL register address,#x Bytes: 3 (Instruction Code, Address Rx, Constant X) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: X= C3h ( Bin.) MASK= 55h ( Bin.) After execution: MASK= 41h ( Bin.) ANL C,bit - Logical-AND operation between bit and Carry bit C: Carry bit: Any bit in RAM Description: Instruction performs logical-and operation between the addressed bit and Carry bit. bit C C AND bit

77 Syntax: ANL C, Bit Address Bytes: 2 (Instruction Code, Bit Address) Effect on STATUS register flags: C EXAMPLE: Before execution: ACC= 43h ( Bin.) C=1 After execution: ACC= 43h ( Bin.) C=0 ANL C,/bit - Logical-AND opertaion between complement of bit and Carry bit C: Carry bit: Any bit in RAM Description: Instruction performs logical-and operation between the inverted addressed bit and Carry bit. The result is stored in the Carry bit. bit bit C C AND bit Syntax: ANL C,/[bit address] Bytes: 2 (Instruction Code, Bit Address) Effect on STATUS register flags: No flags are affected. EXAMPLE: 77

78 Before execution: ACC= 43h ( Bin.) C=1 After execution: ACC= 43h ( Bin.) C=1 CJNE A,Rx,rel - Compare directly addessed byte with Accumulator and jump if they are not equal A: Accumulator Rx: Arbitrary register with address (0 - FFh) adr. Jump Address Description: Instruction first compares the number in the Accumulator with the number in Rx register. If they are equal, the program continues execution. Otherwise, a jump to the indicated address in the program will be executed. This is a short jump instruction, which means that the address of a new location must be relatively near the current position in the program (-128 to +127 locations relative to the first following instruction). Syntax: CJNE A,Rx,[jump address ] Bytes: 3 (Instruction Code, Address Rx, Jump value) Effect on STATUS register flags: C EXAMPLE: 78

79 Before execution: PC=0145h A=27h After execution: if MAX 27: PC=0123h If MAX=27: PC=0146h CJNE A,#X,rel - Compare number X with Accumulator and jump if they are not equal A: Accumulator X: Constant in the range of (0-FFh) Description: Instruction first compares the number in the Accumulator with number X. If they are equal, the program continues execution. Otherwise, a jump to the indicated address in the program will be executed. This is a short jump instruction, which means that the address of a new location must be relatively near the current position in the program (-128 to +127 locations relative to the first following instruction) Syntax: CJNE A,X,[jump address ] Bytes: 3 (Instruction Code, Constant X, Jump value) Effect on STATUS register flags: C EXAMPLE: 79

80 Before execution: PC=0445h After execution: If A 33: PC=0423h If A=33: PC=0446h CJNE Rn,#X,rel - Compare number X with register Rn and jump if they are not equal Rn: Any R register (R0-R7) X: Constant in the range of (0-FFh) adr: Jump address Description: Instruction first compares the number in the Rx register with number X. If they are equal, the program continues execution. Otherwise, a jump to the indicated address in the program will be executed. This is a short jump instruction, which means that the address of a new location must be relatively near the current position in the program ( -128 to locations relative to the first following instruction). Syntax: CJNE Rn,X,[jump address ] Bytes: 3 (Instruction Code, Constant X, Jump value) Effect on STATUS register flags: C EXAMPLE: 80

81 Before execution: PC=0345h After execution : If R5 44h: PC=0323h If R5=44h: PC=0346h - Compare indirectly addressed register with number X and jump if they are not equal Ri: Register R0 or R1 X: Constant in the range of (0-FFh) Description: Register Rx address is stored in the Ri register (R0 or R1). This instruction first compares the number in Rx register with number X. If they are equal, the program continues execution. Otherwise, a jump to the indicated address in the program will be executed.this is a short jump instruction, which means that the address of a new location must be relatively near the current position in the program (-128 to +127 locations relative to the next instruction). Syntax: address ] Bytes: 3 (Instruction Code, Constant X, Jump value) Effect on STATUS register flags: C EXAMPLE: 81

82 Before execution: Register Address SUM=F3h PC=0345h R0=F3h After execution : If SUM 44h: PC=0323h If SUM=44h: PC=0346h CLR A - Clear Accumulator A: Accumulator Description: Instruction clears the Accumulator. Syntax: CLR A Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: 82

83 After execution : A=0 CLR C - Clear Carry Bit C: Carry Bit Description: Instruction writes 0 to the Carry bit. Syntax: CLR C Byte: 1 (Instruction Code) Effect on STATUS register flags: C EXAMPLE: After execution: C=0 CLR bit - Clear Directly Addressed Bit bit: Any bit in RAM Description: Instruction clears the indicated bit. Syntax: CLR [bit address] Bytes: 2 (Instruction Code, Bit Address) Effect on STATUS register flags: No flags are affected. 83

84 EXAMPLE: Before execution: P0.3=1 (input pin) After execution: P0.3=0 (output pin) CPL A - Complement number in Accumulator A: Accumulator Description: Instruction complements all bits in the Accumulator (1==>0, 0==>1) Syntax: CPL A Bytes: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: A= ( ) After execution A= ( ) CPL bit - Complement bit bit: Any bit in RAM Description: Instruction coplements the indicated bit (0==>1, 1==>0) 84

85 Syntax: CPL [bit address] Bytes: 2 (Instruction Code, Bit Address) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: P0.3=1 (input pin) After execution: P0.3=0 (output pin) CPL C - Complement Carry Bit C: Carry bit Description: Instruction complements the Carry bit (0==>1, 1==>0) Syntax: CPL C Byte: 1 (Instruction Code) Effect on STATUS register flags: C EXAMPLE: Before execution: C=1 After execution: C=0 DA A - Conversion into BCD format A: Accumulator 85

86 Description: This instruction corrects the value after binary addition to fit BCD format. Prior to addition, both numbers have to be in BCD format, which means that it is not just a simple coversion of hexadecimal numbers into BCD numbers.the result of this operation in form of two 4-digit BCD numbers is stored in the Accumaulator. Syntax: DA A Byte: 1 (Instruction Code) Effect on STATUS register flags: C EXAMPLE: Before execution: A=56h ( ) 56 BCD B=67h ( ) 67BCD After execution: A=BDh ( ) After BCD conversion: A=23h ( ), C=1 (Overflow) (C+23=123) = DEC A - Decrement value in Accumulator by 1 A: Accumulator Description: Instruction decrements the value in the Accumulator by 1. If there is a 0 in the Accumulator, the result of the operation is FFh. (255 dec.) Syntax: DEC A Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: 86

87 Before execution: A=E4h After execution: A=E3h DEC Rn - Decrement value in register Rn by 1 Rn: Any R register (R0-R7) Description: Instruction decrements the value in the Rn register by 1. If there is a 0 in the register, the result of the operation will be FFh. (255 dec.) Syntax: DEC Rn Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: R3=B0h After execution: R3=AFh DEC Rx - Decrement value in register Rx by 1 Rx: Arbitrary register with address (0 - FFh) Description: Instruction decrements the value of the register Rx by 1. As it is direct addressing, Rx must be within the first 255 locations of RAM. If there is a 0 in the register, the result will be FFh. 87

88 Syntax: DEC [register address] Byte: 2 (Instruction Code, Address Rx) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: CNT=0 After execution: CNT=FFh DIV AB - Divide value in Accumulator by value in register B A: Accumulator B: Register B Description: Instruction divides the value in the Accumulator by the value in the B register. After division the integer part of the result is stored in the Accumulator while the register contains the remainder. In case of dividing by 1, the flag OV is set and the result of division is unpredictable. (The 8-bit quotient is stored in the Accumulator and the 8-bit remainder is stored in the B register. Syntax: DIV AB Byte: 1 (Instruction Code) Effect on STATUS register flags: C, OV EXAMPLE: 88

89 Before execution: A=FBh (251dec.) B=12h (18 dec.) After execution: A=0Dh (13dec.) B=11h (17dec.) =251 - Decrement value in indirectly Addressed Register by 1 Ri: Register R0 or R1 Description: This instruction decrements the value in the Rx register by 1. Rx register address is in the Ri register (R0 or R1). If there is 0 in the register, the result will be FFh. Syntax: Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: Register Address CNT = 4Fh R0=4Fh Before execution: CNT=35h After execution: CNT= 34h DJNZ Rx,rel - Decrement Rx Register by 1 then jump if the result is not 0 Rx: Arbitrary register with address (0 - FFh) adr: Jump address Description: This instruction first decrements the value in the register. If the result is 0, the program continues execution. Otherwise, a jump to the indicated address in the program will be executed. As it is direct addressing, Rx must be within the first 255 locations in RAM. This is a short jump instruction, which means that the address of a new location must be relatively near the current position in the program ( -128 to +127 locations relative to the first following instruction). Syntax: DJNZ Rx,[jump address] Bytes: 3 (Instruction Code, Address Rx, Jump Value) Effect on STATUS register flags: No flags are affected. 89

90 EXAMPLE: Before execution: PC=0445h After execution: If CNT 0: PC=0423h If CNT=0: PC=0446h DJNZ Rn,rel - Decrement Rn Register by 1 then jump if the result is not 0 Rn: Any R register (R0-R7) adr: jump address Description: This instruction first decrements the value in the Rn register. If the result is 0, the program continues execution. Otherwise, a jump to the indicated address in the program will be executed. This is a short jump instruction, which means that the address of a new location must be realtively near the current position in the program (- 128 to +127 locations relative to the first following instruction). Syntax: DJNZ Rn, [jump address] Bytes: 2 (Instruction Code, Jump Value) Effect on STATUS register flags: No flags are affected. EXAMPLE: 90

91 Before execution: PC=0445h After execution: If R1 0: PC=0423h If R1=0: PC=0446h INC Rn - Increment value in Rn Register by 1 Rn: Any R register (R0-R7) Description: This 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) Effect on STATUS register flags: No flags are affected. EXAMPLE: 91

92 Before execution: R4=18h After execution: R4=19h INC A - Increment Value in Accumulator by 1 A: Accumulator Description: This instruction increments the value in the Accumulator by 1. If the Accumulator includes the number 255, the result of the operation will be 0. Syntax: INC A Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: A=E4h After execution: A=E5h - Increment Value in indirectly addressed register by 1 Ri: Register R0 or R1 92

93 Description: This instruction increments the value in the Rx register by 1. Register Rx address is in the Ri Register ( R0 or R1). If the register includes the number 255, the result of the operation will be 0. Syntax: Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: Register Address CNT = 4Fh Before execution: CNT=35h R1=4Fh After execution: CNT=36h INC Rx - Increment Number in Rx register by 1 Rx: Arbitrary register with address (0 - FFh) Description: This instruction increments the value of the Rx register by 1.If the register includes the number 255, the result of the operation will be 0. As it is direct addressing, Rx must be within the first 255 RAM locations. Syntax: INC Rx Bytes: 2 (Instruction Code, Address Rx) Effect on STATUS register flags: No flags are affected. EXAMPLE: 93

94 Before execution: CNT=33h After execution: CNT=34h JB bit,rel - Jump if Bit is Set adr: Jump address bit: Any bit in RAM Description: If the bit is set, a jump to the indicated address will be executed. Otherwise, if the value of the bit is 0, the program proceeds with the next instruction. This is a short jump instruction, which means that the address of a new location must be relatively near the current position in the program (-128 to locations relative to the first following instruction). Syntax: JB bit, [jump address] Bytes: 3 (Instruction Code, Bit Address, Jump value) Effect on STATUS register flags: No flags are affected. EXAMPLE: 94

95 Before execution: PC=0323h After execution: If P0.5=0: PC=0324h If P0.5=1: PC=0345h INC DPTR - Increment Value of Data Pointer by 1 DPTR: Data Pointer Description: This instruction increments the value of the 16-bit data pointer by 1. This is a single 16-bit register on which this operation can be performed. Syntax: INC DPTR Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: 95

96 Before execution: DPTR = 13FF (DPH = 13h DPL = FFh ) After execution: DPTR = 1400 (DPH = 14h DPL = 0) JC rel - Jump if Carry Bit is Set adr: Jump address Description: This instruction first check if the Carry bit is set. If it is set, a jump to the indicated address is executed. Otherwise, the program proceeds with the next instruction. This is a short jump instruction, which means that the address of a new location must be relatively near the current position in the program (-129 to locations relative to the first following instruction). Syntax: JC [jump address] Bytes: 2 (Instruction Code, Jump Value) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before instruction: PC=0323h After instruction: If C=0: PC=0324h If C=1: PC=0345h JBC bit,rel - If bit is set, clear it and jump to a new address bit: Any bit in RAM adr: Jump Addrress 96

97 Description: This instruction first checks if the bit is set. If it is set, a jump to the indicated address is executed and afterwards the bit is cleared. Otherwise, the program proceeds with the first next instruction. This is a short jump instruction, which means that the address of a new location must be relatively near the current position in the program (-129 to locations relative to the first following instruction). Syntax: JBC bit, [jump address] Bytes: 3 (Instruction Code, Bit Address, Jump Value) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: PC=0323h After execution: If TEST0.4=1: PC=0345h, TEST0.4=0 If TEST0.4=0: PC=0324h, TEST0,4=0 JNB bit,rel - Jump if the bit is not set adr: Jump address bit: Any bit in RAM Description: If the bit is cleared, a jump to the indicated address will be executed. Otherwise, if the bit value is 1, the program proceeds with the first next instruction. This is a short jump instruction, which means that the address of a new location must be relatively near the actual position in the program (-129 to locations relative to the first following instruction). Syntax: JNB bit,[jump address] Bytes: 3 (Instruction Code, Bit Address, Jump Value) Effect on STATUS register flags: No flags are affected. 97

98 EXAMPLE: Before execution: PC=0323h After execution: If P0.5=1: PC=0324h If P0.5=0: PC=0345h - Indirect jump A: Accumulator DPTR: Data Pointer Description: This instruction causes a jump to address which is accessed by adding value in the Accumulator and 16-bit number in the DPTR Register. It is used with complex program branching where the accumulator affects jump address, for example while reading table. Neither the Accumulator nor DPTR register are affected. Syntax: Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: 98

99 Before execution: PC=223 DPTR=1400h After execution: PC = 1402h if A=2 PC = 1404h if A=4 PC = 1406h if A=6 Note: As instructions AJMP LABELS occupy two locations each, the values in the Accumulator indicating them must be mutually different from each other by 2. JNZ rel - Jump if value in Accumulator is not 0 adr: Jump Address Description: This instruction checks if the value in the Accumulator is 0. If it is not 0, a jump to the indicated address will be executed. Otherwise, the program proceeds with the first next instruction. This is a short jump instruction, which means that the address of a new location must be relatively near the current position in the program (-129 to locations relative to the first following instruction). Syntax: JNZ [jump address] Bytes: 2 (Instruction Code, Jump Value) Effect on STATUS register flags: No flags are affected. EXAMPLE: 99

100 Before execution: PC=0323h After execution: If A=0: PC=324h If A 0: PC=283h JNC rel - Jump if Carry Bit is cleared adr: Jump Address Description: This instruction first checks if the bit is set. If it is not set, a jump to the indicated address will be executed. Otherwise, the program proceeds with the first next instruction.this is a short jump instruction, which means that the address of a new location must be relatively near the current position in the program (-129 to locations relative to the first following instruction). Syntax: JNC [jump address] Bytes: 2 (Instruction Code, Jump Value) Effect on STATUS register flags: No flags are affected. EXAMPLE: 100

101 Before execution: PC=0323h After Sexecution: If C=0: PC=360h If C=1: PC=324h LCALL adr16 - Apsolute long subroutine call adr16: Subroutine Address Description: This instruction unconditionally calls a subroutine located at the indicated address. The current address and the beginning of the called subroutine can be located anywhere within the memory space of 64K. Syntax: LCALL [subroutine name] Bytes: 3 (Instruction Code, Address (15-8), Address (7-0)) Effect on STATUS register flags: No flags are affected. EXAMPLE: 101

102 Before execution: PC=0123h After execution: PC=1234h JZ rel - Jump if the value in accumulator is 0 adr: Jump Address Description: The instruction checks if the value in the accumulator is 0. If it is 0, a jump to the indicated address will be executed. Otherwise, the program proceeds with the next instruction.this is a short jump instruction, which means that the address of a new location must be relatively near the current position in the program (-129 to locations relative to the first following instruction). Syntax: JZ [jump address] Bytes: 2 (Instruction Code, Jump Value) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: PC=0323h After execution: If A0: PC=324h If A=0: PC=283h MOV A,Rn - Move Rn register to Accumulator Rn: Any R register (R0-R7) A: Accumulator Description: The instruction moves the Rn register to the Accumulator. The Rn register is not affected. 102

103 Syntax: MOV A,Rn Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: R3=58h After execution: R3=58h A=58h LJMP adr16 - Long jump adr16: Jump address Description: Instruction causes a jump to the indicated 16-bit address. Syntax: LJMP [jump address] Bytes: 3 (Instruction Code, Address (15-8), Address (7-0)) Effect on STATUS register flags: No flags are affected. EXAMPLE: 103

104 Before execution: PC=0123h After execution: PC=1234h MOV - Move indirect addressed register Rx to Accumulator Ri: Register R0 or R1 A: Accumulator Description: Instruction moves the Rx register to the Accumulator. Rx register address is stored in the Ri register (R0 or R1). After instruction execution, the result is stored in the Accumulator. The Rx Register is not affected. Syntax: MOV Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: Register Address SUM=F2h R0=F2h Before execution: SUM=58h After execution : A=58h SUM=58h MOV A,Rx - Move Rx register to Accumulator Rx: arbitrary register with address (0 - FFh) A: Accumulator Description: Instruction moves the Rx register to the Accumulator. As it is direct addressing, Rx can be some of SFRs or general-purpose register with address 0-7Fh. (0-127 dec.). After instruction execution, Rx is not affected. Syntax: MOV A,Rx Byte: 2 (Instruction Code, Address Rx) Effect on STATUS register flags: No flags are affected. EXAMPLE: 104

105 Before execution: Rx=68h After execution : Rx=68h A=68h MOV Rn,A - Move Accumulator to Rn register Rn: Any R register (R0-R7) A: Accumulator Desription: Instruction moves the Accumulator to Rn register. The Accumulator is not affected. Syntax: MOV Rn,A Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: A=58h After execution: R3=58h A=58h MOV A,#X - Move number X to Accumulator A: Accumulator X: Constant in the range of (0-FFh) 105

106 Desription: Instruction writes number X to the Accumulator. Syntax: MOV A,#X Bytes: 2 (Instruction Code, Constant X) Effect on STATUS register flags: No flags are affected. EXAMPLE: After execution: A=28h MOV Rn,#X - Move number X to Rn register Rn: Any R register (R0-R7) X: Constant in the range of (0-FFh) Description: Instruction writes number X to the Rn register. Syntax: MOV Rn,#X Bytes: 2 (Instruction Code, Constant X) Effect on STATUS register flags: No flags are affected. EXAMPLE: After execution : R5=32h MOV Rn,Rx - Move Rx register to Rn register Rn: Any R registar (R0-R7) Rx: Arbitrary register with address (0 - FFh) 106

107 Description: Instruction moves the Rx register to Rn register. As it is direct addressing, Rx can be some of SFRs or general-purpose register with address 0-7Fh. (0-127 dec.). After instruction execution, Rx is not affected. Syntax: MOV Rn,Rx Bytes: 2 (Instruction Code, Address Rx) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: SUM=58h After execution: SUM=58h R3=58h MOV Rx,Rn - Move Rn register to Rx register Rn: Any R register (R0-R7) Rx: Arbitrary register with address (0 - FFh) Description: Instruction moves the Rn register to Rx register. As it is direct addressing, Rx can be some of SFRs or general-purpose register with address 0-7Fh. (0-127 dec.). After instruction execution, Rx is not affected. Syntax: MOV Rx,Rn Bytes: 2 (Instruction Code, Address Rx) Effect on STATUS register flags: No flags are affected. EXAMPLE: 107

108 Before execution: R3=18h After execution: R3=18h CIF=18h MOV Rx,A - Move Accumulator to Rx register Rx: Arbitrary register with address (0 - FFh) A: Accumulator Description: Instrction moves the Accumulator to Rx register. As it is direct addressing, Rx can be some of SFRs or general-purpose register with address 0-7Fh. (0-127 dec.). After instruction execution, Rx is not affected. Syntax: MOV Rx,A Bytes: 2 (Instruction Code, Address Rx) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: A=98h After execution: A=98h REG=98h MOV Rx,@Ri - Move number from indirectly addressed register to Rx register Rx: Arbitrary register with address (0 - FFh) Ri: Register R0 or R1 Description: Instruction moves the Ry register to Rx register. Ry register address is stored in the Ri register (R0 or R1). The Ry register is not affected. 108

109 Syntax: MOV Bytes: 2 (Instruction Code, Address Rx) Effect on STATUS register flags: No flags are affected. EXAMPLE: Register Address SUM=F3 Before execution: SUM=58h R1=F3 After execution: SUM=58h TEMP=58h MOV Rx,Ry - Move Ry register to Rx register Rx: Arbitrary register with address (0 - FFh) Ry: Arbitrary register with address (0 - FFh) Description: Instruction moves the Ry register to Rx register. As it is direct addressing, Rx and Ry can be some of SFRs or general-purpose registers with address 0-7Fh. (0-127 dec.). The Ry register is not affected. Syntax: MOV Rx,Ry Bytes: 3 (Instruction Code, Address Ry, Address Rx) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: TEMP=58h After execution: TEMP=58h SUM=58h 109

110 - Move Accumulator to indirect addressed register A: Accumulator Ri: Register R0 or R1 Description: Instruction moves the Accumulator to the Rx register. Rx register address is stored in the Ri register (R0 or R1). After instruction execution, the Accumulator is not affected. Syntax: Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: Register Address SUMA=F2h Before execution: R0=F2h A=58h After execution: SUMA=58h A=58h MOV Rx,#X - Move number X to Rx register Rx: Arbitrary register with address (0 - FFh) X: Constant in the range of (0-FFh) Description: Instruction moves number X to the Rx register. As it is direct addressing, Rx can be some of SFRs or general-purpose register with address 0-7Fh. (0-127 dec.). Syntax: MOV Rx,#X Bytes: 3 (Instruction Code, Address Rx, Constant X) Effect on STATUS register flags: No flags are affected. EXAMPLE: 110

111 After execution: TEMP=22h - Move number X to indirectly addressed register Ri: Register R0 or R1 X: Constant in the range of (0-FFh) Description: Instruction moves number X to the idirectly addressed register Rx. Register Rx address is stored in the Ri register ( R0 or R1). Syntax: Bytes: 2 (Instruction Code, Constant X) Effect on STATUS register flags: No flags are affected. EXAMPLE: Register address TEMP=E2h Before execution: R1=E2h After execution: TEMP=44h - Move Rx register to indirectly addressed register Rx: Arbitrary register with address (0 - FFh) Ri: Register R0 or R1 Description: Instruction moves the Rx register to Ry register. Register Ry address is stored in the Ri register ( R0 or R1). After instruction execution, the Rx register is not affected. 111

112 Syntax: Bytes: 2 (Instruction Code, Address Rx) Effect on STATUS register flags: No flags are affected. EXAMPLE: Register address TEMP=E2h Before execution: SUM=58h R1=E2h After execution: SUM=58h TEMP=58h MOV bit,c - Move Carry bit to indicated bit C: Carry bit bit: Any bit in RAM Description: Instruction moves the value of the Carry bit to the indicated bit. After this operation, the Carry bit is not affected. Syntax: MOV bit,c Bytes: 2 (Instruction Code, Address bit) Effect on STATUS register flags: No flags are affected. EXAMPLE: After execution: If C=0 P1.2=0 If C=1 P1.2=1 MOV C,bit - Move indicated bit to Carry bit 112

113 C: Carry bit bit: Any bit in RAM Description: Instruction moves the value of the indicated bit to the Carry bit. After this operation, the bit is not affected. Syntax: MOV C,bit Bytes: 2 (Instruction Code, Bit address) Effect on STATUS register flags: C EXAMPLE: After execution: If P1.4=0 C=0 If P1.4=1 C=1 MOVC A,@A+DPTR - Move relatively addressed byte from program memory to Accumulator A: Accumulator DPTR: Data Pointer Description: Instruction first adds the 16-bit DPTR Register and the Accumulator. The result of addition is afterwards used as address in the program memory indicating from which the 8-bit content is moved to the Accumulator. Syntax: MOVC A,@A+DPTR Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags affected. EXAMPLE: 113

114 Before execution : DPTR=1000: A=0 A=1 A=2 A=3 After A=66h A=77h A=88h A=99h execution: Note: DB (Define Byte) is a directive in assembler used to define constant. MOV DPTR,#X16 - Write 16-bit number to Data Pointer X: constant in the range of (0-FFFFh) DPTR: Data Pointer Description: Instruction writes 16-bit number into the DPTR register. The 8 highorder bits of this number are stored in the DPH register while the 8 low-order bits are stored in the DPL register. Syntax: MOV DPTR,#X Bytes: 3 (Instruction Code, Constant (15-8), Constant (7-0)) Effect on STATUS register flags: No flags affected. EXAMPLE: 114

115 After execution: DPH=12h DPL=34h MOVX - Write from external memory (8-bit address) to Accumulator Ri: Register R0 or R1 A: Accumulator Description: Instruction reads the content of the Rx register in external RAM and moves it to the Accumulator. Register Rx address is stored in the Ri register (R0 or R1). Syntax: MOVX Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags affected. EXAMPLE: Register Address SUMA=12h Before execution: SUMA=58h R0=12h After execution: A=58h Note: SUMA Register is stored in external RAM in size of 256 bytes. MOVC A,@A+PC - Write relatively addressed byte from program memory to Accumulator 115

116 A: Accumulator PC: Program Counter Description: Instruction first adds the 16-bit PC Register with the content of the Accumulator (the current address in the program is stored in the PC register). The result of addition is afterwards used as address in the program memory from which the 8-bit content is moved to the Accumulator. Syntax: MOVC Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags affected. EXAMPLE: After the subroutine "Tabela" has been executed, one of four values is stored in the Accumulator: Before A=0 A=1 A=2 A=3 After A=66h A=77h A=88h A=99h execution: execution: Note: DB (Define Byte) is directiv in assembler used to define constant. 116

117 - Write the content of Accumulator into byte of external memory (8- bit address) Ri: Register R0 or R1 A: Accumulator Description: Instruction reads the content of the Accumulator and moves it to the Rx register which is stored in external RAM. Rx Register address is located in the Ri register. Syntax: Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags affected. EXAMPLE: Register address SUM=34h Before execution: A=58 R1=34h After execution: SUM=58h NOTE: Register SUM is located in external RAM in size of 256 byte. MOVX A,@DPTR - Write the content of Accumulator into byte of external memory (8-bit address) A: Accumulator DPRTR: Data Pointer Description: Instruction reads the content of the Rx register in external memory and moves it to the Accumulator. The 16-bit address of the Rx register is stored in the DPTR register (DPH and DPL). Syntax: MOVX A,@DPTR Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags affected. EXAMPLE: 117

118 Register Address SUM=1234h Before execution: DPTR=1234h SUM=58 After execution: A=58h Note: Register SUM is located in external RAM in size of up to 64K. MUL AB - Multiply value in Accumulator with value in B register A: Accumulator B: Register B Description: Instruction multiplies the value in the Accumulator with the value in the B register. The low-order byte of the 16-bit result is left in the Accumulator, and the high-order byte is left in the B register. If the result is greater than 255, the overflow flag is set. The Carry bit (C flag) is not affected. Syntax: MUL AB Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags affected. EXAMPLE: Before execution: A=80 (50h) B=160 (A0h) After execution: A=0 B=32h A B=80 160=12800 (3200h) 118

119 - Write value in accumulator to byte of external memory (16-bit address) A: Accumulator DPTR: Data Pointer Description: Instruction reads the value in the Accumulator and moves it to the Rx register which is located in external RAM. 16-bit address of the Rx register is located in the DPTR register (DPH and DPL). Syntax: Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags affected. EXAMPLE: Register address ZBIR=1234h Before execution: A=58 DPTR=1234h After execution: SUM=58h Note: Register SUM is located in RAM in size of up to 64K. ORL A,Rn - Logical-OR operation between Accumulator and Rn register Rn: Any R register (R0-R7) A: Accumulator Description: Instruction performs logical-or operation between the Accumulator and Rn register. The result of this logical operation is stored in the Accumulator. Syntax: ORL A,Rn Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags affected. EXAMPLE: 119

120 Before execution: A= C3h ( Bin.) R5= 55h ( Bin.) After execution : A= D7h ( Bin.) NOP - No operation Description: Instruction doesn t perform any operation and is used when additional delays are needed. Syntax: NOP Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags affected. EXAMPLE: Sequence like this one provides on the P2.3 a negative pulse which lasts exactly 5 machine cycles. If a 12 MHz quartz crystal is used then 1 cycle lasts 1uS, which means that this output will be a low-going output pulse for 5 us. 120

121 ORL - Logical-OR operation between Accumulator and indirectly addressed register Ri: Register R0 or R1 A: Accumulator Description: Instruction performs logical-or operation between the Accumulator and Rx register. As it is indirect addressing, register Rx address is stored in the Ri register ( R0 or R1). The result of this logical operation is stored in the Accumulator. Syntax: ANL A,@Ri Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags affected. EXAMPLE: Register Address TEMP=FAh Before execution: R1=FAh TEMP= C2h ( Bin.) A= 54h ( Bin.) After execution: A= D6h ( Bin.) ORL A,Rx - logical-or operation between Accumulator and Rx register Rx: Arbitrary register with address (0 - FFh) A: Accumulator Description: Instruction performs logical-or operation between the Accumulator and Rx register. As it is direct addressing, Rx can be some of SFRs or generalpurpose register with address 0-7Fh (0-127 dec.). The result of this logical operation is stored in the Accumulator. Syntax: ORL A,Rx Bytes: 2 (Instruction Code, Address Rx) Effect on STATUS register flags: No flags affected. EXAMPLE: 121

122 Before execution: A= C2h ( Bin.) LOG= 54h ( Bin.) After execution: A= D6h ( Bin.) ORL Rx,A - Logical-OR operation between directly addressed register Rx and Accumulator Rx: Arbitrary register with address (0 - FFh) A: Accumulator Description: Instruction performs logical-or operation between the Rx register and Accumulator. As it is direct addressing, the Rx register can be some of SFRs or general- purpose register with address 0-7Fh (0-127 dec.). The result of this logical operation is stored in the Rx register. Syntax: ORL [register address], A Bytes: 2 (Instruction Code, Address Rx) Effect on STATUS register flags: No flags affected. EXAMPLE: Before execution: TEMP= C2h ( Bin.) A= 54h ( Bin.) After execution: A= D6h ( Bin.) ORL A,#X - Logical-OR operation between Accumulator and number X 122

123 X: Constant in the range of (0-FFh) A: Accumulator Description: Instruction performs logical-or operation between the Accumulator and number X. The result of this logical operation is stored in the Accumulator. Syntax: ORL A, #X Bytes: 2 (Instruction Code, Constant X) Effect on STATUS register flags: No flags affected. EXAMPLE: Before execution: A= C2h ( Bin.) After execution: A= C3h ( Bin.) ORL C,bit - Logical-OR operation between bit and Carry bit C: Carry bit bit: Any bit in RAM Description: Instruction performs logical-or operation (logical OR) between the addressed bit and Carry bit. The result is stored in the Carry bit. Syntax: ORL C,bit Bytes: 2 (Instruction Code, Bit address) Effect on STATUS register flags: No flags affected. EXAMPLE: 123

124 Before execution: ACC= C6h ( Bin.) C=0 After execution: C=1 ORL Rx,#X - Logical-OR operation between directly addressed register Rx and number X Rx: Arbitrary register with address (0 - FFh) X: Constant in the range of (0-FFh) Description: Instruction performs logical-or operation between the Rx registers and number X. As it is direct addressing, Rx can be some of SFRs or general-purpose register with address 0-7Fh (0-127 dec.). The result of this logical operation is stored in the Rx register. Syntax: ORL [register address],#x Bytes: 3 (Instruction Code, Address Rx, Constant X) Effect on STATUS register flags: No flags affected. EXAMPLE: Before execution: TEMP= C2h ( Bin.) After execution: A= D2h ( Bin.) POP Rx - Pop data from Stack Rx: Arbitrary register with address (0 - FFh) Description: Instruction first reads data from the location the Stack Pointer is currently ponting to. Afterwards, the data is copied to the register Rx and the value of the Stack Pointer is decremented by 1. As it is direct addressing, Rx can be some of SFRs or general-purpose register with address 0-7Fh. (0-127 dec.) Syntax: POP Rx Bytes: 2 (Instruction Code, Address Rx) Effect on STATUS register flags: No flags affected. EXAMPLE: 124

125 Before execution: Address Value 030h 20h 031h 23h SP==> 032h 01h DPTR=0123h (DPH=01, DPL=23h) After execution: Address Value SP==> 030h 20h 031h 23h 032h 01h ORL C,/bit - Logical-OR operation between complement bit and Carry bit C: Carry bit bit: Any bit in RAM Description: Instruction performs logical-and operation (logical OR) between the addressed inverted bit and Carry bit. The result is stored in the Carry bit. bit bit C C AND bit Syntax: ORL C,/bit Bytes: 2 (Instruction Code, Bit address) Effect on STATUS register flags: No flags affected. EXAMPLE: 125

126 Before execution: ACC= C6h ( Bin.) C=0 After execution: C=0 RET - Return from subroutine Description: This instruction ends every subroutine. After execution, the program proceeds with the instruction currently following an ACALL or LCALL. Syntax: RET Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags affected. EXAMPLE: 126

127 PUSH Rx - Push Data onto Stack Rx: Arbitrary register with address (0 - FFh) Description: Address currently pointed to by the Stack Pointer is first incremented by 1 and afterwards the data from the register Rx are copied to it. As it is direct addressing, Rx can be some of SFRs or general-purpose register with address 0-7Fh. (0-127 dec.) Syntax: PUSH Rx Bytes: 2 (Instruction Code, Address Rx) Effect on STATUS register flags: No flags affected. EXAMPLE: 127

128 Before execution: Address Value SP==> 030h 20h DPTR=0123h (DPH=01, DPL=23h) After execution: Address Value 030h 20h 031h 23h SP==> 032h 01h RL A - Rotate Accumulator one bit left A: Accumulator Description: The 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) Effect on STATUS register flags: No flags affected. EXAMPLE: Before execution: A= C2h ( Bin.) After execution: A=85h ( Bin.) 128

129 RETI - Return from interrupt Description: This instruction ends every interrupt routine and informs processor that interrupt routine is no longer in progress. After instruction execution, the execution of the interrupted program continues from where it left off. The PSW is not autotomatically restored to its pre-interrupt status. Syntax: RETI Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags affected. RR A - Rotate Accumulator one bit right A: Accumulator Description: All eight bits in the Accumulator are rotaded one bit right so that the bit 0 is rotated into the bit 7 position. Syntax: RR A Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags affected. EXAMPLE: Before execution: A= C2h ( Bin.) After execution: A= 61h ( Bin.) 129

130 RLC A - Rotate Accumulator one bit left through Carry bit A: Accumulator Description: All eight bits in the Accumulator and Carry bit are rotated one bit left. After this operation, the bit 7 is rotated into the Carry bit position and the Carry bit is rotated into the bit 0 position. Syntax: RLC A Byte: 1 (Instruction Code) Effect on STATUS register flags: C EXAMPLE: Before execution: A= C2h ( Bin.) C=0 After execution: A= 85h ( Bin.) C=1 130

131 SETB C - Set Carry bit C: Carry bit Description: Instruction sets the Carry bit. Syntax: SETB C Byte: 1 (Instruction Code) Effect on STATUS register flags: C EXAMPLE: After execution: C=1 RRC A - Rotate Accumulator one bit right through Carry bit A: Accumulator Description: All eight bits in the Accumulator and Carry bit are rotated one bit right. After this operation, the Carry bit is rotated into the bit 7 position and the bit 0 is rotated into the Carry position. Syntax: RRC A Byte: 1 (Instruction Code) Effect on STATUS register flags: C 131

132 EXAMPLE: Before execution: A= C2h ( Bin.) C=0 After execution: A= 61h ( Bin.) C=0 SJMP rel - Short Jump adr: Jump Address Description: Instruction enables jump to the address located in the range of -128 to +127 locations relative to the first following instruction. Syntax: SJMP [jump address] Bytes: 2 (Instruction Code, Jump Value) Effect on STATUS register flags: No flags are affected. EXAMPLE: 132

133 Before execution: PC=323 After execution: PC=345 SETB bit - Set bit bit: Any bit in RAM Description: Instruction sets the indicated bit. The register including that bit must belong to the group of so called bit addressable registers. Syntax: SETB [bit address] Bytes: 2 (Instruction Code, Bit Address) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: P0.1 = 34h ( ) pin 1 is configured as output After execution: P0.1 = 35h ( ) pin 1 is configured as input SUBB A,Rx - Subtract Rx from Accumulator 133

134 Rx: Arbitrary register with address (0 - FFh) A: Accumulator Description: Instruction performs subtract operation: A-Rx including the Carry bit as well which acts as borrow (if the higher bit is subtracted from the lower bit then the Carry bit is set). As it is direct addressing, Rx can be some of SFRs or generalpurpose register with address 0-7Fh. (0-127 dec.). The result is stored in the Accumulator. Syntax: SUBB A,Rx Bytes: 2 (Instruction Code, Address Rx) Effect on STATUS register flags: C, OV, AC EXAMPLE: Before execution: A=C9h, DIF=53h, C=0 After execution: A=76h, C=0 SUBB A,Rn - Subtruct Rn from accumulator Rn: Any R register (R0-R7) A: Accumulator Description: Instruction performs subtract operation: A-Rn including the Carry as well which acts as borrow (if the higher bit is subtracted from the lower bit then the Carry bit is set). The result is stored in the Accumulator. Syntax: SUBB A,Rn Byte: 1 (Instruction Code) Effect on STATUS register flags: C, OV, AC EXAMPLE: 134

135 Before execution: A=C9h, R4=54h, C=1 After execution: A=74h, C=0 Note: The result is different (C9-54=75!) because the Carry bit has been set (C=1)before instruction execution. SUBB A,#X - Subtract number X from Accumulator A: Accumulator X: Constant in the range of (0-FFh) Description: Instruction performs subtract operation: A-X including the Carry bit as well which acts as borrow (if the higher bit is subtracted from the lower bit then the Carry bit is set). The result is stored in the Accumulator. Syntax: SUBB A,#X Bytes: 2 (Instruction Code, Constant X) Effect on STATUS register flags: C, OV, AC EXAMPLE: Before execution: A=C9h, C=0 After execution: A=A7h, C=0 SUBB A,@Ri - Subtract indirectly addressed register from Accumulator 135

136 Ri: Register R0 or R1 A: Accumulator Description: Instruction performs subtract operation: A-Rx including the Carry bit as well which acts as borrow (if the higher bit is subtracted from the lower bit then the Carry bit is set). As it is indirect addressing, register Rx address is located in the Ri register (R0 or R1). The result of the operation is stored in the Accumulator. Syntax: SUBB Byte: 1 (Instruction Code) Effect on STATUS register flags: C, OV, AC EXAMPLE: Register Address MIN=F4 Before execution: A=C9h, R1=F4h, MIN=04, C=0 After execution: A=C5h, C=0 XCH A,Rn - Exchange registers Rn with Accumulator Rn: Any R register (R0-R7) A: Accumulator Description: Instruction causes the Accumulator and Rn Registers to exchange data. The content of the Accumulator is loaded in the register Rn. At the same time, the content of the Rn register is set in the Accumulator. Syntax: XCH A,Rn Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: 136

137 Before execution: A=C6h, R3=29h After execution: R3=C6h, A=29h SWAP A - Swap nibbles within Accumulator A: Accumulator Description: A word nibble designates a group of 4 adjacent bits within one register (bit0-bit3 and bit4-bit7).this instruction interchanges the high and low nibbles of the Accumulator. Syntax: SWAP A Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: A=E1h ( )bin. After execution: A=1Eh ( )bin. 137

138 XCH - Exchange Accumulator with indirectly addressed register Rx Ri: Register R0 or R1 A: Accumulator Description: Instruction loads the contents of Accumulator into register Rx. At the same time, the content of register Rx is set into the Accumulator. As it is indirect addressing, register Rx address is located in the register Ri (R0 or R1). Syntax: XCH Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: Register Address SUM=E3 Before execution: R0=E3, SUM=29h, A=98h After execution: A=29h, SUM=98h XCH A,Rx - Exchange the content of registers Rx with the content of accumulator Rx: Arbitrary register with address (0 - FFh) A: Accumulator Description: Instruction loads the contents of the Accumulator into the register Rx. At the same time, the content of the Rx register is set into the Accumulator. As it is direct addressing, the register Rx can be some of SFRs or general-purpose register with address 0-7Fh (0-127 dec.). Syntax: XCH A,Rx Bytes: 2 (Instruction Code, Address Rx) Effect on STATUS register flags: No flags are affected. EXAMPLE: 138

139 Before execution: A=FFh, SUM=29h After execution: SUM=FFh A=29h XRL A,Rn - Exclusive-OR operation between register Rn and Accumulator Rn: Any R register (R0-R7) A: Accumulator Description: Instruction performs exclusive-or operation between the Accumulator and Rn Register. The result of this logical operation is located in the Accumulator. Syntax: XRL A,Rn Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: A= C3h ( Bin.) R3= 55h ( Bin.) After execution: A= 96h ( Bin.) XCHD A,@Ri - Exchange the content of low nibbles Accumulator with indirectly addressed register Rx Ri: Register R0 or R1 A: Accumulator 139

140 Description: This instruction interchanges the low nibbles (bits 0-3) of the Accumulator with the low nibbles of indirectly addressed register Rx. High nibbles of the Accumulator and Rx register are not affected. This instruction is mainly used in operating with BCD values. As it is indirect addressing, regiter Rx address is located in the register Ri (R0 or R1). Syntax: XCHD Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: Register Address SUM=E3 Before execution: R0=E3 SUM=29h A=A8h, After execution: A=A9h, SUM=28h XRL A,@Ri - Exclusive-OR operation between Accumulator and indirectly addressed register Ri: Register R0 or R1 A: Accumulator 140

141 Description: Instruction performs exclusive-or operation between the Accumulator and Rx Register. As it is indirect addressing, register Rx address is located in the Ri register (R0 or R1). The result of this logical operation is stored in the Accumulator. Syntax: XRL Byte: 1 (Instruction Code) Effect on STATUS register flags: No flags are affected. EXAMPLE: Register Address TEMP=FAh, R1=FAh Before execution: TEMP= C2h ( Bin.) A= 54h ( Bin.) After execution: A= 96h ( Bin.) XRL A,Rx - Exclusive-OR operation between Accumulator and register Rx Rx: Arbitrary register with address (0 - FFh) A: Accumulator Description: Instruction performs exclusive-or operation between the Accumulator and Rx Register. As it is direct addressing, the Rx register can be some of SFRs or general-purpose register with address 0-7Fh (0-127 dec.). The result of this logical operation is stored in the Accumulator. Syntax: XRL A,Rx Bytes: 2 (Instruction Code, Address Rx) Effect on STATUS register flags: No flags are affected. EXAMPLE: 141

142 Before execution: A= C2h ( Bin.) LOG= 54h ( Bin.) After execution: A= 96h ( Bin.) XRL Rx,A - Exclusive-OR operation between directly addressed register Rx and Accumulator Rx: Arbitrary register with address (0 - FFh) A: Accumulator Description: Instruction performs exclusive-or operation between the Rx Register and Accumulator. As it is direct addressing, the Rx register can be some of SFRs or general-purpose register with address 0-7Fh (0-127 dec.). The result of this logical operation is stored in the Rx register. Syntax: XRL Rx,A Bytes: 2 (Instruction Code, Address Rx) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: TEMP= C2h ( Bin.) A= 54h ( Bin.) After execution: A= 96h ( Bin.) XRL A,#X - Exclusive-OR between Accumulator and number X 142

143 X: Constant in the range of (0-FFh) A: Accumulator Description: Instruction performs exclusive-or operation between the Accumulator and number X. The result of this logical operation is stored in the Accumulator. Syntax: XRL A,#X Bytes: 2 (Instruction Code, Constant X) Effect on STATUS register flags: No flags are affected. EXAMPLE: Before execution: A= C2h ( Bin.) X= 11h ( Bin.) After execution: A= D3h ( Bin.) XRL Rx,# - Exclusive-OR operation between directly addressed register Rx and number X Rx: Arbitrary register with address (0 - FFh) X: Constant in the range of (0-FFh) Description: Instruction performs exclusive-or operation between the Rx Register and number X. As it is direct addressing, the Rx register can be some of SFRs or general-purpose register with address 0-7Fh (0-127 dec.). The result of this logical operation is stored in the Rx register. Syntax: XRL Rx,#X Bytes: 3 (Instruction Code, Address Rx, Constant X) Effect on STATUS register flags: No flags are affected. EXAMPLE: 143

144 Before execution: TEMP= C2h ( Bin.) X=12h ( Bin.) After execution: A= D0h ( Bin.) 144

145 Chapter 4 : AT89S8253 Microcontroller 4.1 AT89S8253 Microcontroller ID 4.2 Pin Description 4.3 AT89S8253 Microcontroller Memory Organisation 4.4 SFRs (Special Function Registers) 4.5 Watchdog Timer (WDT) 4.6 Interrupts 4.7 Counters and Timers 4.8 UART (Universal Asynchronous Receiver Transmitter) 4.9 SPI System (Serial Peripheral Interface) 4.10 Power Consumption Control 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 compliant or 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. 4.1 The AT89S8253 microcontroller ID Compatible with 8051 family. 12Kb of Flash Memory for storing programs. o Program is loaded via SPI System (Serial Peripheral Interface). o Program may be loaded/erased up to 1000 times. 2Kb of EEPROM Memory. Power supply voltage: 4-6V. Operating clock frequency: 0-24MHz. 256 bytes of internal RAM for storing variables. 32 input/output pins. Three 16-bit timers/counters. 9 interrupt sources. 2 additional power saving modes (low-power idle and power-down mode). Programmable UART serial communication. Programmable watchdog timer. 145

146 Three-level program memory lock The AT89S53 comes in the following packages: 146

147 4.2 Pinout Description VCC Power supply voltage (4-6V) GND Ground ( Negative supply pole) Port 0 (P0.0-P0.7) If configured as outputs, each of these pins can be connected to up to 8 TTL inputs. If configured as inputs, the pins can be used as high-impedance inputs as their potential is not defined 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: 147

148 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. 148

149 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. 4.3 The AT89S8253 Microcontroller Memory Organisation Program Memory (ROM) Program memory (ROM) with a capacity of 12Kb is designed in FLASH technology, which enables programs to be loaded and erased a large number of times. It is programmed via embedded SPI module (Serial Peripheral Interface). If necessary, it is possible to add external ROM memory chip, although 12Kb of ROM is usually more than enough. Random Access Memory (RAM) RAM memory consists of 3 blocks containing 128 registers each. Its structure falls into the 8051 standard: 128 general-purpose registers; 128 memory locations reserved for SFRs. Even though only some of them are trully used, free locations shouldn t be used for storing variables; and 128 additional registers available for use (have no special purpose). Since they have the same addresses as SFRs, they are accessed by indirect addressing. 149

150 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). 4.4 Special Function Registers (SFRs) The AT89S8253 microcontroller has in total of 40 Special Function Registers. For the sake of the compatibility with the previous 8051 models, the core registers (22 in total) are the same for all of them, while the others were added later for the purpose of controlling upgraded functions of the microcontroller. As shown in the table above, each of these registers has its name and specific address 150

151 in RAM. Unoccupied locations are intended for the future upgraded versions of the microcontroller and shouldn t 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 operands upon which these operations are performed. PSW register (Program Status Word Register) The PSW register belongs to the core registers of the 8051 microcontroller. Bits of this register are not modified. SP registar (Stack Pointer Register) The SP register belongs to the core registers of the 8051 microcontroller. Bits of this register are not modified. 151

152 Registers P0, P1, P2, P3 Each bit of these registers corresponds to one of the port pins having the same name. These registers are therefore used for comminication with peripheral environment which is carried out by sending data from registers to the corresponding pins and vice versa. They belong to the core registers of the 8051 microcontroller and their bits are not modified. R registers (R0 - R7) They belong to the core registers of the 8051 microcontroller. Their bits are not modified. 152

153 AUXR register (Auxiliary register) The AUXR register contains only two active bits: 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 don t 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. 153

154 DPS=1 -> Data pointer consists of DP1L and DP1H registers and is marked as DPTR1. Handling EEPROM memory 2 Kb of on-chip EEPROM memory enables this microcontroller to store data created during operation which must be permanently saved. In other words, all data stored in this memory remains permanently saved even after the loss of power. Minimum writing cycles can be executed. This memory is easily used since there are only a few control bits enabling it. EEPROM write and read is under control of the EECON special function register. Since the process of programming EEPROM is relatively slow (write to one register takes approximately 4mS), a small hardware trick is done in order to speed it up. When the EELD bit of the EECON register is set, the data is not directly written to the EEPROM registers, but loaded in a small buffer (temporary memory) with a capacity of 32 bytes. When this bit is cleared, the first data following it will be normally 154

155 written to the EEPROM (takes 4 ms) along with all registers currently loaded in the buffer. Thus, it takes only 4mS to write all 32 bytes instead of 128mS otherwise required in a single byte writing. EEPROM memory is handled in the same way as external memory. For this reason, a special instruction for additional memory chip (MOVX) is also used for EEPROM write and read. The EEMEN bit of the EECON register determines whether the data is to be written/read from additional memory chip or on-chip EEPROM memory. 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 155

156 The RDY/BSY bit is read-only. DPS 0 - Write in progress (takes approximately 4mS). 1 - Write complete (data is written to EEPROM). 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. 4.5 Watchdog Timer (WDT) The watchdog timer uses pulses generated by the quartz oscillator for its operation. It is disabled after reset and during Power Down Mode, thus having no effect on the program execution. If enabled, every time it counts up to the program end, the microcontroller reset occurs and program execution starts from the first instruction. Reset condition indicates that the program doesn t work properly for some reason. The point is to prevent this from happening by setting instruction to reset the watchdog timer at the appropriate program location. Practically, the whole this process is in control of several bits of the WDTCON register. Three bits (PS2, PS1 and PS0), which are in control of the prescaler, determine the most important feature of the watchdog timer- nominal time, i.e. time required to count up a full cycle. The values contained in the table below are applied only when the 12MHz quartz oscillator is used. 156

157 Prescaler Bits PS2 PS1 PS ms ms ms ms ms ms Nominal Time ms ms WDTCON Register (Watchdog Control Register) PS2,PS1,PS0 These three bits are in control of the prescaler and determine the nominal time of the watchdog timer. If the program doesn t 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 doesn t 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: 157

158 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 doesn t clear the watchdog timer, it only enables/disables it. This means that the current state of the counter remains unchanged as long as WDTEN= 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. 158

159 IE register (Interrupt Enable Register) EA bit enables or disables all interrupt sources (globally): 0 - disables all interrupts (even enabled). 1 - enables specific interrupts. ET2 bit enables or disables Timer T2 interrupt: 0 - Timer T2 interrupt disabled. 1 - Timera T2 interrupt enabled. ES bit enables or disables serial communication (UART and SPI) interrupts: 0 - UART and SPI interrupt disabled. 1 - UART and SPI interrupts enabled. 159

160 ET1 bit enables or disables Timer T1 interrupt: 0 - Timer T1 interrupt disabled. 1 - Timer T1 interrupt enabled. EX1 bit enables or disables external interrupt through the INT0 pin: 0 - Interrupt on the INT0 pin disabled. 1 - Interrupt on the INT0 pin enabled. ET0 bit enables or disables Timer T0 interrupt: 0 - Timer T0 interrupt disabled. 1 - Timer T0 interrupt enabled. EX0 bit enables or disables external interrupt through the INT1 pin: 0 - Interrupt on the INT1 pin disabled. 1 - Interrupt on the INT1 pin enabled. Interrupt Priorities When several interrupts are enabled, it may happen that while one of them is in progress, another one is requested. In such situations, the microcontroller needs to know whether to proceed with the execution of current interrupt routine or to meet a new interrupt request. For this reason, there is a priority list on the basis of which the microcontroller knows what to do. The previous versions of the microcontrollers differentiate between two priority levels defined in the IP register. As for the AT89S8253 microcontroller, there is an additional SFR register IPH which enables all the interrupts to be assigned 1 out of 4 priorities (excluding reset). Here is a list of priorities: 1. Reset. If a reset request arrives, all processes are stopped and the microcontroller restarts. 2. The high priority interrupt (3) can be disabled by reset only. 3. The low priority interrupt (2, 1 or 0) can be disabled by any high priority interrupt and reset. It is usually defined at the beginning of the program which one of the existing interrupt sources have high and which one has low priority level. According to this, the following occurs: If two interrupt requests, at different priority levels, arrive at the same time then the higher priority interrupt is always serviced first. If the both interrupt requests, at the same priority level, occur one after another, the one which came later has to wait until routine being in progress ends. If two interrupt requests of equal priority arrive at the same time then the interrupt to be serviced is selected according to the following priority list : 160

161 1. External interrupt INT0 2. Timer T0 interrupt 3. External interrupt INT1 4. Timer T1 interrupt 5. Serial communication interrupt 6. Timer T2 Interrupt IP register (Interrupt Priority Register) Bits of this register determine the interrupt source priority. PT2 Timer T2 interrupt priority: 0 - Priority Priority 1 PS Serial port interrupt priority: 0 - Priority Priority 1 PT1 Timer T1 interrupt priority: 0 - Priority Priority 1 PX1 External interrupt INT1 priority: 0 - Priority Priority 1 PT0 Timer T0 interrupt priority: 0 - Priority Priority 1 PX0 External interrupt INT0 priority: 0 - Priority Priority 1 IPH Register (Interrupt Priority High) 161

162 PT2H Timer T2 interrupt priority PSH Serial port interrupt priority PT1H Timer T1interrupt priority PX1H External interrupt INT1 priority PT0H Timer T0 interrupt priority PX0H External interrupt INT0 Priority Bits of this register can be combined with appropriate bits of the IP register. This is how a new priority list with 4 interrupt priority levels (5 including reset) is obtained. IP bit IPH bit Interrupts 0 0 Priority 0 (lowest) 0 1 Priority 1 (low) 1 0 Priority 2 (high) 1 1 Priority 3 (highest) Processing interrupt When an interrupt request arrives, the microcontroller automatically detects the interrupt source and the 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 IE0 TF0 IE1 TF1 RI, TI, SPIF TF2, EXF2 All addresses are in hex format Jump Address 3h Bh 13h 1Bh 23h 2Bh 162

163 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. 4.7 Counters and Timers Timers T0 and T1 The AT89S8253 has three timers/counters marked as T0, T1 and T2. Timers T0 and T1 completely fall under the 8051 Standard. There are no changes in their operation. Timer T2 Timer 2 is a 16-bit timer/counter installed only in new versions of the 8051 family. Unlike timers T0 and T1, this timer consists of 4 registers. Two of them, TH2 and TL2, are connected serially in order to form a larger 16-bit timer register. Like timers 0 and 1, it can operate either as a timer or as an event counter. Another two registers, RCAP2H and RCAP2L, are also serially connected and operate as capture registers. They are used to temporarily store the contents of the counter register. The main adventage of this timer compared to timers 0 and 1 is that all read and swap operations are easily performed using one instruction. Similar to T0 and T1, it has four different modes of operation to be described later in this chapter. 163

164 T2CON (Timer/Counter 2 Control Register) This register contains bits controlling the operation of timer 2. TF2 bit is automatically set on timer 2 overflow. In order to detect the next overflow, this bit must be cleared from within the program. If bits RCLK and TCLK are set, overflow has no effect on the TF2 bit. EXF2 bit is automatically set when a capture or a reload is caused by a negative transition on the T2EX pin. It generates an interrupt (if enabled), unless the DCEN bit of the T2CON register is set. The EXF2 bit must be cleared from within the program. RCLK is receive clock bit which determines which timer is to be used as receive clock for serial port: 1 - T2 is used as receive clock for serial port. 0 - T1 is used as receive clock for serial port. TCLK is transmit clock bit which determines which timer is to be used as transmit clock for serial port: 1 - T2 is used as transmit clock for serial port. 0 - T1 is used as transmit clock for serial port. EXEN2 is timer 2 external enable bit used to include the T2EX pin in timer 2 operation: 1 - Signal on the T2EX pin affects timer 2 operation. 0 - Signal on the T2EX pin is ignored. TR2 is timer 2 run control bit used to enable/disable timer 2: 1 - Timer 2 enabled. 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) 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. 164

165 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: 165

166 Timer T2 in auto-reload mode The auto-reload mode configures timer 2 as a 16-bit timer or event counter with automatic reload. It is controlled by the DCEN bit of the T2MOD register. Setting the DCEN bit enables timer 2 to count up or down from the specified value. The T2EX pin controls the counting direction: T2OE - Enables timer 2 to operate as independent clock generator. DCEN - When set, it enables counting in either direction- "up" and "down". 166

167 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: 167

168 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, 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: 168

169 There are a few details to be aware of: 1. This formula works only if the internal oscillator is used as a clock generator (in this mode, clock is divided by 2, instead of 12) 2. Overflow has no effect on the TF2 bit and does not generate an interrupt. 3. Whether the EXEN2 bit is set or not, the T2EX pin logic state has no effect on the timer. It means that the T2EX pin can be used as an external interrupt source in this mode. 4. Timer should be disabled (TR2=0) prior to writing or reading from registers TH2 and TL2. Otherwise, an error in serial communication might occur. Timer T2 as a clock generator As previously mentioned, timer T2 can also be used as a clock generator. In all previous examples, the P1.0 pin (marked as T2 in figures) is used as an alternative clock generator for this timer, i.e. it acts as an input. Besides, it can also output pulses. By using a 16MHz quartz crystal, the frequency of pulses it generates ranges from 61Hz to 4MHz with a 50% duty-cycle. To configure this pin as an output, the C/T2 bit of the T2CON register must be cleared, whereas the T2OE bit of the T2MOD register must be set. The TR2 bit enables the timer and the pin outputs rectangular waves the frequency of which ca be calculated using the formula below: 4.8 Universal Asynchronous Receiver Transmitter (UART) The Universal Asynchronous Receiver Transmitter (UART) has the same features as that of the standard 8051 microcontrollers. It means that it can operate in 1 out of 4 different modes, which is controlled by bits SM0 and SM1 of the SCON register. Multiprocessor Communication 169

170 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 = SADEN = Address = X0 Microcontroller C: SADDR = SADEN = Address = X 170

171 Although both microcontrollers B and C are assigned the same address ( ), 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 , the data will be sent to slave device B. If transmit address is the data will be sent to slave device C. If transmit address is the data will be sent to both slave devices. 4.9 SPI System (Serial Peripheral Interface) In addition to UART system, the AT89S8253 has also another system for serial communication which doesn t 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 generalpurpose input. 171

172 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. Knowing abbraviations makes connection easier: MISO - master in, slave out; MOSI - master out, slave in; SCK - serial clock; SS - slave select; Similar to many other circuits within the microcontroller, the SPI system can also be configured to operate in several modes. Normal SPI mode (buffer out of use) Data written to the SPI data register SPDR is automatically transferred to an 8- bit shift register. SPI clock generator is enabled and serial data appears on the MOSI pin. An initial delay may occur for the sake of synchronization with the main oscillator. 172

173 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). 173

174 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. SPSR (SPI Status Register) 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 174

175 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. MSTR Bit determines whether the microcontroller is to operate as master or slave: 0 - Operate as slave. 1 - Operate as master. CPOL Bit controls the SCK pin logic state when the SPI communication is not in progress: 0 - Pin SCK is cleared. 1 - Pin SCK is set. CPHA This bit along with the CPOL bit controls relation between clock and data in serial format. Refer to the figure below. 175

176 SPR1,SPR0 When SPI system operates as master, these two bits determine boud rate, i.e. clock signal frequency of the master device. When operates as slave, these bits have no effect and SPI system operates at a rate imposed by the master device. SPR1 SPR0 SCK 0 0 Fosc/4 0 1 Fosc/ Fosc/ Fosc/128 Serial data format if CPHA=0 * not defined. It is usually MSB of previously received byte. Serial data format if CPHA=1 176

177 * not defined. It is usually LSB of previously received byte. Two things are important to remember when configuring SPI system: Master should be configured before slave. When writing bits to the SPCR register, the SPE bit enabling SPI should be set last, i.e. after setting all other parameters Power Consumption Control Like all models belonging to the 8051 series, this microcontroller can operate in 1 out of 3 modes: normal (consumption ca. 25 ma), Idle (consumption ca. 6.5 ma) and Power Down (consumption ca. 40 ua). The mode of operation is selected by bits of the PCON register (Power Control Register). Three bits are changed compared to the basic model: PCON register The purpose of the bits of the PCON register: SMOD1 When set, this bit makes boud rate twice as high. SMOD0 Bit determines the purpose of the 7th bit of the SCON register: 0 Seventh bit of the SCON register has the function of SM0, i.e. selects mode of operation. 1 Seventh bit has the function of FE, i.e. detects errors. It is rarely used. POF Bit is automatically set when the voltage level reaches maximum (must be higher than 3V) after powering on. It is used for detecting cause for reset (power on or restart condition after exiting Power Down mode). GF1 General purpose bit (available for use). GF0 General purpose bit (available for use). PD By setting this bit, the microcontroller is set in Power Down mode. IDL By setting this bit, the microcontroller is set in Idle mode. When something goes wrong

178 If something unexpected happens during the operation of the microcontroller, what most bothers is the fact that it s never the microcontroller's fault. Although it s not self-evident, the microcontroller always obediently follows program instructions. For this reason, it is necessary to pay special attention to several critical points when writing a program. The first one is RAM memory. Even though it is designed to meet needs of the majority of users and has all required, a memory space intended for RAM is still only a single entity. It means that there are no phisically separated registers R0-R7, general purpose registers, stack etc. Instead, these are differently designated parts of the same memory shelf. Refer to the figure below. 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. 178

179 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 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 doesn t 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 179

180 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) ACC After reset Bit name Bit address E7 E6 E5 E4 E3 E2 E1 E0 B register (Address: F0) B After reset Bit name Bit address F7 F6 F5 F4 F3 F2 F1 F0 Interrupt Priority register (Address: B8) IP After reset X X Bit name - - PT2 PS PT1 PX1 PT0 PX0 Bit address BF BE BD BC BB BA B9 B8 Interrupt Enable register (Address: A8) IE After reset 0 X Bit name EA - ET2 ES ET1 EX1 ET0 EX0 Bit address AF AE AD AC AB AA A9 A8 Port 0 (Address: 80) P0 After reset Bit name Bit address Port 1 (Address: 90) 180

181 P1 After reset Bit name Bit address Port 2 (Address: A0) P2 After reset Bit name Bit address A7 A6 A5 A4 A3 A2 A1 A0 Port 3 (Address: B0) P3 After reset Bit name Bit address B7 B6 B5 B4 B3 B2 B1 B0 Program Status Word (Address: D0) PSW After reset 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) SCON After reset Bit name SM0 SM1 SM2 REN TB8 RB8 TI RI Bit address 9F 9E 9D 9C 9B 9A Timer Control register (Address: 88) TCON After reset Bit name TF1 TR1 TF0 TR0 IF1 IT1 IF0 IT0 Bit address 8F 8E 8D 8C 8B 8A Timer/Counter 2 Control register (Address: C8) 181

182 T2CON After reset 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) AUXR After reset X X X X X X X 0 Bit name Intel_Pwd_Exit DISALE Clock register (Address: 8F) CLKREG After reset X X X X X X X 0 Bit name X2 Data Pointer 0 High (Address: 83) DP0H After reset Bit name Data Pointer 0 Low (Address: 82) DP0L After reset Bit name Data Pointer 1 High Byte (Address: 85) DP1H After reset Bit name Data Pointer 1 Low Byte (Address: 84) DP1L After reset Bit name

183 EEPROM Control (Address: 96) EECON After reset X X Bit name - - EELD EEMWE EEMEN DPS RDY/BSY WRTINH Interrupt Priority High Byte (Address: B7) IPH After reset X X Bit name - - PT2H PSH PT1H PX1H PT0H PX0H Power Control (Address: 87) PCON After reset 0 X X X Bit name SMOD GF1 GF0 PD IDL Slave Address (Address: A9) SADDR After reset Bit name Slave Address Enable (Address: B9) SADEN After reset Bit name Serial buffer (Address: 99) SBUF After reset X X X X X X X X Bit name Stack Pointer (Address: 81) SP After reset Bit name

184 SPI Control register (Address: D5) SPCR After reset Bit name SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0 SPI Data register (Address: 86) SPDR After reset Bit name SPI Status register (Address: AA) SPSR After reset Bit name SPIF WCOL LDEN DISSO ENH Timer 2 Reload Capture High (Address: CB) RCAP2H After reset Bit name Timer 2 Reload Capture Low (Address: CA) RCAP2L After reset Bit name Timer 0 Low (Address: 8A) TL0 After reset Bit name Timer 1 Low (Address: 8B) TL1 After reset Bit name

185 Timer 2 Low (Address: CC) TL2 After reset Bit name Timer 0 High Byte (Address: 8C) TH0 After reset Bit name Timer 1 High Byte (Address: 8D) TH1 After reset Bit name Timer 2 High Byte (Address: CD) TH2 After reset Bit name Timer Mode (Address: 89) TMOD After reset Bit name GATE1 C/T1 T1M1 T1M0 GATE0 C/T0 T0M1 T0M0 Timer 2 Mode Control (Address: C9) T2MOD After reset X X X X X X 0 0 Bit name T2OE DCEN Watchdog Timer Control (Address: A7) WDTCO N After reset Bit PS PS PS WDIDL DISRT HWD WSWRS WDTE 185

186 nam e E O T T N Watchdog Timer Reset (Address: A6) WDTCON After reset Bit name Voltage characteristics of the AT89S8253 microcontrollers Symbol Parameter Condition Min. Max. VIL VIL1 VIH VIH1 VOL VOH1 IIL IILI RRST CIO ICC Input Low-voltage Input Low-voltage on EA pin High- Input voltage Input Highvoltage on pins XTAL1 and RST High- Output voltage Output Highvoltage when Pullup resistors are enabled (Port P0 in External BUS mode, ports P1,2,3, pins ALE and PSEN) Logical 0 input current (ports P1,2,3) Input leakage current (port P0, pin EA) Reset pull-down resistor I/O Capacitance pin All pins except EA All pins except XTAL1 and RST Iol = 10mA, Vcc = 4.0V, Ta = 85 C Ioh = -40mA, Ta = 85 C Ioh = -25mA, Ta = 85 C Ioh = -10mA, Ta = 85 C Vin = 0.45V, Vcc = 5.5V, Ta = - 40 C 0.45V < Vin < Vcc f = 1Mhz, Ta = 25 C -0.5 V 0.2Vcc - 0.1V -0.5 V 0.2Vcc - 0.3V 0.2 Vcc + 0.9V Vcc V 0.7 Vcc Vcc V 2.4 V 0.75 Vcc 0.9 Vcc 0.4 V - 50 μa ± 10 μa 50 KΩ 150 KΩ 10 pf Power-supply current Normal mode: f = 12Mhz, Vcc = 5.5V Ta = -40 C 25 ma 6.5 ma 186

187 Power-down mode Idlle mode f = 12Mhz, Vcc = 5.5V Ta = -40 C Vcc = 5.5V Ta = -40 C Vcc = 4V Ta = - 40 C 100 μa 40 μa 187

188 Chapter 5: Assembly Language 5.1 Elements of Assembly Language 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. 5.1 Elements of Assembly Language Assembly language is basically like any other language, which means that it has its words, rules and syntax. The basic elements of assembly language are: Labels; Orders; Directives; and Comments. 188

189 Syntax of Assembly language When writing a program in assembly language it is necessary to observe specific rules in order to enable the process of compiling into executable HEX-code to run without errors. These compulsory rules are called syntax and there are only several of them: Every program line may consist of a maximum of 255 characters; Every program line to be compiled, must start with a symbol, label, mnemonics or directive; Text following the mark ; in a program line represents a comment ignored (not compiled) by the assembler; and 189

190 All the elements of one program line (labels, instructions etc.) must be separated by at least one space character. For the sake of better clearness, a push button TAB on a keyboard is commonly used instead of it, so that it is easy to delimit columns with labels, directives etc. in a program. 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 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 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 In order to distinguish binary numbers from other numbers, they are followed by the letter b (either in upper- or lowercase). For example B. 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: 190

191 Name Operation Example Result + Addition Subtraction * Multiplication 7*4 28 / MOD SHR SHL NOT Division (with no remainder) Remainder of division Shift register bits to the right Shift register bits to the left Negation (first complement of number) 7/4 1 7 MOD B SHR B SHL 2 NOT B B B AND Logical AND 1101B AND 0101B 0101B OR Logical OR 1101B OR 0101B 1101B XOR Exclusive OR 1101B XOR 0101B 1000B LOW HIGH 8 low significant bits 8 high significant bits LOW(0AADDH) HIGH(0AADDH) 0DDH 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. 191

192 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 AB ACALL ADD ADDC AJMP AND ANL AR0 AR1 AR2 AR3 AR4 AR5 AR6 AR7 BIT BSEG C CALL CJNE CLR CODE CPL CSEG DA DATA DB DBIT DEC DIV DJNZ DPTR DS DSEG DW END EQ EQU GE GT HIGH IDATA INC ISEG JB JBC JC JMP JNB JNC JNZ JZ LCALL LE LJMP LOW LT MOD MOV MOVC MOVX MUL NE NOP NOT OR ORG ORL PC POP PUSH R0 R1 R2 R3 R4 R5 R6 R7 RET RETI RL RLC 192

193 Labels RR RRC SET SETB SHL SHR SJMP SUBB SWAP USING XCH XCHD XDATA XOR XRL XSEG 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

194 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 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 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 ORG 1000h TABLE

195 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 0 ;Bank 0 is used (registers R0-R7 at RAM-addresses 0-7) USING 1 ;Bank 1 is used (registers R0-R7 at RAM-addresses 8-15) USING 2,Bank 2 is used (registers R0-R7 at RAM-addresses 16-23) USING 3 ;Bank 3 is used (registers R0-R7 at RAM-addresses 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 Directives used for selecting memory segments There are 5 directives used for selecting one out of five memory segments in the microcontroller: CSEG ;Indicates that the next segment refers to program memory; BSEG ;Selects bit-addressable part of RAM; DSEG ;Indicates that the next segment refers to the part of internal RAM accessed by ;direct addressing; ISEG ;Indicates that the next segment refers to the part of internal RAM accessed by ;indirect addressing using registers R0 and R1); and XSEG ;Selects external RAM memory. 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. 195

196 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: 196

197 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 197

198 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 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. 198

199 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 Basic connecting As seen in the figure above, in order to enable the microcontroller to operate properly it is necessary to provide: Power supply: 199

200 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 Murphy s low?! A 5V DC is most commonly used. The circuit, shown in the figure, uses a cheap integrated three-terminal 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. 200

201 6.2 Additional components Regardless of the fact that the microcontroller is a product of modern technology, it is of no use without being connected to additional components. Simply put, the appearance of voltage on its pins means nothing if not used for performing certain operations (turn something on/off, shift, display etc.). Switches and Push buttons There are no simpler devices than switches and push-buttons. This is the simplest way of detecting appearance of a voltage on the microcontroller input pin. 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. 201

202 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 microcontroller s 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 202

203 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). 203

204 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. 204

205 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 diode s 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 Maximal Voltage current Id current If (ma) Ud (V) (ma) Infrared Red Standard Red Super Bright Red Low Current Orange Green Low Current Yellow Blue White drop 205

206 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. 206

207 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 ( ) is replaced by the binary number 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 207

208 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. Digits to display Display Segments dp a b c d e f g

209 In addition to digits from 0 to 9, some letters of alphabet - A, C, E, J, F, U, H, L, b, c, d, o, r, t - can also be displayed by performing appropriate masking. If the event that common chatode displays are used all units in the table should be replaced by zeros and vice versa. Additionally, NPN transistors should be used as drivers as well. Liquid Crystal Displays (LCD) An LCD display is specifically manufactured to be used with microcontrollers, which means that it cannot be activated by standard IC circuits. It is used for displaying different messages on a miniature liquid crysal display. 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: 209

210 Function Pin Logic Name Number State Description Ground 1 Vss - 0V Power supply 2 Vdd - +5V Contrast 3 Vee Vdd Control operating 4 RS of 5 R/W D0 D7 are interpreted as commands D0 D7 are interpreted as data Write data (from controller to LCD) Read data (from LCD to controller) 0 Access to LCD disabled 6 E 1 Normal operating From 1 to Data/commands are transferred 0 to LCD 7 D0 0/1 Bit 0 LSB 8 D1 0/1 Bit 1 9 D2 0/1 Bit 2 Data / 10 D3 0/1 Bit 3 commands 11 D4 0/1 Bit 4 12 D5 0/1 Bit 5 13 D6 0/1 Bit 6 14 D7 0/1 Bit 7 MSB LCD screen 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 210

211 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. 211

212 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 to- from 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 leftright 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. 212

213 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 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 213

214 symbol from 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: 214

215 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 215

216 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 RS RW D7 D6 D5 D4 D3 D2 D1 D0 Execution Time Clear display mS Cursor home x 1.64mS Entry mode set I/D S 40uS Display on/off control D U B 40uS Cursor/Display Shift D/C R/L x x 40uS Function set DL N F x x 40uS Set CGRAM address CGRAM address 40uS Set DDRAM address DDRAM address 40uS Read BUSY flag (BF) 0 1 BF DDRAM address - Write to CGRAM or 1 DDRAM 0 D7 D6 D5 D4 D3 D2 D1 D0 40uS Read from CGRAM or 1 DDRAM 1 D7 D6 D5 D4 D3 D2 D1 D0 40uS I/D 1 = Increment (by 1) R/L 1 = Shift right 0 = Decrement (by 1) 0 = Shift left S 1 = Display shift on DL 1 = 8-bit interface 0 = Display shift off 0 = 4-bit interface D 1 = Display on N 1 = Display in two lines 0 = Display off 0 = Display in one line U 1 = Cursor on F 1 = Character format 5x10 dots 0 = Cursor off 0 = Character format 5x7 dots B 1 = Cursor blink on D/C 1 = Display shift 0 = Cursor blink off 0 = Cursor shift What is the Busy flag? Compared to the microcontroller, the LCD is an extremely slow component. Because of this, it was necessary to provide a signal which will, upon command execution, 216

217 indicate that the display is ready to receive a new data. That signal, called the busy flag, can be read from line D7. When the BF bit is cleared (BF=0), the display is ready to receive a new data. LCD Connection Depending on how many lines are used for connecting the LCD to the microcontroller, there are 8-bit and 4-bit LCD modes. The appropriate mode is selected at the beginning of the operation. This process is called initialization. 8-bit LCD mode uses outputs D0-D7 to transfer data in the way explained on the previous page. The main purpose of 4-bit LED mode is to save valuable I/O pins of the microcontroller. Only 4 higher bits (D4-D7) are used for communication, while other may be left unconnected. Each data is sent to the LCD in two steps: four higher bits are sent first (normally through the lines D4-D7), then four lower bits. Initialization enables the LCD to link and interpret received bits correctly. Data is rarely read from the LCD (it is mainly transferred from the microcontroller to LCD) so that it is often possible to save an extra I/O pin by simple connecting R/W pin to ground. Such saving has its price. Messages will be normally displayed, but it will not be possible to read the busy flag since it is not possible to read the display either. 217

218 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 218

219 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: 219

220 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: 220

221 221

222 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 222

223 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 AT 03FH STACK_START: DS 040H ;RESET VECTORS CSEG AT 0 JMP XRESET ;Reset vector ORG 100H XRESET: MOV SP,#STACK_START ;Define Stack pointer MOV P1,#0FFh ;All pins are configured as inputs LOOP: CPL P1.0 ;Pin P1.0 state is inverted LCALL Delay ;Time delay SJMP LOOP Delay: MOV R2,#20 ;500 ms time delay F02: MOV R1,#50 ;25 ms F01: MOV R0,#230 DJNZ R0,$ DJNZ R1,F01 DJNZ R2,F02 END Using Watch-dog Timer ;End of program This example describes how the watch-dog timer should not operate. The watch-dog timer is properly adjusted (nominal time for counting is 1024mS), but instruction used to reset it is intentionally left out so that this timer always "wins". As a result, the microcontroller is reset (state in registers remains unchanged), program starts execution from the beginning and the number in register R3 is incremented by 1 and then copied to port P1. LEDs display this number in binary format

224 ;******************************************************************** **** ;* PROGRAM NAME : WatchDog.ASM ;* DESCRIPTION : After watch-dog reset, program increments number in ;* register R3 and shows it on port P1 in binary format. ;******************************************************************** **** ;BASIC DIRECTIVES $MOD53 $TITLE(WATCHDOG.ASM) $PAGEWIDTH(132) $DEBUG $OBJECT $NOPAGING WMCON DATA 96H WDTEN EQU B ; Watch-dog timer is enabled PERIOD EQU B ; Nominal Watch-dog period is set to be 1024ms ;RESET VECTOR CSEG AT 0 JMP XRESET ; Reset vector CSEG ORG 100H XRESET: ORL WMCON,#PERIOD ; Define Watch-dog period ORL WMCON,#WDTEN ; Watch-dog timer is enabled MOV A,R3 ; R3 is moved to port 1 MOV P1,A INC R3 ; Register R3 is incremented by 1 LAB: SJMP LAB ; Wait for watch-dog reset END Timer T0 in mode 1 ; End of program 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 2 16 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) 224

225 $DEBUG $OBJECT $NOPAGING ;DECLARATION OF VARIABLES ;STACK DSEG AT 03FH STACK_START: DS 040H ;RESET VECTORS CSEG AT 0 JMP XRESET ; Reset vector ORG 00BH JMP TIM0_ISR ; Timer T0 reset vector ORG 100H XRESET: MOV SP,#STACK_START ; Define Stack pointer MOV TMOD,#01H ; MOD1 is selected MOV A,#0FFH MOV P1,#0FFH SETB TR0 ; Timer T0 is enabled MOV IE,#082H ; Interrupt enabled CLR C LOOP1: SJMP LOOP1 ; Remain here TIM0_ISR: RRC A ; Rotate accumulator A through Carry flag MOV P1,A ; Contents of accumulator A is moved to PORT1 RETI ; Return from interrupt END Timer T0 in Split mode ; End of program Similarly to the previous example, the program spends most of its time in a loop called LOOP1. Since 16-bit Timer T0 is split into two 8-bit timers, there are also two interrupt sources. 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 225

226 ;* 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 0 ;DECLARATION OF BIT-VARIABLES SEMAPHORE: DBIT 8 DIRECTION BIT SEMAPHORE ;STACK DSEG AT 03FH STACK_START: DS 040H ;RESET VECTORS CSEG AT 0 JMP XRESET ; Reset vector ORG 00BH JMP TIM0_ISR ; Timer T0 reset vector ORG 01BH JMP TIM1_ISR ; Timer T1 reset vector ORG 100H XRESET: MOV SP,#STACK_START ; Define Stack pointer MOV TMOD,# B ; Define MOD3 MOV A,#0FFH MOV P1,#0FFH MOV R0,#30D SETB TR0 ; TL0 is turned on SETB TR1 ; TL1 is turned on MOV IE,#08AH ; Interrupt enabled CLR C CLR DIRECTION ; Rotate to the right LOOP1: SJMP LOOP1 ; Remain here TIM0_ISR: DJNZ R0,LAB3 ; Slow down rotation by 256 times JB DIRECTION,LAB1 RRC A ; Rotate contents of Accumulator to the right through ; Carry flag SJMP LAB2 226

227 LAB1: RLC A ; Rotate contents of Accumulator to the left through ; Carry flag LAB2: MOV P1,A ; Contents of Accumulator is moved to port P1 LAB3: RETI ; Return from interrupt TIM1_ISR: DJNZ R1,LAB4 ; Slow down direction of rotation by 256 times DJNZ R2,LAB4 ; When time expires, change rotation direction CPL SMER MOV R2,#30D LAB4: RETI END Simultaneous use of timers T0 and T1 ; End of program This program can be considered as continuation of the previous one. They share the same idea, but in this case true timers T0 and T1 are used. In order to demonstrate the operation of both timers on the same port at the same time, timer T0 reset is used to shift logic zero (0) on the port, while Timer T1 reset is used to change rotation direction. This program spends most of its time in the loop LOOP1 waiting for an interrupt to be caused by reset. By checking the DIRECTION bit, information on rotation direction of both bits in accumulator as well as of moving port LED is obtained. ;******************************************************************** **** ;* PROGRAM NAME : Tim0Tim1.ASM ;* DESCRIPTION: Timer TO rotates bit on port P1 while Timer1 ;* changes rotation direction. Both timers are configured to operate in mode 1. ;******************************************************************** **** ;BASIC DIRECTIVES $MOD53 $TITLE(TIM0TIM1.ASM) $PAGEWIDTH(132) $DEBUG $OBJECT $NOPAGING ;DECLARATION OF VARIABLES BSEG AT 0 ;DECLARATION OF BIT-VARIABLES SEMAPHORE: DBIT 8 DIRECTION BIT SEMAPHORE ;STACK DSEG AT 03FH STACK_START: DS 040H 227

228 ;RESET VECTORS CSEG AT 0 JMP XRESET ; Reset vector ORG 00BH ; Timer 0 Reset vector JMP TIM0_ISR ORG 01BH ; Timer 1 Reset vector JMP TIM1_ISR ORG 100H XRESET: MOV SP,#STACK_START ; Define Stack pointer MOV TMOD,#11H ; Select MOD1 for both timers MOV A,#0FFH MOV P1,#0FFH MOV R0,#30D ; R0 is initialized SETB TR0 ; TIMER0 is turned on SETB TR1 ; TIMER1 is turned on MOV IE,#08AH ; Timer0 and Timer1 Interrupt enabled CLR C CLR DIRECTION ; Rotate to the right LOOP1: SJMP LOOP1 ; Remain here TIM0_ISR: JB DIRECTION,LAB1 RRC A accumulator to the right through ; Carry flag ; Rotate contents of SJMP LAB2 LAB1: RLC A ; Rotate contents of Accumulator to the left through ; Carry flag LAB2: MOV P1,A ; Contents of Accumulator is moved to port P1 RETI ; Return from interrupt TIM1_ISR: DJNZ R0,LAB3 ; When time expires, change rotation direction CPL DIRECTION MOV R0,#30D ; Initialize R0 LAB3: RETI END Using Timer T2 ; End of program 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, 228

229 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 ;STACK DSEG AT 03FH STACK_START: DS 040H 229

230 ;RESET VECTORS CSEG AT 0 JMP XRESET ; Reset vector ORG 02BH ; Timer T2 Reset vector JMP TIM2_ISR ORG 100H XRESET: MOV SP,#STACK_START ; Define Stack pointer MOV A,#0FFH MOV P3,#0FFH MOV RCAP2L,#0FH ; Prepare 16-bit autoreload mode MOV RCAP2L,#01H CLR CAP2 ; Enable 16-bit auto-reload mod SETB EXEN2 ; Pin P1.1 reset is enabled SETB TR2 ; Enable Timer T2 MOV IE,#0A0H ; Interrupt is enabled CLR C LOOP1: SJMP LOOP1 ; Remain here TIM2_ISR: RRC A ; Rotate contents of Accumulator to the right through ; Carry flag MOV P3,A ; Move the contents of Accumulator A to PORT3 CLR TF2 ; Clear timer T2 flag TF2 CLR EXF2 ; Clear timer T2 flag EXF2 RETI ; Return from interrupt END Using External Interrupt ; End of program Here is another example of interrupt execution. An external iterrupt is generated when a logic zero (0) is present on pin P3.2 or P3.3. Depending on which input is active, one of two routines will be executed: A logic zero (0) on the P3.2 pin initiates execution of interrupt routine Isr_Int0, thus incrementing number in register R0 and copying it to port P0. Logic zero on the P3.3 pin initiates execution of subroutine Isr_Int1, number in register R1 is incremented by 1 and then copied to port P1. In short, each press on push buttons INT0 and INT1 will be counted and immediately shown in binary format on appropriate port (LED which emitts light represents a logic zero (0)). 230

231 ;******************************************************************** **** ;* 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 highto-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 AT 0 JMP XRESET ; Reset vector 231

232 INT0 INT1 ORG 003H ; Interrupt routine address for JMP Isr_Int0 ORG 013H ; Interrupt routine address for JMP Isr_Int1 ORG 100H XRESET: MOV TCON,# B ; Interrupt INT0 is generated by appearing ; high-to-low transition signal on pin P3.2 ; Interrupt INT0 is generated by appearing ; high-to-low transition signal on pin P3.3 MOV IE,# B ; Interrupt enabled MOV R0,#00H ; Counter starting value MOV R1,#00H MOV P0,#00H ; Reset port P0 MOV P1,#00H ; Reset port P1 LOOP: SJMP LOOP ; Remain here Isr_Int0: INC R0 INT0 counter MOV P0,R0 RETI Isr_Int1: INC R1 INT1 counter MOV P1,R1 RETI END Using LED display ; Increment value of interrupt ; Increment value of interrupt ; End of program The following examples describe the use of LED displays. Common chatode displays are used here, which means that all built-in LEDs are polarized in such a way that their anodes are connected to the microcontroller pins. Since the common way of thinking is that logic one (1) turns something on and logic zero (0) turns something of, Low Current displays (low power consumption) and their diodes (segments) are connected serially to resistors of relatively high resistance. In order to save I/O pins, four LED displays are connected to operate in multiplex mode. It means that all segments having the same name are connected to one output port each and only one display is active at a time. Tranzistors and segmenats on displays are quickly activated, thus making impression that all digits are active simultaneously. 232

233 Writing digits on LED display This program is a kind of warming up exerciese before real work starts. The purpose of this example is to display something on any display. Multiplex mode is not used this time. Instead, digit 3 is displayed on only one of them (first one on the right). Since the microcontroller does not know how we write number 3, a small subroutine called Disp is used (the microcontroller writes this number as ). This subroutine enables all decimal digits (0-9) to be displayed (masked). The principle of operation is simple. A number to be displayed is added to the current address and program jump is executed. Different numbers require different jump length. Precisely determined combination of zeroes and ones appears on each of these new locations (digit 1 mask, digit 2 mask...digit 9 mask). When this combination is transferred to the port, the display shows desired digit. 233

234 ;******************************************************************** **** ;* PROGRAM NAME : 7Seg1.ASM ;* DESCRIPTION: Program displays number "3" on 7-segment LED display ;******************************************************************** **** ;BASIC DIRECTIVES $MOD53 $TITLE(7SEG1.ASM) $PAGEWIDTH(132) $DEBUG $OBJECT $NOPAGING ;STACK DSEG AT 03FH STACK_START: DS 040H ;RESET VECTORS CSEG AT 0 JMP XRESET ; Reset vector ORG 100H XRESET: MOV SP,#STACK_START ; Define Stack pointer MOV P1,#0 ; Turn off all segments on displays MOV P3,#20h ; Activate display D4 LOOP: MOV A,#03 ; Send number 3 to display LCALL Disp ; Perform appropriate masking for the number MOV P1,A SJMP LOOP Disp: digits INC A MOVC A,@A+PC RET DB 3FH ; Digit 0 mask DB 06H ; Digit 1 mask DB 5BH ; Digit 2 mask DB 4FH ; Digit 3 mask DB 66H ; Digit 4 mask DB 6DH ; Digit 5 mask DB 7DH ; Digit 6 mask DB 07H ; Digit 7 mask DB 7FH ; Digit 8 mask ; Subroutine for displaying DB 6FH ; Digit 9 mask END ; End of program Writing and changing digits on LED display This program is only an extended verson of the previous one. There is only one digit active- the first one on the right, and there is no use of multiplexing. Unlike the previous example, all decimal numbers are displayed (0-9). In order to enable digits to change at reasonable pace, a soubroutine L2 which causes a short time delay is 234

235 executed prior to each change occurs. Basically, the whole process is very simple and takes place in the main loop called LOOP which looks as follows: 1. R3 is copied to Accumulator and subroutine for masking digits Disp is executed; 2. Accumulator is copied to the port and displayed; 3. The contents of the R3 register is incremented; 4. It is checked whether 10 cycles are counted or not. If it is, register R3 is reset in order to enable counting to start from 0; and 5. Instruction labeled as L2 within subroutine is executed. ;******************************************************************** **** ;* PROGRAM NAME: 7Seg2.ASM ;* DESCRIPTION: Program writes numbers 0-9 on 7-segment LED display ;******************************************************************** **** ;BASIC DIRECTIVES $MOD53 $TITLE(7SEG2.ASM) $PAGEWIDTH(132) $DEBUG $OBJECT $NOPAGING ;STACK DSEG AT 03FH STACK_START: DS 040H ;RESET VECTORS CSEG AT 0 JMP XRESET ; Reset vector ORG 100H XRESET: MOV SP,#STACK_START ; Define Stack pointer MOV R3,#0 ; Counter initial value MOV P1,#0 ; Turn off all display segments MOV P3,#20h ; Activate display D4 LOOP: MOV A,R3 LCALL Disp ; Perform appropriate masking for number in ; Accumulator MOV P1,A INC R3 ; Increment number in register by 1 CJNE R3,#10,L2 ; Check whether the number 10 is in R3 MOV R3,#0 ; If it is, reset counter L2: MOV R2,#20 ; 500 ms time delay F02: MOV R1,#50 ; 25 ms F01: MOV R0,#230 DJNZ R0,$ 235

236 DJNZ R1,F01 DJNZ R2,F02 SJMP LOOP Disp: digits ; Subroutine for writing INC A MOVC A,@A+PC RET DB 3FH ; Digit 0 mask DB 06H ; Digit 1 mask DB 5BH ; Digit 2 mask DB 4FH ; Digit 3 mask DB 66H ; Digit 4 mask DB 6DH ; Digit 5 mask DB 7DH ; Digit 6 mask DB 07H ; Digit 7 mask DB 7FH ; Digit 8 mask DB 6FH ; Digit 9 mask END Writing two-digit number on LED display ; End of program It is time for time multiplexing! This is the simplest example which displays the number 23 on two displays in such a way that one of them displays units, while the other displays tens. The most important thing in the program is time synchronization. Otherwise, everything is very simple. Transistor T4 enables display D4 and at the same time a bit combination corresponding to the digit 3 is set on the port. After that, transistor T4 is disabled and the whole process is repeated using transistor T3 and display D3 in order to display digit 2. This procedure must be continuosly repeated in order to make impression that both displays are active at the same time. ;******************************************************************** **** ;* PROGRAM NAME: 7Seg3.ASM ;* DESCRIPTION: Program displays number "23" on 7-segment LED display ;******************************************************************** **** ;BASIC DIRECTIVES $MOD53 $TITLE(7SEG3.ASM) $PAGEWIDTH(132) $DEBUG $OBJECT $NOPAGING ;STACK DSEG AT 03FH STACK_START: DS 040H ;RESET VECTORS CSEG AT 0 JMP XRESET ; Reset vector ORG 100H XRESET: MOV SP,#STACK_START ; Define Stack pointer 236

237 LOOP: MOV P1,#0 ; Turn off all display segments MOV P3,#20h ; Activate display D4 MOV A,#03 ; Write digit 3 on display D4 LCALL Disp ; Find appropriate mask for that digit MOV P1,A ; Put the mask on the port MOV P1,#0 ; Turn off all dislay segments MOV P3,#10h ; Activate display D3 MOV A,#02 ; Write digit 2 on display D3 LCALL Disp ; Find mask for that digit MOV P1,A ; Put the mask on the port SJMP LOOP ; Return to the label LOOP Disp: digits ; Subroutine for writing INC A MOVC A,@A+PC RET DB 3FH ; Digit 0 mask DB 06H ; Digit 1 mask DB 5BH ; Digit 2 mask DB 4FH ; Digit 3 mask DB 66H ; Digit 4 mask DB 6DH ; Digit 5 mask DB 7DH ; Digit 6 mask DB 07H ; Digit 7 mask DB 7FH ; Digit 8 mask DB 6FH ; Digit 9 mask END Using four digit LED display ; End of program In this example all four displays, instead of two, are active so that it is possible to write numbers from 0 to Here, the number is displayed. After initialization, the program remains in the loop LOOP where digital multiplexing is performed. The subroutine Disp is used to convert binary numbers into corresponding combinations of bits for the purpose of activating display lighting segments. ;******************************************************************** **** ;* PROGRAM NAME : 7Seg5.ASM ;* DESCRIPTION : Program displays number"1234" on 7-segment LED display ;******************************************************************** **** ;BASIC DIRECTIVES $MOD53 $TITLE(7SEG5.ASM) $PAGEWIDTH(132) 237

238 $DEBUG $OBJECT $NOPAGING ;STACK DSEG AT 03FH STACK_START: DS 040H ;RESET VECTORS CSEG AT 0 JMP XRESET ; Reset vector ORG 100H XRESET: MOV SP,#STACK_START ; Define Stack pointer LOOP: MOV P1,#0 ; Turn off all display segments MOV P3,#20h ; Activate display D4 MOV A,#04 ; Write digit 4 on display D4 LCALL Disp ; Find mask for that digit MOV P1,A ; Put the mask on the port MOV P1,#0 ; Turn off all display segments MOV P3,#10h ; Activate display D3 MOV A,#03 ; Write digit 3 on display D3 LCALL Disp ; Find mask for that digit MOV P1,A ; Put the mask on the port MOV P1,#0 ; Turn off all display segments MOV P3,#08h ; Activate display D2 MOV A,#02 ; Write digit 2 on display D2 LCALL Disp ; Find mask for that digit MOV P1,A ; Put the mask on the port MOV P1,#0 ; Turn off all display segments MOV P3,#04h ; Activate display D1 MOV A,#01 ; Write digit 1 on display D1 LCALL Disp ; Find mask for that digit MOV P1,A ; Put the mask on the port SJMP LOOP ; Return to the lable LOOP Disp: digits INC A MOVC A,@A+PC RET DB 3FH ; Digit 0 mask DB 06H ; Digit 1 mask DB 5BH ; Digit 2 mask DB 4FH ; Digit 3 mask DB 66H ; Digit 4 mask DB 6DH ; Digit 5 mask DB 7DH ; Digit 6 mask DB 07H ; Digit 7 mask DB 7FH ; Digit 8 mask DB 6FH ; Digit 9 mask ; Subroutine for writing 238

239 END ; End of program LED display as a two digit counter Things are getting complicated... In addition to two digit multiplexing, the microcontroller also performs other operations. In this example, contents of registers R2 and R3 are incremented in order to display number counting (97, 98, 99, 00, 01, 02...). This time, transistors which activate displays remain turned on for 25mS. The soubroutine Delay is in charge of that. Even though digits shift much slower now, it is still not slow enough to make impression of simultaneous operation. After both digits of a number blink for 20 times, the number on displays is incremented by 1 and the whole procedure is repeated. ;******************************************************************** **** ;* PROGRAM NAME : 7Seg4.ASM ;* DESCRIPTION: Program displays numbers 0-99 on 7-segment LED displays ;******************************************************************** **** ;BASIC DIRECTIVES $MOD53 $TITLE(7SEG4.ASM) $PAGEWIDTH(132) $DEBUG $OBJECT $NOPAGING ;STACK DSEG AT 03FH STACK_START: DS 040H ;RESET VECTORS CSEG AT 0 JMP XRESET ; Reset vector ORG 100H XRESET: MOV SP,#STACK_START ; Define Stack pointer MOV R2,#0 ; Counter starting value MOV R3,#0 MOV R4,#0 LOOP: INC R4 ;Wait for display to be "refreshed" for 100 times CJNE R4,#20d,LAB1 ;before incrementing the counter MOV R4,#0 MOV P1,#0 ; Turn off all display segments INC R2 ; Increment Register containing units by 1 CJNE R2,#10d,LAB1 MOV R2,#0 ; Reset units 239

240 INC R3 ; Increment Register with tens by 1 CJNE R3,#10d,LAB1 ; MOV R3,#0 ; Reset tens LAB1: MOV P3,#20h ; Activate display D4 MOV A,R2 ; Copy Register containing units to A LCALL Disp ; Call mask for that digit MOV P1,A ; Write units on display D4 LCALL Delay ; 25ms delay MOV P1,#0 ; Turn off all display segments MOV P3,#10h ; Activate display D3 MOV A,R3 ; Copy Register contaning tens to A LCALL Disp ; Call mask for that digit MOV P1,A ; Write tens on display D3 LCALL Delay ; 25ms delay SJMP LOOP Delay: MOV R1,#50 ; 5 ms delay F01: MOV R0,#250 DJNZ R0,$ DJNZ R1,F01 RET Disp: ; Subroutine for displaying digits INC A MOVC A,@A+PC RET DB 3FH ; Digit 0 mask DB 06H ; Digit 1 mask DB 5BH ; Digit 2 mask DB 4FH ; Digit 3 mask DB 66H ; Digit 4 mask DB 6DH ; Digit 5 mask DB 7DH ; Digit 6 mask DB 07H ; Digit 7 mask DB 7FH ; Digit 8 mask DB 6FH ; Digit 9 mask END Handling EEPROM ; End of program 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). 240

241 ;******************************************************************** **** ;* 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 DATA 96H EEMEN EQU B ; Access to internal EEPROM is enabled EEMWE EQU B ; Write to EEPROM is enabled TEMP DATA 030H ; Define Auxiliary register THE END EQU 071H ; Display "F" ERROR EQU 033H ; Display "E" ;STACK DSEG AT 03FH STACK_START: DS 040H ;RESET VECTORS CSEG AT 0 JMP XRESET ; Reset vector ORG 100H XRESET: MOV IE,#00 ; All interrupts are disabled MOV SP,#STACK_START MOV DPTR,#0000H ; Choose location address in EEPROM ORL WMCON,#EEMEN ; Access to EEPROM is enabled ORL WMCON,#EEMWE ; Write to EEPROM is enabled MOV TEMP,#23H ; Number written to EEPROM is moved to MOV A,TEMP ; register TEMP and Accumulator ; Write byte to EEPROM CALL DELAY ; 10ms delay MOVX A,@DPTR ; Read the same location and compare to TEMP, CJNE A,TEMP,ERROR ; If they don't match, jump to label ERROR MOV A,#KRAJ ; Display F (correct) MOV P1,A 241

242 XRL WMCON,#EEMWE ; Write to EEPROM is disabled XRL WMCON,#EEMEN ; Access to EEPROM is disabled LOOP1: SJMP LOOP1 ; Remain here ERROR: MOV A,#ERROR ; Display E (error) MOV P1,A LOOP2: SJMP LOOP2 DELAY: MOV A,#0AH ; Delay MOV R3,A LOOP3: NOP LOOP4: DJNZ B,LOOP4 LOOP5: DJNZ B,LOOP5 DJNZ R3,LOOP3 RET END Data reception via UART ; End of program In order to enable successful UART serial communication, it is necessary to meet specific rules of the RS232 standard. It primarily refers to voltage levels required by this standard. Accordingly, -10V stands for logic one (1) in the message, while +10V stands for logic zero (0). The microcontroller converts accurately data into serial format, but its power supply voltage is only 5V. Since it is not easy to convert 0V into 10V and 5V into -10V, this operation is on both transmit and receive side left to a specialized IC circuit. Here, the MAX232 by MAXIM is used because it is widespread, cheap and reliable. This example shows how to receive message sent by a PC. Timer T1 generates boud rate. Since the MHz quartz crystal is used here, it is easy to obtain standard baud rate which amouts to 9600 bauds. Each received data is immediately transferred to port P1 pins. 242

243 ;******************************************************************** **** ;* 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 AT 03FH STACK_START: DS 040H ;RESET VECTORS CSEG AT 0 JMP XRESET ; Reset vector ORG 023H ; Starting address of UART interrupt routine JMP IR_SER ORG 100H 243

244 XRESET: MOV IE,#00 ; All interrupts are disabled MOV SP,#STACK_START ; Initialization of Stack pointer MOV TMOD,#20H ; Timer1 in mode2 MOV TH1,#0FDH ; 9600 baud rate at the frequency of ; MHz MOV SCON,#50H ; Receiving enabled, 8-bit UART MOV IE,# B ; UART interrupt enabled CLR TI ; Clear transmit flag CLR RI ; Clear receive flag SETB TR1 ; Start Timer1 LOOP: SJMP LOOP ; Remain here IR_SER: JNB RI,OUTPUT ; If any data is received, ; move it to the port MOV A,SBUF ; P1 MOV P1,A CLR RI ; Clear receive flag OUTPUT RETI END Data transmission via UART ; End of program This program describes how to use UART to transmit data. A sequence of numbers (0-255) is transmitted to a PC at 9600 baud rate. The MAX 232 is used as a voltage regulator. ;******************************************************************** **** ;* PROGRAM NAME : UartS.ASM ;* DESCRIPTION: Sends values to PC. ;******************************************************************** **** ;BASIC DIRECTIVES $MOD53 $TITLE(UARTS.ASM) $PAGEWIDTH(132) $DEBUG $OBJECT $NOPAGING ;STACK DSEG AT 03FH STACK_START: DS 040H ;RESET VECTORS CSEG AT 0 JMP XRESET ; Reset vector ORG 100H XRESET: MOV IE,#00 ; All interrupts are disabled MOV SP,#STACK_START ; Initialization of Stack pointer 244

245 MOV TMOD,#20H ; Timer1 in mode 2 MOV TH1,#0FDH ; 9600 baud rate at the frequency of ; MHz MOV SCON,#40H ; 8-bit UART CLR TI ; Clear transmit bit CLR RI ; Clear receive flag MOV R3,#00H ; Reset caunter SETB TR1 ; Start Timer 1 START: MOV SBUF,R3 ; Move number from counter to a PC LOOP1: JNB TI,LOOP1 ; Wait here until byte transmission is ; complete CLR TI ; Clear transmit bit INC R3 ; Increment the counter value by 1 CJNE R3,#00H,START ; If 255 bytes are not sent return to the ; label START LOOP: SJMP LOOP ; Remain here END Writing message on LCD display ; End of program This example uses the most frequently used type of LCD which displays text in two lines with 16 characters each. In order to save I/O ports, only 4 pins are used for communication here. In this way each byte is transmitted in two steps: first higher then lower nible. LCD needs to be initialized at the beginning of the program. Besides, parts of the program which repeat in the program create special subroutines. All this may seem extremely complicated, but the whole program basically performs several simple operations and displays Mikroelektronika Razvojni sistemi. ********************************************************************* **** ;* 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 245

246 $MOD53 $TITLE(LCD.ASM) $PAGEWIDTH(132) $DEBUG $OBJECT $NOPAGING ;Stack DSEG AT 0E0h Stack_Start: DS 020h Start_address EQU 0000h CSEG AT 0 ORG Start_address JMP Inic ;Reset vectors ORG Start_address+100h disabled MOV IE,#00 ; All interrupts are MOV SP,#Stack_Start Inic: CALL LCD_inic ; Initialize LCD ;************************************************* ;* MAIN PROGRAM ;************************************************* START: MOV A,#80h ; Next character will appear on the first CALL LCD_status ; location in the first line of LCD display. MOV A,#'M' ; Display character M. 246

247 CALL LCD_putc ; Call subroutine for character transmission. MOV A,#'i' ; Display character i. CALL LCD_putc MOV A,#'k' ; Display character k. CALL LCD_putc MOV A,#'r' ; Display character r. CALL LCD_putc MOV A,#'o' ; Display character o. CALL LCD_putc MOV A,#'e' ; Display character e. CALL LCD_putc MOV A,#'l' ; Display character l. CALL LCD_putc MOV A,#'e' ; Display character e. CALL LCD_putc MOV A,#'k' ; Display character k. CALL LCD_putc MOV A,#'t' ; Display character t. CALL LCD_putc MOV A,#'r' ; Display character r. CALL LCD_putc MOV A,#'o' ; Display character o. CALL LCD_putc MOV A,#'n' ; Display character n. CALL LCD_putc MOV A,#'i' ; Display character i. CALL LCD_putc MOV A,#'k' ; Display character k. CALL LCD_putc MOV A,#'a' ; Display character a. CALL LCD_putc MOV A,#0c0h ; Next character will appear on the first CALL LCD_status ; location in the second line of LCD display. MOV A,#'R' ; Display character R. CALL LCD_putc ; Call subroutine for character transmission. MOV A,#'a' ; Display character a. CALL LCD_putc MOV A,#'z' ; Display character z. CALL LCD_putc MOV A,#'v' ; Display character v. CALL LCD_putc MOV A,#'o' ; Display character o. CALL LCD_putc MOV A,#'j' ; Display character j. CALL LCD_putc MOV A,#'n' ; Display character n. CALL LCD_putc MOV A,#'i' ; Display character i. CALL LCD_putc MOV A,#' ' ; Display character. CALL LCD_putc MOV A,#'s' ; Display character s. CALL LCD_putc MOV A,#'i' ; Display character i. CALL LCD_putc MOV A,#'s' ; Display character s. 247

248 CALL LCD_putc MOV A,#'t' ; Display character t. CALL LCD_putc MOV A,#'e' ; Display character e. CALL LCD_putc MOV A,#'m' ; Display character m. CALL LCD_putc MOV A,#'i' ; Display character i. CALL LCD_putc MOV R0,#20d ; Wait time (20x10ms) CALL Delay_10ms ; MOV DPTR,#LCD_DB ; Clear display MOV A,#6d ; CALL LCD_inic_status ; MOV R0,#10d ; Wait time(10x10ms) CALL Delay_10ms JMP START ;********************************************* ;* Subroutine for wait time (T= r0 x 10ms) ;********************************************* Delay_10ms: MOV R5,00h ; 1+(1+(1+2*r7+2)*r6+2)*r5 approximately MOV R6,#100d ; (if r7>10) MOV R7,#100d ; 2*r5*r6*r7 DJNZ R7,$ ; $ indicates current instruction. DJNZ R6,$-4 DJNZ R5,$-6 RET ;******************************************************************** ****************** ;* 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 microcontroller s 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 BIT P1.3 ; Bit for activating pin E on LCD. LCD_read_write BIT P1.1 ; Bit for activating pin RW on LCD. LCD_reg_select BIT P1.2 ; Bit for activating pin RS on LCD. 248

249 LCD_port SET P1 ; Port for connection to LCD. Busy BIT P1.7 ; Port pin on which Busy flag appears. LCD_Start_I_red EQU 00h ; Address of the first message character ; in the first line of LCD display. LCD_Start_II_red EQU 40h ; Address of the first message character ; in the second line of LCD display. LCD_DB: DB b ; 0-8b, 2/1 lines, 5x10/5x7 format DB b ; 1-4b, 2/1 lines, 5x10/5x7 format DB b ; 2 -Display/cursor shift, right/left DB b ; 3 -Display ON, cursor OFF, cursor blink off DB b ; 4 -Increment mode, display shift off DB b ; 5 -Display/cursor home DB b ; 6 -Clear display DB b ; 7 -Display OFF, cursor OFF, cursor blink off LCD_inic: ;***************************************** MOV DPTR,#LCD_DB MOV A,#00d ; Triple initialization in 8-bit CALL LCD_inic_status_8 ; mode is performed at the beginning MOV A,#00d ; (in case of slow increment of CALL LCD_inic_status_8 ; power supply when the power supply is on MOV A,#00d lcall LCD_inic_status_8 MOV A,#1d ; Change from 8-bit into CALL LCD_inic_status_8 ; 4-bit mode MOV A,#1d CALL LCD_inic_status MOV A,#3d ; As from this point the program executes in ;4-bit mode CALL LCD_inic_status MOV A,#6d CALL LCD_inic_status MOV A,#4d CALL LCD_inic_status RET 249

250 LCD_inic_status_8: ;****************************************** PUSH B LCD MOVC A,@A+DPTR CLR LCD_reg_select ; RS=0 - Write command CLR LCD_read_write ; R/W=0 - Write data on MOV B,LCD_port ; Lower 4 bits from LCD port are memorized ORL B,# b ORL A,# b ANL A,B to LCD port signal LCD's EN pin improper reset MOV LCD_port,A ; Data is moved from A SETB LCD_enable CLR LCD_enable ; high-to-low transition ; is generated on the MOV B,#255d ; Time delay in case of DJNZ B,$ DJNZ B,$ DJNZ B,$ ; during initialization 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: to LCD PUSH B MOV B,#255d DJNZ B,$ DJNZ B,$ DJNZ B,$ CLR LCD_reg_select ; RS=O: Command is sent CALL LCD_port_out accumulator SWAP A DJNZ B,$ DJNZ B,$ ; Nibles are swapped in 250

251 to LCD DJNZ B,$ CLR LCD_reg_select ; RS=0: Command is sent CALL LCD_port_out POP RET B ;******************************************************************** ******** ;* SUBROUTINE: LCD_putc ;* DESCRIPTION: Sending character to be displayed on LCD. ;******************************************************************** ******** LCD_putc: sent to LCD PUSH B MOV B,#255d DJNZ B,$ SETB LCD_reg_select ; RS=1: Character is CALL LCD_port_out accumulator SWAP A ; Nibles are swapped in sent to LCD DJNZ B,$ SETB LCD_reg_select ; RS=1: Character is CALL LCD_port_out POP B RET ;******************************************************************** ******** ;* SUBROUTINE: LCD_port_out ;* DESCRIPTION: Sending commands or characters on LCD display ;******************************************************************** ******** LCD_port_out: PUSH ACC PUSH B MOV B,LCD_port ; Lower 4 bits of LCD port are memorized ORL B,# b ORL A,# b ANL A,B to LCD port MOV LCD_port,A ; Data is copied from A signal LCD's EN pin SETB LCD_enable CLR LCD_enable ; high-to-low transition ; is generated on the POP POP RET B ACC 251

252 END ; End of program Binary to decimal number conversion When using LED and LCD displays, it is often necessary to convert numbers from binary to decimal. For example, if some register contains a number in binary format that should be displayed on a three digit LED display it is first necessary to convert it to decimal format. In other words, it is necessary to define what should be displayed on the most right display (units), middle display (tens) and most left display (hundreds). The subroutine below performs conversion of one byte. Binary number is stored in the accumulator, while digits of that number in decimal format are stored in registers R3, R2 and accumulator (units, tens and hundreds, respectively). ;******************************************************************** **** ;* SUBROUTINE NAME : BinDec.ASM ;* DESCRIPTION : Content of accumulator is converted into three decimal digits ;******************************************************************** **** BINDEC: MOV B,#10d ; Store decimal number 10 in B DIV AB ; A:B. Remainder remains in B MOV R3,B ; Move units to register R3 MOV B,#10d ; Store decimal number 10 in B DIV AB ; A:B. Remainder remains in B MOV R2,B ; Move tens to register R2 MOV B,#10d ; Store decimal number 10 in B DIV AB ; A:B. Remainder remains in B MOV A,B ; Move hundreds to accumulator RET ; Return to the main program 252

253 Chapter 7 : Development systems 7.1 At the end - from the beginning Easy8051A Development system 7.1 At the end - from the beginning... What is always the most difficult thing to do? You have bought the microcontroller, you have learned everything about its circuits and registers, you have a great idea how to apply all your knowledge in practice. But the most difficult thing to do is to start... How to start working? A microcontroller is a good-natured genie in the bottle and no extra knowledge is required to use it. In order to create a device controlled by the microcontroller, it is necessary to provide the simplest PC, program for compiling and simple device to transfer the code from PC to the chip itself. Even though the whole process is quite logical, there are often some queries, not because it is complicated, but for numerous variations. Let s take a look. Writing program in assembly language In order to write a program for the microcontroller, a specialized program in the Windows environment 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. That s all! ;RESET VECTOR CSEG AT 0 JMP XRESET ; Reset vector CSEG ORG 100H XRESET: ORL WMCON,#PERIOD ; Define Watch-dog period ORL WMCON,#WDTEN ; Watch-dog timer is enabled 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. 253

254 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. : FA F 7590FFB D80F97A1479D EAF3698E8EB25B A585FEA2569AD96E6D8FED9FAD AF6DD FF255AFED589EA F3698E8EB25BA585FEA2569AD96 DAC59700D E6D8FED9FA DAF6DD FF255AFED8FED 9FADAF6DD000F7590FFB E6D8FED9FADAF6DD FF2 55AFED589EAF3698E8EB25BA585 FEA2569AD96DAC59D9FADAF6D D FF255AFED8FED9FADA F6DD000F7590FFB E6D82 78E6D8FED9FA589EAF3698E8EB2 5BA585FEA2569AD96DAF6DD FF2DAF6DD FF255A ADAF6DD FF255AFED8FE 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 254

255 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 end or...? This section briefly describes the use of MPLAB and programmer software developed by Mikroelektronika. Everything is very simple... Start the program Mikroelektronika Asm51 Console. The window appears

256 ...Open a new document: File -> New. Write your program or copy text Save and name your document: File -> Save As... (Document name is limited to 8 characters!) Finally, to compile program into HEX code select: Project -> Build or click the 'play' icon. If everything works properly, the computer will respond with a short report. 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... Program installation is performed as usually - just click Next, Accept, Next......and finally - Finish! The program has been installed and ready for use. The settings are easily performed so that there is no need for additional explanations (the type of the microcontroller, frequency and clock oscillator etc.). 256

257 Connect the PC and programmer via a USB cable; Load the HEX code using command: File -> Load HEX; and Click the 'Write' push button and wait... That s 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 257

258 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 microcontroller s 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. 258

259 7.2 Easy8051A Development System The Easy8051A development system is a high-quality development system used for programming 8051 compatible microcontrollers manufactured by Atmel. In addition to chip programming, this system enables all the parts of the program to be tested as it contains most components which are normally built in real devices. The Easy8051A development system consists of: Sockets for placing microcontrollers in (14, 16, 20 and 40- pin packages) Connector for external power supply (DC 12V) USB programmer Power Supply Selector (external or via USB cable) 8 Mhz Quartz Crystal Oscillator 32 LEDs for output pin state indication 32 push buttons for input pin activation Four 7-segment LED displays in multiplex mode Graphic LCD display Alphanumeric LCD display (4- or 8- bit mode) Connector and driver for serial communication RS232 Digital thermometer DS bit A/D converter (MCP3204) 12- bit D/A converter (MCP4921) Reference voltage source 4.096V (MCP1541) Multiple-pin connectors for direct access to I/O ports The following text describes in short some circuits within this development system. It is rather illustration of its features than complete manual. Besides, by learning about this device, one understands that microcontrollers and its tools are intended to everybody, not only to the privileged. Sockets 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 259

260 (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 used for it are automatically available for other application. 260

261 Development system power supply 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. 261

262 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,. 262

263 LEDs for output pin state indication 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. 263

264 Push buttons for input pin activation 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. 264

265 7-segment LED displays 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. 265

266 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. 266

267 Serial communication via RS232 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 J

268 DS1820 Digital thermometer 268

269 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 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. 12-bit A/D converter MCP

270 A built-in 12-bit AD Converter MCP3204 has four input channels connected to onboard 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 converter s 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. 270

271 12-bit D/A converter MCP4921 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 271

272 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. Connectors for direct access to I/O ports 272

Architecture and Programming of 8051 Microcontrollers

Architecture and Programming of 8051 Microcontrollers Architecture and Programming of 8051 Microcontrollers Learn in a quick and easy way to program 8051 microcontroller using many practical examples we have provided for you. Despite its relative old age,

More information

e-pg Pathshala Subject : Computer Science Paper: Embedded System Module: 8051 Architecture Module No: CS/ES/5 Quadrant 1 e-text

e-pg Pathshala Subject : Computer Science Paper: Embedded System Module: 8051 Architecture Module No: CS/ES/5 Quadrant 1 e-text e-pg Pathshala Subject : Computer Science Paper: Embedded System Module: 8051 Architecture Module No: CS/ES/5 Quadrant 1 e-text In this lecture the detailed architecture of 8051 controller, register bank,

More information

THE 8051 MICROCONTROLLER Simple comparison: Pentium vs. 8051

THE 8051 MICROCONTROLLER Simple comparison: Pentium vs. 8051 THE 8051 MICROCONTROLLER Simple comparison: Pentium vs. 8051 FEATURE 8051 PENTIUM COMMENT Clock Speed 12Mhz. typical 1,000 MHz. (1GHz.) but 60MHz. ICs available 8051 internally divides clock by 12 so for

More information

UNIT 5. Microcontrollers. Syllabus

UNIT 5. Microcontrollers. Syllabus UNIT 5 Microcontrollers Syllabus Architecture of 8051 Signals Operational features Memory and I/O addressing Interrupts Instruction set Applications. OVERVIEW The past three decades have seen the introduction

More information

Memory Organization. Program Memory

Memory Organization. Program Memory Memory Organization The 8051 has two types of memory and these are Program Memory and Data Memory. Program Memory (ROM) is used to permanently save the program being executed, while Data Memory (RAM) is

More information

8051 MICROCONTROLLER

8051 MICROCONTROLLER 8051 MICROCONTROLLER Mr.Darshan Patel M.Tech (Power Electronics & Drives) Assistant Professor Department of Electrical Engineering Sankalchand Patel College of Engineering-Visnagar WHY DO WE NEED TO LEARN

More information

EEE3410 Microcontroller Applications Department of Electrical Engineering Lecture 4 The 8051 Architecture

EEE3410 Microcontroller Applications Department of Electrical Engineering Lecture 4 The 8051 Architecture Department of Electrical Engineering Lecture 4 The 8051 Architecture 1 In this Lecture Overview General physical & operational features Block diagram Pin assignments Logic symbol Hardware description Pin

More information

8051 Microcontrollers

8051 Microcontrollers 8051 Microcontrollers Richa Upadhyay Prabhu NMIMS s MPSTME richa.upadhyay@nmims.edu March 8, 2016 Controller vs Processor Controller vs Processor Introduction to 8051 Micro-controller In 1981,Intel corporation

More information

8051 Microcontroller

8051 Microcontroller 8051 Microcontroller The 8051, Motorola and PIC families are the 3 leading sellers in the microcontroller market. The 8051 microcontroller was originally developed by Intel in the late 1970 s. Today many

More information

Module I. Microcontroller can be classified on the basis of their bits processed like 8bit MC, 16bit MC.

Module I. Microcontroller can be classified on the basis of their bits processed like 8bit MC, 16bit MC. MICROCONTROLLERS AND APPLICATIONS 1 Module 1 Module I Introduction to Microcontrollers: Comparison with Microprocessors Harvard and Von Neumann Architectures - 80C51 microcontroller features - internal

More information

MICROCONTROLLER AND PLC LAB-436 SEMESTER-5

MICROCONTROLLER AND PLC LAB-436 SEMESTER-5 MICROCONTROLLER AND PLC LAB-436 SEMESTER-5 Exp:1 STUDY OF MICROCONTROLLER 8051 To study the microcontroller and familiarize the 8051microcontroller kit Theory:- A Microcontroller consists of a powerful

More information

Understanding the basic building blocks of a microcontroller device in general. Knows the terminologies like embedded and external memory devices,

Understanding the basic building blocks of a microcontroller device in general. Knows the terminologies like embedded and external memory devices, Understanding the basic building blocks of a microcontroller device in general. Knows the terminologies like embedded and external memory devices, CISC and RISC processors etc. Knows the architecture and

More information

8051 Microcontroller Interrupts

8051 Microcontroller Interrupts 8051 Microcontroller Interrupts There are five interrupt sources for the 8051, which means that they can recognize 5 different events that can interrupt regular program execution. Each interrupt can be

More information

8051 microcontrollers

8051 microcontrollers 8051 microcontrollers Presented by: Deepak Kumar Rout Synergy Institute of Engineering and Technology, Dhenkanal Chapter 2 Introduction Intel MCS-51 family of microcontrollers consists of various devices

More information

8051 Microcontroller

8051 Microcontroller 8051 Microcontroller 1 Salient Features (1). 8 bit microcontroller originally developed by Intel in 1980. (2). High-performance CMOS Technology. (3). Contains Total 40 pins. (4). Address bus is of 16 bit

More information

Microcontrollers. Fig. 1 gives a comparison of a microprocessor system and a microcontroller system.

Microcontrollers. Fig. 1 gives a comparison of a microprocessor system and a microcontroller system. Syllabus: : Introduction to, 8051 Microcontroller Architecture and an example of Microcontroller based stepper motor control system (only Block Diagram approach). (5 Hours) Introduction to A microcontroller

More information

MAHALAKSHMI ENGINEERING COLLEGE TIRUCHIRAPALLI

MAHALAKSHMI ENGINEERING COLLEGE TIRUCHIRAPALLI MAHALAKSHMI ENGINEERING COLLEGE TIRUCHIRAPALLI-621213. QUESTION BANK DEPARTMENT: EEE SUB CODE: EE2324 YR/ SEM:III/ VI SUB NAME: MICROPROCESSORS & MICROCONTROLLERS UNIT 4-8051 MICROCONTROLLER PART A (2

More information

UNIT V MICRO CONTROLLER PROGRAMMING & APPLICATIONS TWO MARKS. 3.Give any two differences between microprocessor and micro controller.

UNIT V MICRO CONTROLLER PROGRAMMING & APPLICATIONS TWO MARKS. 3.Give any two differences between microprocessor and micro controller. UNIT V -8051 MICRO CONTROLLER PROGRAMMING & APPLICATIONS TWO MARKS 1. What is micro controller? Micro controller is a microprocessor with limited number of RAM, ROM, I/O ports and timer on a single chip

More information

Embedded Systems Lab Lab 1 Introduction to Microcontrollers Eng. Dalia A. Awad

Embedded Systems Lab Lab 1 Introduction to Microcontrollers Eng. Dalia A. Awad Embedded Systems Lab Lab 1 Introduction to Microcontrollers Eng. Dalia A. Awad Objectives To be familiar with microcontrollers, PIC18F4550 microcontroller. Tools PIC18F4550 Microcontroller, MPLAB software,

More information

The Microcontroller. Lecture Set 3. Major Microcontroller Families. Example Microcontroller Families Cont. Example Microcontroller Families

The Microcontroller. Lecture Set 3. Major Microcontroller Families. Example Microcontroller Families Cont. Example Microcontroller Families The Microcontroller Lecture Set 3 Architecture of the 8051 Microcontroller Microcontrollers can be considered as self-contained systems with a processor, memory and I/O ports. In most cases, all that is

More information

8051 Overview and Instruction Set

8051 Overview and Instruction Set 8051 Overview and Instruction Set Curtis A. Nelson Engr 355 1 Microprocessors vs. Microcontrollers Microprocessors are single-chip CPUs used in microcomputers Microcontrollers and microprocessors are different

More information

Introduction to 8051 microcontrollers

Introduction to 8051 microcontrollers Introduction to 8051 microcontrollers Posted on May 7, 2008, by Ibrahim KAMAL, in Micro-controllers, tagged This tutorial is specially tailored to electronics and robotics hobbyists that have already realized

More information

Sencer Yeralan and Helen Emery Gainesville, Florida January 2000

Sencer Yeralan and Helen Emery Gainesville, Florida January 2000 Preface This book is an outgrowth of the notes and experiments developed for the graduate classes at the University of Florida. It is intended for students, hobbyists, engineers, and scientists who would

More information

Question Bank Microprocessor and Microcontroller

Question Bank Microprocessor and Microcontroller QUESTION BANK - 2 PART A 1. What is cycle stealing? (K1-CO3) During any given bus cycle, one of the system components connected to the system bus is given control of the bus. This component is said to

More information

Embedded World Television, Radio, CD player, Washing Machine Microwave Oven Card readers, Palm devices

Embedded World Television, Radio, CD player, Washing Machine Microwave Oven Card readers, Palm devices A presentation on INTRODUCTION We are living in the Embedded World. We are surrounded with many embedded products and our daily life largely depends on the proper functioning of these gadgets. Television,

More information

1. INTRODUCTION TO MICROPROCESSOR AND MICROCOMPUTER ARCHITECTURE:

1. INTRODUCTION TO MICROPROCESSOR AND MICROCOMPUTER ARCHITECTURE: 1. INTRODUCTION TO MICROPROCESSOR AND MICROCOMPUTER ARCHITECTURE: A microprocessor is a programmable electronics chip that has computing and decision making capabilities similar to central processing unit

More information

Lecture 1. Course Overview and The 8051 Architecture

Lecture 1. Course Overview and The 8051 Architecture Lecture 1 Course Overview and The 8051 Architecture MCUniversity Program Lectures 8051 architecture t System overview of C8051F020 8051 instruction set System clock, crossbar and GPIO Assembler directives

More information

Memory organization Programming model - Program status word - register banks - Addressing modes - instruction set Programming examples.

Memory organization Programming model - Program status word - register banks - Addressing modes - instruction set Programming examples. MICROCONTROLLERS AND APPLICATIONS 1 Module 2 Module-2 Contents: Memory organization Programming model - Program status word - register banks - Addressing modes - instruction set Programming examples. MEMORY

More information

Three criteria in Choosing a Microcontroller

Three criteria in Choosing a Microcontroller The 8051 Microcontroller architecture Contents: Introduction Block Diagram and Pin Description of the 8051 Registers Some Simple Instructions Structure of Assembly language and Running an 8051 program

More information

8-bit Microcontroller with 8K Bytes In-System Programmable Flash AT89S52

8-bit Microcontroller with 8K Bytes In-System Programmable Flash AT89S52 Features Compatible with MCS -51 Products 8K Bytes of In-System Programmable (ISP) Flash Memory Endurance: 10,000 Write/Erase Cycles 4.0V to 5.5V Operating Range Fully Static Operation: 0 Hz to 33 MHz

More information

CHAPTER 5 : Introduction to Intel 8085 Microprocessor Hardware BENG 2223 MICROPROCESSOR TECHNOLOGY

CHAPTER 5 : Introduction to Intel 8085 Microprocessor Hardware BENG 2223 MICROPROCESSOR TECHNOLOGY CHAPTER 5 : Introduction to Intel 8085 Hardware BENG 2223 MICROPROCESSOR TECHNOLOGY The 8085A(commonly known as the 8085) : Was first introduced in March 1976 is an 8-bit microprocessor with 16-bit address

More information

MICROPROCESSOR MICROPROCESSOR. From the above description, we can draw the following block diagram to represent a microprocessor based system: Output

MICROPROCESSOR MICROPROCESSOR. From the above description, we can draw the following block diagram to represent a microprocessor based system: Output 8085 SATISH CHANDRA What is a Microprocessor? The word comes from the combination micro and processor. Processor means a device that processes whatever. In this context, processor means a device that processes

More information

Computer Hardware Requirements for ERTSs: Microprocessors & Microcontrollers

Computer Hardware Requirements for ERTSs: Microprocessors & Microcontrollers Lecture (4) Computer Hardware Requirements for ERTSs: Microprocessors & Microcontrollers Prof. Kasim M. Al-Aubidy Philadelphia University-Jordan DERTS-MSc, 2015 Prof. Kasim Al-Aubidy 1 Lecture Outline:

More information

MODULE-1. Short Answer Questions

MODULE-1. Short Answer Questions MODULE-1 Short Answer Questions 1. Give the comparison between microprocessor and microcontroller. It is very clear from figure that in microprocessor we have to interface additional circuitry for providing

More information

Architecture & Instruction set of 8085 Microprocessor and 8051 Micro Controller

Architecture & Instruction set of 8085 Microprocessor and 8051 Micro Controller of 8085 microprocessor 8085 is pronounced as "eighty-eighty-five" microprocessor. It is an 8-bit microprocessor designed by Intel in 1977 using NMOS technology. It has the following configuration 8-bit

More information

CHAPTER ASSEMBLY LANGUAGE PROGRAMMING

CHAPTER ASSEMBLY LANGUAGE PROGRAMMING CHAPTER 2 8051 ASSEMBLY LANGUAGE PROGRAMMING Registers Register are used to store information temporarily: A byte of data to be processed An address pointing to the data to be fetched The vast majority

More information

1 MALP ( ) Unit-1. (1) Draw and explain the internal architecture of 8085.

1 MALP ( ) Unit-1. (1) Draw and explain the internal architecture of 8085. (1) Draw and explain the internal architecture of 8085. The architecture of 8085 Microprocessor is shown in figure given below. The internal architecture of 8085 includes following section ALU-Arithmetic

More information

MICROPROCESSORS AND MICROCONTROLLERS MATERIAL. Features of 8051:

MICROPROCESSORS AND MICROCONTROLLERS MATERIAL. Features of 8051: DEPARTMENT OF ECE MICROPROCESSORS AND MICROCONTROLLERS MATERIAL UNIT V 8051 MICROCONTROLLERS To make a complete microcomputer system, only microprocessor is not sufficient. It is necessary to add other

More information

EE6502- MICROPROCESSOR AND MICROCONTROLLER

EE6502- MICROPROCESSOR AND MICROCONTROLLER . EE6502- MICROPROCESSOR AND MICROCONTROLLER UNIT III - 8051 MICROCONTROLLER PART - A 1. What is Microcontroller? A device which contains the microprocessor with integrated peripherals like memory, serial

More information

8051 MICROCONTROLLER

8051 MICROCONTROLLER What is a Microcontroller? UNIT 5 8051 MICROCONTROLLER A Microcontroller is a programmable digital processor with necessary peripherals. Both microcontrollers and microprocessors are complex sequential

More information

Infineon C167CR microcontroller, 256 kb external. RAM and 256 kb external (Flash) EEPROM. - Small single-board computer (SBC) with an

Infineon C167CR microcontroller, 256 kb external. RAM and 256 kb external (Flash) EEPROM. - Small single-board computer (SBC) with an Microcontroller Basics MP2-1 week lecture topics 2 Microcontroller basics - Clock generation, PLL - Address space, addressing modes - Central Processing Unit (CPU) - General Purpose Input/Output (GPIO)

More information

Chapter 1. Microprocessor architecture ECE Dr. Mohamed Mahmoud.

Chapter 1. Microprocessor architecture ECE Dr. Mohamed Mahmoud. Chapter 1 Microprocessor architecture ECE 3130 Dr. Mohamed Mahmoud The slides are copyright protected. It is not permissible to use them without a permission from Dr Mahmoud http://www.cae.tntech.edu/~mmahmoud/

More information

EXPERIMENT NO.1. A Microcontroller is a complete computer system built on a single chip.

EXPERIMENT NO.1. A Microcontroller is a complete computer system built on a single chip. EXPERIMENT NO.1 AIM: Study of 8051 Microcontroller TOOLS: 8051 kit THEORY: Salient Features of 8051 A Microcontroller is a complete computer system built on a single chip. It contains all components like

More information

Four Categories Of 8085 Instructions That >>>CLICK HERE<<<

Four Categories Of 8085 Instructions That >>>CLICK HERE<<< Four Categories Of 8085 Instructions That Manipulate Data When the data byte isloaded by CPU the transmitter will stop transmitting synchronous List the four categories of 8085 instructions. manipulate

More information

Chapter 1 Microprocessor architecture ECE 3120 Dr. Mohamed Mahmoud http://iweb.tntech.edu/mmahmoud/ mmahmoud@tntech.edu Outline 1.1 Computer hardware organization 1.1.1 Number System 1.1.2 Computer hardware

More information

1. Internal Architecture of 8085 Microprocessor

1. Internal Architecture of 8085 Microprocessor 1. Internal Architecture of 8085 Microprocessor Control Unit Generates signals within up to carry out the instruction, which has been decoded. In reality causes certain connections between blocks of the

More information

Microcomputer Architecture and Programming

Microcomputer Architecture and Programming IUST-EE (Chapter 1) Microcomputer Architecture and Programming 1 Outline Basic Blocks of Microcomputer Typical Microcomputer Architecture The Single-Chip Microprocessor Microprocessor vs. Microcontroller

More information

Engr. A. N. Aniedu Electronic and Computer Engineering Nnamdi Azikiwe University, Awka

Engr. A. N. Aniedu Electronic and Computer Engineering Nnamdi Azikiwe University, Awka Engr. A. N. Aniedu Electronic and Computer Engineering Nnamdi Azikiwe University, Awka INTRODUCTION Microcontroller vs General Purpose Microprocessor General-purpose microprocessors contains No RAM No

More information

Introducing The MCS 251 Microcontroller -- 8XC251SB

Introducing The MCS 251 Microcontroller -- 8XC251SB E AP- 708 APPLICATION NOTE Introducing The MCS 251 Microcontroller -- 8XC251SB YONG-YAP SOH TECHNICAL MARKETING EIGHT-BIT MICROCONTROLLERS February 1995 Order Number: 272670-001 Intel Corporation makes

More information

8051 Memory Organization BY D. BALAKRISHNA, Research Assistant, IIIT-H Chapter 1: Memory Organization There are 2 types of memories available in 8051 microcontroller. Program memory/c code memory (ROM)

More information

Department of Electronics and Instrumentation Engineering Question Bank

Department of Electronics and Instrumentation Engineering Question Bank www.examquestionpaper.in Department of Electronics and Instrumentation Engineering Question Bank SUBJECT CODE / NAME: ET7102 / MICROCONTROLLER BASED SYSTEM DESIGN BRANCH : M.E. (C&I) YEAR / SEM : I / I

More information

CS 320. Computer Architecture Core Architecture

CS 320. Computer Architecture Core Architecture CS 320 Computer Architecture 8051 Core Architecture Evan Hallam 19 April 2006 Abstract The 8051 is an 8-bit microprocessor designed originally in the 1980 s by the Intel Corporation. This inexpensive and

More information

Module Contents of the Module Hours COs

Module Contents of the Module Hours COs Microcontrollers (EE45): Syllabus: Module Contents of the Module Hours COs 1 8051 MICROCONTROLLER ARCHITECTURE: Introduction to Microprocessors and Microcontrollers, the 8051 Architecture, 08 1 and pin

More information

Distributed by: www.jameco.com 1-800-831-4242 The content and copyrights of the attached material are the property of its owner. 8051 8052 and 80C51 Hardware Description December 1992 Order Number 270252-006

More information

Architecture of 8085 microprocessor

Architecture of 8085 microprocessor Architecture of 8085 microprocessor 8085 consists of various units and each unit performs its own functions. The various units of a microprocessor are listed below Accumulator Arithmetic and logic Unit

More information

ENE 334 Microprocessors

ENE 334 Microprocessors Page 1 ENE 334 Microprocessors Lecture 7: MCS-51 Architecture I : Dejwoot KHAWPARISUTH http://webstaff.kmutt.ac.th/~dejwoot.kha/ ENE 334 MCS-51 Architecture I Page 2 Outlines: 8051 Microcontroller Hardware

More information

Moodle WILLINGDON COLLEGE SANGLI (B. SC.-II) Digital Electronics

Moodle WILLINGDON COLLEGE SANGLI (B. SC.-II) Digital Electronics Moodle 4 WILLINGDON COLLEGE SANGLI (B. SC.-II) Digital Electronics Advanced Microprocessors and Introduction to Microcontroller Moodle developed By Dr. S. R. Kumbhar Department of Electronics Willingdon

More information

Microprocessor Architecture

Microprocessor Architecture Microprocessor - 8085 Architecture 8085 is pronounced as "eighty-eighty-five" microprocessor. It is an 8-bit microprocessor designed by Intel in 1977 using NMOS technology. It has the following configuration

More information

Microcontroller and Embedded Systems:

Microcontroller and Embedded Systems: Microcontroller and Embedded Systems: Branches: 1. Electronics & Telecommunication Engineering 2. Electrical & Electronics Engineering Semester: 6 th Semester / 7 th Semester 1. Explain the differences

More information

FIFTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLOGY-MARCH 2014 EMBEDDED SYSTEMS (Common for CT,CM) [Time: 3 hours] (Maximum marks : 100)

FIFTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLOGY-MARCH 2014 EMBEDDED SYSTEMS (Common for CT,CM) [Time: 3 hours] (Maximum marks : 100) (Revision-10) FIFTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLOGY-MARCH 2014 EMBEDDED SYSTEMS (Common for CT,CM) [Time: 3 hours] (Maximum marks : 100) PART-A (Maximum marks : 10) I. Answer all

More information

CHAPTER 1 MICROCOMPUTER SYSTEMS. 1.1 Introduction. 1.2 Microcontroller Evolution

CHAPTER 1 MICROCOMPUTER SYSTEMS. 1.1 Introduction. 1.2 Microcontroller Evolution CHAPTER 1 MICROCOMPUTER SYSTEMS 1.1 Introduction The term microcomputer is used to describe a system that includes a microprocessor, program memory, data memory, and an input/output (I/O). Some microcomputer

More information

Microprocessors/Microcontrollers

Microprocessors/Microcontrollers Microprocessors/Microcontrollers A central processing unit (CPU) fabricated on one or more chips, containing the basic arithmetic, logic, and control elements of a computer that are required for processing

More information

CPEG300 Embedded System Design. Lecture 3 Memory

CPEG300 Embedded System Design. Lecture 3 Memory CPEG300 Embedded System Design Lecture 3 Memory Hamad Bin Khalifa University, Spring 2018 Review Von Neumann vs. Harvard architecture? System on Board, system on chip? Generic Hardware Architecture of

More information

Chapter Operation Pinout Operation 35

Chapter Operation Pinout Operation 35 68000 Operation 35 Chapter 6 68000 Operation 6-1. 68000 Pinout We will do no construction in this chapter; instead, we will take a detailed look at the individual pins of the 68000 and what they do. Fig.

More information

Chapter 1: Basics of Microprocessor [08 M]

Chapter 1: Basics of Microprocessor [08 M] Microprocessor: Chapter 1: Basics of Microprocessor [08 M] It is a semiconductor device consisting of electronic logic circuits manufactured by using either a Large scale (LSI) or Very Large Scale (VLSI)

More information

2. List the five interrupt pins available in INTR, TRAP, RST 7.5, RST 6.5, RST 5.5.

2. List the five interrupt pins available in INTR, TRAP, RST 7.5, RST 6.5, RST 5.5. DHANALAKSHMI COLLEGE OF ENGINEERING DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING EE6502- MICROPROCESSORS AND MICROCONTROLLERS UNIT I: 8085 PROCESSOR PART A 1. What is the need for ALE signal in

More information

UNIT IV MICROCONTROLLER

UNIT IV MICROCONTROLLER UNIT IV 8051- MICROCONTROLLER Prepared by R. Kavitha Page 1 Application Prepared by R. Kavitha Page 2 Pin Description of the 8051 UNIT IV- 8051 MICROCONTROLLER P1.0 P1.1 P1.2 P1.3 P1.4 P1.5 P1.6 P1.7 RST

More information

_ V Intel 8085 Family In-Circuit Emulation. Contents. Technical Notes

_ V Intel 8085 Family In-Circuit Emulation. Contents. Technical Notes _ V9.12. 225 Technical Notes Intel 8085 Family In-Circuit Emulation This document is intended to be used together with the CPU reference manual provided by the silicon vendor. This document assumes knowledge

More information

Control Unit: The control unit provides the necessary timing and control Microprocessor resembles a CPU exactly.

Control Unit: The control unit provides the necessary timing and control Microprocessor resembles a CPU exactly. Unit I 8085 and 8086 PROCESSOR Introduction to microprocessor A microprocessor is a clock-driven semiconductor device consisting of electronic logic circuits manufactured by using either a large-scale

More information

SYLLABUS UNIT - I 8086/8088 ARCHITECTURE AND INSTRUCTION SET

SYLLABUS UNIT - I 8086/8088 ARCHITECTURE AND INSTRUCTION SET 1 SYLLABUS UNIT - I 8086/8088 ARCHITECTURE AND INSTRUCTION SET Intel 8086/8088 Architecture Segmented Memory, Minimum and Maximum Modes of Operation, Timing Diagram, Addressing Modes, Instruction Set,

More information

Architecture of Computers and Parallel Systems Part 6: Microcomputers

Architecture of Computers and Parallel Systems Part 6: Microcomputers Architecture of Computers and Parallel Systems Part 6: Microcomputers Ing. Petr Olivka petr.olivka@vsb.cz Department of Computer Science FEI VSB-TUO Architecture of Computers and Parallel Systems Part

More information

CHAPTER 1 - World of microcontrollers

CHAPTER 1 - World of microcontrollers CHAPTER 1 - World of microcontrollers One Time Programmable ROM (OTP ROM) One time programmable ROM enables you to download a program into it, but, as its name states, one time only. If an error is detected

More information

MCS-51 Serial Port A T 8 9 C 5 2 1

MCS-51 Serial Port A T 8 9 C 5 2 1 MCS-51 Serial Port AT89C52 1 Introduction to Serial Communications Serial vs. Parallel transfer of data Simplex, Duplex and half-duplex modes Synchronous, Asynchronous UART Universal Asynchronous Receiver/Transmitter.

More information

MICROPROCESSOR AND MICROCONTROLLER BASED SYSTEMS

MICROPROCESSOR AND MICROCONTROLLER BASED SYSTEMS MICROPROCESSOR AND MICROCONTROLLER BASED SYSTEMS UNIT I INTRODUCTION TO 8085 8085 Microprocessor - Architecture and its operation, Concept of instruction execution and timing diagrams, fundamentals of

More information

QUESTION BANK CS2252 MICROPROCESSOR AND MICROCONTROLLERS

QUESTION BANK CS2252 MICROPROCESSOR AND MICROCONTROLLERS FATIMA MICHAEL COLLEGE OF ENGINEERING & TECHNOLOGY Senkottai Village, Madurai Sivagangai Main Road, Madurai -625 020 QUESTION BANK CS2252 MICROPROCESSOR AND MICROCONTROLLERS UNIT 1 - THE 8085 AND 8086

More information

Serial I-O for Dinesh K. Sharma Electrical Engineering Department I.I.T. Bombay Mumbai (version 14/10/07)

Serial I-O for Dinesh K. Sharma Electrical Engineering Department I.I.T. Bombay Mumbai (version 14/10/07) Serial I-O for 8051 Dinesh K. Sharma Electrical Engineering Department I.I.T. Bombay Mumbai 400 076 (version 14/10/07) 1 Motivation Serial communications means sending data a single bit at a time. But

More information

Basics of Microprocessor

Basics of Microprocessor Unit 1 Basics of Microprocessor 1. Microprocessor Microprocessor is a multipurpose programmable integrated device that has computing and decision making capability. This semiconductor IC is manufactured

More information

The Microcontroller Idea Book

The Microcontroller Idea Book The following material is excerpted from: The Microcontroller Idea Book Circuits, Programs, & Applications featuring the 8052-BASIC Microcontroller by Jan Axelson copyright 1994, 1997 by Jan Axelson ISBN

More information

AVR MICROCONTROLLER ARCHITECTURTE

AVR MICROCONTROLLER ARCHITECTURTE AVR MICROCONTROLLER ARCHITECTURTE AVR MICROCONTROLLER AVR- Advanced Virtual RISC. The founders are Alf Egil Bogen Vegard Wollan RISC AVR architecture was conceived by two students at Norwegian Institute

More information

Microcontrollers. Microcontroller

Microcontrollers. Microcontroller Microcontrollers Microcontroller A microprocessor on a single integrated circuit intended to operate as an embedded system. As well as a CPU, a microcontroller typically includes small amounts of RAM and

More information

A First Look at Microprocessors

A First Look at Microprocessors A First Look at Microprocessors using the The General Prototype Computer (GPC) model Part 4 Ports CPU Ecosystem All CPUs need RAM, ROM, a clock source and reset circuit, and power. Power Supply 1 Vio Vcore

More information

b. List different system buses of 8085 microprocessor and give function of each bus. (8) Answer:

b. List different system buses of 8085 microprocessor and give function of each bus. (8) Answer: Q.2 a. Discuss and differentiate between a Microprocessor and a Microcontroller. Microprocessor is an IC which has only the CPU inside them i.e. only the processing powers such as Intel s Pentium 1,2,3,4,

More information

In this tutorial, we will discuss the architecture, pin diagram and other key concepts of microprocessors.

In this tutorial, we will discuss the architecture, pin diagram and other key concepts of microprocessors. About the Tutorial A microprocessor is a controlling unit of a micro-computer, fabricated on a small chip capable of performing Arithmetic Logical Unit (ALU) operations and communicating with the other

More information

HCS12 BDM Getting Started V4.3

HCS12 BDM Getting Started V4.3 HCS12 BDM Getting Started V4.3 Background The term BDM stands for Background Debug Mode. It is used for the system development and FLASH programming. A BDM firmware is implemented on the CPU silicon providing

More information

MicroProcessor. MicroProcessor. MicroProcessor. MicroProcessor

MicroProcessor. MicroProcessor. MicroProcessor. MicroProcessor 1 2 A microprocessor is a single, very-large-scale-integration (VLSI) chip that contains many digital circuits that perform arithmetic, logic, communication, and control functions. When a microprocessor

More information

Unit I. Introduction Microcontrollers and Embedded processors Overview of the 8051 Inside the 8051 Addressing Modes

Unit I. Introduction Microcontrollers and Embedded processors Overview of the 8051 Inside the 8051 Addressing Modes Unit I Introduction Microcontrollers and Embedded processors Overview of the 8051 Inside the 8051 Addressing Modes 1.1.1. Basic Introduction 1.1.1. Basic Introduction (contd.) 1.1.1. Basic Introduction

More information

MAHALAKSHMI ENGINEERING COLLEGE TIRUCHIRAPALLI UNIT I THE 8085 & 8086 MICROPROCESSORS. PART A (2 Marks)

MAHALAKSHMI ENGINEERING COLLEGE TIRUCHIRAPALLI UNIT I THE 8085 & 8086 MICROPROCESSORS. PART A (2 Marks) MAHALAKSHMI ENGINEERING COLLEGE TIRUCHIRAPALLI-621213. UNIT I THE 8085 & 8086 MICROPROCESSORS PART A (2 Marks) 1. Give the significance of SIM and RIM instruction available in 8085. [NOV/DEC 2006] Instruction

More information

Mechatronics and Measurement. Lecturer:Dung-An Wang Lecture 6

Mechatronics and Measurement. Lecturer:Dung-An Wang Lecture 6 Mechatronics and Measurement Lecturer:Dung-An Wang Lecture 6 Lecture outline Reading:Ch7 of text Today s lecture: Microcontroller 2 7.1 MICROPROCESSORS Hardware solution: consists of a selection of specific

More information

A microprocessor-based system

A microprocessor-based system 7 A microprocessor-based system How simple can a microprocessor-based system actually be? It must obviously contain a microprocessor otherwise it is simply another electronic circuit. A microprocessor

More information

Introduction to Computers - Chapter 4

Introduction to Computers - Chapter 4 Introduction to Computers - Chapter 4 Since the invention of the transistor and the first digital computer of the 1940s, computers have been increasing in complexity and performance; however, their overall

More information

1. Internal Architecture of 8085 Microprocessor

1. Internal Architecture of 8085 Microprocessor Practical 1 Date : AIM : Introduction Of Microprocessor 8085. 1. Internal Architecture of 8085 Microprocessor Control Unit Generates signals within µp to carry out the instruction, which has been decoded.

More information

8/26/2010. Introduction to 8085 BLOCK DIAGRAM OF INTEL Introduction to Introduction to Three Units of 8085

8/26/2010. Introduction to 8085 BLOCK DIAGRAM OF INTEL Introduction to Introduction to Three Units of 8085 BLOCK DIAGRAM OF INTEL 8085 GURSHARAN SINGH TATLA Introduction to 8085 It was introduced in 1977. It is 8-bit microprocessor. Its actual name is 8085 A. It is single NMOS device. It contains 6200 transistors

More information

Segment 1A. Introduction to Microcomputer and Microprocessor

Segment 1A. Introduction to Microcomputer and Microprocessor Segment 1A Introduction to Microcomputer and Microprocessor 1.1 General Architecture of a Microcomputer System: The term microcomputer is generally synonymous with personal computer, or a computer that

More information

Chapter 7 Central Processor Unit (S08CPUV2)

Chapter 7 Central Processor Unit (S08CPUV2) Chapter 7 Central Processor Unit (S08CPUV2) 7.1 Introduction This section provides summary information about the registers, addressing modes, and instruction set of the CPU of the HCS08 Family. For a more

More information

Introduction to Microprocessor

Introduction to Microprocessor Introduction to Microprocessor The microprocessor is a general purpose programmable logic device. It is the brain of the computer and it performs all the computational tasks, calculations data processing

More information

12-Dec-11. Gursharan Singh Maninder Kaur. Introduction to 8085 BLOCK DIAGRAM OF INTEL Introduction to Introduction to 8085

12-Dec-11. Gursharan Singh Maninder Kaur. Introduction to 8085 BLOCK DIAGRAM OF INTEL Introduction to Introduction to 8085 mailme@gursharansingh.in BLOCK DIAGRAM OF INTEL 8085 mailme@maninderkaur.in Introduction to 8085 It was introduced in 1977. It is 8-bit microprocessor. Its actual name is 8085 A. It is single NMOS device.

More information

THE 8051 MICROCONTROLLER

THE 8051 MICROCONTROLLER THIRD EDITION THE 8051 MICROCONTROLLER I. Scott MacKenzie University of Guelph Prentice Hall Upper Saddle River, New Jersey Columbus, Ohio 1 INTRODUCTION TO MICROCONTROLLERS 1 1.1 Introduction 1 1.2 Terminology

More information

1. Pin diagram of 8051 and ports

1. Pin diagram of 8051 and ports e-pg Pathshala Subject : Computer Science Paper: Embedded System Module: Programming parallel ports Module No: CS/ES/9 Quadrant 1 e-text In this lecture pin diagram of 8051 controller will be shown and

More information

CENG-336 Introduction to Embedded Systems Development. Timers

CENG-336 Introduction to Embedded Systems Development. Timers CENG-336 Introduction to Embedded Systems Development Timers Definitions A counter counts (possibly asynchronous) input pulses from an external signal A timer counts pulses of a fixed, known frequency

More information

ELEG3924 Microprocessor

ELEG3924 Microprocessor Department of Electrical Engineering University of Arkansas ELEG3924 Microprocessor Ch.2 Assembly Language Programming Dr. Jing Yang jingyang@uark.edu 1 OUTLINE Inside 8051 Introduction to assembly programming

More information