Tải bản đầy đủ (.pdf) (20 trang)

CHƯƠNG 9 LẬP TRÌNH GIAO TIẾP MÁY TÍNH VÀ THIẾT BỊ ppsx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (145.29 KB, 20 trang )

1
1
KỸ THUẬT LẬP TRÌNH
CHƯƠNG 9
LẬP TRÌNH GIAO TIẾP MÁY TÍNH VÀTHIẾT BỊ
2
Mục lục chương 9
•9.1. Giao tiếp qua cổng RS232
•9.2. Giao tiếp qua cổng song song
•9.3. Giao tiếp qua cổng nối tiếp
•9.4. Giao tiếp qua cổng máy in
3
GIAO TIẾP QUA CỔNG RS232
CHƯƠNG 9
4
Giao tiếp qua cổng RS232
• Cổng RS232 làcổng thông dụng nhất trong truyền dữ liệu giữa máy tính
vàthiết bị
•Mặc dùcổng RS232 phức tạp hơn cổng song song nhưng nólàcổng hữu
hiệu nhất trong truyền dữ liệu, cóthể làwireless trong một số ngành vàít
tốn chi phí.
• Liên kết cổng RS232 bằng dây vàdây này có3 chức năng chính: “truyền”,
“nhận”, “nối đất”,
5
Giao tiếp qua cổng RS232
6
Giao tiếp qua cổng RS232
7
Giao tiếp qua cổng RS232
•Dây “nhận”và“truyền”này được kết nối giữa 2 máy tính với nhau.
•Dữliệu được truyền theo chuỗi. Có2 chân chính làTXD vàRXD. Các


chân khác của cổng làRTS, CTS, DSR, DTR, and RTS, RI
•Dữliệu ‘1’và‘0’ được xác định theo mức điện áp 3V to 25V và-3V to -
25V
8
Giao tiếp qua cổng RS232
• Đặc tính điện áp của cổng nối tiếp theo EIA (Electronics Industry
Association) RS232C tiêu chuẩn cótốc độ baud rate là20,000bps, khá
thấp so với tiêu chuẩn tốc độ hiện nay.
•Vìlý do này, chúng ta nên chọn cổng RS-232D với tiêu chuẩn mới và
được áp dụng trên các máy tính thế hệ mới hiện nay
9
Giao tiếp qua cổng RS232
• Baud: tốc độ truyền dữ liệu.
•Các tốc độ thiết lập: 300, 600, 1200, 2400, 4800, 9600, 19200,

2
38400,57600, 115200
• Kíhiệu baud tương ứng với số bit truyền được trong 1 giây
•Có1 bit bắt đầu và1 bit dừng được gửi kèm theo với 1 byte dữ liệu
• à nếu định 9600 baud thìcótốc độ truyền 960 byte/giây
10
Giao tiếp qua cổng RS232
• Cổng RS232Dhiện đang tồn tại ở 2 dạng: D loại 25 chân vàD loại 9 chân,
vàcả2 dạng này ở dạng đầu “cái”nằm ở phía sau máy tính.
•Chúng ta cần cómột đầu “đực” để kết nối từ máy tính này sang máy tính
khác.
•Các chân ra của D-9 và D-25 được trình bày dưới đây:
11
Giao tiếp qua cổng RS232
12

Giao tiếp qua cổng RS232
13
Giao tiếp qua cổng RS232
14
Giao tiếp qua cổng RS232
15
Giao tiếp qua cổng RS232
•Các thiết bị dùng các cổng nối tiếp cho giao tiếp được phân làm hai loại. Chúng gồm DCE (Data
Communications Equipment) và DTE (Data Terminal Equipment)
•DCE làcác thiết bị tương tự modem thiết bị, TA adapter, máy in chẳng hạn trong khi DTE làmáy
tính bạn hoặc các thiết bị ngoại vi.
•Một DTE làmột máy tính vàmột modem là DCE. Thông thường, mọi người hay nói về DTE tới
DCE hoặc DCE tới các bộ phát DCE.
•Bộtruyền DTE tới DCE làgiữa modem vàmáy tính của chúng ta (đôi khi được xem như làmột bộ
thiết bị ngoại vi ngoài). Điều này cho thấy truyền dự liệu rất nhanh hơn so với từ DCE đến DCE.
DCE to DCE làkết nối giữa các modem, đôi khi còn được gọi làbộkết nối các đường truyền .
16
Giao tiếp qua cổng RS232
•Hầu hết hiện nay người dùng phổ biến các modem 28.8K hoặc 33.6K. Do vậy, chúng
ta nên sử dụng các modem cótốc độ DCE đến DCE là28.8K hoặc 33.6K.
•Nếu cần loại modem cótốc độ cao, chúng ta nên dùng DTE đến DCE cótốc độ
khoảng 115,200 BPS. (Tốc độ tối đa là16550a UART) .
•Các chương trình giao tiếp chúng ta sử dụng được thiết lập cho DCE đến DTE. Tuy
nhiên, tốc độ thiết lập là9.6 KBPS, 144 KBPS, vàtheo tốc độ modem cóthể
truyền.
17
Giao tiếp qua cổng RS232
•Nếu chúng ta chuyển dữ liệu dạng file text tại 28.8K (DCE-DCE), thìmodem sẽ nén
file này lại vàtốc độ truyền thực tế là115.2 KBPS giữa các máy tình và do đó, tốc độ
truyền giữa DCE-DTE là115.2 KBPS.

•Vìvậy, điều này lý giải tại sao DCE-DTE nên cótốc độ kết nối cao hơn tốc độ kết
nối của modem. Do đó, nếu tốc độ DTE đến DCE của chúng ta nhiều lần nhanh hơn
tốc độ DCE đến DCE, PC cóthể gửi dữ liệu đến modem của chúng ta ở tốc độ
115,200 BPS.

3
18
Giao tiếp qua cổng RS232
• NULL MODEM (modem rỗng):
•Null modem được dùng để kết nối giữa hai DTE với nhau.
•Thường được sử dụng để truyền các file dữ liệu giữa các máy tính, sử
dụng các giao thức (protocol) như Zmodem, xmodem,
19
Giao tiếp qua cổng RS232
20
Giao tiếp qua cổng RS232
•Hình vẽ được đề cập ở trên cho thấy kết nối các dây của null modem. Đặc tính chính được
chỉ ra ở đây làsửdụng một máy tính để trao đổi mọi thứ (chat) với modem gần giống như
với một máy tính khác.
• Máy tính khách (guest) vàmáy tính chủ (host) được kết nối thông qua các chốt TD, RD, và
SG.
•Bất kỳ dữ liệu được truyền thông qua dây TD từ máy chủ đến máy khách, được nhận theo
dây RD. Máy tính chủ phải được thiết lập thông số tương tự máy tính khách.
•Tín hiệu dây nối đất_signal ground (SG) của cả hai máy tính phải được ngắn lại.
21
Giao tiếp qua cổng RS232
•Data Terminal Ready (DTR) được nối kín từ bộ Data Set Ready vàCarrier Detect
trên cả hai máy tính.
•Khi bộ Data Terminal Ready được xác nhận hoạt động, thìData Set Ready và
Carrier Detect ngay lập tức được hoạt động.

• Ở điểm này, máy tính được xem như làmodem ảo Virtual Modem được kết nối sẵn
sàng và được phát hiện bởi các modem truyền dữ liệu khác.
22
Giao tiếp qua cổng RS232
•All left to worry about now is the Request to Send and Clear To Send.
•As both computers communicate together at the same speed, flow control is not
needed thus these two lines are also linked together on each computer.
•When the computer wishes to send data, it asserts the Request toSend high and as
it is hooked together with the Clear to Send, It immediately gets a reply that it is ok to
send and does so.
23
Giao tiếp qua cổng RS232
•The Ring indicator line is only used to tell the computer that there is a
ringing signal on the phone line. As we do not have, a modem connected
to the phone line this is left disconnected
24
Giao tiếp qua cổng RS232
•To know about the RS232 ports available in your computer, Right click on "My
Computer", Goto 'Properties', Select tab 'Device Manager', go toPorts( COM & LPT
), In that you will find 'Communication Port(Com1)' etc.
•If you right click on that and go to properties, you will get device status. Make sure
that you have enabled the port( Use this port is selected).
25
Giao tiếp qua cổng RS232

4
•There are two popular methods of sending data to or from the serial port in
Turbo C.
•One is using outportb(PORT_ID, DATA) or outport(PORT_ID,DATA)
defined in “dos.h”

•Another method is using bioscom() function defined in “bios.h”
26
Giao tiếp qua cổng RS232
• Using outportb() :
•The function outportb () sends a data byte to the port ‘PORT_ID’. The function
outport() sends a data word. These functions can be used for anyport including
serial port, parallel ports. Similarly to receive data these areused.
• inport reads a word from a hardware port
• inportb reads a byte from a hardware port
• outport outputs a word to a hardware port
• outportb outputs a byte to a hardware port
27
Giao tiếp qua cổng RS232
• Declaration: (Cúpháp)
• int inport(int portid);
• unsigned char inportb(int portid);
• void outport(int portid, int value);
• void outportb(int portid, unsigned char value);
28
Giao tiếp qua cổng RS232
• Remarks:
• inport works just like the 80x86 instruction IN. It reads the low byte of a word from
portid, the high byte from portid + 2.
• inportb is a macro that reads a byte
• outport works just like the 80x86 instruction OUT. It writes thelow byte of value to
portid, the high byte to portid + 1.
• outportb is a macro that writes value Argument
29
Giao tiếp qua cổng RS232
• portid:

• Inport-port that inport and inportb read from;
• Outport-port that outport and outportb write to
• value:
• Word that outport writes to portid;
• Byte-that outportb writes to portid.
30
Giao tiếp qua cổng RS232
•If you call inportb or outportb when dos.h has been included, they are
treated as macros that expand to inline code.
•If you don't include dos.h, or if you do include dos.h and #undef the
macro(s), you get the function(s) of the same name.

5
31
Giao tiếp qua cổng RS232
• Return Value:
•# inport and inportb return the value read
•# outport and outportb do not return
32
Giao tiếp qua cổng RS232
• Using bioscom:
•The macro bioscom () and function _bios_serialcom() are used inthis method inthe serial
communication using RS-232 connecter.
•First we have to set the port with the settings depending on ourneed and availability. In this
method, same function is used to make the settings using controlword, to send data to the port
and check the status of the port.
•These actions are distinguished using the first parameter of thefunction. Along with that we are
sending data and the port to be used to communicate.
•Here are the deatails of the Turbo C Functions for communicationports.
33

Giao tiếp qua cổng RS232
• Declaration: (Cúpháp)
• bioscom(int cmd, char abyte, intport)
• _bios_serialcom(int cmd ,int port, char abyte)
•bioscom() and _bios_serialcom() uses the biosinterrupt 0x14 to perform
various communicate the serial communication over the I/O ports given
inport.
• cmd: The I/O operation to be performed.
34
Giao tiếp qua cổng RS232
35
Giao tiếp qua cổng RS232
• portid: port to which data is to be sent or from which data is to be read.
• 0: COM1
1: COM2
2: COM3
36
Giao tiếp qua cổng RS232
• abyte:
•When cmd =2 or 3 (_COM_SEND or _COM_RECEIVE) parameter abyte
is ignored.
•When cmd = 0 (_COM_INIT), abyte is an OR combination of the following
bits (One from each group):
37
Giao tiếp qua cổng RS232
38
Giao tiếp qua cổng RS232
• For example, if

6

• abyte = 0x8B = (0x80 | 0x08 | 0x00 | 0x03) = (_COM_1200 | _COM_ODDPARITY |
_COM_STOP1 | _COM_CHR8)
• the communications port is set to
1200 baud (0x80 = _COM_1200)
Odd parity(0x08 = _COM_ODDPARITY)
1 stop bit(0x00 = _COM_STOP1)
8 data bits (0x03 = _COM_CHR8)
•To initialise the port with above settings we have to write,
• bioscom(0, 0x8B, 0);
39
Giao tiếp qua cổng RS232
•To send a data to COM1, the format of the function will be bioscom(1,
data, 0).
•Similarly bioscom(1, 0, 0 ) will read a data byte from the port.
40
Giao tiếp qua cổng RS232
41
Giao tiếp qua cổng RS232
•When you compile and run the above program in both the computers, The characters typed in one
computer should appear on the other computer screen and vice versa.
•Initially, we set the port to desired settings as defined in macro settings. Then we waited in an idle
loop until akey is pressed or a data is available on the port. If any key is pressed, then kbhit()
function returns non zero value.
•So will go to getch function where we are finding out which key is pressed. Then we are sending it
to the com port. Similarly, if any data is available on the port, we are receiving it from the port and
displaying it on the screen.
42
Giao tiếp qua cổng RS232
•To check the port,If you have a single computer,you can use loop-back
connection as follows.

•This is most commonly used method for developing communication
programs. Here, data is transmitted to that port itself. Loop-back plug
connection is as follows.
43
Giao tiếp qua cổng RS232
44
Giao tiếp qua cổng RS232
•If you run the above program with the connection as in this diagram, the character entered
in the keyboard should be displayed on the screen.
•This method is helpful in writing serial port program with single computer.Also you can
make changes in the port id if your computer has 2 rs232ports.
•You can connect the com1 port to com2 of the same computer and change the port id in the
program.
•The data sent to the port com1 should come to port com2. then also whatever you type in
the keyboard should appear on the screen.
45
GIAO TIẾP QUA CỔNG MÁY IN
CHƯƠNG 9
46
Giao tiếp qua cổng máy in

7
• Port Assignments
•Each printer port consists of three port addresses; data, statusand control
port.
•These addresses are in sequential order. That is, if the data port is at
address 0x0378, the corresponding status port is at 0x0379 and the control
port is at 0x037a.
47
Giao tiếp qua cổng máy in

• Printer: LPT1, LPT2, LPT3
• Data port: 0x03bc, 0x0378, 0x0278
• Status: 0x03bd, 0x0379, 0x0279
• Control: 0x03be, 0x037a, 0x027a
•To definitively identify the assignments for a particular machine, use the DOS debug
program to display memory locations 0040:0008. For example:
• >debug
•-d 0040:0008 L8 0040:0008 78 03 78 02 00 00 00 00
48
Giao tiếp qua cổng máy in
•Note in the example that LPT1 is at 0x0378, LPT2 at 0x0278 and LPT3
and LPT4 are not assigned.
•Thus, for this hypothetical machine;
•Printer: LPT1, LPT2, LPT3, LPT4
•Data port: 0x0378, 0x0278, none, none
•Status: 0x0379, 0x0279
•Control: 0x037a, 0x027a
49
Giao tiếp qua cổng máy in
•An alternate technique is to run Microsoft Diagnostics (MSD.EXE)and
review the LPT assignments.
50
Giao tiếp qua cổng máy in
• Outputs
51
Giao tiếp qua cổng máy in
52
Giao tiếp qua cổng máy in
•Note that there are eight outputs on the Data Port (Data 7(msb) -Data 0) and four
additional outputs on the low nibble of the Control Port. /SELECT_IN, INIT, /AUTO

FEED and /STROBE.
•[Note that with /SELECT_IN, the "in" refers to the printer. For normal printer
operation, the PC exerts a logic zero to indicate to the printerit is selected. The
original function of INIT was to initialize the printer, AUTO FEED to advance the
paper. In normal printing, STROBE is high. The character to be printed is output on
the Data Port and STROBE is momentarily brought low.]

8
53
Giao tiếp qua cổng máy in
•All outputs on the Data Port are true logic. That is, writing a logic one to a bit causes
the corresponding output to go high.
•However, the /SELECT_IN, /AUTOFEED and /STROBE outputs on the Control Port
have inverted logic.
•That is, outputting a logic one to a bit causes a logic zero on the corresponding
output. This adds some complexity in using the printer port, butthe fix is to simply
invert those bits using the exclusive OR function prior to outputting.
54
Giao tiếp qua cổng máy in
•[One might ask why the designers of the printer port designed the port in this manner. Assume
you have a printer with no cable attached. An open usually is read as a logic one. Thus, if a
logic one on the SELECT_IN, AUTOFEED and STROBE leads meant to take the appropriate
action, an unconnected printer would assume it was selected, go into the autofeed mode and
assume there was data on the outputs associated with the Data Port.
•The printer would be going crazy when in fact it wasn't even connected. Thus, the designers
used inverted logic. A zero forces the appropriate action.]
55
Giao tiếp qua cổng máy in
•#define DATA 0x03bc
•#define STATUS DATA+1

•#define CONTROL DATA+2

•int val1, val2;

•val1 = 0x81; /* 1000 0001 */ /* Data bits 7 and 0 at one */
•outportb(DATA, val1);
•val2 = 0x08; /* 0000 1000 */ outportb(CONTROL, VAL2^0x0b); /* SELECT_IN
= 1, INIT = 0, /AUTO_FEED = 0, /STROBE = 0 */
56
Giao tiếp qua cổng máy in
•Note that only the lower nibble of val2 is significant. Note that in the last
line of code, /SELECT_IN, /AUTO_FEED and /STROBE are output in
inverted form by using the exclusive-or function so as to compensate for
the hardware inversion.
57
Giao tiếp qua cổng máy in
•For example; if I intended to output 1 0 0 0 on the lower nibbleand did not do the
inversion, the hardware would invert bit 3, leave bit 2 as true and invert bits 1 and 0.
The result, appearing on the output would then be 0 0 1 1 which is about as far from
what was desired as one could get. By using the exclusive-or function, 1 0 0 0 is
actually sent to the port as 0 0 1 1. The hardware then inverts bits 3, 1 and 0 and the
output is then the desired 1 0 0 0.
58
Giao tiếp qua cổng máy in
•Note that in the diagram showing the Status Port there are five status leads from the printer.
(BSY, /ACK, PE (paper empty), SELECT, /ERROR).
•[The original intent in the naming of most of these is intuitive. A high on SELECT indicates
the printer is on line. A high on BSY or PE indicates to the PC that the printer is busy or out
of paper. A low wink on /ACK indicates the printer received something. A low on ERROR


9
indicates the printer is in an error condition.]
•These inputs are fetched by reading the five most significant bits of the status port
59
Giao tiếp qua cổng máy in
•However, the original designers of the printer interface circuitry, inverted the bit
associated with the BSY using hardware. That is, when a zero is present on input
BSY, the bit will actually be read as a logic one. Normally, youwill want to use "true"
logic, and thus you will want to invert this bit.
•The following fragment illustrates the reading the five most significant bits in "true"
logic.
60
Giao tiếp qua cổng máy in
• #define DATA 0x03bc
• #define STATUS DATA+1

• unsigned int in_val;

• in_val = ((inportb(STATUS)^0x80) >> 3);
61
Giao tiếp qua cổng máy in
•Note that the Status Port is read and the most significant bit, corresponding to the
BSY lead is inverted using the exclusive-or function. The result is then shifted such
that the upper five bits are in the lower five bit positions.
• 0 0 0 BUSY /ACK PE SELECT /ERROR Another input, IRQ on the Status
Port is not brought to a terminal on the DB-25 printer port connector. I have yet to
figure out how to use this bit.
62
Giao tiếp qua cổng máy in
•At this point, you should see that, at a minimum, there are 12 outputs;

eight on the Data Port and four on the lower nibble of the Control Port.
There are five inputs, on the highest five bits of the Status Port. Three
output bits on the Control Port and one input on the Status Portare
inverted by the hardware, but this is easily handled by using the exclusive-
or function to selectively invert bits.
63
Giao tiếp qua cổng máy in
• Refer to the figure titled Figure #3 -Typical Application showing a normally
open push button switch being read on the BUSY input (Status Port, Bit 7)
and an LED which is controlled by Bit 0 on the Data Port. A C language
program which causes the LED to flash when the push-button is
depressed appears below. Note that an output logic zero causes the LED
to light.
64
• #include <stdio.h>
• #include <dos.h> /* required for delay function */
• #define DATA 0x03bc
• #define STATUS DATA+1

10
• #define CONTROL DATA+2
• void main(void)
• {
• int in;
• while(1)
• {
• in = inportb(STATUS);
• if (((in^0x80)&0x80)==0) /* if BUSY bit is at 0 (sw closed) */
• {
• outportb(DATA,0x00); /* turn LED on */

• delay(100);
• outportb(DATA, 0x01); /* turn it off */
• delay(100);
• }
• else
• {
• outportb(DATA,0x01); /* if PB not depressed, turn LED off */
• }
• }
• }
65
Giao tiếp qua cổng máy in
66
Giao tiếp qua cổng máy in
• Circuit Description: Logic 1 on output DATA 0 (Data Port -Bit 0) causes LED to be
off. Logic 0 causes LED to turn on.
•Normally open push-button causes +5V (logic 1) to appear on input BUSY (STATUS
PORT -Bit 7). When depressed, push-button closes and ground (logic 0) is applied
to input Busy.
•Note external source of 5V.
• Program Description: When idle, push-button is open and LED is off. On
depressing push-button, LED blinks on and off at nominally 5 pulses per second.
67
GIAO TIẾP CỔNG SONG SONG
CHƯƠNG 9
68
9.2. Giao tiếp qua cổng song song
•Parallel ports are easy to program and faster compared to the serial ports.
•But main disadvantage is it needs more number of transmission lines.
Because of this reason parallel ports are not used in long distance

communications.
69
9.2. Giao tiếp qua cổng song song
•Let us know the basic difference between working of parallel port and serial port.
• In serial ports, there will be two data lines: One transmission and one receive line.
To send a data in serial port, it has to be sent one bit after another with some extra
bits like start bit, stop bit and parity bit to detect errors.
• But in parallel port, all the 8 bits of a byte will be sent to the port at a time and a
indication will be sent in another line.
70
9.2. Giao tiếp qua cổng song song
•In the PC there will be D-25 type of female connector having 25 pins and
in the printer, there will be a 36-pin Centronics connector.
•Connecting cable will combine these connecter using following convention.

11
Pin structure of D-25 and Centronics connecters are explained bellow
71
9.2. Giao tiếp qua cổng song song
72
9.2. Giao tiếp qua cổng song song
•Now let us know how communication between PC and printer takes place. Computer
places the data in the data pins, then it makes the strobe low.
•When strobe goes low, printer understands that there is a valid data in data pins.
Other pins are used to send controls to the printer and get status of the printer, you
can understand them by the names assigned to the pins.
73
9.2. Giao tiếp qua cổng song song
•To use the printer port for applications other than printing, Weneed to know how ports are
organized.

•There are three registers associated with LPT port: Data register, Control register and
Status register.
•Data register will hold the data of the data pins of the port. That means, if we store a byte of
data to the data register, that data will be sent to the data pins of the port.
•Similarly control and status registers. The following table explains how these registers are
associated with ports.
74
75
9.2. Giao tiếp qua cổng song song
•* Pins with * symbol in this table are hardware inverted. Than means, If a pin has a
'low' ie. 0V, Corresponding bit in the register will have value 1.
•Signals with prefix 'n' are active low. That means, Normally these pins will have low
value. When it needs to send some indication, it will become high.
•For example, Normally nStrobe will be high, when the data is placed in the port,
computer makes that pin low.
76
9.2. Giao tiếp qua cổng song song
•Normally, data, control and status registers will have followingaddresses.
We need these addresses in programming later
77
9.2. Giao tiếp qua cổng song song
78
9.2. Giao tiếp qua cổng song song
•Note: All the parallel ports do not have bidirectional capability. Earlier parallel ports
had only output enabled in data pins since printers only inputs data. But latter, to
make parallel port capable of communicating with other devises, bidirectional ports
are introduced.
•By default, data port is output port. To enable the bidirectional property of the port,
we need to set the bit 5 of control register.
79

9.2. Giao tiếp qua cổng song song
•To know the details of parallel ports available in your computer, follow this procedure:
• Right click on My Computer, go to "Properties".
• Select the tab Hardware, Click Device manager.
• You will get a tree structure of devices; In that Expand "Ports(Com1 & LPT)".
• Double Click on the ECP Printer Port(LPT1) or any other LPT portif available.

12
• You will get details of LPT port. Make sure that "Use this Port (enable)" is selected.
• Select tab recourses. In that you will get the address range of port.
80
9.2. Giao tiếp qua cổng song song
•To start programming, you will need a D-25 type Male connector. Its pin structures
can be found in the connector as follows:
81
9.2. Giao tiếp qua cổng song song
• Programming the printer port in DOS:
•To start programming the port, we will use DOS.
•In DOS we have commands to access the port directly. But, these programs will not
work on the systems based on Windows XP, Windows NT or higher versions.
•For security reason, higher versions of the windows does not allow accessing the
port directly.
•To program the parallel port in these systems, we need to write kernel mode driver.
82
9.2. Giao tiếp qua cổng song song
•When we want to find out whether particular pin of the port is high or low, we need to
input the value of corresponding register as a byte.
•In that, we have to find out whether the corresponding bit is high or low using bitwise
operators.
•We can't access the pins individually. So, you need to know basic bitwise operations.

83
9.2. Giao tiếp qua cổng song song
•Main bitwise operators that we need are bitwise AND '&' and bitwise OR '|'.
•To make a particular bit in a byte high without affecting other bits, write a
byte with corresponding bit 1 and all other bits 0; OR it with original byte.
•Similarly, to make particular bit low, write a byte with corresponding bit 0
and all other bits 1; AND it with original byte.
84
9.2. Giao tiếp qua cổng song song
•In Turbo C, there are following functions used for accessing theport:
• outportb( PORTID, data);
• data = inportb( PORTID);
• outport( PORTID, data);
• data = inport( PORTID);
85
9.2. Giao tiếp qua cổng song song
•outport() function sends a word to port, inport() reads a word from the port. outportb() sends a byte
to port and inportb() reads a byte from the port. If you includeDOS.H header, these functions will be
considured as macro, otherwise as functions.
•Function inport() will return a word having lower byte as data at PORTID and higher byte as data at
PORTID+2. So, we can use this function to read status and control registers together. inportb()
function returns byte at PORTID. outport() writes the lower byteto PORTID and higher byte to
PORTID+1.
•So this can be used to write data and control together. outportb() function write the data to PORTID.
outport() and outportb() returns nothing.
86
9.2. Giao tiếp qua cổng song song
• Let us start with inputting first. Here is an example program, copy it and

13

run in Turbo C or Borland C without anything connected to parallel port.
• Then you should see data available in status register and pin numbers 10,
11, 12, 13 and 15 of the parallel port.
• Pin 11 (active low) is 0 and all other pins are 1 means it is OK.
87
9.2. Giao tiếp qua cổng song song
• #include"stdio.h"
#include"conio.h"
#include"dos.h"
#define PORT 0x378
void main()
{
int data;
clrscr();
while(!kbhit())
{
data=inportb(PORT+1);
gotoxy(3,10);
printf("Data available in status register: %3d (decimal), %3X (hex)\n", data, data);
printf("\n Pin 15: %d",(data & 0x08)/0x08);
printf("\n Pin 13: %d",(data & 0x10)/0x10);
printf("\n Pin 12: %d",(data & 0x20)/0x20);
printf("\n Pin 11: %d",(data & 0x80)/0x80);
printf("\n Pin 10: %d",(data & 0x40)/0x40);
delay(10);
}
}
88
9.2. Giao tiếp qua cổng song song
•To understand bitwise operations: you want to find data in pin 15, value of

(data & 0x08) will be 0x08 if bit 3 of register is high, 0therwise.
89
9.2. Giao tiếp qua cổng song song
•We will use the same logic throughout the article.
•Now, take a D-25 male with cables connected to each pins. Short all the pins from 18
to 25, call it as ground. Now you can run above program and see the change by
shorting pins 10, 11, 12, 13 and 15 to ground. I prefer using switches between each
input pins and ground. Be careful, do not try to ground the output pins.
•To find out the availability of ports in a computer programmatically, we will use the
memory location where the address of port is stored.
90
9.2. Giao tiếp qua cổng song song
91
9.2. Giao tiếp qua cổng song song
•If you run the the following code in Turbo C or Borland C, You will get the
addresses of available ports.
92
93
9.2. Giao tiếp qua cổng song song
•Next we will go to check output pins. To check the output, we will use LED's. I have
driven LED's directly from the port.
•But it is preferred to connect a buffer to prevent excessive draw of current from the
port. Connect an LED in series with a resister of1KW or 2.2KW between any of the
data pins(2 to 9) and ground. With that, if you run the program given below, you

14
should see the LED blinking with app. 1 sec frequency.
94
9.2. Giao tiếp qua cổng song song
95

GIAO TIẾP QUA CỔNG NỐI TIẾP
CHƯƠNG 9
96
9.3. Giao tiếp qua cổng nối tiếp
97
9.3. Giao tiếp qua cổng nối tiếp
•Above is the standard port addresses. These should work for mostP.C's.
•If you just happen to be lucky enough to own a IBM P/S2 which has a
micro-channel bus, then expect a different set of addresses and IRQ's.
•Just like the LPT ports, the base addresses for the COM ports can be read
from the BIOS Data Area.
98
9.3. Giao tiếp qua cổng nối tiếp
99
9.3. Giao tiếp qua cổng nối tiếp
•The above table shows the address at which we can find the
Communications (COM) ports addresses in the BIOS Data Area.
•Each address will take up 2 bytes.
•The following sample program in C, shows how you can read these
locations to obtain the addresses of your communications ports.
100
9.3. Giao tiếp qua cổng nối tiếp
• #include <stdio.h>
• #include <dos.h>
• void main(void)
• {
• unsigned int far *ptraddr; /* Pointer to location of Port Addresses */
• unsigned int address; /* Address of Port */
• int a;
• ptraddr=(unsigned int far *)0x00000400;

• for (a = 0; a < 4; a++)
• { address = *ptraddr;
• if (address == 0) printf("No port found for COM%d \n",a+1);
• else
• printf("Address assigned to COM%d is %Xh\n",a+1,address);
• *ptraddr++;
• }
• }
101
BÀI TẬP CĂN BẢN
CHƯƠNG 9
102
Bài 1.
•Lập trình C giao tiếp lấy tín hiệu và điều khiển đèn giao thông (xanh, đỏ,
vàng)

15
103
Bài 1.
• #include<stdio.h>
• #include<conio.h>
• #include<bios.h>
• #include<time.h>
• #include<dos.h>


• #defineCOM10x03F8
• #defineCOM20x02F8
• #defineDATA_READY0X60B0
• #defineSETTINGS(_COM_9600|_COM_NOPARITY|_COM_STOP1|_COM_CHR8)


• intstart_addr();
• intend_addr();
• voidgroup_addr();
• voiddisplay_time();
• voidtransmit_frame(int*,int*);
• voidrecieve_frame(int*);
104
Bài 1.
• voidmain(void)

• {
• charsend;
• intabyte,in;
• inta,b,c,r,addr,status;
• unsignedintret_value;
• intcount,arr[6];
• intbit_num,s_addr,e_addr;
• intparity,baud,port,mode;
• intcom_port_no,stop_bit;
• charabyte_stopbit,abyte_baud,abyte_parity,abyte_databit;
• chararr_baud[]={0x00,0x20,0x40,0x60,0x80,0xA0,0xC0,0xE0};;

• clrscr();
105
Bài 1.
•//COMPORTSELECTSETTINGS//
• printf("\nSelectCOMPort\nCOM1\nCOM2\n");
• scanf("%d",&com_port_no);
• switch(com_port_no)

• {
• case1:port=0;
• break;

• case2:port=1;
• break;
• }
106
Bài 1.
• //TRANSMISSIONMODE//
• clrscr();
• addr=start_addr();
• printf("\nESCtoexit\n");
• //for(;;)

• {
• transmit_frame(&addr,&port);
• delay(5);
• printf("\n");
• recieve_frame(&port);

16
• }
• printf("\n");
107
Bài 1.
• getch();

• }


• voidtransmit_frame(int*addr,int*port)
• {

• unsignedintin;
• inttrans,i;
• chararr[]={0x01};



• if(kbhit())
• {
• if(getch()=='\x1B')
• {exit(0);
• }
• }
108
Bài 1.
•else
• {
• trans=arr[0];
• printf("%x",trans);
• _bios_serialcom(_COM_SEND,*port,trans);
• delay(100);
• }

• }
109
Bài 1.
• voidrecieve_frame(int*port)
• {intv;

• inttrans;

• unsignedintstatus,out;
• {
• status=_bios_serialcom_COM_STATUS,*port,SETTINGS);
• printf("%x",status);

• out=_bios_serialcom(_COM_RECEIVE,*port,0);
• trans=out;
• printf("\n%x",trans);



• }

• }
110
Bài 1.
•start_addr()
• {ints_addr1;
• printf("\nStartAddress:");
• scanf("%x",&s_addr1);
• return(s_addr1);
• }

17
111
Bài 2.
•Lập trình C giao tiếp lấy tín hiệu từ Card của hãng Advantech.
112

Bài 3.
•Lập trình C giao tiếp với mô đun của màn hình LCD
113
Bài 3.
•LCD modules are available in a wide range like 8x1, 8x2, 16x1, 16x2, 20x2, 20x4,
40x4. Here we have used 16x2-that means 2 rows of 16 characters.
•It is a Hitachi HD44780 compatible module, having 16 pins including 2 pins for
backlight
•Following table gives pin structure of LCD module. LCD modules without backlight
will have only 14 pins. If you are using such LCDs, simply ignore 15th and 16th pins
114
Bài 3.
115
Bài 3.
•Here, we are going to write on the LCD module and not reading back. So, R/W is
connected to ground directly.
•We need not have to input any data through, so all output pins are used in our
application. Data pins of LCD are connected to data pins of the port.
•Strobe signal (Pin 1 of D25 connector) is given to E (Pin 6 of LCD), Select printer (Pin
17 of D25) is connected to RS (pin 4 of the LCD).
116
Bài 3.
117
Bài 3.
•In the above diagram, LCD module is connected to the lpt port using D25
male connector.
•Pin number 3 of the LCD is for adjusting the contrast, connectedin such a
way that it can be varied from 0V to 5V. Keep it to 0 initially.
118
Bài 3.

119
Bài 3.
120
Bài 3.
• #include <dos.h>
#include <string.h>
#include <conio.h>
#include <time.h>
#define PORTADDRESS 0x378 /* Enter Your Port Address Here */
#define DATA PORTADDRESS+0
#define STATUS PORTADDRESS+1
#define CONTROL PORTADDRESS+2
void lcd_init(void);
void lcd_write(char char2write);

18
void lcd_putch(char char2write);
void lcd_puts(char * str2write);
void lcd_goto(int row, int column);
void lcd_clear(void);
void lcd_home(void);
void lcd_cursor(int cursor);
void lcd_entry_mode(int mode);
121
Bài 3.
•void main(void)
{
•lcd_init();
lcd_goto(1,1);
lcd_puts("Welcome To");

lcd_goto(1,0);
lcd_puts("electroSofts.com");
while(!kbhit() ) //wait until a key is pressed
{}
•}
void lcd_init()
{
•outportb(CONTROL, inportb(CONTROL) & 0xDF);
//config data pins as output
outportb(CONTROL, inportb(CONTROL) | 0x08);
//RS is made high: control (register select)
122
Bài 3.
•lcd_write(0x0f);
delay(20);
lcd_write( 0x01);
delay(20);
lcd_write( 0x38);
delay(20);
•}
void lcd_write(char char2write)
{
•outportb(DATA, char2write);
outportb(CONTROL,inportb(CONTROL) | 0x01); /* Set Strobe */
delay(2);
outportb(CONTROL,inportb(CONTROL) & 0xFE); /* Reset Strobe */
delay(2);
•}
123
Bài 3.

•void lcd_putch(char char2write)
{
•outportb(CONTROL, inportb(CONTROL) & 0xF7);
//RS=low: data
lcd_write(char2write);
•}
void lcd_puts(char *str2write)
{
•outportb(CONTROL, inportb(CONTROL) & 0xF7);
//RS=low: data
while(*str2write)
lcd_write(*(str2write++));

19
•}
124
Bài 3.
•void lcd_goto(int row, int column)
{
•outportb(CONTROL, inportb(CONTROL) | 0x08);
if(row==2) column+=0x40;
/* Add these if you are using LCD module with 4 columns
if(row==2) column+=0x14;
if(row==3) column+=0x54;
*/
lcd_write(0x80 | column);
•}
125
Bài 3.
• void lcd_clear()

{
• outportb(CONTROL, inportb(CONTROL) | 0x08);
lcd_write(0x01);
• }
• void lcd_home()
{
• outportb(CONTROL, inportb(CONTROL) | 0x08);
lcd_write(0x02);
• }
• void lcd_entry_mode(int mode)
{
• /*
if you dont call this function, entry mode sets to 2 by default.
mode: 0 -cursor left shift, no text shift
1 -no cursor shift, text right shift
2 -cursor right shift, no text shift
3 -no cursor shift, text left shift
*/
outportb(CONTROL, inportb(CONTROL) | 0x08);
lcd_write(0x04 + (mode%4));
• }
126
Bài 3.
•void lcd_cursor(int cursor)
{
•/*
set cursor: 0 -no cursor, no blink
1 -only blink, no cursor
2 -only cursor, no blink
3 -both cursor and blink

*/
outportb( CONTROL, inportb(CONTROL) | 0x08 );
lcd_write( 0x0c + (cursor%4));
•}
127
Bài 3.
128
Bài 3.
•Program to display date and time in an LCD module: Just replace the
'main' of previous program with the following and run.

20
129
Bài 3.
•void main(void)
{
•struct time t;
struct date d;
char strtime[17];
•textbackground(0);
clrscr();
textcolor(0);
textbackground(10);
gotoxy(8,5);
cputs(" ");
gotoxy(8,4);
cputs(" ");
•lcd_init();
lcd_cursor(0);
130

Bài 3.
• while(!kbhit())
{
• gettime(&t);
getdate(&d);
lcd_goto(0,4);
sprintf(strtime,"%02d:%02d:%02d", t.ti_hour%12, t.ti_min, t.ti_sec);
lcd_puts(strtime);
gotoxy(12,4);
cputs(strtime);
lcd_goto(1,3);
sprintf(strtime,"%02d:%02d:%4d", d.da_day, d.da_mon, d.da_year);
lcd_puts(strtime);
gotoxy(11,5);
cputs(strtime);
delay(200);
• }
textbackground(0);
textcolor(7);
• }
131
KẾT THÚC
CHƯƠNG 9

×