Embedded Systems 简明教程

Embedded Systems - Quick Guide

Embedded Systems - Overview

System

系统是一组按照规则一起工作的单元的排列。也可以被定义为按照固定计划工作、组织或做一项或多项任务的方式。例如,手表是一个显示时间的系统。它的组件遵循一套规则来显示时间。如果其中一个部件发生故障,手表将停止工作。因此,我们可以说,在一个系统中,它的所有子组件相互依赖。

A system is an arrangement in which all its unit assemble work together according to a set of rules. It can also be defined as a way of working, organizing or doing one or many tasks according to a fixed plan. For example, a watch is a time displaying system. Its components follow a set of rules to show time. If one of its parts fails, the watch will stop working. So we can say, in a system, all its subcomponents depend on each other.

Embedded System

如其名称所示,嵌入式是指附加到另一事物上的东西。可以将嵌入式系统视为具有嵌入式软件的计算机硬件系统。嵌入式系统可以是一个独立的系统,也可以是大型系统的一部分。嵌入式系统是基于微控制器或微处理器的系统,旨在执行特定任务。例如,火灾报警器是一个嵌入式系统;它只感知烟雾。

As its name suggests, Embedded means something that is attached to another thing. An embedded system can be thought of as a computer hardware system having software embedded in it. An embedded system can be an independent system or it can be a part of a large system. An embedded system is a microcontroller or microprocessor based system which is designed to perform a specific task. For example, a fire alarm is an embedded system; it will sense only smoke.

嵌入式系统有三个组件:

An embedded system has three components −

  1. It has hardware.

  2. It has application software.

  3. It has Real Time Operating system (RTOS) that supervises the application software and provide mechanism to let the processor run a process as per scheduling by following a plan to control the latencies. RTOS defines the way the system works. It sets the rules during the execution of application program. A small scale embedded system may not have RTOS.

因此,我们可以将嵌入式系统定义为基于微控制器、软件驱动、可靠、实时的控制系统。

So we can define an embedded system as a Microcontroller based, software driven, reliable, real-time control system.

Characteristics of an Embedded System

  1. Single-functioned − An embedded system usually performs a specialized operation and does the same repeatedly. For example: A pager always functions as a pager.

  2. Tightly constrained − All computing systems have constraints on design metrics, but those on an embedded system can be especially tight. Design metrics is a measure of an implementation’s features such as its cost, size, power, and performance. It must be of a size to fit on a single chip, must perform fast enough to process data in real time and consume minimum power to extend battery life.

  3. Reactive and Real time − Many embedded systems must continually react to changes in the system’s environment and must compute certain results in real time without any delay. Consider an example of a car cruise controller; it continually monitors and reacts to speed and brake sensors. It must compute acceleration or de-accelerations repeatedly within a limited time; a delayed computation can result in failure to control of the car.

  4. Microprocessors based − It must be microprocessor or microcontroller based.

  5. Memory − It must have a memory, as its software usually embeds in ROM. It does not need any secondary memories in the computer.

  6. Connected − It must have connected peripherals to connect input and output devices.

  7. HW-SW systems − Software is used for more features and flexibility. Hardware is used for performance and security.

Advantages

  1. Easily Customizable

  2. Low power consumption

  3. Low cost

  4. Enhanced performance

Disadvantages

  1. High development effort

  2. Larger time to market

Basic Structure of an Embedded System

下图显示了嵌入式系统的基本结构:

The following illustration shows the basic structure of an embedded system −

embedded systems structure
  1. Sensor − It measures the physical quantity and converts it to an electrical signal which can be read by an observer or by any electronic instrument like an A2D converter. A sensor stores the measured quantity to the memory.

  2. A-D Converter − An analog-to-digital converter converts the analog signal sent by the sensor into a digital signal.

  3. Processor & ASICs − Processors process the data to measure the output and store it to the memory.

  4. D-A Converter − A digital-to-analog converter converts the digital data fed by the processor to analog data

  5. Actuator − An actuator compares the output given by the D-A Converter to the actual (expected) output stored in it and stores the approved output.

Embedded Systems - Processors

处理器是一个嵌入式系统的核心。它是接收输入并处理数据后产生输出的基本单元。对于嵌入式系统设计人员而言,有必要了解微处理器和微控制器。

Processor is the heart of an embedded system. It is the basic unit that takes inputs and produces an output after processing the data. For an embedded system designer, it is necessary to have the knowledge of both microprocessors and microcontrollers.

Processors in a System

一个处理器有两个基本单元:

A processor has two essential units −

  1. Program Flow Control Unit (CU)

  2. Execution Unit (EU)

CU 包含一个从内存中获取指令的获取单元。EU 有用于实现与数据传输操作和数据从一种形式转换到另一种形式有关的指令的电路。

The CU includes a fetch unit for fetching instructions from the memory. The EU has circuits that implement the instructions pertaining to data transfer operation and data conversion from one form to another.

EU 包含算术和逻辑单元 (ALU),还包含执行程序控制任务的指令的电路,例如中断,或跳至另一组指令。

The EU includes the Arithmetic and Logical Unit (ALU) and also the circuits that execute instructions for a program control task such as interrupt, or jump to another set of instructions.

一个处理器按从内存中获取的相同顺序运行获取循环并执行指令。

A processor runs the cycles of fetch and executes the instructions in the same sequence as they are fetched from memory.

Types of Processors

处理器可以划分为以下类别:

Processors can be of the following categories −

  1. General Purpose Processor (GPP) MicroprocessorMicrocontrollerEmbedded ProcessorDigital Signal ProcessorMedia Processor

  2. Application Specific System Processor (ASSP)

  3. Application Specific Instruction Processors (ASIPs)

  4. GPP core(s) or ASIP core(s) on either an Application Specific Integrated Circuit (ASIC) or a Very Large Scale Integration (VLSI) circuit.

Microprocessor

微处理器是具有 CPU 的单个 VLSI 芯片。此外,它还可能具有其他单元,例如缓存、浮点处理算术单元和流水线单元,这些单元有助于更快地处理指令。

A microprocessor is a single VLSI chip having a CPU. In addition, it may also have other units such as coaches, floating point processing arithmetic unit, and pipelining units that help in faster processing of instructions.

早期的微处理器取指执行周期由大约 1 MHz 的时钟频率控制。现在的处理器以 2GHz 的时钟频率工作

Earlier generation microprocessors’ fetch-and-execute cycle was guided by a clock frequency of order of ~1 MHz. Processors now operate at a clock frequency of 2GHz

microprocessors

Microcontroller

微控制器是个单芯片 VLSI 单元(也称为 microcomputer ),虽然计算能力有限,但具备增强的输入/输出能力和许多片上功能单元。

A microcontroller is a single-chip VLSI unit (also called microcomputer) which, although having limited computational capabilities, possesses enhanced input/output capability and a number of on-chip functional units.

CPU

RAM

ROM

I/O Port

Timer

Serial COM Port

微控制器尤其用于实时控制应用的嵌入式系统,具有片上程序内存和设备。

Microcontrollers are particularly used in embedded systems for real-time control applications with on-chip program memory and devices.

Microprocessor vs Microcontroller

下面我们来看一看微处理器和微控制器之间最显著的区别。

Let us now take a look at the most notable differences between a microprocessor and a microcontroller.

Microprocessor

Microcontroller

Microprocessors are multitasking in nature. Can perform multiple tasks at a time. For example, on computer we can play music while writing text in text editor.

Single task oriented. For example, a washing machine is designed for washing clothes only.

RAM, ROM, I/O Ports, and Timers can be added externally and can vary in numbers.

RAM, ROM, I/O Ports, and Timers cannot be added externally. These components are to be embedded together on a chip and are fixed in numbers.

Designers can decide the number of memory or I/O ports needed.

Fixed number for memory or I/O makes a microcontroller ideal for a limited but specific task.

External support of external memory and I/O ports makes a microprocessor-based system heavier and costlier.

Microcontrollers are lightweight and cheaper than a microprocessor.

External devices require more space and their power consumption is higher.

A microcontroller-based system consumes less power and takes less space.

Embedded Systems - Architecture Types

8051 微控制器使用 8 位数据总线工作。所以它们最多能支持 64K 外部数据内存和 64k 外部程序内存。总的来说,8051 微控制器可寻址 128k 外部内存。

The 8051 microcontrollers work with 8-bit data bus. So they can support external data memory up to 64K and external program memory of 64k at best. Collectively, 8051 microcontrollers can address 128k of external memory.

当数据和代码位于不同的存储器块中时,那么架构被称为 Harvard architecture 。当数据和代码位于同一个存储器块中时,那么架构被称为 Von Neumann architecture

When data and code lie in different memory blocks, then the architecture is referred as Harvard architecture. In case data and code lie in the same memory block, then the architecture is referred as Von Neumann architecture.

Von Neumann Architecture

冯·诺伊曼架构最早由计算机科学家约翰·冯·诺依曼提出。在该架构中,一条数据路径或总线既负责指令又负责数据。结果,CPU 一次只能执行一项操作。它要么从内存中获取一条指令,要么对数据执行读/写操作。因此,指令获取和数据操作不能同时进行,同时共享一条公共总线。

The Von Neumann architecture was first proposed by a computer scientist John von Neumann. In this architecture, one data path or bus exists for both instruction and data. As a result, the CPU does one operation at a time. It either fetches an instruction from memory, or performs read/write operation on data. So an instruction fetch and a data operation cannot occur simultaneously, sharing a common bus.

von neuman architecture

冯·诺伊曼架构支持简单的硬件。它允许使用一个单一顺序存储器。当今的处理速度远远超过内存访问时间,并且我们采用了一种非常快速但容量较小的存储器(高速缓存),它位于处理器的本地。

Von-Neumann architecture supports simple hardware. It allows the use of a single, sequential memory. Today’s processing speeds vastly outpace memory access times, and we employ a very fast but small amount of memory (cache) local to the processor.

Harvard Architecture

哈佛架构为指令和数据提供单独的存储和信号总线。该架构的数据存储完全包含在 CPU 中,并且无法将指令存储作为数据进行访问。使用内部数据总线,计算机为程序指令和数据分别设置存储器区域,从而允许同时访问指令和数据。

The Harvard architecture offers separate storage and signal buses for instructions and data. This architecture has data storage entirely contained within the CPU, and there is no access to the instruction storage as data. Computers have separate memory areas for program instructions and data using internal data buses, allowing simultaneous access to both instructions and data.

程序需要由操作员加载;处理器无法自行启动。在哈佛架构中,无需让这两个存储器共享属性。

Programs needed to be loaded by an operator; the processor could not boot itself. In a Harvard architecture, there is no need to make the two memories share properties.

harvard architecture

Von-Neumann Architecture vs Harvard Architecture

以下几点将冯·诺伊曼架构与哈佛架构区分开来。

The following points distinguish the Von Neumann Architecture from the Harvard Architecture.

Von-Neumann Architecture

Harvard Architecture

Single memory to be shared by both code and data.

Separate memories for code and data.

Processor needs to fetch code in a separate clock cycle and data in another clock cycle. So it requires two clock cycles.

Single clock cycle is sufficient, as separate buses are used to access code and data.

Higher speed, thus less time consuming.

Slower in speed, thus more time-consuming.

Simple in design.

Complex in design.

CISC and RISC

CISC 是一种复杂指令集计算机。它是一台可以寻址大量指令的计算机。

CISC is a Complex Instruction Set Computer. It is a computer that can address a large number of instructions.

在 20 世纪 80 年代初,计算机设计师建议计算机应该使用更少指令和简单的结构,以便它们可以在 CPU 内更快地执行而无需使用内存。此类计算机被归类为精简指令集计算机或 RISC。

In the early 1980s, computer designers recommended that computers should use fewer instructions with simple constructs so that they can be executed much faster within the CPU without having to use memory. Such computers are classified as Reduced Instruction Set Computer or RISC.

CISC vs RISC

以下几点将 CISC 与 RISC 区分开来 −

The following points differentiate a CISC from a RISC −

CISC

RISC

Larger set of instructions. Easy to program

Smaller set of Instructions. Difficult to program.

Simpler design of compiler, considering larger set of instructions.

Complex design of compiler.

Many addressing modes causing complex instruction formats.

Few addressing modes, fix instruction format.

Instruction length is variable.

Instruction length varies.

Higher clock cycles per second.

Low clock cycle per second.

Emphasis is on hardware.

Emphasis is on software.

Control unit implements large instruction set using micro-program unit.

Each instruction is to be executed by hardware.

Slower execution, as instructions are to be read from memory and decoded by the decoder unit.

Faster execution, as each instruction is to be executed by hardware.

Pipelining is not possible.

Pipelining of instructions is possible, considering single clock cycle.

Embedded Systems - Tools & Peripherals

Compilers and Assemblers

Compiler

编译器是一个计算机程序(或一组程序),它将用编程语言(源语言)编写的源代码转换为另一种计算机语言(通常是二进制格式)。转换的最常见原因是创建可执行程序。“编译器”一词主要用于将源代码从高级程序语言翻译成低级语言(例如汇编语言或机器代码)的程序。

A compiler is a computer program (or a set of programs) that transforms the source code written in a programming language (the source language) into another computer language (normally binary format). The most common reason for conversion is to create an executable program. The name "compiler" is primarily used for programs that translate the source code from a highlevel programming language to a low-level language (e.g., assembly language or machine code).

Cross-Compiler

如果已编译的程序可以在具有与编译器编译程序时计算机不同的 CPU 或操作系统的计算机上运行,那么该编译器称为交叉编译器。

If the compiled program can run on a computer having different CPU or operating system than the computer on which the compiler compiled the program, then that compiler is known as a cross-compiler.

Decompiler

能够将程序从低级语言翻译成高级语言的程序称为反编译器。

A program that can translate a program from a low-level language to a high-level language is called a decompiler.

Language Converter

一个能翻译用不同高级语言编写的程序的程序通常称为语言翻译器,源到源翻译器或语言转换器。

A program that translates programs written in different high-level languages is normally called a language translator, source to source translator, or language converter.

编译器可能会执行以下操作:

A compiler is likely to perform the following operations −

  1. Preprocessing

  2. Parsing

  3. Semantic Analysis (Syntax-directed translation)

  4. Code generation

  5. Code optimization

Assemblers

汇编器是一个接受基本计算机指令(称为汇编语言)并将其转换为计算机处理器可用于执行其基本操作的比特模式的程序。汇编器通过将汇编指令助记符转换成操作码,将符号名解析成存储器位置来创建目标代码。汇编语言使用助记符表示每个低级机器操作(操作码)。

An assembler is a program that takes basic computer instructions (called as assembly language) and converts them into a pattern of bits that the computer’s processor can use to perform its basic operations. An assembler creates object code by translating assembly instruction mnemonics into opcodes, resolving symbolic names to memory locations. Assembly language uses a mnemonic to represent each low-level machine operation (opcode).

Debugging Tools in an Embedded System

调试是一个有条理的过程,用于查找和减少计算机程序或电子硬件块中的错误数量,以便其按预期工作。当子系统紧密耦合时,调试很困难,因为一个子系统中的一个小改动可能会在另一个子系统中产生错误。嵌入式系统中使用的调试工具在开发时间和调试功能方面差异很大。我们将在下面讨论以下调试工具:

Debugging is a methodical process to find and reduce the number of bugs in a computer program or a piece of electronic hardware, so that it works as expected. Debugging is difficult when subsystems are tightly coupled, because a small change in one subsystem can create bugs in another. The debugging tools used in embedded systems differ greatly in terms of their development time and debugging features. We will discuss here the following debugging tools −

  1. Simulators

  2. Microcontroller starter kits

  3. Emulator

Simulators

代码通过在用于代码开发的主机计算机上模拟它来测试 MCU / 系统。模拟器尝试在软件中模拟完整微控制器的行为。

Code is tested for the MCU / system by simulating it on the host computer used for code development. Simulators try to model the behavior of the complete microcontroller in software.

Functions of Simulators

模拟器执行以下功能:

A simulator performs the following functions −

  1. Defines the processor or processing device family as well as its various versions for the target system.

  2. Monitors the detailed information of a source code part with labels and symbolic arguments as the execution goes on for each single step.

  3. Provides the status of RAM and simulated ports of the target system for each single step execution.

  4. Monitors system response and determines throughput.

  5. Provides trace of the output of contents of program counter versus the processor registers.

  6. Provides the detailed meaning of the present command.

  7. Monitors the detailed information of the simulator commands as these are entered from the keyboard or selected from the menu.

  8. Supports the conditions (up to 8 or 16 or 32 conditions) and unconditional breakpoints.

  9. Provides breakpoints and the trace which are together the important testing and debugging tool.

  10. Facilitates synchronizing the internal peripherals and delays.

Microcontroller Starter Kit

微控制器入门套件包括:

A microcontroller starter kit consists of −

  1. Hardware board (Evaluation board)

  2. In-system programmer

  3. Some software tools like compiler, assembler, linker, etc.

  4. Sometimes, an IDE and code size limited evaluation version of a compiler.

与模拟器相比,这些套件的一大优点是它们可在实时环境中工作,从而便于验证输入/输出功能。但是,入门套件完全足够,并且是最节省成本的开发简单微控制器项目的选项。

A big advantage of these kits over simulators is that they work in real-time and thus allow for easy input/output functionality verification. Starter kits, however, are completely sufficient and the cheapest option to develop simple microcontroller projects.

Emulators

仿真器是一个硬件套件或软件程序,或二者兼有,它在另一个与第一个不同的计算机系统(主机)中模拟一个计算机系统(来宾)的功能,从而模拟行为与真实系统(来宾)的行为非常相似。

An emulator is a hardware kit or a software program or can be both which emulates the functions of one computer system (the guest) in another computer system (the host), different from the first one, so that the emulated behavior closely resembles the behavior of the real system (the guest).

模拟是指电子设备中的计算机程序模拟(仿效)另一个程序或设备的能力。模拟专注于重新创建一个原始计算机环境。仿真器有能力保持与数字对象真实性的更紧密连接。仿真器帮助用户在一个平台上的任何类型的应用程序或操作系统中工作,类似于软件在其原始环境中运行的方式。

Emulation refers to the ability of a computer program in an electronic device to emulate (imitate) another program or device. Emulation focuses on recreating an original computer environment. Emulators have the ability to maintain a closer connection to the authenticity of the digital object. An emulator helps the user to work on any kind of application or operating system on a platform in a similar way as the software runs as in its original environment.

Peripheral Devices in Embedded Systems

嵌入式系统通过其外围设备与外部世界通信,如下所示:

Embedded systems communicate with the outside world via their peripherals, such as following &mins;

  1. Serial Communication Interfaces (SCI) like RS-232, RS-422, RS-485, etc.

  2. Synchronous Serial Communication Interface like I2C, SPI, SSC, and ESSI

  3. Universal Serial Bus (USB)

  4. Multi Media Cards (SD Cards, Compact Flash, etc.)

  5. Networks like Ethernet, LonWorks, etc.

  6. Fieldbuses like CAN-Bus, LIN-Bus, PROFIBUS, etc.

  7. imers like PLL(s), Capture/Compare and Time Processing Units.

  8. Discrete IO aka General Purpose Input/Output (GPIO)

  9. Analog to Digital/Digital to Analog (ADC/DAC)

  10. Debugging like JTAG, ISP, ICSP, BDM Port, BITP, and DP9 ports

Criteria for Choosing Microcontroller

在选择微处理器时,请确保它满足手头任务并具有成本效益。我们必须判断 8 位、16 位或 32 位微处理器能否最佳地处理任务的计算需求。此外,在选择微处理器时应牢记以下几点:

While choosing a microcontroller, make sure it meets the task at hand and that it is cost effective. We must see whether an 8-bit, 16-bit or 32-bit microcontroller can best handle the computing needs of a task. In addition, the following points should be kept in mind while choosing a microcontroller −

  1. Speed − What is the highest speed the microcontroller can support?

  2. Packaging − Is it 40-pin DIP (Dual-inline-package) or QFP (Quad flat package)? This is important in terms of space, assembling, and prototyping the end-product.

  3. Power Consumption − This is an important criteria for battery-powered products.

  4. Amount of RAM and ROM on the chip.

  5. Count of I/O pins and Timers on the chip.

  6. Cost per Unit − This is important in terms of final cost of the product in which the microcontroller is to be used.

此外,请确保您准备好该微处理器随附的工具,例如编译器、调试器和汇编器。最重要的是,您应从可靠的来源购买微处理器。

Further, make sure you have tools such as compilers, debuggers, and assemblers, available with the microcontroller. The most important of all, you should purchase a microcontroller from a reliable source.

Embedded Systems - 8051 Microcontroller

Brief History of 8051

第一款微处理器 4004 是由英特尔公司发明的。 80858086 微处理器也是由英特尔发明的。1981 年,英特尔推出了一个称为 8051 的 8 位微控制器。它被称为 system on a chip 是因为它有 128 字节的 RAM、4K 字节的片上 ROM、两个定时器、一个串行端口和 4 个端口(8 位宽),所有这些都集成在一个芯片中。当它变得广受欢迎时,英特尔允许其他制造商制造和销售与 8051 代码兼容的不同版本的 8051。这意味着如果您针对一种版本的 8051 编写程序,它将无论制造商如何也在其他版本上运行。这导致了几个具有不同速度和片上 RAM 大小的版本。

The first microprocessor 4004 was invented by Intel Corporation. 8085 and 8086 microprocessors were also invented by Intel. In 1981, Intel introduced an 8-bit microcontroller called the 8051. It was referred as system on a chip because it had 128 bytes of RAM, 4K byte of on-chip ROM, two timers, one serial port, and 4 ports (8-bit wide), all on a single chip. When it became widely popular, Intel allowed other manufacturers to make and market different flavors of 8051 with its code compatible with 8051. It means that if you write your program for one flavor of 8051, it will run on other flavors too, regardless of the manufacturer. This has led to several versions with different speeds and amounts of on-chip RAM.

8051 Flavors / Members

  1. 8052 microcontroller − 8052 has all the standard features of the 8051 microcontroller as well as an extra 128 bytes of RAM and an extra timer. It also has 8K bytes of on-chip program ROM instead of 4K bytes.

  2. 8031 microcontroller − It is another member of the 8051 family. This chip is often referred to as a ROM-less 8051, since it has 0K byte of on-chip ROM. You must add external ROM to it in order to use it, which contains the program to be fetched and executed. This program can be as large as 64K bytes. But in the process of adding external ROM to the 8031, it lost 2 ports out of 4 ports. To solve this problem, we can add an external I/O to the 8031

Comparison between 8051 Family Members

下表比较了 8051、8052 和 8031 中可用的功能。

The following table compares the features available in 8051, 8052, and 8031.

Feature

8051

8052

8031

ROM(bytes)

4K

8K

0K

RAM(bytes)

128

256

128

Timers

2

3

2

I/O pins

32

32

32

Serial port

1

1

1

Interrupt sources

6

8

6

Features of 8051 Microcontroller

8051 微控制器随以下功能捆绑提供 −

An 8051 microcontroller comes bundled with the following features −

  1. 4KB bytes on-chip program memory (ROM)

  2. 128 bytes on-chip data memory (RAM)

  3. Four register banks

  4. 128 user defined software flags

  5. 8-bit bidirectional data bus

  6. 16-bit unidirectional address bus

  7. 32 general purpose registers each of 8-bit

  8. 16 bit Timers (usually 2, but may have more or less)

  9. Three internal and two external Interrupts

  10. Four 8-bit ports,(short model have two 8-bit ports)

  11. 16-bit program counter and data pointer

  12. 8051 may also have a number of special features such as UARTs, ADC, Op-amp, etc.

Block Diagram of 8051 Microcontroller

下图显示了 3051 微控制器的框图 -

The following illustration shows the block diagram of an 8051 microcontroller −

block diagram

Embedded System - I/O Programming

在 8051 中,I/O 操作使用四个端口和 40 个引脚完成。以下引脚图显示了 40 个引脚的详细信息。I/O 操作端口预留 32 个引脚,每个端口有 8 个引脚。其他 8 个引脚指定为 Vcc、GND、XTAL1、XTAL2、RST、EA(条形)、ALE/PROG(条形)和 PSEN(条形)。

In 8051, I/O operations are done using four ports and 40 pins. The following pin diagram shows the details of the 40 pins. I/O operation port reserves 32 pins where each port has 8 pins. The other 8 pins are designated as Vcc, GND, XTAL1, XTAL2, RST, EA (bar), ALE/PROG (bar), and PSEN (bar).

它是 40 针 PDIP(塑料双列直插式封装)

It is a 40 Pin PDIP (Plastic Dual Inline Package)

pin diagram

Note - 在 DIP 封装中,你可以通过 IC 中间的切口识别第一个引脚和最后一个引脚。第一个引脚位于此切口标记的左侧,最后一个引脚(即本例中的第 40 个引脚)位于切口标记的右侧。

Note − In a DIP package, you can recognize the first pin and the last pin by the cut at the middle of the IC. The first pin is on the left of this cut mark and the last pin (i.e. the 40th pin in this case) is to the right of the cut mark.

I/O Ports and their Functions

四个端口 P0、P1、P2 和 P3 各使用 8 个引脚,使其成为 8 位端口。复位后,所有端口都配置为输入,可立即用作输入端口。当第一个 0 写入端口时,它将变为输出。要重新配置它为输入,必须向端口发送 1。

The four ports P0, P1, P2, and P3, each use 8 pins, making them 8-bit ports. Upon RESET, all the ports are configured as inputs, ready to be used as input ports. When the first 0 is written to a port, it becomes an output. To reconfigure it as an input, a 1 must be sent to a port.

Port 0 (Pin No 32 – Pin No 39)

它有 8 个引脚(32 到 39)。它可以用于输入或输出。与 P1、P2 和 P3 端口不同,我们通常将 P0 连接到 10K-ohm 上拉电阻,以便用作输入或输出端口,因为它是一个开漏输出。

It has 8 pins (32 to 39). It can be used for input or output. Unlike P1, P2, and P3 ports, we normally connect P0 to 10K-ohm pull-up resistors to use it as an input or output port being an open drain.

它还指定为 AD0-AD7,允许它同时用作地址和数据。对于 8031(即无 ROM 芯片),当我们需要访问外部 ROM 时,P0 将同时用于地址和数据总线。ALE(引脚号 31)指示 P0 具有地址或数据。当 ALE = 0 时,它提供数据 D0-D7,但当 ALE = 1 时,它具有地址 A0-A7。如果没有外部存储器连接,则必须将 P0 外部连接到 10K-ohm 上拉电阻。

It is also designated as AD0-AD7, allowing it to be used as both address and data. In case of 8031 (i.e. ROMless Chip), when we need to access the external ROM, then P0 will be used for both Address and Data Bus. ALE (Pin no 31) indicates if P0 has address or data. When ALE = 0, it provides data D0-D7, but when ALE = 1, it has address A0-A7. In case no external memory connection is available, P0 must be connected externally to a 10K-ohm pull-up resistor.

port0
MOV A,#0FFH  ;(comments: A=FFH(Hexadecimal  i.e. A=1111 1111)

MOV P0,A     ;(Port0 have 1's on every pin so that it works as Input)

Port 1 (Pin 1 through 8)

它是一个 8 位端口(第 1 至 8 个引脚),可以作为输入或输出使用。它不需要上拉电阻,因为它们已经内部连接。复位后,端口 1 配置为输入端口。以下代码可用于向端口 1 发送 55H 和 AAH 的交替值。

It is an 8-bit port (pin 1 through 8) and can be used either as input or output. It doesn’t require pull-up resistors because they are already connected internally. Upon reset, Port 1 is configured as an input port. The following code can be used to send alternating values of 55H and AAH to Port 1.

;Toggle all bits of continuously
MOV     A,#55
BACK:

MOV     P2,A
ACALL   DELAY
CPL     A      ;complement(invert) reg. A
SJMP    BACK

如果端口 1 配置为用作输出端口,那么要再次用作输入端口,请对它进行编程,方法是像以下代码一样向它的所有位写入 1。

If Port 1 is configured to be used as an output port, then to use it as an input port again, program it by writing 1 to all of its bits as in the following code.

;Toggle all bits of continuously

MOV     A ,#0FFH    ;A = FF hex
MOV     P1,A        ;Make P1 an input port
MOV     A,P1        ;get data from P1
MOV     R7,A        ;save it in Reg R7
ACALL   DELAY       ;wait

MOV     A,P1        ;get another data from P1
MOV     R6,A        ;save it in R6
ACALL   DELAY       ;wait

MOV     A,P1        ;get another data from P1
MOV     R5,A        ;save it in R5

Port 2 (Pins 21 through 28)

端口 2 共占用 8 个引脚(第 21 至 28 个引脚),可用于输入和输出操作。就像 P1(端口 1)一样,P2 也不需要外部上拉电阻,因为它们已经内部连接。它必须与 P0 一起使用,以便为外部存储器提供 16 位地址。因此,它也指定为 (A0–A7),如引脚图所示。当 8051 连接到外部存储器时,它为 16 位地址的高 8 位提供路径,并且不能用作 I/O。复位后,端口 2 配置为输入端口。以下代码可用于向端口 2 发送 55H 和 AAH 的交替值。

Port 2 occupies a total of 8 pins (pins 21 through 28) and can be used for both input and output operations. Just as P1 (Port 1), P2 also doesn’t require external Pull-up resistors because they are already connected internally. It must be used along with P0 to provide the 16-bit address for the external memory. So it is also designated as (A0–A7), as shown in the pin diagram. When the 8051 is connected to an external memory, it provides path for upper 8-bits of 16-bits address, and it cannot be used as I/O. Upon reset, Port 2 is configured as an input port. The following code can be used to send alternating values of 55H and AAH to port 2.

;Toggle all bits of continuously
MOV     A,#55
BACK:
MOV     P2,A
ACALL   DELAY
CPL     A         ; complement(invert) reg. A
SJMP    BACK

如果端口 2 配置为用作输出端口,那么要再次用作输入端口,请对它进行编程,方法是像以下代码一样向它的所有位写入 1。

If Port 2 is configured to be used as an output port, then to use it as an input port again, program it by writing 1 to all of its bits as in the following code.

;Get a byte from P2 and send it to P1
MOV    A,#0FFH    ;A = FF hex
MOV    P2,A       ;make P2 an input port
BACK:
MOV    A,P2       ;get data from P2
MOV    P1,A       ;send it to Port 1
SJMP   BACK       ;keep doing that

Port 3 (Pins 10 through 17)

它也是 8 位的,可以用作输入/输出。此端口提供一些非常重要的信号。P3.0 和 P3.1 分别是 RxD(接收器)和 TxD(发送器),并共同用于串行通信。P3.2 和 P3.3 引脚用于外部中断。P3.4 和 P3.5 分别用于计时器 T0 和 T1。P3.6 和 P3.7 是写(WR)和读(RD)引脚。这些是低电平有效引脚,这意味着当向它们提供 0 时它们将变为活动状态,并且它们用于向基于 8031 的系统中的外部 ROM 提供读写操作。

It is also of 8 bits and can be used as Input/Output. This port provides some extremely important signals. P3.0 and P3.1 are RxD (Receiver) and TxD (Transmitter) respectively and are collectively used for Serial Communication. P3.2 and P3.3 pins are used for external interrupts. P3.4 and P3.5 are used for timers T0 and T1 respectively. P3.6 and P3.7 are Write (WR) and Read (RD) pins. These are active low pins, means they will be active when 0 is given to them and these are used to provide Read and Write operations to External ROM in 8031 based systems.

P3 Bit

Function

Pin

P3.0

RxD

10

P3.1

TxD

11

P3.2

Complement of INT0

12

P3.3

INT1

13

P3.4

T0

14

P3.5

T1

15

P3.6

WR

16

P3.7

Complement of RD

17

Dual Role of Port 0 and Port 2

  1. Dual role of Port 0 − Port 0 is also designated as AD0–AD7, as it can be used for both data and address handling. While connecting an 8051 to external memory, Port 0 can provide both address and data. The 8051 microcontroller then multiplexes the input as address or data in order to save pins.

  2. Dual role of Port 2 − Besides working as I/O, Port P2 is also used to provide 16-bit address bus for external memory along with Port 0. Port P2 is also designated as (A8– A15), while Port 0 provides the lower 8-bits via A0–A7. In other words, we can say that when an 8051 is connected to an external memory (ROM) which can be maximum up to 64KB and this is possible by 16 bit address bus because we know 216 = 64KB. Port2 is used for the upper 8-bit of the 16 bits address, and it cannot be used for I/O and this is the way any Program code of external ROM is addressed.

Hardware Connection of Pins

  1. Vcc − Pin 40 provides supply to the Chip and it is +5 V.

  2. Gnd − Pin 20 provides ground for the Reference.

  3. XTAL1, XTAL2 (Pin no 18 & Pin no 19) − 8051 has on-chip oscillator but requires external clock to run it. A quartz crystal is connected between the XTAL1 & XTAL2 pin of the chip. This crystal also needs two capacitors of 30pF for generating a signal of desired frequency. One side of each capacitor is connected to ground. 8051 IC is available in various speeds and it all depends on this Quartz crystal, for example, a 20 MHz microcontroller requires a crystal with a frequency no more than 20 MHz.

xtal
  1. RST (Pin No. 9) − It is an Input pin and active High pin. Upon applying a high pulse on this pin, that is 1, the microcontroller will reset and terminate all activities. This process is known as Power-On Reset. Activating a power-on reset will cause all values in the register to be lost. It will set a program counter to all 0’s. To ensure a valid input of Reset, the high pulse must be high for a minimum of two machine cycles before it is allowed to go low, which depends on the capacitor value and the rate at which it charges. (Machine Cycle is the minimum amount of frequency a single instruction requires in execution).

  2. EA or External Access (Pin No. 31) − It is an input pin. This pin is an active low pin; upon applying a low pulse, it gets activated. In case of microcontroller (8051/52) having on-chip ROM, the EA (bar) pin is connected to Vcc. But in an 8031 microcontroller which does not have an on-chip ROM, the code is stored in an external ROM and then fetched by the microcontroller. In this case, we must connect the (pin no 31) EA to Gnd to indicate that the program code is stored externally.

rst
  1. PSEN or Program store Enable (Pin No 29) − This is also an active low pin, i.e., it gets activated after applying a low pulse. It is an output pin and used along with the EA pin in 8031 based (i.e. ROMLESS) Systems to allow storage of program code in external ROM.

  2. ALE or (Address Latch Enable) − This is an Output Pin and is active high. It is especially used for 8031 IC to connect it to the external memory. It can be used while deciding whether P0 pins will be used as Address bus or Data bus. When ALE = 1, then the P0 pins work as Data bus and when ALE = 0, then the P0 pins act as Address bus.

I/O Ports and Bit Addressability

这是在编写 8051 代码时对 8051 使用最广泛的功能。有时我们只需要访问端口的 1 或 2 位,而不是整个 8 位。8051 提供了访问端口的各个位的能力。

It is a most widely used feature of 8051 while writing code for 8051. Sometimes we need to access only 1 or 2 bits of the port instead of the entire 8-bits. 8051 provides the capability to access individual bits of the ports.

在以单比特方式访问端口时,我们使用语法“SETB X. Y”,其中 X 是端口号 (0 到 3),Y 是数据位 D0-D7 的位号 (0 到 7),其中 D0 是 LSB,而 D7 是 MSB。例如,“SETB P1.5”设置端口 1 的高电平位 5。

While accessing a port in a single-bit manner, we use the syntax "SETB X. Y" where X is the port number (0 to 3), and Y is a bit number (0 to 7) for data bits D0-D7 where D0 is the LSB and D7 is the MSB. For example, "SETB P1.5" sets high bit 5 of port 1.

以下代码展示了我们如何连续切换位 P1.2。

The following code shows how we can toggle the bit P1.2 continuously.

AGAIN:
SETB    P1.2
ACALL   DELAY
CLR     P1.2
ACALL   DELAY
SJMP    AGAIN

Single-Bit Instructions

Instructions

Function

SETB bit

Set the bit (bit = 1)

CLR bit

clear the bit (bit = 0)

CPL bit

complement the bit (bit = NOT bit)

JB bit, target

jump to target if bit = 1 (jump if bit)

JNB bit, target

jump to target if bit = 0 (jump if no bit)

JBC bit, target

jump to target if bit = 1, clear bit (jump if bit, then clear)

Embedded Systems - Terms

Program Counter

程序计数器是一个 16 位或 32 位寄存器,其中包含要执行的下一条指令的地址。每次获取指令时,PC 会自动递增到下一个顺序内存位置。分支、跳转和中断操作会使用其他于下一个顺序位置的地址加载程序计数器。

The Program Counter is a 16- or 32-bit register which contains the address of the next instruction to be executed. The PC automatically increments to the next sequential memory location every time an instruction is fetched. Branch, jump, and interrupt operations load the Program Counter with an address other than the next sequential location.

激活上电复位将导致寄存器中的所有值丢失。这意味着上电复位后 PC(程序计数器)的值为 0,迫使 CPU 从 ROM 存储器位置 0000 获取第一个操作码。这意味着我们必须将第一个字节的上行码放在 ROM 位置 0000,因为这是 CPU 希望找到第一条指令的位置

Activating a power-on reset will cause all values in the register to be lost. It means the value of the PC (program counter) is 0 upon reset, forcing the CPU to fetch the first opcode from the ROM memory location 0000. It means we must place the first byte of upcode in ROM location 0000 because that is where the CPU expects to find the first instruction

Reset Vector

复位向量的意义在于它指向处理器包含固件的第一条指令的内存地址。没有复位向量,处理器将不知道从何处开始执行。上电复位后,处理器使用预定义的内存位置中的复位向量值为程序计数器 (PC) 加载。在 CPU08 架构中,它位于位置 $FFFE:$FFFF。

The significance of the reset vector is that it points the processor to the memory address which contains the firmware’s first instruction. Without the Reset Vector, the processor would not know where to begin execution. Upon reset, the processor loads the Program Counter (PC) with the reset vector value from a predefined memory location. On CPU08 architecture, this is at location $FFFE:$FFFF.

当复位向量不必要时,开发人员通常会认为理所当然,并且不会对其编程以生成最终映像。结果,处理器不会在最终产品上启动。这是在调试阶段发生的常见错误。

When the reset vector is not necessary, developers normally take it for granted and don’t program into the final image. As a result, the processor doesn’t start up on the final product. It is a common mistake that takes place during the debug phase.

Stack Pointer

栈在RAM中实现,一个CPU寄存器用于访问它,称为SP(堆栈指针)寄存器。SP寄存器是8位寄存器,可以寻址范围为00h到FFh的存储器地址。最初,SP寄存器包含值07,指向位置08,作为8051为堆栈使用的第一个位置。

Stack is implemented in RAM and a CPU register is used to access it called SP (Stack Pointer) register. SP register is an 8-bit register and can address memory addresses of range 00h to FFh. Initially, the SP register contains value 07 to point to location 08 as the first location being used for the stack by the 8051.

当CPU寄存器的内容存储在堆栈中时,称为PUSH操作。当堆栈的内容存储在CPU寄存器中时,称为POP操作。换句话说,将寄存器推送到堆栈中以保存它,并将其弹出堆栈以检索它。

When the content of a CPU register is stored in a stack, it is called a PUSH operation. When the content of a stack is stored in a CPU register, it is called a POP operation. In other words, a register is pushed onto the stack to save it and popped off the stack to retrieve it.

Infinite Loop

无限循环或无穷循环可以标识为计算机程序中的一系列指令,由于以下原因,它们在循环中无限地执行−

An infinite loop or an endless loop can be identified as a sequence of instructions in a computer program that executes endlessly in a loop, because of the following reasons −

  1. loop with no terminating condition.

  2. loop with a terminating condition that can never be met.

  3. loop with a terminating condition that causes the loop to start over.

此类无限循环通常会导致较旧的操作系统无响应,因为无限循环会消耗所有可用的处理器时间。等待用户输入的I/O操作也称为“无限循环”。计算机“冻结”的一个可能是无限循环;其他原因包括 deadlockaccess violations

Such infinite loops normally caused older operating systems to become unresponsive, as an infinite loop consumes all the available processor time. I/O operations waiting for user inputs are also called "infinite loops". One possible cause of a computer "freezing" is an infinite loop; other causes include deadlock and access violations.

与PC不同,嵌入式系统从不“退出”应用程序。它们通过无限循环空闲,等待事件以中断的形式发生,或 pre-scheduled task 。为了节省电能,一些处理器进入特殊的 sleepwait modes ,而不是通过无限循环空闲,但它们将在计时器或外部中断时退出此模式。

Embedded systems, unlike a PC, never "exit" an application. They idle through an Infinite Loop waiting for an event to take place in the form of an interrupt, or a pre-scheduled task. In order to save power, some processors enter special sleep or wait modes instead of idling through an Infinite Loop, but they will come out of this mode upon either a timer or an External Interrupt.

Interrupts

中断主要是硬件机制,用于指示程序事件已发生。它们可能随时发生,因此与程序流异步。它们需要处理器进行特殊处理,最终由相应的Interrupt Service Routine(ISR)处理。中断需要迅速处理。如果您花太多时间来处理中断,那么您可能会错过另一个中断。

Interrupts are mostly hardware mechanisms that instruct the program that an event has occurred. They may occur at any time, and are therefore asynchronous to the program flow. They require special handling by the processor, and are ultimately handled by a corresponding Interrupt Service Routine (ISR). Interrupts need to be handled quickly. If you take too much time servicing an interrupt, then you may miss another interrupt.

Little Endian Vs Big Endian

尽管数字总是以相同的方式显示,但它们在存储器中不是以相同的方式存储的。大端序机器将数据最重要的字节存储在最低的存储器地址中。大端序机器将0x12345678存储为−

Although numbers are always displayed in the same way, they are not stored in the same way in memory. Big-Endian machines store the most significant byte of data in the lowest memory address. A Big-Endian machine stores 0x12345678 as −

ADD+0: 0x12
ADD+1: 0x34
ADD+2: 0x56
ADD+3: 0x78

另一方面,小端序机器将数据的最小有效字节存储在最低存储器地址中。小端序机器将0x12345678存储为−

Little-Endian machines, on the other hand, store the least significant byte of data in the lowest memory address. A Little-Endian machine stores 0x12345678 as −

ADD+0: 0x78
ADD+1: 0x56
ADD+2: 0x34
ADD+3: 0x12

Embedded Systems - Assembly Language

汇编语言被开发用于为机器级代码指令提供 mnemonics 或符号。汇编语言程序由助记符组成,因此它们应该被翻译成机器代码。负责此转换的程序称为 assembler 。汇编语言通常被称为低级语言,因为它直接与CPU的内部结构一起工作。为了用汇编语言进行编程,程序员必须了解CPU的所有寄存器。

Assembly languages were developed to provide mnemonics or symbols for the machine level code instructions. Assembly language programs consist of mnemonics, thus they should be translated into machine code. A program that is responsible for this conversion is known as assembler. Assembly language is often termed as a low-level language because it directly works with the internal structure of the CPU. To program in assembly language, a programmer must know all the registers of the CPU.

不同的编程语言,如C、C++、Java和各种其他语言,被称为高级语言,因为它们不处理CPU的内部细节。相反,汇编器用于将汇编语言程序翻译成机器代码(有时也称为 object codeopcode )。类似地,编译器将高级语言翻译成机器代码。例如,要编写C语言程序,必须使用C编译器将程序翻译成机器语言。

Different programming languages such as C, C++, Java and various other languages are called high-level languages because they do not deal with the internal details of a CPU. In contrast, an assembler is used to translate an assembly language program into machine code (sometimes also called object code or opcode). Similarly, a compiler translates a high-level language into machine code. For example, to write a program in C language, one must use a C compiler to translate the program into machine language.

Structure of Assembly Language

汇编语言程序是一系列语句,它们要么是诸如ADD和MOV的汇编语言指令,要么是称为 directives 的语句。

An assembly language program is a series of statements, which are either assembly language instructions such as ADD and MOV, or statements called directives.

instruction 告诉CPU要做什么,而 directive (也称为 pseudo-instructions )则向汇编器发出指令。例如,ADD和MOV指令是CPU运行的命令,而ORG和END是汇编器指令。当使用ORG指令时,汇编器将操作码放在存储器位置0,而END则指示源代码的末尾。程序语言指令包含以下四个字段−

An instruction tells the CPU what to do, while a directive (also called pseudo-instructions) gives instruction to the assembler. For example, ADD and MOV instructions are commands which the CPU runs, while ORG and END are assembler directives. The assembler places the opcode to the memory location 0 when the ORG directive is used, while END indicates to the end of the source code. A program language instruction consists of the following four fields −

[ label: ]   mnemonics  [ operands ]   [;comment ]

方括号([ ])表示该字段是可选的。

A square bracket ( [ ] ) indicates that the field is optional.

  1. The label field allows the program to refer to a line of code by name. The label fields cannot exceed a certain number of characters.

  2. The mnemonics and operands fields together perform the real work of the program and accomplish the tasks. Statements like ADD A , C & MOV C, #68 where ADD and MOV are the mnemonics, which produce opcodes ; "A, C" and "C, #68" are operands. These two fields could contain directives. Directives do not generate machine code and are used only by the assembler, whereas instructions are translated into machine code for the CPU to execute.

1.0000         ORG  0H            ;start (origin) at location 0
2 0000 7D25    MOV  R5,#25H       ;load 25H into R5
3.0002 7F34    MOV  R7,#34H       ;load 34H into  R7
4.0004 7400    MOV  A,#0          ;load 0 into A
5.0006 2D      ADD  A,R5          ;add contents of R5 to A
6.0007 2F      ADD  A,R7          ;add contents of R7 to A
7.0008 2412    ADD  A,#12H        ;add to A value 12 H
8.000A 80FE    HERE: SJMP HERE    ;stay in this loop
9.000C END                        ;end of asm source file
  1. The comment field begins with a semicolon which is a comment indicator.

  2. Notice the Label "HERE" in the program. Any label which refers to an instruction should be followed by a colon.

Assembling and Running an 8051 Program

在此,我们将讨论汇编语言的基本形式。创建、汇编和运行汇编语言程序的步骤如下:

Here we will discuss about the basic form of an assembly language. The steps to create, assemble, and run an assembly language program are as follows −

  1. First, we use an editor to type in a program similar to the above program. Editors like MS-DOS EDIT program that comes with all Microsoft operating systems can be used to create or edit a program. The Editor must be able to produce an ASCII file. The "asm" extension for the source file is used by an assembler in the next step.

  2. The "asm" source file contains the program code created in Step 1. It is fed to an 8051 assembler. The assembler then converts the assembly language instructions into machine code instructions and produces an .obj file (object file) and a .lst file (list file). It is also called as a source file, that’s why some assemblers require that this file have the "src" extensions. The "lst" file is optional. It is very useful to the program because it lists all the opcodes and addresses as well as errors that the assemblers detected.

  3. Assemblers require a third step called linking. The link program takes one or more object files and produces an absolute object file with the extension "abs".

  4. Next, the "abs" file is fed to a program called "OH" (object to hex converter), which creates a file with the extension "hex" that is ready to burn in to the ROM.

steps program

Data Type

8051 微控制器包含一个 8 位的单数据类型,每个寄存器的大小也都是 8 位。程序员必须将大于 8 位的数据(00 到 FFH,或十进制的 255)分解,以便 CPU 能够处理它。

The 8051 microcontroller contains a single data type of 8-bits, and each register is also of 8-bits size. The programmer has to break down data larger than 8-bits (00 to FFH, or to 255 in decimal) so that it can be processed by the CPU.

DB (Define Byte)

DB 指令是汇编器中最广泛使用的数据指令。它用于定义 8 位数据。它还可用于定义十进制、二进制、十六进制或 ASCII 格式的数据。对于十进制,“D”位于十进制数字后是可选的,但对于“B”(二进制)和“Hl”(十六进制)来说,它则是必需的。

The DB directive is the most widely used data directive in the assembler. It is used to define the 8-bit data. It can also be used to define decimal, binary, hex, or ASCII formats data. For decimal, the "D" after the decimal number is optional, but it is required for "B" (binary) and "Hl" (hexadecimal).

要指示 ASCII,只需将字符放在引号中(“这样”)。汇编器会自动为数字/字符生成 ASCII 代码。DB 指令是唯一可用于定义大于两个字符的 ASCII 字符串的指令;因此,它应用于所有 ASCII 数据定义。下面给出了一些 DB 示例:

To indicate ASCII, simply place the characters in quotation marks ('like this'). The assembler generates ASCII code for the numbers/characters automatically. The DB directive is the only directive that can be used to define ASCII strings larger than two characters; therefore, it should be used for all the ASCII data definitions. Some examples of DB are given below −

        ORG  500H
DATA1:  DB   28                     ;DECIMAL (1C in hex)
DATA2:  DB   00110101B              ;BINARY  (35 in hex)
DATA3:  DB   39H                    ;HEX
        ORG  510H
DATA4:  DB   "2591"                 ;ASCII  NUMBERS
        ORG  520H
DATA6:  DA   "MY NAME IS Michael"   ;ASCII CHARACTERS

可以在 ASCII 字符串周围使用单引号或双引号。DB 还用于在字节大小块中分配内存。

Either single or double quotes can be used around ASCII strings. DB is also used to allocate memory in byte-sized chunks.

Assembler Directives

8051 的一些指令如下:

Some of the directives of 8051 are as follows −

  1. ORG (origin) − The origin directive is used to indicate the beginning of the address. It takes the numbers in hexa or decimal format. If H is provided after the number, the number is treated as hexa, otherwise decimal. The assembler converts the decimal number to hexa.

  2. EQU (equate) − It is used to define a constant without occupying a memory location. EQU associates a constant value with a data label so that the label appears in the program, its constant value will be substituted for the label. While executing the instruction "MOV R3, #COUNT", the register R3 will be loaded with the value 25 (notice the # sign). The advantage of using EQU is that the programmer can change it once and the assembler will change all of its occurrences; the programmer does not have to search the entire program.

  3. END directive − It indicates the end of the source (asm) file. The END directive is the last line of the program; anything after the END directive is ignored by the assembler.

Labels in Assembly Language

汇编语言中的所有标签都必须遵守以下规则:

All the labels in assembly language must follow the rules given below −

  1. Each label name must be unique. The names used for labels in assembly language programming consist of alphabetic letters in both uppercase and lowercase, number 0 through 9, and special characters such as question mark (?), period (.), at the rate @, underscore (_), and dollar($).

  2. The first character should be in alphabetical character; it cannot be a number.

  3. Reserved words cannot be used as a label in the program. For example, ADD and MOV words are the reserved words, since they are instruction mnemonics.

Embedded Systems - Registers

寄存器用在 CPU 中,以临时存储信息,这些信息可能是要处理的数据,或指向要获取的数据的地址。在 8051 中,有一种数据类型为 8 位,从 MSB(最高有效位)D7 到 LSB(最低有效位)D0。对于 8 位数据类型,任何大于 8 位的数据类型都必须在处理之前分解为 8 位块。

Registers are used in the CPU to store information on temporarily basis which could be data to be processed, or an address pointing to the data which is to be fetched. In 8051, there is one data type is of 8-bits, from the MSB (most significant bit) D7 to the LSB (least significant bit) D0. With 8-bit data type, any data type larger than 8-bits must be broken into 8-bit chunks before it is processed.

8051 中使用最广泛的寄存器有 A(累加器)、B、R0-R7、DPTR(数据指针)和 PC(程序计数器)。除 DPTR 和 PC 之外,所有这些寄存器都是 8 位的。

The most widely used registers of the 8051 are A (accumulator), B, R0-R7, DPTR (data pointer), and PC (program counter). All these registers are of 8-bits, except DPTR and PC.

Storage Registers in 8051

我们将在此处讨论以下类型的存储寄存器 −

We will discuss the following types of storage registers here −

  1. Accumulator

  2. R register

  3. B register

  4. Data Pointer (DPTR)

  5. Program Counter (PC)

  6. Stack Pointer (SP)

Accumulator

累加器,寄存器 A,用于所有算术和逻辑运算。如果不存在累加器,则每次计算的结果(加法、乘法、移位等)都将存储到主存储器中。与累加器等寄存器相比,访问主存储器比访问寄存器更慢,这是因为用于大型主存储器的技术比用于寄存器的技术慢(但便宜)。

The accumulator, register A, is used for all arithmetic and logic operations. If the accumulator is not present, then every result of each calculation (addition, multiplication, shift, etc.) is to be stored into the main memory. Access to main memory is slower than access to a register like the accumulator because the technology used for the large main memory is slower (but cheaper) than that used for a register.

The "R" Registers

“R”寄存器是一组八个寄存器,即 R0、R1 至 R7。这些寄存器在许多操作中用作辅助或临时存储寄存器。考虑将 10 和 20 相加的示例。将变量 10 存储在累加器中,并将另一个变量 20 存储在(例如)寄存器 R4 中。要处理加法运算,请执行以下命令 −

The "R" registers are a set of eight registers, namely, R0, R1 to R7. These registers function as auxiliary or temporary storage registers in many operations. Consider an example of the sum of 10 and 20. Store a variable 10 in an accumulator and another variable 20 in, say, register R4. To process the addition operation, execute the following command −

ADD A,R4

执行此指令后,累加器将包含值 30。因此,“R”寄存器是非常重要的辅助或 helper registers 。如果没有这些“R”寄存器,累加器本身将不会非常有用。“R”寄存器用于临时存储值。

After executing this instruction, the accumulator will contain the value 30. Thus "R" registers are very important auxiliary or helper registers. The Accumulator alone would not be very useful if it were not for these "R" registers. The "R" registers are meant for temporarily storage of values.

我们再举一个例子。我们将把 R1 和 R2 中的值相加,然后从结果中减去 R3 和 R4 的值。

Let us take another example. We will add the values in R1 and R2 together and then subtract the values of R3 and R4 from the result.

MOV A,R3   ;Move the value of R3 into the accumulator
ADD A,R4   ;Add the value of R4
MOV R5,A   ;Store the resulting value temporarily in R5
MOV A,R1   ;Move the value of R1 into the accumulator
ADD A,R2   ;Add the value of R2
SUBB A,R5  ;Subtract the value of R5 (which now contains R3 + R4)

如你所见,我们使用 R5 来临时保存 R3 和 R4 的总和。当然,这不是计算 (R1 + R2) – (R3 + R4) 最有效的方法,但它确实说明了使用“R”寄存器作为临时存储值的途径。

As you can see, we used R5 to temporarily hold the sum of R3 and R4. Of course, this is not the most efficient way to calculate (R1 + R2) – (R3 + R4), but it does illustrate the use of the "R" registers as a way to store values temporarily.

8bit registers

The "B" Register

“B”寄存器与累加器非常相似,因为它可以保存 8 位(1 字节)的值。“B”寄存器仅由两个 8051 指令使用: MUL ABDIV AB 。为了快速轻松地将 A 乘以或除以另一个数字,你可以将另一个数字存储在“B”中并使用这两个指令。除了使用 MUL 和 DIV 指令之外,“B”寄存器通常用作另一个临时存储寄存器,很像第九个 R 寄存器。

The "B" register is very similar to the Accumulator in the sense that it may hold an 8-bit (1-byte) value. The "B" register is used only by two 8051 instructions: MUL AB and DIV AB. To quickly and easily multiply or divide A by another number, you may store the other number in "B" and make use of these two instructions. Apart from using MUL and DIV instructions, the "B" register is often used as yet another temporary storage register, much like a ninth R register.

The Data Pointer

数据指针 (DPTR) 是 8051 唯一可由用户访问的 16 位(2 字节)寄存器。累加器、R0–R7 寄存器和 B 寄存器是 1 字节值寄存器。DPTR 用于指向数据。它由 8051 使用,并使用 DPTR 指示的地址访问外部存储器。DPTR 是唯一可用的 16 位寄存器,通常用于存储 2 字节值。

The Data Pointer (DPTR) is the 8051’s only user-accessible 16-bit (2-byte) register. The Accumulator, R0–R7 registers and B register are 1-byte value registers. DPTR is meant for pointing to data. It is used by the 8051 to access external memory using the address indicated by DPTR. DPTR is the only 16-bit register available and is often used to store 2-byte values.

The Program Counter

程序计数器 (PC) 是一个 2 字节地址,用于告诉 8051 在存储器中可以找到要执行的下一条指令。在 8051 初始化时,PC 从 0000h 开始,并在每次执行指令后递增。PC 并不总是递增 1。有些指令可能需要 2 或 3 个字节;在这种情况下,PC 将递增 2 或 3。

The Program Counter (PC) is a 2-byte address which tells the 8051 where the next instruction to execute can be found in the memory. PC starts at 0000h when the 8051 initializes and is incremented every time after an instruction is executed. PC is not always incremented by 1. Some instructions may require 2 or 3 bytes; in such cases, the PC will be incremented by 2 or 3.

Branch, jumpinterrupt 操作使用除下一个顺序位置之外的地址加载程序计数器。激活上电复位将导致寄存器中的所有值丢失。这意味着 PC 的值在复位时为 0,强制 CPU 从 ROM 位置 0000 获取第一个操作码。这意味着我们必须将第一个字节的命令放在 ROM 位置 0000,因为这是 CPU 期望找到第一条指令的位置。

Branch, jump, and interrupt operations load the Program Counter with an address other than the next sequential location. Activating a power-on reset will cause all values in the register to be lost. It means the value of the PC is 0 upon reset, forcing the CPU to fetch the first opcode from the ROM location 0000. It means we must place the first byte of upcode in ROM location 0000 because that is where the CPU expects to find the first instruction.

The Stack Pointer (SP)

堆栈指针与除 DPTR 和 PC 之外的所有寄存器一样,都可以保存 8 位(1 字节)的值。堆栈指针指示从该位置移走堆栈中下一个值的位置。当一个值被压入堆栈时,SP 的值会递增,然后该值会存储在生成的存储器位置。当一个值从堆栈中弹出时,该值将从 SP 指示的存储器位置返回,然后递减 SP 的值。

The Stack Pointer, like all registers except DPTR and PC, may hold an 8-bit (1-byte) value. The Stack Pointer tells the location from where the next value is to be removed from the stack. When a value is pushed onto the stack, the value of SP is incremented and then the value is stored at the resulting memory location. When a value is popped off the stack, the value is returned from the memory location indicated by SP, and then the value of SP is decremented.

此操作顺序很重要。当 8051 初始化时,SP 将初始化为 07h。如果同时将值压入堆栈,则该值将存储在内部 RAM 地址 08h,因为 8051 会首先递增 SP 的值(从 07h 到 08h),然后将压入的值存储在该存储器地址(08h)。SP 由 8051 通过六条指令直接修改:PUSH、POP、ACALL、LCALL、RET 和 RETI。

This order of operation is important. SP will be initialized to 07h when the 8051 is initialized. If a value is pushed onto the stack at the same time, the value will be stored in the internal RAM address 08h because the 8051 will first increment the value of SP (from 07h to 08h) and then will store the pushed value at that memory address (08h). SP is modified directly by the 8051 by six instructions: PUSH, POP, ACALL, LCALL, RET, and RETI.

ROM Space in 8051

8051 的某些系列成员仅有 4K 字节的片上 ROM(例如 8751、AT8951);有些有 8K ROM,例如 AT89C52,还有一些系列成员有 32K 字节和 64K 字节的片上 ROM,例如 Dallas Semiconductor。需要记住的一点是,8051 系列的任何成员都无法访问超过 64K 字节的操作码,因为 8051 中的程序计数器是一个 16 位寄存器(0000 到 FFFF 地址)。

Some family members of 8051 have only 4K bytes of on-chip ROM (e.g. 8751, AT8951); some have 8K ROM like AT89C52, and there are some family members with 32K bytes and 64K bytes of on-chip ROM such as Dallas Semiconductor. The point to remember is that no member of the 8051 family can access more than 64K bytes of opcode since the program counter in 8051 is a 16-bit register (0000 to FFFF address).

8051 内部程序 ROM 的第一个位置的地址为 0000H,而最后一个位置可能根据芯片上 ROM 的大小而不同。在 8051 系列成员中,AT8951 具有 $k 字节的片上 ROM,其存储器地址为 0000(第一个位置)到 0FFFH(最后一个位置)。

The first location of the program ROM inside the 8051 has the address of 0000H, whereas the last location can be different depending on the size of the ROM on the chip. Among the 8051 family members, AT8951 has $k bytes of on-chip ROM having a memory address of 0000 (first location) to 0FFFH (last location).

rom space

8051 Flag Bits and PSW Register

程序状态字 (PSW) 寄存器是一个 8 位寄存器,也称为 flag register 。它有 8 位宽,但只使用了 6 位。两个未使用的位是 user-defined flags 。四个标志被称为 conditional flags ,这意味着它们表示执行指令后产生的条件。这四种标志是 CY *(Carry), *AC (辅助进位)、 P (奇偶校验)和 OV (溢出)。位 RS0 和 RS1 用于更改寄存器组。下图显示了程序状态字寄存器。

The program status word (PSW) register is an 8-bit register, also known as flag register. It is of 8-bit wide but only 6-bit of it is used. The two unused bits are user-defined flags. Four of the flags are called conditional flags, which means that they indicate a condition which results after an instruction is executed. These four are CY *(Carry), *AC (auxiliary carry), P (parity), and OV (overflow). The bits RS0 and RS1 are used to change the bank registers. The following figure shows the program status word register.

PSW 寄存器包含反映 CPU 当前状态的状态位。

The PSW Register contains that status bits that reflect the current status of the CPU.

CY

CA

F0

RS1

RS0

OV

-

P

CY

PSW.7

Carry Flag

AC

PSW.6

Auxiliary Carry Flag

F0

PSW.5

Flag 0 available to user for general purpose.

RS1

PSW.4

Register Bank selector bit 1

RS0

PSW.3

Register Bank selector bit 0

OV

PSW.2

Overflow Flag

-

PSW.1

User definable FLAG

P

PSW.0

Parity FLAG. Set/ cleared by hardware during instruction cycle to indicate even/odd number of 1 bit in accumulator.

我们可以使用 RS0 和 RS1 位选择相应的寄存器组位。

We can select the corresponding Register Bank bit using RS0 and RS1 bits.

RS1

RS2

Register Bank

Address

0

0

0

00H-07H

0

1

1

08H-0FH

1

0

2

10H-17H

1

1

3

18H-1FH

  1. CY, the carry flag − This carry flag is set (1) whenever there is a carry out from the D7 bit. It is affected after an 8-bit addition or subtraction operation. It can also be reset to 1 or 0 directly by an instruction such as "SETB C" and "CLR C" where "SETB" stands for set bit carry and "CLR" stands for clear carry.

  2. AC, auxiliary carry flag − If there is a carry from D3 and D4 during an ADD or SUB operation, the AC bit is set; otherwise, it is cleared. It is used for the instruction to perform binary coded decimal arithmetic.

  3. P, the parity flag − The parity flag represents the number of 1’s in the accumulator register only. If the A register contains odd number of 1’s, then P = 1; and for even number of 1’s, P = 0.

  4. OV, the overflow flag − This flag is set whenever the result of a signed number operation is too large causing the high-order bit to overflow into the sign bit. It is used only to detect errors in signed arithmetic operations.

Example

在以下指令中,显示 ADD 9CH 和 64H 后的 CY、AC 和 P 标志的状态。

Show the status of CY, AC, and P flags after the addition of 9CH and 64H in the following instruction.

MOV A, #9CH

ADD A, # 64H

Solution:  9C   10011100
          +64   01100100
          100   00000000

CY = 1 since there is a carry beyond D7 bit
AC = 0 since there is a carry from D3 to D4
P  = 0 because the accumulator has even number of 1's

Embedded Systems - Registers Bank/Stack

8051 微控制器总共拥有 128 字节的 RAM。我们将讨论如何分配这 128 字节的 RAM,并研究其作为堆栈和寄存器的用途。

The 8051 microcontroller has a total of 128 bytes of RAM. We will discuss about the allocation of these 128 bytes of RAM and examine their usage as stack and register.

RAM Memory Space Allocation in 8051

8051 中的 128 字节的 RAM 被分配了地址 00 至 7FH。它们可以直接作为内存位置进行访问,并被划分为三个不同的组,如下所示 −

The 128 bytes of RAM inside the 8051 are assigned the address 00 to 7FH. They can be accessed directly as memory locations and are divided into three different groups as follows −

  1. 32 bytes from 00H to 1FH locations are set aside for register banks and the stack.

  2. 16 bytes from 20H to 2FH locations are set aside for bit-addressable read/write memory.

  3. 80 bytes from 30H to 7FH locations are used for read and write storage; it is called as scratch pad. These 80 locations RAM are widely used for the purpose of storing data and parameters by 8051 programmers.

rom allocation

Register Banks in 8051

总共 32 字节的 RAM 被预留给寄存器组和堆栈。这 32 个字节被划分为四个寄存器组,其中每个组有 8 个寄存器,R0-R7。RAM 位置 0 到 7 被预留给 R0-R7 的组 0,其中 R0 是 RAM 位置 0,R1 是 RAM 位置 1,R2 是位置 2,依此类推,直到内存位置 7,属于组 0 的 R7。

A total of 32 bytes of RAM are set aside for the register banks and the stack. These 32 bytes are divided into four register banks in which each bank has 8 registers, R0–R7. RAM locations from 0 to 7 are set aside for bank 0 of R0–R7 where R0 is RAM location 0, R1 is RAM location 1, R2 is location 2, and so on, until the memory location 7, which belongs to R7 of bank 0.

第二个 R0-R7 寄存器组从 RAM 位置 08 开始,到位置 OFH。第三个 R0-R7 组从内存位置 10H 开始,到位置 17H。最后,RAM 位置 18H 到 1FH 被预留给第四个 R0-R7 组。

The second bank of registers R0–R7 starts at RAM location 08 and goes to locations OFH. The third bank of R0–R7 starts at memory location 10H and goes to location to 17H. Finally, RAM locations 18H to 1FH are set aside for the fourth bank of R0–R7.

Default Register Bank

如果将 RAM 位置 00-1F 预留给四个寄存器组,那么在 8051 上电时,我们可以访问哪个寄存器组的 R0-R7?答案是寄存器组 0;即在对 8051 进行编程时,可以用名称 R0 到 R7 访问 RAM 位置 0 到 7。因为用名称(例如 R0 到 R7)引用这些 RAM 位置比用它们的内存位置容易得多。

If RAM locations 00–1F are set aside for the four registers banks, which register bank of R0–R7 do we have access to when the 8051 is powered up? The answer is register bank 0; that is, RAM locations from 0 to 7 are accessed with the names R0 to R7 when programming the 8051. Because it is much easier to refer these RAM locations by names such as R0 to R7, rather than by their memory locations.

How to Switch Register Banks

当 8051 上电时,寄存器组 0 是默认值。我们可以使用 PSW 寄存器切换到其他组。PSW 的 D4 和 D3 位用于选择所需的寄存器组,因为可以通过按位寻址指令 SETB 和 CLR 访问它们。例如,“SETB PSW.3”将设置 PSW.3 = 1 并选择组寄存器 1。

Register bank 0 is the default when the 8051 is powered up. We can switch to the other banks using PSW register. D4 and D3 bits of the PSW are used to select the desired register bank, since they can be accessed by the bit addressable instructions SETB and CLR. For example, "SETB PSW.3" will set PSW.3 = 1 and select the bank register 1.

RS1

RS2

Bank Selected

0

0

Bank0

0

1

Bank1

1

0

Bank2

1

1

Bank3

Stack and its Operations

Stack in the 8051

堆栈是 CPU 使用的一段 RAM,用于临时存储数据或内存地址等信息。考虑到寄存器的数量有限,CPU 需要这个存储区域。

The stack is a section of a RAM used by the CPU to store information such as data or memory address on temporary basis. The CPU needs this storage area considering limited number of registers.

How Stacks are Accessed

由于堆栈是一段 RAM,因此 CPU 内部有寄存器可以指向它。用于访问堆栈的寄存器称为堆栈指针寄存器。8051 中的堆栈指针是 8 位宽,它可以取 00 到 FFH 的值。当 8051 初始化时,SP 寄存器包含值 07H。这意味着 RAM 位置 08 是用于堆栈的第一个位置。将 CPU 寄存器存储在堆栈中的操作称为 PUSH ,将内容从堆栈获取回 CPU 寄存器称为 POP

As the stack is a section of a RAM, there are registers inside the CPU to point to it. The register used to access the stack is known as the stack pointer register. The stack pointer in the 8051 is 8-bits wide, and it can take a value of 00 to FFH. When the 8051 is initialized, the SP register contains the value 07H. This means that the RAM location 08 is the first location used for the stack. The storing operation of a CPU register in the stack is known as a PUSH, and getting the contents from the stack back into a CPU register is called a POP.

Pushing into the Stack

在 8051 中,堆栈指针 (SP) 指向堆栈的最后使用位置。将数据压入堆栈时,堆栈指针 (SP) 会增加 1。执行 PUSH 时,寄存器的内容将保存在堆栈中,并且 SP 会增加 1。若要将寄存器推送到堆栈,我们必须使用它们的 RAM 地址。例如,指令“PUSH 1”将寄存器 R1 推送到堆栈。

In the 8051, the stack pointer (SP) points to the last used location of the stack. When data is pushed onto the stack, the stack pointer (SP) is incremented by 1. When PUSH is executed, the contents of the register are saved on the stack and SP is incremented by 1. To push the registers onto the stack, we must use their RAM addresses. For example, the instruction "PUSH 1" pushes register R1 onto the stack.

Popping from the Stack

将堆栈的内容弹出到给定寄存器的过程与推送过程相反。对于每次弹出操作,堆栈的顶部字节将被复制到指令指定的寄存器,并且堆栈指针将递减一次。

Popping the contents of the stack back into a given register is the opposite to the process of pushing. With every pop operation, the top byte of the stack is copied to the register specified by the instruction and the stack pointer is decremented once.

Embedded Systems - Instructions

程序流程按顺序进行,从一条指令到下一条指令,除非执行了控制传递指令。汇编语言中的各种类型的控制传递指令包括条件或无条件跳转和调用指令。

The flow of program proceeds in a sequential manner, from one instruction to the next instruction, unless a control transfer instruction is executed. The various types of control transfer instruction in assembly language include conditional or unconditional jumps and call instructions.

Loop and Jump Instructions

Looping in the 8051

重复执行一系列指令的特定次数称为 loop 。指令 DJNZ reg, label 用于执行循环操作。在此指令中,寄存器减 1;如果不为零,则 8051 跳到由标签所引用的目标地址。

Repeating a sequence of instructions a certain number of times is called a loop. An instruction DJNZ reg, label is used to perform a Loop operation. In this instruction, a register is decremented by 1; if it is not zero, then 8051 jumps to the target address referred to by the label.

在循环开始前,用重复次数的计数器加载寄存器。在此指令中,寄存器减量和跳跃决策合并为一条指令。寄存器可以是 R0-R7 中的任何一个。计数器也可以是 RAM 位置。

The register is loaded with the counter for the number of repetitions prior to the start of the loop. In this instruction, both the registers decrement and the decision to jump are combined into a single instruction. The registers can be any of R0–R7. The counter can also be a RAM location.

Example

Multiply 25 by 10 using the technique of repeated addition.

Multiply 25 by 10 using the technique of repeated addition.

Solution − 乘法可以通过多次相加乘数来实现,次数与乘数相同。例如,

Solution − Multiplication can be achieved by adding the multiplicand repeatedly, as many times as the multiplier. For example,

25 * 10 = 250(FAH)

25 + 25 + 25 + 25 + 25 + 25 + 25 + 25 + 25 + 25 = 250

   MOV A,#0             ;A = 0,clean ACC
   MOV R2,#10           ; the multiplier is replaced in R2
   Add A,#25            ;add the multiplicand to the ACC

AGAIN:DJNZ R2,
AGAIN:repeat  until R2 = 0 (10 times)

   MOV R5 , A           ;save A in R5 ;R5 (FAH)

Drawback in 8051 − 使用指令 DJNZ Reg label 的循环操作仅限于 256 次迭代。如果未执行条件跳转,则执行跳转后的指令。

Drawback in 8051 − Looping action with the instruction DJNZ Reg label is limited to 256 iterations only. If a conditional jump is not taken, then the instruction following the jump is executed.

Looping inside a Loop

当我们在另一个循环内使用循环时,它被称为 nested loop 。当最大计数限制为 256 时,使用两个寄存器来保存计数。因此,我们使用这种方法来重复执行操作超过 256 次。

When we use a loop inside another loop, it is called a nested loop. Two registers are used to hold the count when the maximum count is limited to 256. So we use this method to repeat the action more times than 256.

Example

编写一个程序 −

Write a program to −

  1. Load the accumulator with the value 55H.

  2. Complement the ACC 700 times.

Solution − 由于 700 大于 255(任何寄存器的最大容量),因此使用两个寄存器来保存计数。以下代码展示如何对 R2 和 R3 这两个寄存器进行计数。

Solution − Since 700 is greater than 255 (the maximum capacity of any register), two registers are used to hold the count. The following code shows how to use two registers, R2 and R3, for the count.

   MOV A,#55H            ;A = 55H

NEXT: MOV R3,#10         ;R3 the outer loop counter
AGAIN:MOV R2,#70         ;R2 the inner loop counter

   CPL A                 ;complement

Other Conditional Jumps

下表列出了 8051 中使用的条件跳转 −

The following table lists the conditional jumps used in 8051 −

Instruction

Action

JZ

Jump if A = 0

JNZ

Jump if A ≠ 0

DJNZ

Decrement and Jump if register ≠ 0

CJNE A, data

Jump if A ≠ data

CJNE reg, #data

Jump if byte ≠ data

JC

Jump if CY = 1

JNC

Jump if CY ≠ 1

JB

Jump if bit = 1

JNB

Jump if bit = 0

JBC

Jump if bit = 1 and clear bit

  1. JZ (jump if A = 0) − In this instruction, the content of the accumulator is checked. If it is zero, then the 8051 jumps to the target address. JZ instruction can be used only for the accumulator, it does not apply to any other register.

  2. JNZ (jump if A is not equal to 0) − In this instruction, the content of the accumulator is checked to be non-zero. If it is not zero, then the 8051 jumps to the target address.

  3. JNC (Jump if no carry, jumps if CY = 0) − The Carry flag bit in the flag (or PSW) register is used to make the decision whether to jump or not "JNC label". The CPU looks at the carry flag to see if it is raised (CY = 1). If it is not raised, then the CPU starts to fetch and execute instructions from the address of the label. If CY = 1, it will not jump but will execute the next instruction below JNC.

  4. JC (Jump if carry, jumps if CY = 1) − If CY = 1, it jumps to the target address.

  5. JB (jump if bit is high)

  6. JNB (jump if bit is low)

Note − 必须注意,所有条件跳转都是短跳转,即目标地址必须在程序计数器内容的 -128 到 +127 字节内。

Note − It must be noted that all conditional jumps are short jumps, i.e., the address of the target must be within –128 to +127 bytes of the contents of the program counter.

Unconditional Jump Instructions

8051 中有两个无条件跳转 −

There are two unconditional jumps in 8051 −

  1. LJMP (long jump) − LJMP is 3-byte instruction in which the first byte represents opcode, and the second and third bytes represent the 16-bit address of the target location. The 2-byte target address is to allow a jump to any memory location from 0000 to FFFFH.

  2. SJMP (short jump) − It is a 2-byte instruction where the first byte is the opcode and the second byte is the relative address of the target location. The relative address ranges from 00H to FFH which is divided into forward and backward jumps; that is, within –128 to +127 bytes of memory relative to the address of the current PC (program counter). In case of forward jump, the target address can be within a space of 127 bytes from the current PC. In case of backward jump, the target address can be within –128 bytes from the current PC.

Calculating the Short Jump Address

所有条件跳转(JNC、JZ 和 DJNZ)都是短跳转,因为它们是 2 字节指令。在这些指令中,第一个字节表示操作码,第二个字节表示相对地址。目标地址始终相对于程序计数器的值。要计算目标地址,将第二个字节添加到紧跟在跳转之下的指令的 PC。看看下面给出的程序 −

All conditional jumps (JNC, JZ, and DJNZ) are short jumps because they are 2-byte instructions. In these instructions, the first byte represents opcode and the second byte represents the relative address. The target address is always relative to the value of the program counter. To calculate the target address, the second byte is added to the PC of the instruction immediately below the jump. Take a look at the program given below −

Line   PC    Op-code   Mnemonic   Operand
1      0000               ORG       0000
2      0000  7800         MOV       R0,#003
3      0002  7455         MOV       A,#55H0
4      0004  6003         JZ        NEXT
5      0006  08           INC       R0
6      0007  04   AGAIN:  INC       A
7      0008  04           INC       A
8      0009  2477 NEXT:   ADD       A, #77h
9      000B  5005         JNC       OVER
10     000D  E4           CLR       A
11     000E  F8           MOV       R0, A
12     000F  F9           MOV       R1, A
13     0010  FA          MOV       R2, A
14     0011  FB           MOV       R3, A
15     0012  2B   OVER:   ADD       A, R3
16     0013  50F2         JNC       AGAIN
17     0015  80FE HERE:   SJMP      HERE
18     0017             END

Backward Jump Target Address Calculation

对于正向跳转,偏移值是 0 到 127(十六进制为 00 到 7F)之间的正数。但是,对于反向跳转,偏移量是 0 到 -128 的负值。

In case of a forward jump, the displacement value is a positive number between 0 to 127 (00 to 7F in hex). However, for a backward jump, the displacement is a negative value of 0 to –128.

CALL Instructions

CALL 用于调用子例程或方法。子例程用于执行需要频繁执行的操作或任务。这使程序更具结构性并节省了内存空间。有两个指令 − LCALL 和 ACALL。

CALL is used to call a subroutine or method. Subroutines are used to perform operations or tasks that need to be performed frequently. This makes a program more structured and saves memory space. There are two instructions − LCALL and ACALL.

LCALL (Long Call)

LCALL 是 3 字节指令,其中第一个字节表示操作码,第二个和第三个字节用于提供目标子例程的地址。LCALL 可用于调用在 8051 的 64K 字节地址空间内可用的子例程。

LCALL is a 3-byte instruction where the first byte represents the opcode and the second and third bytes are used to provide the address of the target subroutine. LCALL can be used to call subroutines which are available within the 64K-byte address space of the 8051.

为了在调用子例程执行之后成功返回到该点,CPU 将紧跟在 LCALL 下面的指令地址保存在堆栈上。因此,当调用子例程时,控制权将被转移到该子例程,并且处理器将 PC(程序计数器)保存在堆栈上并开始从新位置获取指令。子例程执行完后,RET(返回)指令将控制权转移回调用者。每个子例程都将 RET 用作最后一条指令。

To make a successful return to the point after execution of the called subroutine, the CPU saves the address of the instruction immediately below the LCALL on the stack. Thus, when a subroutine is called, the control is transferred to that subroutine, and the processor saves the PC (program counter) on the stack and begins to fetch instructions from the new location. The instruction RET (return) transfers the control back to the caller after finishing execution of the subroutine. Every subroutine uses RET as the last instruction.

ACALL (Absolute Call)

ACALL 是一条 2 字节指令,而 LCALL 为 3 字节。子例程的目标地址必须在 2K 字节以内,因为 2 字节中只有 11 位用于地址。ACALL 和 LCALL 间存在差异,因为 LCALL 的目标地址可在 8051 的 64K 字节地址空间中的任何位置,而 CALL 的目标地址则在 2K 字节范围中。

ACALL is a 2-byte instruction, in contrast to LCALL which is 3 bytes. The target address of the subroutine must be within 2K bytes because only 11 bits of the 2 bytes are used for address. The difference between the ACALL and LCALL is that the target address for LCALL can be anywhere within the 64K-bytes address space of the 8051, while the target address of CALL is within a 2K-byte range.

Embedded Systems - Addressing Modes

addressing mode 表示如何寻址给定的存储器位置。有五种不同的方式或五种寻址模式可用于执行此指令,如下所示 −

An addressing mode refers to how you are addressing a given memory location. There are five different ways or five addressing modes to execute this instruction which are as follows −

  1. Immediate addressing mode

  2. Direct addressing mode

  3. Register direct addressing mode

  4. Register indirect addressing mode

  5. Indexed addressing mode

Immediate Addressing Mode

让我们从一个示例开始。

Let’s begin with an example.

MOV A, #6AH

一般而言,我们可以编写,

In general, we can write,

MOV A, #data

它被称为 immediate ,因为 8 位数据即刻传输到累加器(目标操作数)。

It is termed as immediate because 8-bit data is transferred immediately to the accumulator (destination operand).

以下插图描述了上述指令及其执行。操作码 74H 保存于 0202 地址。数据 6AH 保存于程序存储器中的 0203 地址。在读取操作码 74H 后,下一个程序存储器地址中的数据将传输到累加器 A(E0H 是累加器的地址)。由于该指令为 2 字节并且在一个周期内执行,程序计数器将递增 2,并将指向程序存储器的 0204。

The following illustration describes the above instruction and its execution. The opcode 74H is saved at 0202 address. The data 6AH is saved at 0203 address in the program memory. After reading the opcode 74H, the data at the next program memory address is transferred to accumulator A (E0H is the address of accumulator). Since the instruction is of 2-bytes and is executed in one cycle, the program counter will be incremented by 2 and will point to 0204 of the program memory.

immidiate addressing mode

Note' symbol before 6AH indicates that the operand is a data (8 bit). In the absence of ' ,十六进制数字将作为地址。

Note − The '' symbol before 6AH indicates that the operand is a data (8 bit). In the absence of '', the hexadecimal number would be taken as an address.

Direct Addressing Mode

这是另一种寻址操作数的方式。在此,数据地址(源数据)提供为操作数。让我们举个例子。

This is another way of addressing an operand. Here, the address of the data (source data) is given as an operand. Let’s take an example.

MOV A, 04H

寄存器库#0(第 4 个寄存器)的地址为 04H。当执行 MOV 指令时,存储于寄存器 04H 中的数据将移动到累加器。由于寄存器 04H 保存数据 1FH,因此 1FH 移动到累加器。

The register bank#0 (4th register) has the address 04H. When the MOV instruction is executed, the data stored in register 04H is moved to the accumulator. As the register 04H holds the data 1FH, 1FH is moved to the accumulator.

Note − 我们未使用 ' in direct addressing mode, unlike immediate mode. If we had used ' ,数据值 04H 会传输到累加器,而不是 1FH。

Note − We have not used '' in direct addressing mode, unlike immediate mode. If we had used '', the data value 04H would have been transferred to the accumulator instead of 1FH.

现在,看一看以下插图。它显示了指令如何执行。

Now, take a look at the following illustration. It shows how the instruction gets executed.

direct addressing mode

如上图所示,这是一条 2 字节指令,需要 1 个周期才能完成。PC 将递增 2,并将指向 0204。指令 MOV A, address 的操作码为 E5H。当执行 0202 处的指令(E5H)时,累加器激活并准备接收数据。然后 PC 转到下一个地址 0203 并查找位置 04H 的地址,即源数据(传送到累加器)所在的位置。在 04H 处,控制找到数据 1F 并将其传输到累加器,因此完成执行。

As shown in the above illustration, this is a 2-byte instruction which requires 1 cycle to complete. The PC will be incremented by 2 and will point to 0204. The opcode for the instruction MOV A, address is E5H. When the instruction at 0202 is executed (E5H), the accumulator is made active and ready to receive data. Then the PC goes to the next address as 0203 and looks up the address of the location of 04H where the source data (to be transferred to accumulator) is located. At 04H, the control finds the data 1F and transfers it to the accumulator and hence the execution is completed.

Register Direct Addressing Mode

在此寻址模式中,我们直接使用寄存器名称(作为源操作数)。让我们尝试在示例中进行理解。

In this addressing mode, we use the register name directly (as source operand). Let us try to understand with the help of an example.

MOV A, R4

一次,寄存器可以获取从 R0 到 R7 的值。有 32 个这样的寄存器。为了使用 32 个寄存器仅使用 8 个变量来寻址寄存器,使用寄存器库。有 4 个寄存器库从 0 到 3 命名。每个库包含 8 个寄存器从 R0 到 R7 命名。

At a time, the registers can take values from R0 to R7. There are 32 such registers. In order to use 32 registers with just 8 variables to address registers, register banks are used. There are 4 register banks named from 0 to 3. Each bank comprises of 8 registers named from R0 to R7.

一次,可以选取单个寄存器库。通过名为 Special Function Register (SFR)的 Processor Status Word (PSW)可以选取寄存器库。PSW 是一个 8 位 SFR,其中每位可以根据需要进行编程。位从 PSW.0 指定到 PSW.7。PSW.3 和 PSW.4 用于选取寄存器库。

At a time, a single register bank can be selected. Selection of a register bank is made possible through a Special Function Register (SFR) named Processor Status Word (PSW). PSW is an 8-bit SFR where each bit can be programmed as required. Bits are designated from PSW.0 to PSW.7. PSW.3 and PSW.4 are used to select register banks.

现在,看一看以下插图,从而清晰了解它是如何工作的。

Now, take a look at the following illustration to get a clear understanding of how it works.

register direct mode

操作码 EC 用于 MOV A,R4。操作码存储于地址 0202 处,当执行它时,控制直接转到所选 PSW 中的寄存器库的 R4(即 PSW 中选择的)。如果选取寄存器库#0,则寄存器库#0 的 R4 中的数据将移动到累加器。此处 2F 存储于 04H。04H 表示寄存器库#0 的 R4 的地址。

Opcode EC is used for MOV A, R4. The opcode is stored at the address 0202 and when it is executed, the control goes directly to R4 of the respected register bank (that is selected in PSW). If register bank #0 is selected, then the data from R4 of register bank #0 will be moved to the accumulator. Here 2F is stored at 04H. 04H represents the address of R4 of register bank #0.

数据(2F)移动以粗体突出显示。2F 从数据存储器位置 0CH 传输到累加器,并显示为虚线。0CH 是寄存器库#1 的寄存器 4(R4)的地址位置。上述指令为 1 字节,需要 1 个周期才能完全执行。这意味着,你可以使用寄存器直接寻址模式来保存程序存储器。

Data (2F) movement is highlighted in bold. 2F is getting transferred to the accumulator from data memory location 0C H and is shown as dotted line. 0CH is the address location of Register 4 (R4) of register bank #1. The instruction above is 1 byte and requires 1 cycle for complete execution. What it means is, you can save program memory by using register direct addressing mode.

Register Indirect Addressing Mode

在此寻址模式中,数据地址存储于操作数中的寄存器内。

In this addressing mode, the address of the data is stored in the register as operand.

MOV A, @R0

此处 R0 中的值被视为地址,其中包含要传输到累加器的值。 Example : 如果 R0 的值为 20H,并且数据 2FH 存储在地址 20H 中,那么在执行此指令后,值 2FH 将传输到累加器中。请参见以下说明:

Here the value inside R0 is considered as an address, which holds the data to be transferred to the accumulator. Example: If R0 has the value 20H, and data 2FH is stored at the address 20H, then the value 2FH will get transferred to the accumulator after executing this instruction. See the following illustration.

register indirect mode

因此 MOV A, @R0 的操作码为 E6H。假设选择了寄存器组 #0,则寄存器组 #0 的 R0 保存数据 20H。程序控制移动到 20H,它在其中找到数据 2FH 并将其传输到 2FH,累加器。这是一条 1 字节指令,程序计数器递增 1 并且移动到程序存储器的 0203。

So the opcode for MOV A, @R0 is E6H. Assuming that the register bank #0 is selected, the R0 of register bank #0 holds the data 20H. Program control moves to 20H where it locates the data 2FH and it transfers 2FH to the accumulator. This is a 1-byte instruction and the program counter increments by 1 and moves to 0203 of the program memory.

Note - 仅允许 R0 和 R1 形成寄存器间接寻址指令。换句话说,程序员可以使用 @R0 或 @R1 创建指令。所有寄存器组均被允许。

Note − Only R0 and R1 are allowed to form a register indirect addressing instruction. In other words, the programmer can create an instruction either using @R0 or @R1. All register banks are allowed.

Indexed Addressing Mode

我们将举两个示例以理解索引寻址模式的概念。请看以下说明:

We will take two examples to understand the concept of indexed addressing mode. Take a look at the following instructions −

MOVC A, @A+DPTR

MOVC A, @A+DPTR

and

MOVC A, @A+PC

MOVC A, @A+PC

其中 DPTR 是数据指针,PC 是程序计数器(两者都是 16 位寄存器)。考虑第一个示例。

where DPTR is the data pointer and PC is the program counter (both are 16-bit registers). Consider the first example.

MOVC A, @A+DPTR

源操作数为 @A+DPTR。它包含此位置的源数据。在这里,我们正在将 DPTR 的内容与累加器的当前内容相加。此加法将给出一个新地址,该地址是源数据的地址。然后将此地址指出的数据传输到累加器。

The source operand is @A+DPTR. It contains the source data from this location. Here we are adding the contents of DPTR with the current content of the accumulator. This addition will give a new address which is the address of the source data. The data pointed by this address is then transferred to the accumulator.

indexed mode

操作码为 93H。DPTR 的值为 01FE,其中 01 位于 DPH(高 8 位)中,FE 位于 DPL(低 8 位)中。累加器的值为 02H。然后执行 16 位加法,01FE H+02H 得到 0200 H。位于位置 0200H 的数据将传输到累加器。累加器中的前一个值(02H)将被 0200H 中的新值替换。说明中的累加器中的新数据将突出显示。

The opcode is 93H. DPTR has the value 01FE, where 01 is located in DPH (higher 8 bits) and FE is located in DPL (lower 8 bits). Accumulator has the value 02H. Then a 16-bit addition is performed and 01FE H+02H results in 0200 H. Data at the location 0200H will get transferred to the accumulator. The previous value inside the accumulator (02H) will be replaced with the new data from 0200H. The new data in the accumulator is highlighted in the illustration.

这是一条 1 字节指令,执行需要 2 个周期,与之前的指令(每个都是 1 个周期)相比,此指令所需的执行时间较长。

This is a 1-byte instruction with 2 cycles needed for execution and the execution time required for this instruction is high compared to previous instructions (which were all 1 cycle each).

另一个示例 MOVC A, @A+PC 的工作方式与上述示例相同。在这里,不是将 DPTR 与累加器相加,而是将程序计数器(PC)中的数据与累加器相加以获得目标地址。

The other example MOVC A, @A+PC works the same way as the above example. Instead of adding DPTR with the accumulator, here the data inside the program counter (PC) is added with the accumulator to obtain the target address.

Embedded Systems - SFR Registers

专用功能寄存器(或特殊目的寄存器,或简称特殊寄存器)是微处理器内部的一个寄存器,用于控制或监视微处理器的各种功能。由于特殊寄存器与处理器的某些特殊功能或状态密切相关,因此可能无法通过普通指令(如加、移动等)直接写入它们。相反,某些处理器架构中的一些特殊寄存器需要特殊指令才能对其进行修改。

A Special Function Register (or Special Purpose Register, or simply Special Register) is a register within a microprocessor that controls or monitors the various functions of a microprocessor. As the special registers are closely tied to some special function or status of the processor, they might not be directly writable by normal instructions (like add, move, etc.). Instead, some special registers in some processor architectures require special instructions to modify them.

在 8051 中,寄存器 A、B、DPTR 和 PSW 是通常称为 SFR(特殊功能寄存器)的寄存器组的一部分。可以通过 SFR 的名称或其地址来访问 SFR。

In the 8051, register A, B, DPTR, and PSW are a part of the group of registers commonly referred to as SFR (special function registers). An SFR can be accessed by its name or by its address.

下表显示了 SFR 及其地址的列表。

The following table shows a list of SFRs and their addresses.

Byte Address

Bit Address

FF

F0

F7

F6

F5

F4

F3

F2

F1

F0

B

E0

E7

E6

E5

E4

E3

E2

E1

E0

ACC

D0

D7

D6

D5

D4

D3

D2

-

D0

PSW

B8

-

-

-

BC

BB

BA

B9

B8

IP

B0

B7

B6

B5

B4

B3

B2

B1

B0

P3

A2

AF

-

-

AC

AB

AA

A9

A8

IE

A0

A7

A6

A5

A4

A3

A2

A1

A0

P2

99

Not bit Addressable

SBUF

98

9F

9E

9D

9C

9B

9A

99

98

SCON

90

97

96

95

94

93

92

91

90

P1

8D

Not bit Addressable

TH1

8C

Not bit Addressable

TH0

8B

Not bit Addressable

TL1

8A

Not bit Addressable

TL0

89

Not bit Addressable

TMOD

88

8F

8E

8D

8C

8B

8A

89

88

TCON

87

Not bit Addressable

PCON

83

Not bit Addressable

DPH

82

Not bit Addressable

DPL

81

Not bit Addressable

SP

80

87

87

85

84

83

82

81

关于 SFR 地址,请考虑到以下两点。

Consider the following two points about the SFR addresses.

  1. A special function register can have an address between 80H to FFH. These addresses are above 80H, as the addresses from 00 to 7FH are the addresses of RAM memory inside the 8051.

  2. Not all the address space of 80 to FF are used by the SFR. Unused locations, 80H to FFH, are reserved and must not be used by the 8051 programmer.

CY

PSW.7

Carry Flag

AC

PSW.6

Auxiliary Carry Flag

F0

PSW.5

Flag 0 available to user for general purpose.

RS1

PSW.4

Register Bank selector bit 1

RS0

PSW.3

Register Bank selector bit 0

OV

PSW.2

Overflow Flag

-

PSW.1

User definable FLAG

P

PSW.0

Parity FLAG. Set/ cleared by hardware during instruction cycle to indicate even/odd number of 1 bit in accumulator.

在以下示例中,SFR 寄存器的名称用其地址替换。

In the following example, the SFR registers’ names are replaced with their addresses.

CY

AC

F0

RS1

RS0

OV

-

P

我们可以使用 RS0 和 RS1 位选择相应的寄存器组位。

We can select the corresponding Register Bank bit using RS0 and RS1 bits.

RS1

RS2

Register Bank

Address

0

0

0

00H-07H

0

1

1

08H-0FH

1

0

2

10H-17H

1

1

3

18H-1FH

程序状态字 (PSW) 包含状态位以反映 CPU 的当前状态。8051 变体提供一个特殊功能寄存器 PSW,其中包含此状态信息。8251 提供两个附加状态标志,Z 和 N,可在称为 PSW1 的第二个特殊功能寄存器中使用。

The Program Status Word (PSW) contains status bits to reflect the current state of the CPU. The 8051 variants provide one special function register, PSW, with this status information. The 8251 provides two additional status flags, Z and N, which are available in a second special function register called PSW1.

Embedded Systems - Timer/Counter

timer 是一种用于测量时间间隔的特殊时钟类型。经常被称为用于测量经过时间从零向上计数的计时器 stopwatch 。它是一种根据指定时间间隔倒数并用于产生时间延迟的设备,例如,沙漏是一种计时器。

A timer is a specialized type of clock which is used to measure time intervals. A timer that counts from zero upwards for measuring time elapsed is often called a stopwatch. It is a device that counts down from a specified time interval and used to generate a time delay, for example, an hourglass is a timer.

counter 是一种存储(有时显示)特定事件或过程相对于时钟信号发生次数的设备。它用于计算微控制器外部发生的事件。在电子领域,可以使用寄存器类型电路(例如触发器)轻松实现计数器。

A counter is a device that stores (and sometimes displays) the number of times a particular event or process occurred, with respect to a clock signal. It is used to count the events happening outside the microcontroller. In electronics, counters can be implemented quite easily using register-type circuits such as a flip-flop.

Difference between a Timer and a Counter

将计时器与计数器区分开来的点如下:

The points that differentiate a timer from a counter are as follows −

Timer

Counter

The register incremented for every machine cycle.

The register is incremented considering 1 to 0 transition at its corresponding to an external input pin (T0, T1).

Maximum count rate is 1/12 of the oscillator frequency.

Maximum count rate is 1/24 of the oscillator frequency.

A timer uses the frequency of the internal clock, and generates delay.

A counter uses an external signal to count pulses.

Timers of 8051 and their Associated Registers

8051 有两个定时器,Timer 0 和 Timer 1。它们可用作定时器或事件计数器。Timer 0 和 Timer 1 均为 16 位宽。由于 8051 遵循 8 位架构,因此每个 16 位可作为低字节和高字节的两个独立寄存器访问。

The 8051 has two timers, Timer 0 and Timer 1. They can be used as timers or as event counters. Both Timer 0 and Timer 1 are 16-bit wide. Since the 8051 follows an 8-bit architecture, each 16 bit is accessed as two separate registers of low-byte and high-byte.

Timer 0 Register

Timer 0 的 16 位寄存器以低字节和高字节的形式访问。低字节寄存器称为 TL0(Timer 0 低字节),高字节寄存器称为 TH0(Timer 0 高字节)。这些寄存器可像任何其他寄存器一样访问。例如,指令 MOV TL0, #4H 将值移入 Timer #0 的低字节。

The 16-bit register of Timer 0 is accessed as low- and high-byte. The low-byte register is called TL0 (Timer 0 low byte) and the high-byte register is called TH0 (Timer 0 high byte). These registers can be accessed like any other register. For example, the instruction MOV TL0, #4H moves the value into the low-byte of Timer #0.

timer0

Timer 1 Register

Timer 1 的 16 位寄存器以低字节和高字节的形式访问。低字节寄存器称为 TL1(Timer 1 低字节),高字节寄存器称为 TH1(Timer 1 高字节)。这些寄存器可像任何其他寄存器一样访问。例如,指令 MOV TL1, #4H 将值移入 Timer 1 的低字节。

The 16-bit register of Timer 1 is accessed as low- and high-byte. The low-byte register is called TL1 (Timer 1 low byte) and the high-byte register is called TH1 (Timer 1 high byte). These registers can be accessed like any other register. For example, the instruction MOV TL1, #4H moves the value into the low-byte of Timer 1.

timer1

TMOD (Timer Mode) Register

Timer 0 和 Timer 1 都使用相同的寄存器来设置各种定时器操作模式。这是一个 8 位寄存器,其中低 4 位留给 Timer 0,高 4 位留给定时器。在每种情况下,低 2 位用于预先设置定时器模式,而高 2 位用于指定位置。

Both Timer 0 and Timer 1 use the same register to set the various timer operation modes. It is an 8-bit register in which the lower 4 bits are set aside for Timer 0 and the upper four bits for Timers. In each case, the lower 2 bits are used to set the timer mode in advance and the upper 2 bits are used to specify the location.

tmod

Gate − 设置后,定时器仅在 INT(0,1) 为高电平时运行。

Gate − When set, the timer only runs while INT(0,1) is high.

C/T − 计数器/定时器选择位。

C/T − Counter/Timer select bit.

M1 − 模式位 1。

M1 − Mode bit 1.

M0 − 模式位 0。

M0 − Mode bit 0.

GATE

每个定时器都有启动和停止的方法。一些定时器通过软件执行此操作,一些通过硬件执行,还有一些同时具有软件和硬件控制。8051 定时器具有软件和硬件控制。定时器的启动和停止由软件使用指令 SETB TR1CLR TR1 (对于定时器 1)以及 SETB TR0CLR TR0 (对于定时器 0)控制。

Every timer has a means of starting and stopping. Some timers do this by software, some by hardware, and some have both software and hardware controls. 8051 timers have both software and hardware controls. The start and stop of a timer is controlled by software using the instruction SETB TR1 and CLR TR1 for timer 1, and SETB TR0 and CLR TR0 for timer 0.

SETB 指令用于启动它,而 CLR 指令用于停止它。只要 TMOD 寄存器中的 GATE = 0,这些指令就会启动和停止定时器。通过使 TMOD 寄存器中的 GATE = 1,定时器可以由外部源启动和停止。

The SETB instruction is used to start it and it is stopped by the CLR instruction. These instructions start and stop the timers as long as GATE = 0 in the TMOD register. Timers can be started and stopped by an external source by making GATE = 1 in the TMOD register.

C/T (CLOCK / TIMER)

TMOD 寄存器中的此位用于决定是否使用定时器作为 delay generatorevent manager 。如果 C/T = 0,则将其用作定时器延迟生成。用于创建时延的时钟源是 8051 的晶体频率。如果 C/T = 0,则附加到 8051 的晶体频率也决定了 8051 定时器以规则间隔发出的滴答声的速度。

This bit in the TMOD register is used to decide whether a timer is used as a delay generator or an event manager. If C/T = 0, it is used as a timer for timer delay generation. The clock source to create the time delay is the crystal frequency of the 8051. If C/T = 0, the crystal frequency attached to the 8051 also decides the speed at which the 8051 timer ticks at a regular interval.

定时器频率总是附加到 8051 的晶体频率的 1/12。尽管基于 8051 的各种系统具有 10 MHz 到 40 MHz 的 XTAL 频率,但我们通常使用 11.0592 MHz 的 XTAL 频率。这是因为 8051 的串行通信波特率。XTAL = 11.0592 允许 8051 系统与 PC 通信且无错误。

Timer frequency is always 1/12th of the frequency of the crystal attached to the 8051. Although various 8051 based systems have an XTAL frequency of 10 MHz to 40 MHz, we normally work with the XTAL frequency of 11.0592 MHz. It is because the baud rate for serial communication of the 8051.XTAL = 11.0592 allows the 8051 system to communicate with the PC with no errors.

M1 / M2

M1

M2

Mode

0

0

13-bit timer mode.

0

1

16-bit timer mode.

1

0

8-bit auto reload mode.

1

1

Spilt mode.

Different Modes of Timers

Mode 0 (13-Bit Timer Mode)

在模式 0 下的 Timer 1 和 Timer 0 均作为 8 位计数器运行(带 32 位预分频器)。定时器寄存器配置为一个 13 位寄存器,由 TH1 的所有 8 位和 TL1 的低 5 位组成。TL1 的高 3 位是不确定的,应该忽略。设置运行标志 (TR1) 不会清除寄存器。当计数从所有 1 到所有 0 时,将设置定时器中断标志 TF1。对于 Timer 0,模式 0 操作与 Timer 1 相同。

Both Timer 1 and Timer 0 in Mode 0 operate as 8-bit counters (with a divide-by-32 prescaler). Timer register is configured as a 13-bit register consisting of all the 8 bits of TH1 and the lower 5 bits of TL1. The upper 3 bits of TL1 are indeterminate and should be ignored. Setting the run flag (TR1) does not clear the register. The timer interrupt flag TF1 is set when the count rolls over from all 1s to all 0s. Mode 0 operation is the same for Timer 0 as it is for Timer 1.

Mode 1 (16-Bit Timer Mode)

定时器模式 "1" 是一个 16 位定时器,是一种常用的模式。它的工作方式与 13 位模式相同,只是使用了所有 16 位。TLx 从 0 开始递增,最大为 255。达到值 255 后,TLx 重置为 0,然后 THx 递增 1。作为一个完整的 16 位定时器,该定时器最多可以包含 65536 个不同的值,并且在 65536 个机器周期后会溢出回 0。

Timer mode "1" is a 16-bit timer and is a commonly used mode. It functions in the same way as 13-bit mode except that all 16 bits are used. TLx is incremented starting from 0 to a maximum 255. Once the value 255 is reached, TLx resets to 0 and then THx is incremented by 1. As being a full 16-bit timer, the timer may contain up to 65536 distinct values and it will overflow back to 0 after 65,536 machine cycles.

Mode 2 (8 Bit Auto Reload)

两个定时器寄存器均配置为具有自动重新加载的 8 位计数器(TL1 和 TL0)。TL1(TL0)溢出将设置 TF1(TF0),并使用软件预设的 Th1(TH0)的内容重新加载 TL1(TL0)。重新加载不会改变 TH1(TH0)。

Both the timer registers are configured as 8-bit counters (TL1 and TL0) with automatic reload. Overflow from TL1 (TL0) sets TF1 (TF0) and also reloads TL1 (TL0) with the contents of Th1 (TH0), which is preset by software. The reload leaves TH1 (TH0) unchanged.

自动重新加载模式的好处在于,你可以让定时器始终包含 200 到 255 的值。如果你使用模式 0 或 1,你必须在代码中检查溢出,然后在这种情况下,将定时器重置为 200。在这种情况下,宝贵的指令会检查值和/或重新加载。在模式 2 中,微控制器会处理这一切。一旦你在模式 2 中配置了一个定时器,你不必担心检查定时器是否溢出,也不必担心重置值,因为微控制器硬件会为你完成这一切。自动重新加载模式用于建立一个通用的波特率。

The benefit of auto-reload mode is that you can have the timer to always contain a value from 200 to 255. If you use mode 0 or 1, you would have to check in the code to see the overflow and, in that case, reset the timer to 200. In this case, precious instructions check the value and/or get reloaded. In mode 2, the microcontroller takes care of this. Once you have configured a timer in mode 2, you don’t have to worry about checking to see if the timer has overflowed, nor do you have to worry about resetting the value because the microcontroller hardware will do it all for you. The auto-reload mode is used for establishing a common baud rate.

Mode 3 (Split Timer Mode)

定时器模式 "3" 称为 split-timer mode 。将 Timer 0 设置为模式 3 时,它将变为两个独立的 8 位定时器。Timer 0 是 TL0,Timer 1 是 TH0。这两个定时器从 0 计数到 255,并在溢出的情况下重置回 0。Timer 1 的所有位现在都将链接到 TH0。

Timer mode "3" is known as split-timer mode. When Timer 0 is placed in mode 3, it becomes two separate 8-bit timers. Timer 0 is TL0 and Timer 1 is TH0. Both the timers count from 0 to 255 and in case of overflow, reset back to 0. All the bits that are of Timer 1 will now be tied to TH0.

当 Timer 0 处于分解模式时,真正的 Timer 1(即 TH1 和 TL1)可以设置为模式 0、1 或 2,但它不能启动/停止,因为执行此操作的位现在链接到 TH0。真正的定时器 1 将在每个机器周期内递增。

When Timer 0 is in split mode, the real Timer 1 (i.e. TH1 and TL1) can be set in modes 0, 1 or 2, but it cannot be started/stopped as the bits that do that are now linked to TH0. The real timer 1 will be incremented with every machine cycle.

Initializing a Timer

决定定时器模式。考虑运行持续且独立于任何外部管脚的 16 位定时器。

Decide the timer mode. Consider a 16-bit timer that runs continuously, and is independent of any external pins.

初始化 TMOD SFR。使用 TMOD 的最低 4 位,并考虑定时器 0。将两个位,GATE 0 和 C/T 0,保持为 0,因为我们想要定时器独立于外部管脚。由于 16 位模式是定时器模式 1,因此清除 T0M1,并设置 T0M0。实际上,唯一要开启的是 TMOD 的第 0 位。现在执行以下指令 −

Initialize the TMOD SFR. Use the lowest 4 bits of TMOD and consider Timer 0. Keep the two bits, GATE 0 and C/T 0, as 0, since we want the timer to be independent of the external pins. As 16-bit mode is timer mode 1, clear T0M1 and set T0M0. Effectively, the only bit to turn on is bit 0 of TMOD. Now execute the following instruction −

MOV TMOD,#01h

现在,定时器 0 处于 16 位定时器模式,但定时器未运行。要以运行模式启动定时器,通过执行以下指令设置 TR0 位 −

Now, Timer 0 is in 16-bit timer mode, but the timer is not running. To start the timer in running mode, set the TR0 bit by executing the following instruction −

SETB TR0

现在,定时器 0 将立即开始计数,每隔一个机器周期递增一次。

Now, Timer 0 will immediately start counting, being incremented once every machine cycle.

Reading a Timer

可以两种方式读取 16 位定时器。读取定时器的实际值作为 16 位数字,或者检测定时器什么时候溢出。

A 16-bit timer can be read in two ways. Either read the actual value of the timer as a 16-bit number, or you detect when the timer has overflowed.

Detecting Timer Overflow

当定时器从最高值溢出到 0 时,微控制器会自动在 TCON 寄存器中设置 TFx 位。因此,无需检查定时器的准确值,而是可以检查 TFx 位。如果设置了 TF0,则定时器 0 已溢出;如果设置了 TF1,则定时器 1 已溢出。

When a timer overflows from its highest value to 0, the microcontroller automatically sets the TFx bit in the TCON register. So instead of checking the exact value of the timer, the TFx bit can be checked. If TF0 is set, then Timer 0 has overflowed; if TF1 is set, then Timer 1 has overflowed.

Embedded Systems - Interrupt

中断是由硬件或软件发出的信号,指示需要立即注意的事件。每当中断发生时,控制器都会完成执行当前指令,并开始执行一个 Interrupt Service Routine (ISR) 或 Interrupt Handler 。ISR 会告诉处理器或控制器在中断发生时做什么。中断可以是硬件中断或软件中断。

An interrupt is a signal to the processor emitted by hardware or software indicating an event that needs immediate attention. Whenever an interrupt occurs, the controller completes the execution of the current instruction and starts the execution of an Interrupt Service Routine (ISR) or Interrupt Handler. ISR tells the processor or controller what to do when the interrupt occurs. The interrupts can be either hardware interrupts or software interrupts.

Hardware Interrupt

硬件中断是从外部设备(如磁盘控制器或外部外围设备)发送到处理器的电子警报信号。例如,当我们在键盘上按一个键或移动鼠标时,它们会触发硬件中断,导致处理器读取击键或鼠标位置。

A hardware interrupt is an electronic alerting signal sent to the processor from an external device, like a disk controller or an external peripheral. For example, when we press a key on the keyboard or move the mouse, they trigger hardware interrupts which cause the processor to read the keystroke or mouse position.

Software Interrupt

软件中断是由特殊情况或指令集中的特殊指令引起的,当它们被处理器执行时会引起中断。例如,如果处理器的算术逻辑单元运行一个将数字除以零的命令,从而导致除以零异常,从而导致计算机放弃计算或显示错误消息。软件中断指令的工作方式类似于子例程调用。

A software interrupt is caused either by an exceptional condition or a special instruction in the instruction set which causes an interrupt when it is executed by the processor. For example, if the processor’s arithmetic logic unit runs a command to divide a number by zero, to cause a divide-by-zero exception, thus causing the computer to abandon the calculation or display an error message. Software interrupt instructions work similar to subroutine calls.

What is Polling?

持续监视的状态被称为 polling 。微控制器持续检查其他设备的状态;在执行此操作时,它不执行任何其他操作,并消耗所有处理时间来进行监视。可以通过使用中断来解决此问题。

The state of continuous monitoring is known as polling. The microcontroller keeps checking the status of other devices; and while doing so, it does no other operation and consumes all its processing time for monitoring. This problem can be addressed by using interrupts.

在中断方法中,控制器仅在发生中断时响应。因此,不需要控制器定期监视接口和内置设备的状态(标志、信号等)。

In the interrupt method, the controller responds only when an interruption occurs. Thus, the controller is not required to regularly monitor the status (flags, signals etc.) of interfaced and inbuilt devices.

Interrupts v/s Polling

以下是将中断与轮询区别开来的类比 −

Here is an analogy that differentiates an interrupt from polling −

Interrupt

Polling

An interrupt is like a shopkeeper. If one needs a service or product, he goes to him and apprises him of his needs. In case of interrupts, when the flags or signals are received, they notify the controller that they need to be serviced.

The polling method is like a salesperson. The salesman goes from door to door while requesting to buy a product or service. Similarly, the controller keeps monitoring the flags or signals one by one for all devices and provides service to whichever component that needs its service.

Interrupt Service Routine

对于每个中断,都必须有一个中断服务例程 (ISR) 或 interrupt handler 。当发生中断时,微控制器会运行中断服务例程。对于每个中断,内存中都有一个固定位置,用于保存其中断服务例程 ISR 的地址。为保存 ISR 地址而留出的内存位置表称为中断向量表。

For every interrupt, there must be an interrupt service routine (ISR), or interrupt handler. When an interrupt occurs, the microcontroller runs the interrupt service routine. For every interrupt, there is a fixed location in memory that holds the address of its interrupt service routine, ISR. The table of memory locations set aside to hold the addresses of ISRs is called as the Interrupt Vector Table.

executing program

Interrupt Vector Table

在 8051 中,包括 RESET 在内有六个中断。

There are six interrupts including RESET in 8051.

Interrupts

ROM Location (Hex)

Pin

Interrupts

ROM Location (HEX)

Serial COM (RI and TI)

0023

Timer 1 interrupts(TF1)

001B

External HW interrupt 1 (INT1)

0013

P3.3 (13)

External HW interrupt 0 (INT0)

0003

P3.2 (12)

Timer 0 (TF0)

000B

Reset

0000

9

  1. When the reset pin is activated, the 8051 jumps to the address location 0000. This is power-up reset.

  2. Two interrupts are set aside for the timers: one for timer 0 and one for timer 1. Memory locations are 000BH and 001BH respectively in the interrupt vector table.

  3. Two interrupts are set aside for hardware external interrupts. Pin no. 12 and Pin no. 13 in Port 3 are for the external hardware interrupts INT0 and INT1, respectively. Memory locations are 0003H and 0013H respectively in the interrupt vector table.

  4. Serial communication has a single interrupt that belongs to both receive and transmit. Memory location 0023H belongs to this interrupt.

Steps to Execute an Interrupt

当一个中断变得活跃时,微控制器将经历以下步骤 −

When an interrupt gets active, the microcontroller goes through the following steps −

  1. The microcontroller closes the currently executing instruction and saves the address of the next instruction (PC) on the stack.

  2. It also saves the current status of all the interrupts internally (i.e., not on the stack).

  3. It jumps to the memory location of the interrupt vector table that holds the address of the interrupts service routine.

  4. The microcontroller gets the address of the ISR from the interrupt vector table and jumps to it. It starts to execute the interrupt service subroutine, which is RETI (return from interrupt).

  5. Upon executing the RETI instruction, the microcontroller returns to the location where it was interrupted. First, it gets the program counter (PC) address from the stack by popping the top bytes of the stack into the PC. Then, it start to execute from that address.

Edge Triggering vs. Level Triggering

中断模块有两种类型——电平触发或边沿触发。

Interrupt modules are of two types − level-triggered or edge-triggered.

Level Triggered

Edge Triggered

A level-triggered interrupt module always generates an interrupt whenever the level of the interrupt source is asserted.

An edge-triggered interrupt module generates an interrupt only when it detects an asserting edge of the interrupt source. The edge gets detected when the interrupt source level actually changes. It can also be detected by periodic sampling and detecting an asserted level when the previous sample was de-asserted.

If the interrupt source is still asserted when the firmware interrupt handler handles the interrupt, the interrupt module will regenerate the interrupt, causing the interrupt handler to be invoked again.

Edge-triggered interrupt modules can be acted immediately, no matter how the interrupt source behaves.

Level-triggered interrupts are cumbersome for firmware.

Edge-triggered interrupts keep the firmware’s code complexity low, reduce the number of conditions for firmware, and provide more flexibility when interrupts are handled.

Enabling and Disabling an Interrupt

复位后,即使所有中断都被激活,所有中断也会被禁用。必须使用软件启用中断,以便微控制器响应这些中断。

Upon Reset, all the interrupts are disabled even if they are activated. The interrupts must be enabled using software in order for the microcontroller to respond to those interrupts.

IE(中断使能)寄存器负责启用和禁用中断。IE 是一个可寻址寄存器。

IE (interrupt enable) register is responsible for enabling and disabling the interrupt. IE is a bitaddressable register.

Interrupt Enable Register

EA

-

ET2

ES

ET1

EX1

ET0

EX0

  1. EA − Global enable/disable.

  2. - − Undefined.

  3. ET2 − Enable Timer 2 interrupt.

  4. ES − Enable Serial port interrupt.

  5. ET1 − Enable Timer 1 interrupt.

  6. EX1 − Enable External 1 interrupt.

  7. ET0 − Enable Timer 0 interrupt.

  8. EX0 − Enable External 0 interrupt.

要启用中断,我们会执行以下步骤 −

To enable an interrupt, we take the following steps −

  1. Bit D7 of the IE register (EA) must be high to allow the rest of register to take effect.

  2. If EA = 1, interrupts will be enabled and will be responded to, if their corresponding bits in IE are high. If EA = 0, no interrupts will respond, even if their associated pins in the IE register are high.

Interrupt Priority in 8051

我们可以通过向任何一个中断分配更高优先级来更改中断优先级。这由对名为 IP (中断优先级) 的寄存器进行编程来完成。

We can alter the interrupt priority by assigning the higher priority to any one of the interrupts. This is accomplished by programming a register called IP (interrupt priority).

下图显示了 IP 寄存器的位。在复位后,IP 寄存器包含所有 0。要向任何一个中断提供更高的优先级,我们会让 IP 寄存器中对应的位变为高电平。

The following figure shows the bits of IP register. Upon reset, the IP register contains all 0’s. To give a higher priority to any of the interrupts, we make the corresponding bit in the IP register high.

-

-

-

-

PT1

PX1

PT0

PX0

-

IP.7

Not Implemented.

-

IP.6

Not Implemented.

-

IP.5

Not Implemented.

-

IP.4

Not Implemented.

PT1

IP.3

Defines the Timer 1 interrupt priority level.

PX1

IP.2

Defines the External Interrupt 1 priority level.

PT0

IP.1

Defines the Timer 0 interrupt priority level.

PX0

IP.0

Defines the External Interrupt 0 priority level.

Interrupt inside Interrupt

如果 8051 正在执行属于中断的 ISR,而另一个中断变得活跃,会发生什么?在这种情况下,高优先级中断可以中断低优先级中断。这称为 interrupt inside interrupt 。在 8051 中,低优先级中断可以被高优先级中断中断,但不能被任何另一个低优先级中断中断。

What happens if the 8051 is executing an ISR that belongs to an interrupt and another one gets active? In such cases, a high-priority interrupt can interrupt a low-priority interrupt. This is known as interrupt inside interrupt. In 8051, a low-priority interrupt can be interrupted by a high-priority interrupt, but not by any another low-priority interrupt.

Triggering an Interrupt by Software

有时我们需要通过模拟的方式测试 ISR。这可以使用向中断设置高电平的简单指令来完成,从而导致 8051 跳至中断向量表。例如,为定时器 1 将 IE 位设置为 1。指令 SETB TF1 会中断 8051 正在进行的任何操作,并强制它跳至中断向量表。

There are times when we need to test an ISR by way of simulation. This can be done with the simple instructions to set the interrupt high and thereby cause the 8051 to jump to the interrupt vector table. For example, set the IE bit as 1 for timer 1. An instruction SETB TF1 will interrupt the 8051 in whatever it is doing and force it to jump to the interrupt vector table.