Professional Documents
Culture Documents
Chương 4 Vào Ra Cơ S
Chương 4 Vào Ra Cơ S
1
Ports
port enable
addr[0-11]
data[0-7]
bus
• Conducting device on periphery
• Connects bus to processor or memory
• Often referred to as a pin
– Actual pins on periphery of IC package that plug into socket on printed-circuit board
– Sometimes metallic balls instead of pins
– Today, metal “pads” connecting processors and memories within single IC
• Single wire or set of wires with single function
– E.g., 12-wire address port
2
Timing Diagrams
3
Basic protocol concepts
req req
data 15:8 7:0 addr/data addr data
4
Basic protocol concepts: control methods
data
data
req 1 3
req 1 3
data 2 4 ack 2 4
data
taccess
1. Master asserts req to receive data 1. Master asserts req to receive data
2. Servant puts data on bus within time taccess 2. Servant puts data on bus and asserts ack
3. Master receives data and deasserts req 3. Master receives data and deasserts req
4. Servant ready for next request 4. Servant ready for next request
5
A strobe/handshake compromise
wait
data
req 1 3 req 1 4
wait wait 2 3
data 2 4 data 5
taccess taccess
1. Master asserts req to receive data 1. Master asserts req to receive data
2. Servant puts data on bus within time taccess 2. Servant can't put data within taccess, asserts wait ack
(wait line is unused) 3. Servant puts data on bus and deasserts wait
3. Master receives data and deasserts req 4. Master receives data and deasserts req
4. Servant ready for next request 5. Servant ready for next request
6
ISA bus protocol – memory access
Microprocessor
• ISA: Industry Standard ISA bus
Memory I/O Device
• Features
CLOCK
D[7-0] DATA
ALE
– Compromise /MEMR
ALE
/MEMW
CHRDY
7
Microprocessor interfacing: I/O addressing
• A microprocessor communicates with other devices
using some of its pins
– Port-based I/O (parallel I/O)
• Processor has one or more N-bit ports
• Processor’s software reads and writes a port just like a register
• E.g., P0 = 0xFF; v = P1.2; -- P0 and P1 are 8-bit ports
– Bus-based I/O
• Processor has address, data and control ports that form a single bus
• Communication protocol is built into the processor
• A single instruction carries out the read or write protocol on the bus
8
Compromises/extensions
9
Types of bus-based I/O:
memory-mapped I/O and standard I/O
• Processor talks to both memory and peripherals using
same bus – two ways to talk to peripherals
– Memory-mapped I/O
• Peripheral registers occupy addresses in same address space as memory
• e.g., Bus has 16-bit address
– lower 32K addresses may correspond to memory
– upper 32k addresses may correspond to peripherals
– Standard I/O (I/O-mapped I/O)
• Additional pin (M/IO) on bus indicates whether a memory or peripheral
access
• e.g., Bus has 16-bit address
– all 64K addresses correspond to memory when M/IO set to 0
– all 64K addresses correspond to peripherals when M/IO set to 1
10
Memory-mapped I/O vs. Standard I/O
• Memory-mapped I/O
– Requires no special instructions
• Assembly instructions involving memory like MOV and ADD work
with peripherals as well
• Standard I/O requires special instructions (e.g., IN, OUT) to move
data between peripheral registers and memory
• Standard I/O
– No loss of memory addresses to peripherals
– Simpler address decoding logic in peripherals possible
• When number of peripherals much smaller than address space then
high-order address bits can be ignored
– smaller and/or faster comparators
11
ISA bus
A[15-0] ADDRESS
20-bit address space for ALE
memory /IOR
memory protocol
12
A basic memory protocol
D<0...7>
P0 Adr. 7..0 Data P0 D Q
A<0...15>
/CS
P2 Adr. 15…8 /OE
ALE G /WE
Q Adr. 7…0 74373 CS2 /CS1
8 HM6264
ALE P2
/WR /CS
/RD /RD
D<0...7>
/PSEN
A<0...14>
/OE
8051 27C256
13
A more complex memory protocol
FSM description
GO=0
Specification for a single GO=1
read operation ADSP=1, ADSP=0,
CLK S0 ADSC=1 ADSC=0 S1
ADV=1, OE=1, ADV=0, OE=1,
Addr = ‘Z’ GO=0 Addr = Addr0
/ADSP
/ADSC Data is
ready
/ADV GO=0
GO=1 here!
addr <15…0>
/WE
ADSP=1, ADSP=1,
/OE
S2 ADSC=0 ADSC=1 S3
ADV=1, OE=1, ADV=0, OE=0,
/CS1 and /CS2 GO=1
Addr = ‘Z’ Addr = ‘Z’
CS3
data<31…0> GO=1
GO=0
• Generates control signals to drive the TC55V2325FF memory chip in burst mode
– Addr0 is the starting address input to device
– GO is enable/disable input to device
14
Chương IV Vào ra cơ sở
Thiết bị
Thiết bị
Sơ đồ
Bộ đệm Cổng
Bộ xử lý ưu tiên
vào/ra
Thiết bị
Thiết bị
-Đặc điểm:
. Thời gian của CPU bị chiếm nhiều để thực hiện chương
trình lặp thăm dò.
. Chỉ nên dùng cho một số thiết bị.
1.Phương pháp thăm dò
1.1. Thăm dò theo ưu tiên quay vòng.
-Đọc nội dung của thanh ghi trạng thái để kiểm tra.
-Chỉ thăm dò hết các thiết bị thì vòng thăm dò mới
quay trở lại để bắt đầu vòng thăm dò tiếp theo.
- Như vậy thiết bị nào vừa được phục vụ xong thì sẽ
phải xếp hàng và được phục vụ sau cùng ( ưu tiên
quay vòng )
-Phụ thuộc vào đặc điểm của thiết bị ngoại vi mà số
vòng nhiều hay ít.
-Phù hợp các hệ thống vi xử lý nhỏ chỉ có một ít thiết
bị ngoại vi và cùng tương tự nhau về đặc điểm.
Bắt đầu
Không
sẵn sàng (No)
Không
sẵn sàng (No)
Không
sẵn sàng (No)
Không
sẵn sàng (No)
Không
sẵn sàng (No)
C có nhu cầu Sẵn sàng (Yes)
Chương trình
phục vụ hay không?
phục vụ C
Không
sẵn sàng (No)
- Đặc điểm:
. Điều khiển chủ yếu bằng phần cứng.
. Thiết bị có yêu cầu được phục vụ phát sinh ra 1 yêu cầu cần
được phục vụ gọi là Ngắt (INTR) gửi về CPU.
. Tiếp nhận tín hiệu ngắt (INTR),CPU thực hiện xong các chu kỳ
dang dở của lệnh máy đang thực hiện,cất giữ nội dung của thanh
ghi cần thiết cho sự tiếp tục thực hiện trở lại chương trình dang
dở và gửi ra thiết bị ngoại vi có yêu cầu ngắt sự chấp nhận ngắt
(ACK).
. Nhận ACK tích cực,thiết bị có yêu cầu ngắt gửi về CPU vectơ
ngắt về CPU để lấy địa chỉ của chương trình con phục vụ ngắt.
. Qua địa chỉ chương trình phục vụ ngắt để vào/ra dữ liệu với thiết
bị có yêu cầu ngắt được thực hiện.
2.Phương pháp ngắt
- Đặc điểm:
. Kết thúc phục vụ ngắt cho thiết bị trở về lại điểm bị ngắt của
chương trình dang dở để tiếp tục thực hiện.
. Các thiết bị được gán mức ưu tiên cho yêu cầu ngắt để CPU
thực hiện các yêu cầu ngăt theo ưu tiên.
. Giảm thiểu thời gian của CPU danh cho điều khiển vào/ra thiết
bị .
. Có thể gắn các yêu cầu ngắt với các sự kiện để xử lý.
. Sự gắn kết các sự kiện ngắt với các số hiệu ngắt làm cho quá
trình thực hiện điều khiển vào/ra dữ liệu dược chuẩn hóa về địa
chỉ.
. Có hiệu quả với những thiết bị có khối lượng dữ liệu vào/ra
theo các khối(block device).
Cách xác định nguồn báo ngắt
1. Xác định nguồn báo ngắt Bằng phần mềm :
Phương pháp này yêu cầu 2 điều kiện
- Mỗi cổng vào ra cần có 1 bit trạng thái
- Khi có ngắt CPU sẽ tự động chạy đến 1 địa chỉ cố định ứng với
ngắt
Trong chương trình phục vụ ngắt CPU sẽ tiến hành chạy chương
trình hỏi vòng xem ngoại vi nào yêu cầu ngắt ( bằng cách kiểm
tra bit trạng thái ) để rẽ nhánh tới chương trình phục vụ ngắt
tương ứng. Lưu đồ chương trình tương tự như chương trình
thăm dò.
Phương pháp này có thể áp dụng cho CPU chỉ có 1 đầu vào ngắt
mà lại có nhiều ngoại vi .
2.Phương pháp ngắt
1.Xác định nguồn báo ngắt Bằng phần mềm :
Thực hiện :
-Các thiết bị ngoại vi được kết hợp vào mạch hoặc cho một
đường dây ngắt dẫn đến chân tín hiệu ngắt của CPU .
-Khi có ngắt Máy tính thực hiện quét các thiết bị để xác định
ngắt xuất phát từ đâu.Mức ưu tiên được tự động gắn vào các thiết
bị theo thứ tự quét.
-Bằng phương pháp mặt nạ hoặc sử dụng các lệnh quay vòng ,
thiết bị ngắt có mức ưu tiên cao nhất được chọn.
-Kỹ thuật này thường sử dụng cho thiết bị trao đổi chậm và
trong hệ thống ngắt đơn.
2.Phương pháp ngắt
DATA BUS
CPU
INT0 NGOẠI VI 1
INTA
PIC 8259
INT
INT7 NGOẠI VI 8
31
2.Phương pháp ngắt
trình chính
EI:cho phép ngắt.
RET trở về
Chương trình chính
34
Microprocessor interfacing: interrupts
35
Interrupt address table
• Compromise between fixed and vectored interrupts
– One interrupt pin
– Table in memory holding ISR addresses (maybe 256 words)
– Peripheral doesn’t provide ISR address, but rather index into
table
• Fewer bits are sent by the peripheral
• Can move ISR location without changing peripheral
36
Additional interrupt issues
• Maskable vs. non-maskable interrupts
– Maskable: programmer can set bit that causes processor to ignore
interrupt
• Important when in the middle of time-critical code
– Non-maskable: a separate interrupt pin that can’t be masked
• Typically reserved for drastic situations, like power failure requiring
immediate backup of data to non-volatile memory
• Jump to ISR
– Some microprocessors treat jump same as call of any subroutine
• Complete state saved (PC, registers) – may take hundreds of cycles
– Others only save partial state, like PC only
• Thus, ISR must not modify registers, or else must save them first
• Assembly-language programmer must be aware of which registers stored
37
3.Phương pháp DMA
3.1.Khái niệm DMA
• Kỹ thuật vào ra DMA(Direct Memory Acess) là phương pháp
truy cập trực tiếp tới bộ nhớ hoặc I/O mà không có sự tham gia
của CPU .Phương pháp này trao đổi dữ liệu giữa bộ nhớ và thiết
bị ngoại vi với tốc độ cao và chỉ bị hạn chế bởi tốc độ của bộ
nhớ hoặc của bộ điều khiển DMA .
• DMA được ứng dụng trong nhiều mục đích nhưng thông
thường nó được dùng trong quá trình "refresh" DRAM, màn
hình, đọc ghi đĩa, truyền dữ liệu giữa các vùng nhớ với tốc độ
cao.
ADDRESS LATCHES
ALE
AD0-AD15
DATA BUS
HOLD HRQ
DMA CONTROL BUS
CONTROLLER
HLDA HLDA DREQ PERIPHERAL
DACK DEVICE
Address bus
8088
HRQ
8237
Quá trình trao đổi thông tin bằng DMA
41
Intel 8237 DMA controller
Signal Description
D[7..0] Intel 8237 REQ 0
A[19..0] ACK 0 D[7..0] These wires are connected to the system bus (ISA) and are used by the
ALE microprocessor to write to the internal registers of the 8237.
MEMR REQ 1
ACK 1 A[19..0] These wires are connected to the system bus (ISA) and are used by the DMA to
MEMW
IOR issue the memory location where the transferred data is to be written to. The 8237 is
IOW REQ 2 ALE* also addressed
This by the
is the address micro-processor
latch through
enable signal. The 8237theuselower bits ofwhen
this signal thesedriving
addressthelines.
ACK 2 system bus (ISA).
HLDA MEMR* This is the memory write signal issued by the 8237 when driving the system bus
HRQ REQ 3
ACK 3 (ISA).
MEMW* This is the memory read signal issued by the 8237 when driving the system bus (ISA).
IOR* This is the I/O device read signal issued by the 8237 when driving the system bus
(ISA) in order to read a byte from an I/O device
IOW* This is the I/O device write signal issued by the 8237 when driving the system bus
(ISA) in order to write a byte to an I/O device.
HLDA This signal (hold acknowledge) is asserted by the microprocessor to signal that it has
relinquished the system bus (ISA).
HRQ This signal (hold request) is asserted by the 8237 to signal to the microprocessor a
request to relinquish the system bus (ISA).
REQ 0,1,2,3 An attached device to one of these channels asserts this signal to request a DMA
transfer.
ACK 0,1,2,3 The 8237 asserts this signal to grant a DMA transfer to an attached device to one of
these channels.
*See the ISA bus description in this chapter for complete details.
42
Vi mạch DMA 8237
Tên tín hiệu Chức năng
D7 – D0 Bus dữ liệu, 2 chiều, 3 trạng thái
RESET Đầu vào thiết lập lại
CS# Đầu vào lựa chọn chip
MEMR# Đọc bộ nhớ
MEMW# Ghi bộ nhớ
A7 – A4 Đầu ra bus địa chỉ, 3 trạng thái
A3 – A0 Bus địa chỉ 2 chiều, 3 trạng thái
I/OR# Đọc I/O 2 chiều, 3 trạng thái
I/OW# Ghi I/O
READY Đầu vào sẵn sàng
CLK Đầu vào CLK
HRQ Đầu ra yêu cầu chờ
HLDA Đầu vào chấp nhận chờ
AEN Đầu ra cho phép địa chỉ
ADSTB Đầu ra định nhịp địa chỉ
EOP# Kết thúc quá trình, 2 chiều
MARK Đầu ra mặt nạ modul 128
DRQ3 - DRQ0 Đầu vào yêu cầu DMA
DACK3# - DACK0# Đầu ra chấp nhận DMA
Vcc +5V
GND Nối đất
Vi mạch DMA 8237
• 8237 là một bộ điều khiển DMA cung cấp địa chỉ bộ nhớ và tín
hiệu điều khiển trong suốt quá trình DMA và truyền số liệu với
tốc độ cao giữa bộ nhớ và thiết bị vào ra .
• 8237 là vi mạch có 4 kênh tương thích với bộ VXL 8088, các
kênh này có thể mở rộng thêm nhiều kênh khác mặc dù đối với
hệ thống nhỏ thì 4 kênh này là qúa đủ.
• DMAC 8237 có thể thực hiện truyền dữ liệu theo 3 kiểu: kiểu
đọc (từ bộ nhớ ra thiết bị ngoại vi), kiểu ghi (từ thiết bị ngoại vi
đến bộ nhớ) và kiểu kiểm tra.
1. Sơ đồ khối chức năng của DMA 8237
CH-0
DRQ0
Bộ đệm 16 bit
D7-D0 DACK0#
Bus dữ liệu ADDR
CNTR
I/OR# CH-1
I/OW# DRQ1
16 bit
CLK
RESET ADDR DACK1#
A0 Logic
CNTR
A1 đọc/ghi
A2 CH-2
A3 DRQ2
CS# 16 bit
DACK2#
ADDR
A4
A5 CNTR
A6
A7 Logic CH-3
DRQ3
READY 16 bit
đ/k và
HRQ
HLDA thanh ghi ADDR
DACK3#
MEMR# thiết lập CNTR
MEMW#
AEN
chế độ
ADSTB Bộ giải quyết
EOP#
ưu tiên
Vi mạch DMA 8237
MEMW# I/OW#
DMAC
I/OR#
MEMR# 8237
- Thanh ghi chế độ:Thiết lập chế độ hoạt động cho mỗi kênh.
-Thanh ghi yêu cầu: dùng yêu cầu truyền DMA bằng phần mềm
- Thanh ghi cấm : xoá hoặc thiết lập việc cấm của tất cả
các kênh bằng một lệnh .
- Thanh ghi trạng thái (SR ) : xác định trạng thái của các
kênh DMA .
Address bus
8088
HRQ
8237
Quá trình trao đổi thông tin
Vi mạch DMA 8237
DRQ HRQ
DMAC HLDA DRQ0
DACK# 8237
DACK0#
DRQ1 HRQ
DACK0#
DMAC
HRQ HLDA CPU
DRQ DRQ2 8237
HLDA DACK0#
DMAC
DACK# 8237 DRQ3
DACK0#
DRQ HRQ
DMAC HLDA
DACK# 8237
Kết nối tầng các mạch DMA
Advanced communication principles
• Layering
– Break complexity of communication protocol into pieces easier to design and
understand
– Lower levels provide services to higher level
• Lower level might work with bits while higher level might work with packets of data
– Physical layer
• Lowest level in hierarchy
• Medium to carry data from one actor (device or node) to another
• Parallel communication
– Physical layer capable of transporting multiple bits of data
• Serial communication
– Physical layer transports one bit of data at a time
• Wireless communication
– No physical connection needed for transport at physical layer
70
Parallel communication
• Multiple data, control, and possibly power wires
– One bit per wire
• High data throughput with short distances
• Typically used when connecting devices on same IC or same
circuit board
– Bus must be kept short
• long parallel wires result in high capacitance values which requires more
time to charge/discharge
• Data misalignment between wires increases as length increases
• Higher cost, bulky
71
Serial communication
72
Wireless communication
• Infrared (IR)
– Electronic wave frequencies just below visible light spectrum
– Diode emits infrared light to generate signal
– Infrared transistor detects signal, conducts when exposed to infrared
light
– Cheap to build
– Need line of sight, limited range
• Radio frequency (RF)
– Electromagnetic wave frequencies in radio spectrum
– Analog circuitry and antenna needed on both sides of transmission
– Line of sight not needed, transmitter power determines range
73
Error detection and correction
• Often part of bus protocol
• Error detection: ability of receiver to detect errors during transmission
• Error correction: ability of receiver and transmitter to cooperate to correct
problem
– Typically done by acknowledgement/retransmission protocol
• Bit error: single bit is inverted
• Burst of bit error: consecutive bits received incorrectly
• Parity: extra bit sent with word used for error detection
– Odd parity: data word plus parity bit contains odd number of 1’s
– Even parity: data word plus parity bit contains even number of 1’s
– Always detects single bit errors, but not all burst bit errors
• Checksum: extra word sent with data packet of multiple words
– e.g., extra word contains XOR sum of all data words in packet
74
4.2 Vào/ ra song song
1. Nguyên lý, cấu trúc cổng vào không đối thoại,có đối thoại.
2. Nguyên lý cấu trúc cổng ra không đối thoại,có đối thoại.
3. Nguyên lý, cấu trúc cổng ra cổng Read-back,cổng định
hướng.
75
4.2 Vào/ ra song song
• Quá trình vào ra trong máy tính là quá trình trao đổi thông tin
giữa CPU và các thiết bị ngoại vi trong hệ thống xử lý.
• Có nhiều phương pháp vào ra khác nhau,nhưng có thể chia
làm 3 nhóm chính:
• Vào ra điều khiển bằng chương trình.
• Vào ra điều khiển bằng ngắt.
• Vào ra thâm nhập trực tiếp bộ nhớ (DMA).
76
4.2 Vào/ ra song song
• Trong phương pháp vào ra điều khiển bằng chương trình,
ngoại vi được ghép nối với Bus hệ thống của vxl qua các
phần: thích ứng về công nghệ và thích ứng về logic. Chúng
được gọi là các mạch ghép nối.
• Thích ứng về công nghệ làm nhiệm vụ làm nhiệm vụ điều
chỉnh mức tín hiệu giữa công nghệ sản xuất thiết bị ngoại vi
và công nghệ sản xuất các mạch cấu tạo nên Bus của VXL.
• Thích ứng về logic có nhiệm vụ tạo tín hiệu điều khiển ngoại
vi từ tín hiệu điều khiển trên Bus hệ thống.
77
4.2 Vào/ ra song song
• Sơ đồ ghép nối:
78
4.2 Vào/ ra song song
• Bộ ghép nối được chia làm 2 nhóm chính:
- Bộ ghép nối song song.
- Bộ ghép nối tiếp.
• Ghép nối song song được sử dụng rộng rãi: để kết nối
máy in tới PC,ghép nối với bộ nhớ ngoài
(SRAM,EPROM…),các hệ thống thu nhận dữ liệu…
• Các bộ ghép nối song song đơn giản,nó là các cửa vào ra
được ghép nối trực tiếp với bộ VXL.Thông thường nó
được cấu tạo bởi các thanh chốt dữ liệu và các mạch đệm.
• Trước hết chúng ta cần biết về bộ VXL được dùng trong
ghép nối này.
79
4.2 Vào/ ra song song
I. Nguyên lý cấu trúc cổng vào có đối thoại và không đối thoại 1.
1. Giới thiệu một số IC để cấu tạo cổng vào ra song song :
• Trước tiên ta cần làm quen với 1 số IC được dùng để cấu tạo nên
cổng.
1. IC chốt 74LS373:
80
4.2 Vào/ ra song song
81
4.2 Vào/ ra song song
82
4.2 Vào/ ra song song
83
4.2 Vào/ ra song song
• Nguyên lý hoạt động:
. Để giảm số chân của CPU người ta thường ghép các tín hiệu
địa chỉ và dữ liệu.VD các chân AD0…AD7 được ghép cho
các bit thấp của địa chỉ.Vì vậy ta cần IC 74LS373 để tách tín
hiệu này ra.
. Khi ALE =1 thì dữ liệu mang 8bit phần thấp của địa chỉ,nó
sẽ làm mở chốt,thông tin về địa chỉ được tách. Khi ALE =0
thông tin về địa chỉ được giữ lại ở bộ chốt 74LS373.
. Khi cần đọc dữ liệu đưa vào CPU gửi tín hiệu =0, tín
hiệu này cùng với tín hiệu giải mã địa chỉ sẽ làm cho bộ đệm
thông ( khi =0, =0),dữ liệu từ ngoại vi sẽ qua bộ đệm
và được CPU đọc.
84
• 3. Cổng vào có đối thoại:
IBF (Input Buffer Full, Input Data Ready )
(INT)
Reset by device
86
4.2 Vào/ ra song song
• Sườn xuống của tín hiệu IORD này sẽ làm thông bộ đệm
74LS244 và dữ liệu sẽ được truyền từ ngoại vi vào CPU.
Sườn lên của xung này sẽ làm cho D flip-flop hoạt động
(đây cũng là kết thúc quá trình đọc của CPU) đầu ra Q sẽ
có mức logic 1 báo cho ngoại vi biết dữ liệu đã được
truyền xong.
• Ngoại vi sẽ tạo ra tín hiệu thiết lập để xóa các latch D flip-
flop về lại trạng thái ban đầu để chuẩn bi cho quá trình gửi
dữ liệu tiếp theo.
87
4.2 Vào/ ra song song
• Biểu đồ thời gian quá trình đọc:
CLK
RR
IORD
Thiết lập
88
4.2 Vào/ ra song song
• Lưu đồ thuật toán để thể hiên quá trình vào có đối thoại:
89
4.2 Vào/ ra song song
II. Nguyên lý cấu trúc cổng ra có đối thoại và không đối thoại:
1. Cổng ra song song không đối thoại:
Đặc điểm : Ngoại vi luôn ở trạng thái sẵn sàng nhận số liệu, Vi xử
lý có thể đưa dữ liệu ra bất cứ khi nào cần mà không phải kiểm
tra tính sẵn sàng của ngoại vi
90
4.2 Vào/ ra song song
• Nguyên lý hoạt động:
. Khi CPU thực hiện câu lệnh đưa dữ liệu ra thì Bộ điều khiển
sẽ thực hiện các bước sau :
- Phát tín hiệu địa chỉ lên kênh địa chỉ
- Phát tín hiệu ALE để chốt địa chỉ
- Phát dữ liệu lên kênh dữ liệu
- Phát tín hiệu điều khiển =0
. Tương tự như cổng vào.thông tin địa chi được phân kênh nhờ
IC chốt. Địa chỉ được giải mã và kết hợp với tín hiệu
qua cổng OR,tín hiệu ra của cổng OR này được đưa vào chân
C của IC chốt thứ 2. Tín hiệu này làm thông các latch và dữ
liệu được ghi vào bộ chốt và đưa đến ngoại vi.
91
4.2 Vào/ ra song song
2. Cổng ra song song có đối thoại:
. Sơ đồ:
OBF (Output Buffer Full,
Output Data Ready)
(ACK)
92
4.2 Vào/ ra song song
• Nguyên lý:
.CPU sẽ kiểm tra ngoại vi xem có sẵn sàng để nhận dữ liệu hay
không.
. Khi ngoại vi sẵn sàng thì tín hiệu ngoại vi sẵn sàng sẽ đươc
thiết lập,sườn lên của xung này sẽ mở đệm và tín hiệu RR sẽ
được gửi đến chân READY của CPU để báo CPU biết ngoại vi
đã sẵn sàng.
. Sau khi biết ngoại vi đã sẵn sàng CPU sẽ gửi tín hiệu =0
cùng với địa chỉ tương ứng của ngoại vi. Qua cổng OR ta được
tín hiệu IOWR, sườn lên của xung này sẽ kích hoạt IC chốt làm
việc,và dữ liệu từ CPU được gửi tới ngoại vi.
93
4.2 Vào/ ra song song
. Sau khi CPU gửi dữ liệu xong,lúc này sườn xuống của
xung IOWR sẽ làm D flip-flop hoạt động, đầu ra Q sẽ có
mức logic 1,báo cho ngoại vi biết dữ liệu đã gửi xong.
Lúc này ngoại vi sẽ sinh ra tín hiệu thiết lập để xóa các D
flip-flop trở lại trạng thái ban đầu.
. Biểu đồ thời gian:
94
4.2 Vào/ ra song song
95
4.2 Vào/ ra song song
• Lưu đồ thuật toán thể hiện quá trình ghi:
96
4.2 Vào/ ra song song
• III. Nguyên lý cấu trúc cơ bản cổng ra cổng read back,
cổng định nghĩa hướng:
97
4.2 Vào/ ra song song
• Hình trên minh họa chi tiết cho cấu trúc bên trong của
cổng máy in(cổng song song).
• Thực tế cổng này được hợp thành bởi 3 cổng:
. Cổng Dữ liệu 8 bit.
. Cổng Điều Khiển 4 bit.
. Cổng Trạng Thái 5 bit.
. Thông thường địa chỉ trong Ram của cổng song song là:
98
4.2 Vào/ ra song song
99
• Hình trên minh họa các chi tiết của cổng Dữ liệu:
. Cổng Dữ liệu gồm 2 cổng : một cổng đầu ra và một cổng
đầu vào có cùng địa chỉ. Cổng đầu vào này thường được
gọi là cổng read-back.
. Đầu vào của latch 74LS374 được nối tới BUS,đầu ra của
latch này được nối tới các chân ra của cổng Dữ Liệu. Và
8bit đầu vào này được nối tới bộ đệm 74LS244 đầu ra của
bộ đệm này được nối trở lại BUS.
100
4.2 Vào/ ra song song
101
4.2 Vào/ ra song song
• Hình trên là cấu trúc của cổng Trạng Thái. Đây là cổng
vào. Tín hiệu vào được qua bộ đệm đảo đảo 74LS240
được đưa tới các bit cao byte dữ liệu (bit D3 – D7).
102
4.2 Vào/ ra song song
103
4.2 Vào/ ra song song
• Hình trên miêu tả cấu trúc của cổng Điều Khiển. 4 bit của
cổng này là 4 bit thấp của byte dữ liệu (D0 – D3). Các bit
này được nối đầu vào của latch 74LS174, đầu ra của latch
được nối các chân ra của cổng Điều Khiển. Các chân này
cũng có tác dụng đọc tín hiệu vào. Khi đọc tín hiệu vào,thì
tín hiệu được nối qua bộ đệm đảo 74LS240 và được đưa
trở lại các bit D0-D3.
• Dữ liệu cũng có thể được gửi qua cổng ĐK giống như gửi
qua cổng Dữ liệu. VD: Ta có thể dùng cổng Điều Khiển
để ghép nối PC với vi điều khiển AVR.
104
4.2 Vào/ ra song song
• Khi gửi dữ liệu,những dữ liệu thích hợp sẽ được gửi tới
cổng ĐK và sẽ được gửi tới AVR. Còn khi đọc dữ
liệu,trước tiên các bit của cổng ĐK được đặt lên ‘1’ và
khi có tín hiệu điều khiển đọc dữ liệu bộ đệm sẽ được mở
và dữ liệu được đọc.
105
4.3 VÀO RA ĐỊNH THỜI
4.3 Vào ra định thời
• 1 Định nghĩa, nguyên lý mạch định thời và Bộ đếm
107
Timers ( Mạch định thời )
• Timer: Đo khoảng thời gian
– Tạo ra các sự kiện đầu ra theo thời gian
• Ví dụ giữ đèn giao thông màu xanh sáng trong 10 s
– Đo sự kiện ở đầu vào
• Ví dụ đo tốc độ xe hơi, tần số
Basic timer
• Dựa trên việc đếm số xung với tần số chuẩn 16-bit up
Clk 16 Cnt
• Ví dụ xung clock có khu kỳ Tclk= 10 ns counter
108
Counters ( Bộ đếm )
• Counter: tương tự như Timer cũng
cấu tạo từ 1 bộ đếm, nhưng xung
đếm được tạo ra từ một sự kiện và
đưa đến đầu vào đếm ( Count_in ) Timer/counter
109
Các cấu trúc timer khác
110
Example: Reaction Timer
indicator reaction
/* main.c */
light button
#define MS_INIT 63535
LCD time: 100 ms void main(void){
int count_milliseconds = 0;
increments every 6 cycles while (user has not pushed reaction button){
if(Top) {
– Resolution = 6*83.33=0.5 microsec. stop timer
set Cnt to MS_INIT
– Range = 65535*0.5 microseconds = 32.77 start timer
reset Top
milliseconds count_milliseconds++;
}
– Want program to count millisec., so initialize }
turn light off
counter to 65535 – 1000/0.5 = 63535 printf(“time: %i ms“, count_milliseconds);
}
111
Watchdog timer
failure, self-reset
• Another use: timeouts /* main.c */ watchdog_reset_routine(){
/* checkreg is set so we can load value into
main(){ timereg. Zero is loaded into scalereg and
– e.g., ATM machine wait until card inserted 11070 is loaded into timereg */
call watchdog_reset_routine
– 16-bit timer, 2 checkreg = 1
microsec. resolution while(transaction in progress){ scalereg = 0
if(button pressed){ timereg = 11070
– timereg value = 2*(216- perform corresponding action }
call watchdog_reset_routine
1)–X = 131070–X } void interrupt_service_routine(){
– For 2 min., X = eject card
/* if watchdog_reset_routine not called every reset screen
120,000 microsec. < 2 minutes, interrupt_service_routine is }
called */
}
112
Intel 8051: Timers/Counters
• Có 2 bộ 16-bit Timer/Counter registers
• Timer: Nội dung thanh ghi tăng thêm 1 sau mỗi chu kỳ máy ( 1 chu
kỳ máy bằng 12 chu kỳ oscillator )
• Counter: Nội dung thanh ghi tăng thêm 1 khi có chuyển tiếp sườn
xuống (1-0 ) tại chân T0, T1 nối với bên ngoài .
– Tín hiệu từ chân T0, T1 được lấy mẫu tại S5P2 của mỗi chu kỳ
máy
– Khi lấy mẫu nếu thấy ở chu kỳ này là mức cao , chu kỳ tiếp theo
là mức thấp thì bộ đếm sẽ tang lên 1
– Giá trị mới sẽ xuất hiệu tại S3P1 ở chu kỳ nhận biết sau
114/175
Intel 8051: Timers/Counters
7 6 5 4 3 2 1 0
TCON TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0
115/175
Intel 8051: Timers/Counters
O SC 1/12
T L1 TH1
T F1 IN T ER R U PT
(5 bits) (8 bits)
T 1 PIN
TR1
G AT E M ODE 0
IN T 1 PIN
Intel 8051: Timers/Counters
OSC 1/12
C /T =0
TL1 TH1
TF1 IN T E R R U P T
(8 b its) (8 b its)
C /T =1
T 1 P IN
TR1
G AT E M O DE 1
IN T 1 P IN
Intel 8051: Timers/Counters
OSC 1/12
TL1
TF1 IN T E R R U P T
(8 b its)
T 1 P IN
R E L O AD
TR1
G AT E TH1
(8 b its)
M O DE 2
IN T 1 P IN
Intel 8051: Timers/Counters
O SC 1/12
C /T =0
T L0
T F0 INT ER RU PT
(8 bits)
C /T =1
T 0 PIN
T R0
G AT E MODE 3
INT 0 PIN
T H0
1/12 f osc T F1 INT ER RU PT
(8 bits)
T R1
‰ The 8051 has two timers/counters,
PROGRAMMING
TIMERS
they can be used either as
Timers to generate a time delay or as
Event counters to count events happening
outside the microcontroller
‰ Both Timer 0 and Timer 1 are 16 bits
wide
Since 8051 has an 8-bit architecture, each
16-bits timer is accessed as two separate
registers of low byte and high byte
2
‰ Accessed as low byte and high byte
PROGRAMMING
The low byte register is called TL0/TL1
TIMERS
and
The high byte register is called TH0/TH1
Timer 0 & 1
Accessed like any other register
Registers
ƒ MOV TL0,#4FH
ƒ MOV R5,TH0
TH0 TL0
TH1 TL1
3
‰ Both timers 0 and 1 use the same
PROGRAMMING
TIMERS
register, called TMOD (timer mode), to
set the various timer operation modes
TMOD ‰ TMOD is a 8-bit register
Register
The lower 4 bits are for Timer 0
The upper 4 bits are for Timer 1
In each case,
ƒ The lower 2 bits are used to set the timer mode
ƒ The upper 2 bits to specify the operation
(MSB) (LSB)
Timer1 Timer0
4
(MSB) (LSB)
5
Example 9-1
PROGRAMMING Indicate which mode and which timer are selected for each of the following.
(a) MOV TMOD, #01H (b) MOV TMOD, #20H (c) MOV TMOD, #12H
TIMERS
Solution:
We convert the value from hex to binary. From Figure 9-3 we have:
TMOD (a) TMOD = 00000001, mode 1 of timer 0 is selected. (b)
Register TMOD = 00100000, mode 2 of timer 1 is selected.
(c) TMOD = 00010010, mode 2 of timer 0, and mode 1 of timer 1 are
(cont’) selected.
If C/T = 0, it is used
as a timer for time Example 9-2
delay generation. Find the timer’s clock frequency and its period for various 8051-based system,
The clock source for with the crystal frequency 11.0592 MHz when C/T bit of TMOD is 0.
the time delay is the
Solution:
crystal frequency of
XTAL
the 8051 ÷12
oscillator
6
‰ Timers of 8051 do starting and stopping
by either software or hardware control
PROGRAMMING
In using software to start and stop the timer
TIMERS where GATE=0
ƒ The start and stop of the timer are controlled by
TMOD way of software by the TR (timer start) bits TR0
Register and TR1
- The SETB instruction starts it, and it is
stopped by the CLR instruction
GATE
- These instructions start and stop the timers
as long as GATE=0 in the TMOD register
The hardware way of starting and stopping
the timer by an external source is achieved
• Timer 0, mode 2 by making GATE=1 in the TMOD register
• C/T = 0 to use
XTAL clock source Find the value for TMOD if we want to program timer 0 in mode 2,
• gate = 0 to use use 8051 XTAL for the clock source, and use instructions to start
internal (software) start and stop the timer.
and stop method.
TMOD = 0000 0010
7
‰ The following are the characteristics
PROGRAMMING and operations of mode1:
TIMERS
1. It is a 16-bit timer; therefore, it allows
value of 0000 to FFFFH to be loaded into
Mode 1 the timer’s register TL and TH
Programming
2. After TH and TL are loaded with a 16-bit
initial value, the timer must be started
ƒ This is done by SETB TR0 for timer 0 and
SETB TR1 for timer 1
3. After the timer is started, it starts to
count up
ƒ It counts up until it reaches its limit of FFFFH
XTAL TH TL TF
÷12
oscillator
TF goes high Overflow
TR when FFFF → 0 flag
C/T = 0
8
3. (cont’)
ƒ When it rolls over from FFFFH to 0000, it sets
PROGRAMMING high a flag bit called TF (timer flag)
TIMERS - Each timer has its own timer flag: TF0 for
timer 0, and TF1 for timer 1
- This timer flag can be monitored
Mode 1 ƒ When this timer flag is raised, one option
Programming would be to stop the timer with the
(cont’) instructions CLR TR0 or CLR TR1, for timer 0
and timer 1, respectively
4. After the timer reaches its limit and rolls
over, in order to repeat the process
ƒ TH and TL must be reloaded with the original
value, and
ƒ TF must be reloaded to 0
XTAL TH TL TF
÷12
oscillator
TF goes high Overflow
C/T = 0 TR when FFFF → 0 flag
9
‰ To generate a time delay
PROGRAMMING 1. Load the TMOD value register indicating
TIMERS which timer (timer 0 or timer 1) is to be
used and which timer mode (0 or 1) is
selected
Mode 1
Programming 2. Load registers TL and TH with initial count
value
Steps to Mode 1 3. Start the timer
Program 4. Keep monitoring the timer flag (TF) with
the JNB TFx,target instruction to see
if it is raised
ƒ Get out of the loop when TF becomes high
5. Stop the timer
6. Clear the TF flag for the next round
7. Go back to Step 2 to load TH and TL
again
Department of Instrumentation and Industrial Information
10
Ha Noi University of Science and Technology,VIETNAM
Example 9-4
PROGRAMMING In the following program, we create a square wave of 50% duty cycle (with
equal portions high and low) on the P1.5 bit. Timer 0 is used to generate the
TIMERS time delay. Analyze the program
11
Example 9-4 (cont’)
DELAY:
PROGRAMMING SETB TR0 ;start the timer 0
AGAIN: JNB TF0,AGAIN ;monitor timer flag 0
TIMERS ;until it rolls over
CLR TR0 ;stop timer 0
CLR TF0 ;clear timer 0 flag
Mode 1 RET
Programming 4. The DELAY subroutine using the timer is called.
5. In the DELAY subroutine, timer 0 is started by the SETB TR0 instruction. 6.
Timer 0 counts up with the passing of each clock, which is provided by the
Steps to Mode 1
crystal oscillator. As the timer counts up, it goes through the states of FFF3,
Program FFF4, FFF5, FFF6, FFF7, FFF8, FFF9, FFFA, FFFB, and so on until it
(cont’) reaches FFFFH. One more clock rolls it to 0, raising the timer flag (TF0=1).
At that point, the JNB instruction falls through.
12
Example 9-5
In Example 9-4, calculate the amount of time delay in the DELAY
PROGRAMMING subroutine generated by the timer. Assume XTAL = 11.0592 MHz.
TIMERS Solution:
The timer works with a clock frequency of 1/12 of the XTAL
Mode 1 frequency; therefore, we have 11.0592 MHz / 12 = 921.6 kHz as the
timer frequency. As a result, each clock has a period of T =
Programming 1/921.6kHz = 1.085us. In other words, Timer 0 counts up each 1.085 us resulting in delay = number of
counts × 1.085us.
Steps to Mode 1 The number of counts for the roll over is FFFFH - FFF2H = 0DH (13
Program decimal). However, we add one to 13 because of the extra clock
(cont’) needed when it rolls over from FFFF to 0 and raise the TF flag. This gives 14 × 1.085us = 15.19us for half
the pulse. For the entire period it is T = 2 × 15.19us = 30.38us as the time delay generated by the timer.
13
Example 9-6
In Example 9-5, calculate the frequency of the square wave generated
on pin P1.5.
PROGRAMMING
TIMERS Solution:
In the timer delay calculation of Example 9-5, we did not include the
overhead due to instruction in the loop. To get a more accurate timing,
Mode 1 we need to add clock cycles due to this instructions in the loop. To do
Programming that, we use the machine cycle from Table A-1 in Appendix A, as
shown below.
Cycles
Steps to Mode 1 HERE: MOV TL0,#0F2H 2
Program MOV TH0,#0FFH 2
(cont’) CPL P1.5 1
ACALL DELAY 2
SJMP HERE 2
DELAY:
SETB TR0 1
AGAIN: JNB TF0,AGAIN 14
CLR TR0 1
CLR TF0 1
RET 2
Total 28
T = 2 × 28 × 1.085 us = 60.76 us and F = 16458.2 Hz
14
Example 9-7
Find the delay generated by timer 0 in the following code, using both
PROGRAMMING of the Methods of Figure 9-4. Do not include the overhead due to
TIMERS instruction.
CLR P2.3 ;Clear P2.3
MOV TMOD,#01 ;Timer 0, 16-bitmode
Mode 1 HERE: MOV TL0,#3EH ;TL0=3Eh, the low byte
Programming MOV TH0,#0B8H ;TH0=B8H, the high byte
SETB P2.3 ;SET high timer 0
SETB TR0 ;Start the timer 0
Steps to Mode 1 AGAIN: JNB TF0,AGAIN ;Monitor timer flag 0
Program CLR TR0 ;Stop the timer 0
(cont’) CLR TF0 ;Clear TF0 for next round
CLR P2.3
Solution:
(a) (FFFFH - B83E + 1) = 47C2H = 18370 in decimal and 18370 × 1.085 us = 19.93145 ms
(b) Since TH - TL = B83EH = 47166 (in decimal) we have 65536 - 47166 = 18370. This means that the
timer counts from B38EH to FFFF. This plus Rolling over to 0 goes through a total of 18370 clock cycles,
where each clock is 1.085 us in duration. Therefore, we have 18370 × 1.085 us = 19.93145 ms as the
width of the pulse.
15
Example 9-8
Modify TL and TH in Example 9-7 to get the largest time delay
PROGRAMMINGp ossible. Find the delay in ms. In your calculation, exclude the
16
Example 9-9
The following program generates a square wave on P1.5 continuously
PROGRAMMING using timer 1 for a time delay. Find the frequency of the square
TIMERS wave if XTAL = 11.0592 MHz. In your calculation do not
include the overhead due to Instructions in the loop.
Also notice that the high portion and low portion of the square wave
pulse are equal. In the above calculation, the overhead due to all
the instruction in the loop is not included.
17
‰ To calculate the values to be loaded
PROGRAMMING
TIMERS
into the TL and TH registers, look at
the following example
Mode 1 Assume XTAL = 11.0592 MHz, we can
Programming use the following steps for finding the TH,
TL registers’ values
Finding the 1. Divide the desired time delay by 1.085 us
Loaded Timer
2. Perform 65536 - n, where n is the decimal
Values
value we got in Step1
3. Convert the result of Step2 to hex, where
yyxx is the initial hex value to be loaded into
the timer’s register
4. Set TL = xx and TH = yy
18
Example 9-10
Assume that XTAL = 11.0592 MHz. What value do we need to load
PROGRAMMING the timer’s register if we want to have a time delay of 5 ms
TIMERS (milliseconds)? Show the program for timer 0 to create a pulse width
of 5 ms on P2.3.
Mode 1 Solution:
Since XTAL = 11.0592 MHz, the counter counts up every 1.085 us.
Programming This means that out of many 1.085 us intervals we must make a 5 ms
pulse. To get that, we divide one by the other. We need 5 ms / 1.085
Finding the us = 4608 clocks. To Achieve that we need to load into TL and TH
Loaded Timer the value 65536 - 4608 = EE00H. Therefore, we have TH = EE and
TL = 00.
Values
(cont’) CLR P2.3 ;Clear P2.3
MOV TMOD,#01 ;Timer 0, 16-bitmode
HERE: MOV TL0,#0 ;TL0=0, the low byte
MOV TH0,#0EEH ;TH0=EE, the high byte
SETB P2.3 ;SET high P2.3
SETB TR0 ;Start timer 0
AGAIN: JNB TF0,AGAIN ;Monitor timer flag 0
CLR TR0 ;Stop the timer 0
CLR TF0 ;Clear timer 0 flag
19
Example 9-11
Assume that XTAL = 11.0592 MHz, write a program to generate a
PROGRAMMING
square wave of 2 kHz frequency on pin P1.5.
TIMERS
Solution:
Mode 1 This is similar to Example 9-10, except that we must toggle the bit to
generate the square wave. Look at the following steps.
Programming (a) T = 1 / f = 1 / 2 kHz = 500 us the period of square wave.
(b) 1 / 2 of it for the high and low portion of the pulse is 250 us.
Finding the (c) 250 us / 1.085 us = 230 and 65536 - 230 = 65306 which in hex
Loaded Timer is FF1AH.
Values (d) TL = 1A and TH = FF, all in hex. The program is as follow.
(cont’) MOV TMOD,#01 ;Timer 0, 16-bitmode
AGAIN: MOV TL1,#1AH ;TL1=1A, low byte of
timer MOV TH1,#0FFH ;TH1=FF, the high
byteTR1
SETB ;Start timer 1
BACK: JNB TF1,BACK ;until timer rolls over
CLR TR1 ;Stop the timer 1
CLR P1.5 ;Clear timer flag 1
CLR TF1 ;Clear timer 1 flag
SJMP AGAIN ;Reload timer
20
Example 9-12
Assume XTAL = 11.0592 MHz, write a program to generate a square
PROGRAMMING wave of 50 kHz frequency on pin P2.3.
TIMERS
Solution:
Look at the following steps.
Mode 1 (a) T = 1 / 50 = 20 ms, the period of square wave.
Programming (b) 1 / 2 of it for the high and low portion of the pulse is 10 ms.
(c) 10 ms / 1.085 us = 9216 and 65536 - 9216 = 56320 in decimal,
and in hex it is DC00H.
Finding the
(d) TL = 00 and TH = DC (hex).
Loaded Timer
Values MOV TMOD,#10H ;Timer 1, mod 1
(cont’) AGAIN: MOV TL1,#00 ;TL1=00,low byte of timer
MOV TH1,#0DCH ;TH1=DC, the high byte
SETB TR1 ;Start timer 1
BACK: JNB TF1,BACK ;until timer rolls over
CLR TR1 ;Stop the timer 1
CLR P2.3 ;Comp. p2.3 to get hi, lo
SJMP AGAIN ;Reload timer
;mode 1 isn’t auto-reload
21
Example 9-13
PROGRAMMING Examine the following program and find the time delay in seconds.
TIMERS Exclude the overhead due to the instructions in the loop.
22
‰ The following are the characteristics
PROGRAMMING and operations of mode 2:
TIMERS
1. It is an 8-bit timer; therefore, it allows
only values of 00 to FFH to be loaded
Mode 2 into the timer’s register TH
Programming
2. After TH is loaded with the 8-bit value,
the 8051 gives a copy of it to TL
ƒ Then the timer must be started
ƒ This is done by the instruction SETB TR0 for
timer 0 and SETB TR1 for timer 1
3. After the timer is started, it starts to
count up by incrementing the TL register
ƒ It counts up until it reaches its limit of FFH ƒ
When it rolls over from FFH to 00, it sets high the
TF (timer flag)
23
When the TL register rolls from FFH to 0
4.
PROGRAMMINGand TF is set to 1, TL is reloaded
TIMERS
automatically with the original value kept
by the TH register
Mode 2 ƒ To repeat the process, we must simply clear
Programming TF and let it go without any need by the
(cont’) programmer to reload the original value ƒ
This makes mode 2 an auto-reload, in
contrast with mode 1 in which the
programmer has to reload TH and TL
XTAL Overflow
÷12 TL TF
oscillator flag
TR TF goes high
C/T = 0 Reload
when FF → 0
TH
24
‰ To generate a time delay
PROGRAMMING
1. Load the TMOD value register indicating
TIMERS
which timer (timer 0 or timer 1) is to be
used, and the timer mode (mode 2) is
Mode 2 selected
Programming 2. Load the TH registers with the initial
count value
Steps to Mode 2
Program 3. Start timer
4.Keep monitoring the timer flag (TF) with
the JNB TFx,target instruction to see
whether it is raised
ƒ Get out of the loop when TF goes high
5. Clear the TF flag
6. Go back to Step4, since mode 2 is auto-
reload
25
Example 9-14
PROGRAMMING Assume XTAL = 11.0592 MHz, find the frequency of the square
TIMERS wave generated on pin P1.0 in the following program
MOV TMOD,#20H ;T1/8-bit/auto reload
Mode 2 MOV TH1,#5 ;TH1 = 5
Programming SETB TR1 ;start the timer 1
BACK: JNB TF1,BACK ;till timer rolls over
CPL P1.0 ;P1.0 to hi, lo
Steps to Mode 2 CLR TF1 ;clear Timer 1 flag
Program SJMP BACK ;mode 2 is auto-reload
(cont’)
Solution:
First notice the target address of SJMP. In mode 2 we do not need to reload TH since it is auto-reload. Now
(256 - 05) × 1.085 us = 251 × 1.085 us = 272.33 us is the high portion of the pulse. Since it is a
50% duty cycle square wave, the period T is twice that; as a result T = 2 × 272.33 us = 544.67 us
and the frequency = 1.83597 kHz
26
Example 9-15
PROGRAMMING Find the frequency of a square wave generated on pin P1.0.
TIMERS
Solution:
27
Example 9-16
PROGRAMMING Assuming that we are programming the timers for mode 2, find the
value (in hex) loaded into TH for each of the following cases.
TIMERS
(a) MOV TH1,#-200 (b) MOV TH0,#-60
Mode 2 (c) MOV TH1,#-3 (d) MOV TH1,#-12
(e) MOV TH0,#-48
Programming
Solution:
Steps to Mode 2 You can use the Windows scientific calculator to verify the result
Program provided by the assembler. In Windows calculator, select
(cont’) decimal and enter 200. Then select hex, then +/- to get the TH
value. Remember that we only use the right two digits and ignore
the rest since our data is an 8-bit data.
Decimal 2’s complement (TH value)
-3 FDH
-12 F4H The advantage of using
The number 200 is the
-48 D0H negative values is that you
timer count till the TF
-60 C4H don’t need to calculate the
is set to 1
-200 38H value loaded to THx
28
‰ Timers can also be used as counters
COUNTER
PROGRAMMING
counting events happening outside the
8051
When it is used as a counter, it is a pulse
outside of the 8051 that increments the
TH, TL registers
TMOD and TH, TL registers are the same as
for the timer discussed previously ‰
Programming the timer in the last section
also applies to programming it as a
counter
Except the source of the frequency
29
‰ The C/T bit in the TMOD registers
COUNTER
PROGRAMMING
decides the source of the clock for the
timer
C/T Bit in When C/T = 1, the timer is used as a
TMOD Register counter and gets its pulses from outside
the 8051
ƒ The counter counts up as pulses are fed from
pins 14 and 15, these pins are called T0 (timer
0 input) and T1 (timer 1 input)
30
Example 9-18
Assuming that clock pulses are fed into pin T1, write a
program COUNTERfor counter 1 in mode 2 to count the pulses and display the state
of the TL1 count on P2, which connects to 8 LEDs.
PROGRAMMING
Solution:
C/T Bit in MOV TM0D,#01100000B ;counter 1, mode 2,
;C/T=1 external pulses
TMOD Register MOV TH1,#0;clear TH1
(cont’) SETB P3.5 ;make T1 input
AGAIN: SETB TR1 ;start the counter
BACK: MOV A,TL1 ;get copy of TL
MOV P2,A ;display it on port 2
JNB TF1,Back ;keep doing, if TF = 0
CLR TR1 ;stop the counter 1
CLR TF1 ;make TF=0
SJMP AGAIN ;keep doing it
Notice in the above program the role of the instruction SETB P3.5.
Since ports are set up for output when the 8051 is powered up,
we make P3.5 an input port by making it high. In other words,
we must configure (set high) the T1 pin (pin P3.5) to allow
pulses to be fed into it.
31
COUNTER Timer with external input (Mode 1)
PROGRAMMING Timer Overflow
external flag
input pin
TH TL TF
C/T Bit in 3.4 or 3.5
TF goes high
TMOD Register C/T = 1 TR when FFFF → 0
(cont’)
32
‰ TCON (timer control) register is an 8-
COUNTER
PROGRAMMING
bit register
TCON: Timer/Counter Control Register
TCON
Register TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0
33
‰ TCON register is a bit-addressable
COUNTER
PROGRAMMING
register
Equivalent instruction for the Timer Control Register
TCON For timer 0
Register SETB TR0 = SETB TCON.4
(cont’) CLR TR0 = CLR TCON.4
SETB TF0 = SETB TCON.5
CLR TF0 = CLR TCON.5
For timer 1
SETB TR1 = SETB TCON.6
CLR TR1 = CLR TCON.6
SETB TF1 = SETB TCON.7
CLR TF1 = CLR TCON.7
34
‰ If GATE = 1, the start and stop of the
COUNTER
PROGRAMMING
timer are done externally through pins
P3.2 and P3.3 for timers 0 and 1,
TCON respectively
Register This hardware way allows to start or stop
the timer externally at any time via a
Case of GATE = 1
simple switch
XTAL
÷12 C/T = 0
oscillator
Tx Pin
Pin 3.4 or 3.5 C/T = 1
Gate TR
INT0 Pin
Pin 3.2 or 3.3
35
Example 9-20
Write an 8051 C program to toggle all the bits of port P1
continuously PROGRAMMINGwith some delay in between. Use Timer 0, 16-bit mode to
generate the delay.
TIMERS IN C
Solution:
Accessing #include <reg51.h>
void T0Delay(void);
Timer Registers void main(void){
while (1) {
P1=0x55;
T0Delay();
P1=0xAA;
T0Delay(); }
}
void T0Delay(){
TMOD=0x01; FFFFH -3500H = CAFFH
TL0=0x00;
TH0=0x35; = 51967 + 1 = 51968
TR0=1; 51968 × 1.085 μs = 56.384 ms is the
while (TF0==0);
TR0=0; approximate delay
TF0=0;
}
36
‰ To speed up the 8051, many recent
PROGRAMMING
TIMERS IN C
versions of the 8051 have reduced the
number of clocks per machine cycle
Calculating from 12 to four, or even one
Delay Length ‰ The frequency for the timer is always
Using Timers
1/12th the frequency of the crystal
attached to the 8051, regardless of the
8051 version
37
Example 9-21
Write an 8051 C program to toggle only bit P1.5 continuously
every PROGRAMMING50 ms. Use Timer 0, mode 1 (16-bit) to create the delay. Test the
program on the (a) AT89C51 and (b) DS89C420.
TIMERS IN C
Solution:
Times 0/1 #include <reg51.h>
void T0M1Delay(void);
Delay Using sbit mybit=P1^5;
void main(void){
Mode 1 (16-bit while (1)
Non Auto- { mybit=~mybi
T0M1Delay();
t;
reload) }
}
void T0M1Delay(void){
TMOD=0x01;
TL0=0xFD; FFFFH - 4BFDH = B402H
TH0=0x4B; = 46082 + 1 = 46083
TR0=1;
while (TF0==0); 46083 × 1.085 μs = 50 ms
TR0=0;
TF0=0; }
38
Example 9-22
Write an 8051 C program to toggle all bits of P2 continuously every
PROGRAMMING 500 ms. Use Timer 1, mode 1 to create the delay.
TIMERS IN C Solution:
//tested for DS89C420, XTAL = 11.0592 MHz
#include <reg51.h>
Times 0/1 void T1M1Delay(void);
void main(void){
Delay Using unsigned char x;
Mode 1 (16-bit P2=0x55;
while (1) {
Non Auto- P2=~P2;
for (x=0;x<20;x++)
reload) T1M1Delay();
(cont’) }
}
void T1M1Delay(void){
TMOD=0x10;
TL1=0xFE; A5FEH = 42494 in decimal
TH1=0xA5; 65536 - 42494 = 23042
TR1=1;
while (TF1==0); 23042 × 1.085 μs = 25 ms and
TR1=0; 20 × 25 ms = 500 ms
TF1=0;
}
39
Example 9-25
PROGRAMMING A switch is connected to pin P1.2. Write an 8051 C program to
TIMERS IN C monitor SW and create the following frequencies on pin P1.7:
SW=0: 500Hz
SW=1: 750Hz, use Timer 0, mode 1 for both of them.
Times 0/1
Solution:
Delay Using #include <reg51.h>
Mode 1 (16-bit sbit mybit=P1^5;
sbit SW=P1^7;
Non Auto- void T0M1Delay(unsigned char);
void main(void){
reload) SW=1;
(cont’) while (1) {
mybit=~mybit; if
(SW==0)
T0M1Delay(0);
else
T0M1Delay(1);
}
}
40
Example 9-25
PROGRAMMING
TIMERS IN C
void T0M1Delay(unsigned char c){
TMOD=0x01;
Times 0/1 if (c==0) {
Delay Using TL0=0x67; FC67H = 64615
TH0=0xFC; 65536 - 64615 = 921
Mode 1 (16-bit }
else { 921 × 1.085 μs = 999.285 μs
Non Auto- TL0=0x9A; 1 / (999.285 μs × 2) = 500 Hz
reload) }
TH0=0xFD;
(cont’) TR0=1;
while (TF0==0);
TR0=0;
TF0=0;
}
41
Example 9-23
Write an 8051 C program to toggle only pin P1.5 continuously every
250 ms. Use Timer 0, mode 2 (8-bit auto-reload) to create the
PROGRAMMING delay.
TIMERS IN C
Solution:
#include <reg51.h>
Times 0/1 void T0M2Delay(void);
sbit mybit=P1^5;
Delay Using void main(void){ Due to overhead of the for loop
Mode 2 (8-bit unsigned char x,y;
while (1) {
in C, we put 36 instead of 40
Auto-reload) mybit=~mybit;
for (x=0;x<250;x++)
for (y=0;y<36;y++) //we put 36, not 40
T0M2Delay();
}
}
void T0M2Delay(void){
TMOD=0x02;
TH0=-23; 256 - 23 = 233
TR0=1; 23 × 1.085 μs = 25 μs and
while (TF0==0);
TR0=0; 25 μs × 250 × 40 = 250 ms
TF0=0;
}
42
Example 9-24
PROGRAMMING Write an 8051 C program to create a frequency of 2500 Hz on pin
TIMERS IN C P2.7. Use Timer 1, mode 2 to create delay.
Solution:
Times 0/1 #include <reg51.h>
void T1M2Delay(void);
Delay Using sbit mybit=P2^7;
Mode 2 (8-bit void main(void){
unsigned char x;
Auto-reload) while (1) {
mybit=~mybit;
(cont’) T1M2Delay();
}
}
void T1M2Delay(void){
TMOD=0x20; 1/2500 Hz = 400 μs
TH1=-184;
TR1=1; 400 μs /2 = 200 μs
while (TF1==0); 200 μs / 1.085 μs = 184
TR1=0;
TF1=0;
}
43
Example 9-26
PROGRAMMING Assume that a 1-Hz external clock is being fed into pin T1 (P3.5). Write
TIMERS IN C a C program for counter 1 in mode 2 (8-bit auto reload) to count
up and display the state of the TL1 count on P1. Start the count at 0H.
C Programming Solution:
#include <reg51.h>
of Timers as sbit T1=P3^5;
Counters void main(void){
T1=1;
TMOD=0x60;
TH1=0;
while (1) {
do {
TR1=1;
P1=TL1;
}
while (TF1==0);
TR1=0;
TF1=0;
}
}
44
Example 9-27
Assume that a 1-Hz external clock is being fed into pin T0 (P3.4).
PROGRAMMINGWrite a C program for counter 0 in mode 1 (16-bit) to count the pulses
TIMERS IN C and display the state of the TH0 and TL0 registers on P2 and P1,
respectively.
C Programming Solution:
#include <reg51.h>
of Timers as void main(void){
T0=1;
Counters TMOD=0x05;
(cont’) TL0=0
TH0=0;
while (1) {
do {
TR0=1;
P1=TL0;
P2=TH0; }
while (TF0==0);
TR0=0;
TF0=0;
}
}
45
4.4 Vào ra nối tiếp
164
SERIAL COMMUNICATION
1. Định nghĩa, Vai trò, mục đích
BASICS OF
Truyền Nối tiếp ( Serial Transfer)
SERIAL
Dữ liệu được truyền từng bít theo thời gian
COMMUNICA-
TION Để truyền dữ liệu đi xa người ta thường sử
dụng truyền tín nối tiếp
Parallel Transfer
D0
Serial Transfer
Sender Receiver
Sender Receiver
D7
2
Tại nơi truyền 1 byte dữ liệu cần phải
BASICS OF biến đổi thành các bit nối tiếp sử dụng
SERIAL
thanh ghi vào song song- ra nối tiếp
COMMUNICA-
TION Tại nơi nhận thì sử dụng thanh ghi
(cont’) Vào nối tiếp – ra song song để nhận
dữ liệu nối tiếp và đóng gói thành 1 byte
Khi khoảng cách gần, tín hiệu số có thể truyền
nguyên bản bằng đường dây đơn giản và không
cần phải điều chế (modulation)
Nếu dữ liệu được truyền trên đường dây điện
thoại , Nó cần được chuyển đổi thành tín hiệu 0/1
dạng audiotones
Thiết bị chuyển đổi này gọi là MODEM
“Modulator/demodulator”
3
Truyền tin nối tiếp sử dụng 2 phương thức
BASICS OF
SERIAL
Phương thức đồng bộ : Truyền cả khối dữ liệu
COMMUNICA- Trong khoảng thời gian
TION
Phương thức không đồng bộ : Truyền từng byte
(cont’)
trong khoảng thời gian
4
Chế độ truyền nối tiếp
Simplex : Nếu data chỉ truyền theo 1 chiều
BASICS OF Half Duplex: Nếu data chỉ truyền theo 1 chiều
SERIAL trong 1 khoảng thời gian
COMMUNICA- Full duplex : Dữ liệu được truyền nhận đồng thời
TION
cả 2 chiều
Half- and Full-
Duplex
Transmission Simplex Transmitter Receiver
Transmitter Receiver
Half Duplex
Receiver Transmitter
Transmitter Receiver
Full Duplex
Receiver Transmitter
5
Giao thức ( Protocol ) là tập hợp các quy định
BASICS OF được đồng ý bởi cả bên phát và bên nhận về việc:
SERIAL Dữ liệu đóng gói như thế nào
COMMUNICA- Dữ liệu dài bao nhiêu bít
TION
Khi nào dữ liệu bắt đầu và kết thúc
Start and Stop
Truyền tin nối tiếp dị bộ sử dụng để truyền từng
Bits
ký tự ( byte)
6
‰ Start bit luôn là 0 (low) và
BASICS OF Stop bit (s) luôn là 1 (high)
SERIAL
COMMUNICA- ASCII character “A” (8-bit binary 0100 0001)
TION
Bit
(cont’)
D7 D0
7
Ký tự ASCII mở rộng có độ dài 8 bit
BASICS OF Sử dụng mã ASCII 8 bit
SERIAL
Trong các hệ thống cũ , ký tự ASCII dài 7 bit
COMMUNICA-
TION Trong các hệ PCs mới sử dụng chuẩn bit
STOP dài 1 bit.
STr Trong các hệ thống cũ thường sử dụng
Start and bit STOP dài 2 bit, lý do là các ngoại vi
Stop Bits thế hệ cũ tốc độ chậm nên cần thời gian
dài hơn để hoàn thành việc nhận dữ liệu.
(cont’)
8
Trong truyền tin nối tiếp nhịp truyền
BASICS OF được định nghĩa là bps (bits per second)
SERIAL
COMMUNICA- Có một thuật ngữ khác tính nhịp truyền là
TION baud rate
Baud rate là thuật ngữ của modem và được định
Data Transfer nghĩa là số lần thay đổi tín hiệu trong 1 s
Rate In modems, có trường hợp một lần thay đổi tín hiệu
Có thể truyền đi vài bit
10
‰ The data transfer rate of given
BASICS OF computer system depends on
SERIAL communication ports incorporated into
COMMUNICA- that system
TION IBM PC/XT could transfer data at the rate
of 100 to 9600 bps
Data Transfer Pentium-based PCs transfer data at rates as
Rate high as 56K bps
(cont’) In asynchronous serial data communication,
the baud rate is limited to 100K bps
11
‰ A line driver such as the MAX232 chip is
8051 required to convert RS232 voltage
CONNECTION levels to TTL levels, and vice versa
TO RS232 ‰ 8051 has two pins that are used
specifically for transferring and receiving
data serially
These two pins are called TxD and RxD and
are part of the port 3 group (P3.0 and P3.1)
These pins are TTL compatible; therefore, they
require a line driver to make them RS232
compatible
18
‰ To allow data transfer between the PC
SERIAL and an 8051 system without any error,
COMMUNICA- we must make sure that the baud rate
TION of 8051 system matches the baud rate
PROGRAMMING of the PC’s COM port
‰ Hyperterminal function supports baud
rates much higher than listed below
PC Baud Rates
110
150
300
600
1200
2400
4800
9600
19200 Baud rates supported by
486/Pentium IBM PC BIOS
21
With XTAL = 11.0592 MHz, find the TH1 value needed to have the
following baud rates. (a) 9600 (b) 2400 (c) 1200
SERIAL Solution:
COMMUNICA- The machine cycle frequency of 8051 = 11.0592 / 12 = 921.6 kHz,
and 921.6 kHz / 32 = 28,800 Hz is frequency by UART to timer 1 to
TION
set baud rate.
PROGRAMMING (a) 28,800 / 3 = 9600 where -3 = FD (hex) is loaded into TH1
(cont’) (b) 28,800 / 12 = 2400 where -12 = F4 (hex) is loaded into TH1
(c) 28,800 / 24 = 1200 where -24 = E8 (hex) is loaded into TH1
Notice that dividing 1/12 of the crystal frequency by 32 is the default
value upon activation of the 8051 RESET pin.
11.0592 MHz
22
4.5 CÁC CHUẨN NỐI TIẾP ( Tiếp theo )
• UART
• Chuẩn I2C
• Chuẩn SPI
• Chuẩn CAN bus
• Chuẩn USB
178
UART
04/18/24
Giới thiệu chung về UART
Cấu trúc
04/18/24
Đặc điểm của UART
04/18/24
Đặc điểm của UART
Định dạng nối tiếp
Việc truyền tải được thực hiện theo từng kí tự 7 hoặc 8 bit,
được bổ sung 2 bit đánh dấu đầu cuối và một bit kiểm tra lỗi
chẵn lẻ (parity bit).Ví dụ với 8 bit được minh hoạ dưới đây:
start 0 1 2 3 4 5 6 7 P Stop
04/18/24 group 6
182
Đặc điểm của UART
04/18/24
Đặc điểm của UART
04/18/24
Đặc điểm của UART
04/18/24
UART- Các chế độ hoạt động
04/18/24
UART- Các chế độ hoạt động
Mode 0:
Dữ liệu truyền nối tiếp vào và ra qua cổng RxD, TxD.
Truyền và nhận 8 bit, bit thấp nhất được truyền trước (LSB).
Tốc độ baud xấp xỉ 1/16 tần số xung nhịp của CPU.
04/18/24
UART- Các chế độ hoạt động
Mode 1:
10 bit phát (qua TxD) hoặc nhận (qua RxD):1start bit
(logic ‘0’), 8 data bit (LSB trước) và 1 stop bit (logic ‘1’).
Khi dữ liệu đang nhận, stop bit chứa trong RB8 trong
thanh ghi chức năng đặc biệt SCON, tốc độ baud là một số
có thể thay đổi và xác định bằng tốc độ tràn của Timer 1
hay từ bộ sinh tốc độ baud.
04/18/24
UART- Các chế độ hoạt động
Mode 2:
11 bit được phát (qua TxD) hoặc nhận(RxD): 1 start bit
(logic ‘0’), 8 data bit, data bit thứ 9 có thể lập trình, và
1 stop bit (logic ‘1’).
Tốc độ baud được chọn bằng 1/16 hoặc 1/32 tần số
CCLK, tùy vào giá trị của bit SMOD ở thanh ghi
PCON.
04/18/24
UART- Các chế độ hoạt động
Mode 3:
04/18/24
UART- Các chế độ hoạt động
04/18/24
UART- Lập trình truyền thông
Tốc độ baud trong 8051.
8051 truyền và nhận dữ liệu nối tiếp theo nhiều
tốc độ khác nhau.
Tốc độ truyền của nó có thể lập trình được, thực
hiện nhờ sự trợ giúp của bộ định thời Timer1.
Muốn Timer1 đặt tốc độ baud thì nó phải được lập
trình về chế độ làm việc mode2, đó là chế độ thanh ghi
8 bít tự động nạp lại.
04/18/24
UART- Lập trình truyền thông
Tốc độ baud trong 8051.
Các giá trị của thanh ghi TH1 trong Timer1 cho các
tốc độ baud khác nhau:
04/18/24
UART- Lập trình truyền thông
Tốc độ baud trong 8051.
2 SMOD * OscillatorFrequency
TH 1 256
384 * BaudRate
04/18/24
UART- Lập trình truyền thông
04/18/24
UART- Lập trình truyền thông
04/18/24
UART- Lập trình truyền thông
04/18/24
UART- Lập trình truyền thông
04/18/24
UART- Lập trình truyền thông
04/18/24
UART- Lập trình truyền thông
04/18/24
UART- Lập trình truyền thông
04/18/24
UART- Lập trình truyền thông
Chú ý:
Bằng việc hiển thị cờ TI ta biết chắc rằng ta không nạp
quá vào thanh ghi SBUF.
Nếu ta nạp một byte vào SBUF trước ghi TI được bật
thì phần dữ liệu của byte trước chưa truyền hết sẽ bị
mất.
Bít cờ TI có thể kiểm tra bằng lệnh “JNB TI …” hoặc
có thể sử dụng ngắt ở địa chỉ 0023H trong ROM
04/18/24
UART- Lập trình truyền thông
04/18/24
UART- Lập trình truyền thông
2. Nạp TH1 giá trị để tạo ra tốc độ baud với giả thiết XTAL =
10.0592MHz, theo bảng:
04/18/24
UART- Lập trình truyền thông
04/18/24
UART- Lập trình truyền thông
Ghép nối
Ưu nhược điểm
04/18/24
RS232- Đặc điểm
04/18/24
RS232- Đặc điểm
04/18/24
RS232- Đặc điểm
04/18/24
RS232- Đặc điểm
Mức điện áp
04/18/24
RS232- Đặc điểm
Mức logic
• Mức 1 ứng với điện áp từ -25V đến -3V
• Mức 0 ứng với điện áp + 3V đến +25V
• Điện áp – 3V đến + 3V là không xác định.
→Vì lý do này để kết nối một RS232 bất kỳ đến một hệ
vi điều khiển thì ta phải sử dụng các bộ biến đổi điện
áp như MAX232 để chuyển đổi các mức lô-gíc TTL
về mức điện áp RS232 và ngược lại. Các chíp IC
MAX232 nhìn chung được coi như các bộ điều khiển
đường truyền.
04/18/24
RS232 – Ghép nối
04/18/24
RS232 – Ghép nối
DB9
04/18/24
RS232 – Ghép nối
DB9
1. Data carrier detect (DCD) – Phát hiện tín hiệu mang dữ liệu
2. Received data (RxD) - Dữ liệu được nhận
3. Transmitted data (TxD) - Dữ liệu được gửi
4. Data terminal ready (DTR) - Đầu cuối dữ liệu sẵn sàng
5. Signal ground (GND) – Đất của tín hiệu
6. Data set ready (DSR) - Dữ liệu sẵn sàng
7. Request to send (RTS) - Yêu cầu gửi
8. Clear to send (CTS) - Xoá để gửi
9. Ring indicator (RL) - Báo chuông
04/18/24
RS232 – Ghép nối
DB25
04/18/24
RS232 – Ghép nối
ALT A
04/18/24
RS232 - Ghép nối
04/18/24
RS232 - Ghép nối
04/18/24
RS232 - Ghép nối
Sơ đồ MAX232
04/18/24
‰ We need a line driver (voltage
8051 converter) to convert the R232’s signals
CONNECTION to TTL voltage levels that will be
TO RS232 acceptable to 8051’s TxD and RxD pins
MAX232 Vcc
C3
MAX232 requires
16 2
+
four capacitors
+
1 MAX232
C1
3 6 8051
4 C4
+
C2
+
MAX232
5 11 11
P3.1
TxD 14 2 5
T1in T1out
11 14
13 3
R1out R1in P3.0 10 12
12 13
RxD
T2in T2out
10 7
DB-9
R2out R2int
9 8
19
RS232 - Ưu nhược điểm
04/18/24
RS232 - Ưu nhược điểm của
04/18/24
RS485
04/18/24
RS485
Ghép nối
Ưu nhược điểm
04/18/24
RS485 - Đặc điểm chung
04/18/24
RS485 - Đặc điểm chung
04/18/24
RS485 - Đặc điểm chung
04/18/24
RS485 – Các chế độ truyền
04/18/24
RS485 - Ưu nhược điểm
04/18/24
SPI
04/18/24 group 6
235
SPI
SPI
04/18/24
SPI – Đặc điểm chung
04/18/24
SPI – Đặc điểm chung
04/18/24
SPI – Đặc điểm chung
04/18/24
SPI – Truyền dữ liệu
04/18/24
SPI – Truyền dữ liệu
04/18/24
SPI – Truyền dữ liệu
Master cấu hình cho Clock, tần số nhỏ hơn hoặc bằng
tần số cực đại mà Slave hỗ trợ.(Tần số phổ biến từ 0-
70MHz).
Master kéo bit SS (slave select) xuống mức thấp để
yêu cầu chip, trên các slave nếu SS ở mức cao không
làm việc. Nếu có một khoảng thời gian chờ được yêu
cầu, thì khi đó master phải chờ ít nhất là khoảng thời
gian trên để bắt đầu cấp phát xung clock.
04/18/24
SPI – Truyền dữ liệu
04/18/24
SPI – Các chế độ hoạt động
Tùy vào pha (phase) và cực tính (polarity) của tín hiệu SCK, có 4
chế độ khác nhau được định nghĩa cho giao thức SPI:
Chế độ (0, 0): Chân SCK ổn định ở mức '0' khi không
có xung, lấy mẫu dữ liệu ở đầu chu kỳ (cạnh trước
của xung clock).
Chế độ (0, 1): Chân SCK ổn định ở mức '0' khi không
có xung, lấy mẫu dữ liệu ở giữa chu kỳ (cạnh sau của
xung clock).
04/18/24
SPI – Các chế độ hoạt động
Chế độ (1, 0): Chân SCK ổn định ở mức '1' khi không
có xung, lấy mẫu dữ liệu ở đầu chu kỳ (cạnh trước của
xung clock).
Chế độ (1, 1): Chân SCK ổn định ở mức '1' khi không
có xung, lấy mẫu dữ liệu ở giữa chu kỳ (cạnh sau của
xung clock).
04/18/24
SPI – Các chế độ hoạt động
Số lượng xung clock (số bit dữ liệu của mỗi từ) không
bị giới hạn là 8, vì thực tế không có ủy ban tiêu chuẩn
nào phê chuẩn giao thức SPI. Cũng vì lý do này, thứ
tự truyền các bit trong các thông điệp cũng có thể khác
nhau, hay mức tích cực của chân SS cũng có thể thay
đổi giữa các vi mạch khác nhau, và một số vi mạch
cũng có thể chỉ thu hoặc phát dữ liệu theo một chiều
duy nhất.
04/18/24
Project
04/18/24
Project
Chương trình viết bằng ASM
MOV TMOD, #20H ; Chọn bộ Timer1, chế độ 2
MOV TH1, # - 3 ; Chọn tốc độ 9600 baud
MOV SCON, #50H ; Truyền 8 bít dữ liệu, 1 bít Stop cho phép thu
SETB TR1 ; Khởi động Timer1
AGAIN: MOV A, # “U" ; Truyền ký tự “U”
ACALL TRANS
MOV A, # “A" ; Truyền ký tự “A”
ACALL TRANS
MOV A, # “R" ; Truyền ký tự “R”
ACALL TRANS
MOV A, # “T" ; Truyền ký tự “T”
ACALL TRANS
SJMP AGAIN ; Tiếp tục
04/18/24
Project
Chương trình viết bằng ASM
; Chương trình con truyền dữ liệu nối tiếp.
TRANS: MOV SBUF, A ; Nạp SBUF
HERE: NB TI, HERE ; Chờ cho đến khi truyền bít cuối cùng
CLR TI ; Chờ sẵn cho một byte kế tiếp
RET
04/18/24
Project
04/18/24
Project
Chương trình viết bằng ASM
MOV TMOD, #20H ; Chọn bộ Timer1, chế độ 2 (tự động nạp lại)
MOV TH1, # - 3 ; Chọn tốc độ 9600 baud
MOV SCON, #50H ; Chọn khung dữ liệu 8 bít, 1 bít Stop.
SETB TR1 ; Khởi động bộ Timer1
HERE: JNB R1, HERE ; Đợi nhận toàn bộ lý tự vào hết
MOV A, SBUF ; Lưu cất ký tự vào thanh A
MOV P1, A ; Gửi ra cổng P.1
CLR RI ; Sẵn sàng nhận byte kế tiếp
SJMP HERE ; Tiếp tục nhận dữ liệu
04/18/24
Project
Sử dụng ngắt
Chương trình trong đó 8051 nhận dữ liệu từ cổng P1 và gửi liên
tục đến cổng P2 trong khi đó dữ liệu đi vào từ cổng nối tiếp
COM được gửi đến cổng P0. Giả thiết tần số XTAL là
11.0592MHz và tốc độ baud 9600.
04/18/24
Project
Sử dụng ngắt
ORG 0
LJMP MAIN
ORG 23H
LJMP SERIAL
ORG 03H
MAIN: MOV P1, # FFH ; Lấy cổng P1 là cổng đầu vào
MOV TMOD, # 20H ; Chọn Timer và chế độ hai tự nạp lại
MOV TH1, # 0FDH ;Khung dữ liệu: 8 bít dữ liệu, 1 stop, cho phép REN
MOV SCON, # 50H
MOV IE, # 10010000B ; Cho phép ngắt nối tiếp
SETB TR1 ; Khởi động Timer1
BACK: MOV A, P1 ; Đọc dữ liệu từ cổng P1
MOV P2, A ; Gửi dữ liệu đến cổng P2
SJMP BACK ; ở lại trong vòng lặp
04/18/24
Project
Sử dụng ngắt ( tiếp theo )
; -------------------------Trình phục vụ ngắt cổng nối tiếp.
ORG 100H
SERIAL: JB TI, TRANS ; Nhảy nếu Ti cao
MOV A, SBUF ; Nếu không tiếp tục nhận dữ liệu
MOV P0, A ; Gửi dữ lệu đầu vào đến cổng P0
CLR RI ; Xoá vờ RI vì CPU không xoá cờ này
RETI ; Trở về từ ISR
TRANS: CLS TI ; Xoá cờ TI và CUP không xoá cờ này.
RETI ; trở về từ ISR
END
04/18/24
Serial protocols: I2C
• I2C (Inter-IC)
– Two-wire serial bus protocol developed by Philips Semiconductors
nearly 20 years ago
– Enables peripheral ICs to communicate using simple communication
hardware
– Data transfer rates up to 100 kbits/s and 7-bit addressing possible in
normal mode
– 3.4 Mbits/s and 10-bit addressing in fast-mode
– Common devices capable of interfacing to I2C bus:
• EPROMS, Flash, and some RAM memory, real-time clocks, watchdog
timers, and microcontrollers
257
I2C bus structure
SCL
SDA
From From
Servant receiver
D
C
S A A A A R A D D D A S O
T R 6 5 0 / C 8 7 0 C T P
T w K K
Typical read/write cycle
258
Serial protocols: CAN
259
Serial protocols: FireWire
260
Serial protocols: USB
• USB (Universal Serial Bus)
– Easier connection between PC and monitors, printers, digital speakers, modems,
scanners, digital cameras, joysticks, multimedia game equipment
– 2 data rates:
• 12 Mbps for increased bandwidth devices
• 1.5 Mbps for lower-speed devices (joysticks, game pads)
– Tiered star topology can be used
• One USB device (hub) connected to PC
– hub can be embedded in devices like monitor, printer, or keyboard or can be standalone
• Multiple USB devices can be connected to hub
• Up to 127 devices can be connected like this
– USB host controller
• Manages and controls bandwidth and driver software required by each peripheral
• Dynamically allocates power downstream according to devices
connected/disconnected
261
Intel 8051: Serial Port Interface
• SM0 SM1:
– 00: Mode 0, Shift register, fosc//12
– 01: Mode 1, 8-bit UART, variable
– 10: Mode 2, 9-bit UART, fosc//32 or fosc//64
– 11: Mode 3, 9-bit UART, variable
• SM2: Cho phép tính năng nhiều uP trong Mode 2 và Mode 3
– Khi nhận được bit STOP, Ngắt dẽ được kích hoạt chỉ khi bit
RB8=1 (9th bit =1)
• REN: Enables serial reception ( Cho phép nhận nối tiếp )
– Set/Clear bằng phần mềm
263/175
Intel 8051: Serial Port Interface
7 6 5 4 3 2 1 0
SCON SM0 SM1 SM0 REN TB8 RB8 TI RI
• TB8: 9th data bit, sẽ được truyền trong Mode2 and Mode3
– Set/Clear bằng phần mềm
• RB8: 9th data bit that was received in Mode2 and Mode3
In Mode 1, if SM2=0, is the stop bit that was received
• TI: Transmit interrupt flag ( Cờ ngắt truyền )
– Set bằng phần cứng. Cần xóa bằng phần mềm
• RI: Receive interrupt flag ( Cờ ngắt nhận )
– Set bằng phần cứng. Cần xóa bằng phần mềm
264/175
Intel 8051: Serial Port Interface
• MODE 0:
– Dữ liệu nối tiếp vào / ra qua chân RXD
– TXD xuất ra xung nhịp truyền
– Truyền/ nhận 8 data bits (LSB ra đầu tiên )
– baud rate cố định và bằng 1/12 tần số oscillator
• MODE 1:
– Dữ liệu nối tiếp vào chân RXD, ra ở TXD
– Truyền/ nhận 10 bits :
start bit(0), 8 data bits (LSB first), stop bit(1)
– Khi nhận thì bít stop được ghi vào bit RB8 trong SCON
– The baud rate thay đổi được
Intel 8051: Serial Port Interface
• MODE 2:
– Dữ liệu nối tiếp vào chân RXD, ra ở TXD
– Truyền/ nhận 11 bits :
start bit(0), 8 data bits (LSB first), a programmable 9th bit,
stop bit(1)
– Khi truyền , 9th bit là bit TB8 trong thanh ghi SCON
– Khi nhận , 9th bit ghi vào bit RB8 trong thanh ghi SCON
– The baud rate lập trình được bằng
1/32 hoặc 1/64 the oscillator frequency
• MODE 3:
– MODE 3 cơ bản giống MODE2, chỉ khác là
– The baud rate thay đổi được giống MODE 1
Intel 8051: Serial Port Interface
• Mode 0 Baud Rate = Oscillator frequency/12
• Mode 2 Baud Rate =[(2SMOD)/64]*Oscillator frequency
– SMOD is bit in Special Function Register PCON
• Mode 1 and Mode3 baud rate is
determined by Timer 1 overflow rate
• Mode 1,3 Baud Rate =[(2SMOD)/32]* Timer 1 Overflow Rate
– Timer mode, auto-reload :
Timer Overflow Rate=Oscillator frequency/[12*(256-TH1)]
Intel 8051: Serial Port Interface
Timer1
Baud
fosc SMOD
Rate Reload
C/T Mode
Value
62.5 K 12 MHz 1 0 2 FF
19.2 K 11.059 MHz 1 0 2 FD
9.6 K 11.059 MHz 0 0 2 FD
4.8 K 11.059 MHz 0 0 2 FA
2.4 K 11.059 MHz 0 0 2 F4
1.2 K 11.059 MHz 0 0 2 E8
135.5 11.059 MHz 0 0 2 1D
110 6 MHz 0 0 2 72
110 12 MHz 0 0 1 FEEB
268/175
Serial Transmission Using UARTs
• UART: Universal
embedded
Asynchronous Receiver 1 0
device
1 1
Transmitter 0
0 1 1
error checking
• Start bit, stop bit
• Baud rate
– signal changes per second
– bit rate usually higher 1 0 0 1 1 0 1 1
269
LẬP TRÌNH TRUYỀN TIN NỐI TIẾP 8051
270
‰ TI (transfer interrupt) is raised when
SERIAL
COMMUNI-
the last bit of the framed data, the
CATION stop bit, is transferred, indicating that
INTERRUPT the SBUF register is ready to transfer
the next byte
‰ RI (received interrupt) is raised when
the entire frame of data, including the
stop bit, is received
In other words, when the SBUF register
has a byte, RI is raised to indicate that the
received byte needs to be picked up before
it is lost (overrun) by new incoming serial
data
33
‰ In the 8051 there is only one interrupt
SERIAL
COMMUNI-
set aside for serial communication
CATION This interrupt is used to both send and
INTERRUPT receive data
If the interrupt bit in the IE register (IE.4)
RI and TI Flags is enabled, when RI or TI is raised the
and Interrupts 8051 gets interrupted and jumps to
memory location 0023H to execute the ISR
In that ISR we must examine the TI and RI
flags to see which one caused the interrupt
and respond accordingly
TI
0023H
RI
Serial interrupt is invoked by TI or RI flags
34
‰ The serial interrupt is used mainly for
SERIAL
COMMUNI-
receiving data and is never used for
CATION sending data serially
INTERRUPT This is like getting a telephone call in
which we need a ring to be notified
Use of Serial If we need to make a phone call there are
COM in 8051 other ways to remind ourselves and there
is no need for ringing
However in receiving the phone call, we
must respond immediately no matter what
we are doing or we will miss the call
35
Example 11-8
Write a program in which the 8051 reads data from P1 and writes it to
SERIAL P2 continuously while giving a copy of it to the serial COM port to be
transferred serially. Assume that XTAL=11.0592. Set the baud rate at
COMMUNI- 9600.
CATION Solution:
INTERRUPT ORG 0000H
LJMP MAIN
ORG 23H
Use of Serial LJMP SERIAL ;jump to serial int ISR
ORG 30H
COM in 8051 MAIN: MOV P1,#0FFH;make P1 an input port
(cont’) MOV TMOD,#20H ;timer 1, auto reload
MOV TH1,#0FDH ;9600 baud rate
MOV SCON,#50H ;8-bit,1 stop, ren enabled
MOV IE,10010000B ;enable serial int.
SETB TR1 ;start timer 1
BACK: MOV A,P1 ;read data from port 1
MOV SBUF,A ;give a copy to SBUF
MOV P2,A ;send it to P2
SJMP BACK ;stay in loop indefinitely
36
;-----------------SERIAL PORT ISR
SERIAL ORG 100H
COMMUNI- SERIAL: JB TI,TRANS;jump if TI is high
MOV A,SBUF ;otherwise due to receive
CATION CLR RI ;clear RI since CPU doesn’t
INTERRUPT RETI ;return from ISR
TRANS: CLR TI ;clear TI since CPU doesn’t
RETI ;return from ISR
Use of Serial END
COM in 8051
(cont’) The moment a byte is written into SBUF it is framed and transferred
serially. As a result, when the last bit (stop bit) is transferred the TI is
raised, and that causes the serial interrupt to be invoked since the
corresponding bit in the IE register is high. In the serial ISR, we check
for both TI and RI since both could have invoked interrupt.
37
Example 11-9
Write a program in which the 8051 gets data from P1 and sends it to
SERIALP2 continuously while incoming data from the serial port is sent to P0.
COMMUNI- Assume that XTAL=11.0592. Set the baud rata at 9600.
CATION Solution:
INTERRUPT ORG 0000H
LJMP MAIN
ORG 23H
Use of Serial LJMP SERIAL ;jump to serial int ISR
COM in 8051 ORG 30H
(cont’) MAIN: MOV P1,#0FFH ;make P1 an input port
MOV TMOD,#20H ;timer 1, auto
reload MOV TH1,#0FDH ;9600 baud
rate
MOV SCON,#50H ;8-bit,1 stop, ren enabled
MOV IE,10010000B ;enable serial int.
SETB TR1 ;start timer 1
BACK: MOV A,P1 ;read data from port 1
MOV P2,A ;send it to P2
SJMP BACK ;stay in loop indefinitely
38
;-----------------SERIAL PORT ISR
SERIAL
ORG 100H
COMMUNI- SERIAL: JB TI,TRANS;jump if TI is high
CATION MOV A,SBUF;otherwise due to receive
INTERRUPT MOV P0,A ;send incoming data to P0
CLR RI ;clear RI since CPU doesn’t
RETI ;return from ISR
Use of Serial TRANS: CLR TI ;clear TI since CPU doesn’t
COM in 8051 RETI ;return from ISR
END
(cont’)
39
Example 11-10
Write a program using interrupts to do the following:
SERIAL (a) Receive data serially and sent it to P0,
(b) Have P1 port read and transmitted serially, and a copy given to
COMMUNI- P2,
CATION(c) Make timer 0 generate a square wave of 5kHz frequency on P0.1.
INTERRUPT Assume that XTAL-11,0592. Set the baud rate at 4800.
Solution:
ORG 0
Clearing RI and LJMP MAIN
TI before RETI ORG 000BH ;ISR for timer 0
CPL P0.1 ;toggle P0.1
RETI ;return from ISR
ORG 23H ;
LJMP SERIAL ;jump to serial interrupt ISR
ORG 30H
MAIN: MOV P1,#0FFH ;make P1 an input port
MOV TMOD,#22H;timer 1,mode 2(autoreload)
MOV TH1,#0F6H;4800 baud rate
MOV SCON,#50H;8-bit, 1 stop, ren enabled
MOV TH0,#-92 ;for 5kHZ wave
40
SERIAL MOV IE,10010010B ;enable serial int.
;start timer 1
COMMUNI- SETB TR1
SETB TR0 ;start timer 0
CATION BACK: MOV A,P1 ;read data from port 1
INTERRUPT MOV SBUF,A ;give a copy to SBUF
MOV P2,A ;send it to P2
Clearing RI and SJMP BACK ;stay in loop indefinitely
;-----------------SERIAL PORT ISR
TI before RETI ORG 100H
(cont’) SERIAL:JB TI,TRANS;jump if TI is high
MOV A,SBUF ;otherwise due to receive
MOV P0,A ;send serial data to P0
CLR RI ;clear RI since CPU doesn’t
RETI ;return from ISR
TRANS: CLR TI ;clear TI since CPU doesn’t
RETI ;return from ISR
END
41
Parallel protocols: PCI Bus
• PCI Bus (Peripheral Component Interconnect)
– High performance bus originated at Intel in the early 1990’s
– Standard adopted by industry and administered by PCISIG (PCI Special Interest
Group)
– Interconnects chips, expansion boards, processor memory subsystems
– Data transfer rates of 127.2 to 508.6 Mbits/s and 32-bit addressing
• Later extended to 64-bit while maintaining compatibility with 32-bit schemes
– Synchronous bus architecture
– Multiplexed data/address lines
Wireless protocols: IrDA
• IrDA
– Protocol suite that supports short-range point-to-point infrared data
transmission
– Created and promoted by the Infrared Data Association (IrDA)
– Data transfer rate of 9.6 kbps and 4 Mbps
– IrDA hardware deployed in notebook computers, printers, PDAs, digital
cameras, public phones, cell phones
– Lack of suitable drivers has slowed use by applications
– Windows 2000/98 now include support
– Becoming available on popular embedded OS’s
281
Wireless protocols: Bluetooth
• Bluetooth
– New, global standard for wireless connectivity
– Based on low-cost, short-range radio link
– Connection established when within 10 meters of each other
– No line-of-sight required
• e.g., Connect to printer in another room
282
Wireless Protocols: IEEE 802.11
• IEEE 802.11
– Proposed standard for wireless LANs
– Specifies parameters for PHY and MAC layers of network
• PHY layer
– physical layer
– handles transmission of data between nodes
– provisions for data transfer rates of 1 or 2 Mbps
– operates in 2.4 to 2.4835 GHz frequency band (RF)
– or 300 to 428,000 GHz (IR)
• MAC layer
– medium access control layer
– protocol responsible for maintaining order in shared medium
– collision avoidance/detection
283