50
HARDWARE INTERFACING USING C Prepared By: Chirag Gohel E-mail: [email protected] - 1 -

Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

  • Upload
    others

  • View
    26

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 1 -

Page 2: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 2 -

Data communication is the process of communicating information in binary from between two or more points. Data communication is sometimes called computer communications because most of the information interchanged today is between computers, or between computers and their terminals, printers or other peripheral devices. The data might be as elementary as the binary symbols 1 and 0, or as complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols represent information. General Data Communication System The following diagram show the general data communication system, which consist of following three component.

1. The Transmitter (SOURCE) 2. The Receiver (DESTINATION) 3. The Transmission Path (Channel)

General Data Communication System

Universal Seven Part Data Circuit The following diagram show the Universal Seven Part Data Circuit, which consist of following seven component.

1. DTE at Point A 2. DCE at Point A 3. DTE at Point B 4. DCE at Point B 5. DTE-DCE Interface at Point A 6. DTE-DCE Interface at Point B 7. Communication Channel

Universal Seven Part Data Circuit

SOURCE

SINK

SINK

SOURCE

DTE

DTE DCE DCE

Point A Point B

Page 3: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 3 -

DTE : Data Terminal Equipment DCE : Data Carrier Equipment DTE-DCE Interface : A set of rule which specify the data movement across the

interface between DTE-DCE. It is also called RS-232 Standard or V.24.

Serial and Parallel Data Transmission If the bits move one by one over a single line it is called SERIAL data transmission. If a groups of bits move over several lines at the same time it is called PARALLE data transmission. Synchronous/Asynchronous Serial Transmission Synchronous Asynchronous 1. Speed of transmitter and receiver is

different. Speed of transmitter and receiver is almost same.

2. Data are send in a GROUP called blocks, with special synchronization characters placed at start and end.

Data are send in bit by bit, many special characters are sent along with data.

3. Error checking is performed automatically on entire block. (if any error entire block is retransmitted)

Manually Error checking is done.

Modes of Communication

Simplex Data in a simplex channel is always one way. Simplex channels are not often used because it is not possible to send back error or control signals to the transmit end.

It's like a one way street. An example of simplex is Television, or Radio.

Page 4: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 4 -

Half Duplex A half-duplex channel can send and receive, but not at the same time. It's like a one-lane bridge where two way traffic must give way in order to cross. Only one end transmits at a time, the other end receives. In addition, it is possible to perform error detection and request the sender to retransmit information that arrived corrupted. In some aspects, you can think of Internet surfing as being half-duplex, as a user issues a request for a web document, then that document is downloaded and displayed before the user issues another request.

Another example of half-duplex is talk-back radio, and CB Radio (Citizens Band). You might have seen movies where truckies (drivers of very big trucks) communicate to each other, and when they want the other person to speak they say "over". This is because only one person can talk at a time.

Full Duplex Data can travel in both directions simultaneously. There is no need to switch from transmit to receive mode like in half duplex. Its like a two lane bridge on a two-lane highway. Have you ever watched these television talk shows where the host has a number of people on the show, and they all try to talk at once. Well, that's full duplex!

Page 5: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 5 -

Page 6: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 6 -

Parallel port is a simple and inexpensive tool for building computer controlled devices and projects. The simplicity and ease of programming makes parallel port popular in electronics hobbyist world. The parallel port is often used in Computer controlled robots, Atmel/PIC programmers, home automation, ...etc... Here a simple tutorial on parallel port interfacing and programming with some examples. Everybody knows what is parallel port, where it can be found, and for what it is being used. the primary use of parallel port is to connect printers to computer and is specifically designed for this purpose. Thus it is often called as printer Port or Centronics port (this name came from a popular printer manufacturing company 'Centronics' who devised some standards for parallel port). You can see the parallel port connector in the rear panel of your PC. On almost all the PCs only one parallel port is present, but you can add more by buying and inserting ISA/PCI parallel port cards. The port is composed of 4 control lines, 5 status lines and 8 data lines. It's found commonly on the back of your PC as a D-Type 25 Pin female connector. There may also be a D-Type 25 pin male connector. Parallel port modes

The IEEE 1284 Standard which has been published in 1994 defines five modes of data transfer for parallel port. They are, 1) Compatibility Mode 2) Nibble Mode 3) Byte Mode 4) EPP 5) ECP The aim was to design new drivers and devices which were compatible with each other and also backwards compatible with the Standard Parallel Port (SPP). Compatibility, Nibble & Byte modes use just the standard hardware available on the original Parallel Port cards while EPP & ECP modes require additional hardware which can run at faster speeds, while still being downwards compatible with the Standard Parallel Port. Compatibility mode or "Centronics Mode" as it is commonly known, can only send data in the forward direction at a typical speed of 50 kbytes per second but can be as high as 150+ kbytes a second. In order to receive data, you must change the mode to either Nibble or Byte mode. Nibble mode can input a nibble (4 bits) in the reverse direction. E.g. from device to computer. Byte mode uses the Parallel's bi-directional feature (found only on some cards) to input a byte (8 bits) of data in the reverse direction.

Page 7: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 7 -

Hardware The pin outs of DB25 connector is shown in the picture below

Pin No (DB25)

Signal name Direction Register - bit

Inverted

1 nStrobe Out Control-0 Yes 2 Data0 In/Out Data-0 No 3 Data1 In/Out Data-1 No 4 Data2 In/Out Data-2 No 5 Data3 In/Out Data-3 No 6 Data4 In/Out Data-4 No 7 Data5 In/Out Data-5 No 8 Data6 In/Out Data-6 No 9 Data7 In/Out Data-7 No 10 nAck In Status-6 No 11 Busy In Status-7 Yes 12 Paper-Out In Status-5 No 13 Select In Status-4 No 14 Linefeed Out Control-1 Yes 15 nError In Status-3 No 16 nInitialize Out Control-2 No 17 nSelect-Printer Out Control-3 Yes

18-25 Ground - - -

LPT1(Parallel Port) is normally assigned base address 378h, while LPT2 is assigned 278h. However this may not always be the case as explained later. 378h & 278h have always been commonly used for Parallel Ports. The lower case h denotes that it is in hexadecimal. These addresses may change from machine to machine.

Page 8: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 8 -

Address Notes: 3BCh - 3BFh Used for Parallel Ports which were

incorporated on to Video Cards - Doesn't support ECP addresses

378h - 37Fh Usual Address For LPT 1 278h - 27Fh Usual Address For LPT 2

Port Addresses

When the computer is first turned on, BIOS (Basic Input/Output System) will determine the number of ports you have and assign device labels LPT1, LPT2 & LPT3 to them. BIOS first looks at address 3BCh. If a Parallel Port is found here, it is assigned as LPT1, then it searches at location 378h. If a Parallel card is found there, it is assigned the next free device label. This would be LPT1 if a card wasn't found at 3BCh or LPT2 if a card was found at 3BCh. The last port of call, is 278h and follows the same procedure than the other two ports. Therefore it is possible to have a LPT2 which is at 378h and not at the expected address 278h. What can make this even confusing, is that some manufacturers of Parallel Port Cards, have jumpers which allow you to set your Port to LPT1, LPT2, LPT3. Now what address is LPT1? - On the majority of cards LPT1 is 378h, and LPT2, 278h, but some will use 3BCh as LPT1, 378h as LPT1 and 278h as LPT2. Life wasn't meant to be easy. The lines in DB25 connector are divided in to three groups, they are 1) Data lines (data bus) 2) Control lines 3) Status lines As the name refers , data is transferred over data lines , Control lines are used to control the peripheral and of course , the peripheral returns status signals back computer through Status lines. These lines are connected to Data, Control And Status registers internally . The details of parallel port signal lines are given below. Parallel port registers As you know, the Data, Control and status lines are connected to there corresponding registers inside the computer. So by manipulating these registers in program , one can easily read or write to parallel port with programming languages like 'C' and BASIC. The registers found in standard parallel port are , 1) data register 2) Status register 3) Control register

Page 9: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 9 -

As there names specifies, Data register is connected to Data lines, Control register is connected to controll lines and Status lregistyer is connected to Status lines. (Here the word connection does not mean that there is some physical connection between data/control/status lines. The registers are virtually connected to the corresponding lines.). So what ever you write to these registers , will appear in corresponding lines as voltages, Of course, you can measure it with a multimeter. And What ever you give to Parallel port as voltages can be read from these registers(with some restrictions). For example , if we write '1' to Data register , the line Data0 will be driven to +5v. Just like this ,we can programmatically turn on and off any of the data lines and Control lines.

Where these registers are ? In an IBM PC, these registers are IO mapped and will have unique address. We have to find these addresses to to work with parallel port. For a typical PC , the base address of LPT1 is 0x378 and of LPT2 is 0x278. The data register resides at this base address , status register at baseaddress + 1 and the control register is at baseaddress + 2. So once we have the base address , we can calculate the address of each registers in this manner. The table below shows the register addresses of LPT1 and LPT2.

Register LPT1 LPT2 data registar(baseaddress + 0) 0x378 0x278 status register (baseaddress + 1) 0x379 0x279 control register (baseaddress + 2) 0x37a 0x27a

Software Registers - Standard Parallel Port (SPP)

Offset Name Read/Write Bit No. Properties Bit 7 Data 7 Bit 6 Data 6 Bit 5 Data 5 Bit 4 Data 4 Bit 3 Data 3 Bit 2 Data 2 Bit 1 Data 1

Base + 0 Data Port

Write (Note-1)

Bit 0 Data 0 Data Port

Note 1 : If the Port is Bi-Directional then Read and Write Operations can be performed on the Data Register. The base address, usually called the Data Port or Data Register is simply used for outputting data on the Parallel Port's data lines (Pins 2-9). This register is normally a write only port. If you read from the port, you should get the last byte sent. However if your port is bi-directional, you can receive data on this address. See Bi-directional Ports for more detail.

Page 10: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 10 -

Offset Name Read/Write Bit No. Properties Bit 7 Busy Bit 6 Ack Bit 5 Paper Out Bit 4 Select In Bit 3 Error Bit 2 IRQ (Not) Bit 1 Reserved

Base + 1

Status Port

Read Only

Bit 0 Reserved Status Port

The Status Port (base address + 1) is a read only port. Any data written to this port will be ignored. The Status Port is made up of 5 input lines (Pins 10,11,12,13 & 15), a IRQ status register and two reserved bits. Please note that Bit 7 (Busy) is a active low input. E.g. If bit 7 happens to show a logic 0, this means that there is +5v at pin 11. Likewise with Bit 2. (nIRQ) If this bit shows a '1' then an interrupt has not occurred.

Offset Name Read/Write Bit No. Properties Bit 7 Unused Bit 6 Unused Bit 5 Enable Bi-

Directional Port Bit 4 Enable IRQ Via

Ack Line Bit 3 Select Printer Bit 2 Initialize Printer

(Reset) Bit 1 Auto Linefeed

Base + 2 Control Port

Read/Write

Bit 0 Strobe Control Port

PORT ACCESS The C language can be used to transfer data to and from the contents of the various registers and controllers associated with the IBM-PC. These registers and control devices are port mapped, and are accessed using special IN and OUT instructions. Most C language support library's include functions to do this. The following is a brief description of how this may be done. #include <conio.h> outp( Port_Address, value); /* turboC uses outportb() */ value = inp( Port_address); /* and inportb() */ Example : outp (0x378,10); /*send the decimal value (10) to the port

(0x378)(lpt1)(Parallel Port)*/ value = inp(0x378); /*recive the value from the port

(0x378)(lpt1)(Parallel Port)*/

Page 11: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 11 -

The various devices, and their port values, are shown below, Port Range Device 00 - 0f DMA Chip 8737 20 - 21 8259 PIC 40 - 43 Timer Chip 8253 60 - 63 PPI 8255 (cassette, sound) 80 - 83 DMA Page registers 200 - 20f Game I/O Adapter 278 - 27f Reserved 2f8 - 2ff COM2 378 - 37f Parallel Printer 3b0 - 3bf Monochrome Display 3d0 - 3df Color Display 3f0 - 3f7 Diskette 3f8 - 3ff COM1 Example of Interfacing Parallel Port :

1. Demonstration of control of light Bulb through parallel port :

Page 12: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 12 -

The Software Controlling the above Circuit :

1. C program to control ON/OFF Through keyboard #include<stdio.h> void main(void) { outportb(0x378,0x01); //turn on the bulb getch(); //wait for any key to be pressed outportb(0x378,0x00); //turn off the bulb getch(); // wait for a key to be Pressed }

2. C program to have the bulb blink for five times for (int i=1; i<=5,i++); { outport b (0x378,0x01); //turn on the bulb delay (1000); // wait for 1000msec=1sec outportb(0x378,0x00); //turn off the bulb }

Page 13: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 13 -

Page 14: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 14 -

What happens, when you press a key on the keyboard while processor is busy doing some other work .No matter what the processor is doing, we'll see a letter, corresponding to the key pressed, displayed on the screen. Since pressing a key interrupts the processor, we say that keyboard interrupt is generated. So in simple terms, interrupt is a signal that causes the processor to stop what it is doing and initiates the processor to take up another job. Once the newly taken job is completed, it resumes doing what it was doing before the interrupt occurred. This resumption is possible because, whenever an interrupt occurs, the processor saves it's current state by pushing all it's internal registers(CPU's internal memory) onto the stack (data structure that stores elements in last-in-first-out "LIFO" manner) and pops out the registers when it is ready for resumption. There are two types of interrupts (i) software interrupts (generated by program) also called as trap or exception (256), (ii) Hardware interrupts (generated by hardware)(15). Every interrupt has it's own interrupt handler. An interrupt handler is a program that resides some where in the memory. So when an interrupt occurs processor executes the corresponding interrupt handler. Addresses of these interrupt handlers are stored in a table known as IVT (Interrupt Vector Table).When an interrupt occurs, processor obtains the address of the interrupt handler from the IVT and executes the handler. Every interrupt is assigned a number, interrupt-9h for keyboard,interrupt-8h for timer and so on. When invoking an interrupt we also need to pass some parameters, which are simply numbers. These parameters are passed in CPU registers and known as sub-functions. Why do we need these subfunctions? For example, let’s take interrupt-10h,which deals with screen. This interrupt allows us to switch between text and graphic modes(sub-functions 41h and 42h),allows to write a character to the screen(sub-function Ah),allows us to clear the screen(sub-function 42h) and so on. So we pass sub-functions to tell which specific functionality of the interrupt we want to use. THE INT86() FUNCTION This function is general 8086 software interrupt interface used to make a software interrupt occur and then invoke ROM-BIOS function. Here int stands for ‘interrupt’ and 86 represnts 8086 family of processor.

Int int86(int into_no, union REGS *inregs, union REGS *outregs);

• prototype in dos.h • executes 8086 software interrupt specified by intr_num • copies register values from inregs into the registers • after the software interrupt execution it returns register values into the outregs. • Status of the carry flag into x.cflag in outregs • Value of the 8086 flags register into the x.flags field in outregs.

Page 15: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 15 -

Example :

(1) Following program display the “HELLO” at 34,54 position using int86() function. #include <dos.h> Void main()

{ clrscr(); function(34,54); printf(“HELLO”);

}

void function (int x, int y) { union REGS regs; regs.ah=2; /*sets cursor position */ regs.h.dh = y; regs.h.dl = x; regs.h.bh = 0; /*video page*/ int86(VIDEO,&regs,&regs); }

(2) Following program returns the number of 1kbyet memory blocks present in the system. The value is return in AX register. #include <dos.h> void main()

{ biosmemory();

}

int biosmemory() {

union REGS regs; int86(0x12,&regs,&regs); return(regs.x.ax);

} KEY BOARD BIOS CALL Int 16H interrupt in the ROM BIOS provides for inimal character transfer from the keyboards. To perform desired task we have to set the value in AH register. AH = 0 Get Key Returns AH = Scan Code AL = Ascii char, 0 = non-ascii, (ie Function Keys)

Page 16: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 16 -

AH = 2 Get Shift Status Returns AL = 7 right shift pressed

AL = 6 Left shift pressed AL = 5 ctrl AL = 4 altr AL = 3 scroll lock 1 = on AL = 2 num lock AL = 1 caps lock AL = 0 Ins

int int86x( int intr_num, union REGS *inregs, union REGS *outregs,

struct SREGS *segregs )

• prototype in dos.h • Executes 8086 software interrupt specified by intr_num • Copies register values from inregs into the registers • also copies segregs->x.ds and segregs->y.es into DS/ES

FOLLOWING INTERRUPT EXECUTE DOS INTERRUPT 0x21

int intdos(union REGS *inregs, union REGS *outregs )

• prototype in dos.h • Executes 8086 software interrupt INT 21 (DOS INTERRUPT) • Copies register values from inregs into the registers • unique to DOS

int intdosx(union REGS *inregs, union REGS *outregs,

struct SREGS *segres )

• prototype in dos.h • Executes 8086 software interrupt INT 21 (DOS INTERRUPT) • Copies register values from inregs into the registers • also copies segregs->x.ds and segregs->y.es into DS/ES

There are many ways to interact with hardware.

1. Using high level language functions. 2. Using ROM-BIOS Function. 3. Using DOS function stored in IO.SYS and MSDOS.SYS 4. Direct programming the hardware.

As programmer moves from fist to last approach his reliability decreases and speed increases.

Page 17: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 17 -

ROM BIOS CALLS The ROM BIOS (Basic Input Output System) provides device control for the PC's major devices (disk, video, keyboard, serial port, printer), allowing a programmer to communicate with these devices without needing detailed knowledge of their operation. The ROM routines are accessed via the Intel 8088/86 software generated interrupts. The interrupts 10H through to 1AH each access a different routine. There are mainly three operation performed by BIOS are

• Keyboard routine • Video routine • Printer routines

The start-up routine Routines are responsible for the POST, the process by which the computer test for the minimum hardware requirements. Second task is to initialized memory and create equipment list as well as Interrupt Vector Table. Then rest of the boot-up process goes on. Lastly the start-up routine load into memory the first of several bootstrap loader routines into memory. The ROM Basic Routine It is not much used now a days, but used for imbedded routines which were designed to support the early BASIC programming language. These routines were used to boot computer without an operating system installed. The ROM Extensions routines These types of routines provides support for new hardware. How to use ROM-BIOS Function Parameters are passed to and from the BIOS routines using the 8088/86 CPU registers. The routines normally preserve all registers except AX and the flags. Some registers are altered if they return values to the calling process. ROM BIOS INTERRUPT ROUTINES 10 Video routines 11 Equipment Check 12 Memory Size Determination 13 Diskette routines 14 Communications routines 15 Cassette 16 Keyboard routines 17 Printer 18 Cassette BASIC 19 Bootstrap loader 1A Time of Day

Page 18: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 18 -

The interrupts which handle devices are like a gateway which provide access to more than one routine. The routine executed will depend upon the contents of a particular CPU register. Each of the software interrupt calls use the 8088/86 register contents to determine the desired function calls. It is necessary to use a C definition of the CPU programming model; this allows the registers to be initialized with the correct values before the interrupt is generated. The definition also provides a convenient place to store the returned register values. Luckily, the definition has already been created, and resides in the header file dos.h. It is a union of type REGS, which has two parts, each structures. One structure contains the eight bit registers (accessed by .h.), whilst the other structure contains the 16 bit registers (accessed by .x.) To generate the desired interrupt, a special function call has been provided. This function accepts the interrupt number, and pointers to the programming model union for the entry and return register values. General Purpose Register Unioun REGS

{ Struct WORDREGS x; Struct BYTEREGS h; }; WORDREGS and BYTEREGS structure stores the following registers. Struct BYTEREGS

{ Unsigned char al,ah,bl,bh; Unsigned char cl,ch,dl,dh; };

Struct WORDREGS {

Unsigned char ax,bx,cx,dx; Unsigned char si,di,cflag,flaghs; }; Segment Register Struct SREGS

{ unsigned int es; unsigned int cs; unsigned int ss; unsigned int ds; }

Page 19: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 19 -

There are total 16 registers in the 8086 Microprocessor. First 4 Registers :

• It is also known as DATA registers. Because these registers are used for data manipulation.

• They are ax, bx, cx & dx. • All registers are 16-bit long. • All registers are divided into two part (i.e High Order bit and Low Order bit).

16-bit

Register 8-bit Register 8-bit Register

ax ah Al bx bh Bl cx ch Cl dx dh dl

• Each 16-bit registers either can be used for a whole register (i.e all 16-bit) or can be used as two register (i.e two 8-bit).

• We can't used one 16-bit register and two 8-bit registers at a time. • Ex:- if we are using ax as 16-bit register then we can't used ah or al.

Second 4 Registers :

• It is also know as Index / Pointer registers. • They are sp, bp, si & di. • Index and Pointer registers are used for the arithmetic operation in 8086

architecture.

Another 2 Registers :

(i) Instruction Pointer (ip):

• It has important instruction that which instruction is executed by our CPU. • IP/Program Counter is used to store the memory location of the next

instruction to be executed. • CPU will check each time the program counter and then it will execute the

next instruction. • On each instruction it will update the program counter. (ii) Status Register (Flags):

• 9-bits of status registers are used as control flags(3) and status(6). • Control Flags are used to control come mode of CPU. • Status Flags gives the status of any operation performed by CPU. • There is only one value possible either 0 or 1. • If 1 is there, we can say flag is set.

Page 20: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 20 -

• Status Flag stores info of the arithmetic & logical instruction. • Ex.: Zero Flag is set to 1 when the result of any arithmetic operation is zero. • Total Flag Registers are shown below.

O D I T S Z A P C • In above figure red flags are not used. Other flags (registers) are explain

below.

O - OverFlow S - Sign D - Direction Z - Zero I - Interrupt A - Auxiliary T - Trip P – Parity

Page 21: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 21 -

Page 22: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 22 -

The Serial Port is harder to interface than the Parallel Port. In most cases, any device you connect to the serial port will need the serial transmission converted back to parallel so that it can be used. This can be done using a UART. On the software side of things, there are many more registers that you have to attend to than on a Standard Parallel Port. (SPP) So what are the advantages of using serial data transfer rather than parallel? 1. Serial Cables can be longer than Parallel cables. The serial port transmits a '1' as -

3 to -25 volts and a '0' as +3 to +25 volts where as a parallel port transmits a '0' as 0v and a '1' as 5v. Therefore the serial port can have a maximum swing of 50V compared to the parallel port which has a maximum swing of 5 Volts. Therefore cable loss is not going to be as much of a problem for serial cables than they are for parallel.

2. You don't need as many wires than parallel transmission. If your device needs to be mounted a far distance away from the computer then 3 core cable (Null Modem Configuration) is going to be a lot cheaper that running 19 or 25 core cable. However you must take into account the cost of the interfacing at each end.

3. Infra Red devices have proven quite popular recently. You may of seen many electronic diaries and palmtop computers which have infra red capabilities build in. However could you imagine transmitting 8 bits of data at the one time across the room and being able to (from the devices point of view) decipher which bits are which? Therefore serial transmission is used where one bit is sent at a time. IrDA-1 (The first infra red specifications) was capable of 115.2k baud and was interfaced into a UART. The pulse length however was cut down to 3/16th of a RS232 bit length to conserve power considering these devices are mainly used on diaries, laptops and palmtops.

4. Microcontroller's have also proven to be quite popular recently. Many of these have in built SCI (Serial Communications Interfaces) which can be used to talk to the outside world. Serial Communication reduces the pin count of these MPU's. Only two pins are commonly used, Transmit Data (TXD) and Receive Data (RXD) compared with at least 8 pins if you use a 8 bit Parallel method (You may also require a Strobe).

Page 23: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 23 -

Hardware :

Hardware Properties

Devices which use serial cables for their communication are split into two categories. These are DCE (Data Communications Equipment) and DTE (Data Terminal Equipment.) Data Communications Equipment are devices such as your modem, TA adapter, plotter etc while Data Terminal Equipment is your Computer or Terminal. The electrical specifications of the serial port is contained in the EIA (Electronics Industry Association) RS232C standard. It states many parameters such as –

1. A "Space" (logic 0) will be between +3 and +25 Volts. 2. A "Mark" (Logic 1) will be between -3 and -25 Volts. 3. The region between +3 and -3 volts is undefined. 4. An open circuit voltage should never exceed 25 volts. (In

Reference to GND) 5. A short circuit current should not exceed 500mA. The

driver should be able to handle this without damage. (Take note of this one!)

Above is no where near a complete list of the EIA standard. Line Capacitance, Maximum Baud Rates etc are also included. For more information please consult the EIA RS232-C standard. It is interesting to note however, that the RS232C standard specifies a maximum baud rate of 20,000 BPS!, which is rather slow by today's standards. A new standard, RS-232D has been recently released. Serial Ports come in two "sizes", There are the D-Type 25 pin connector and the D-Type 9 pin connector both of which are male on the back of the PC, thus you will require a female connector on your device. Below is a table of pin connections for the 9 pin and 25 pin D-Type connectors.

Page 24: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 24 -

Serial Pinouts (D25 and D9 Connectors)

D-Type-25 Pin No.

D-Type-9 Pin No.

Abbreviation Full Name

Pin 2 Pin 3 TD Transmit Data Pin 3 Pin 2 RD Receive Data Pin 4 Pin 7 RTS Request To

Send Pin 5 Pin 8 CTS Clear To Send Pin 6 Pin 6 DSR Data Set Ready Pin 7 Pin 5 SG Signal Ground Pin 8 Pin 1 CD Carrier Detect Pin 20 Pin 4 DTR Data Terminal

Ready Pin 22 Pin 9 RI Ring Indicator

Table : D Type 9 Pin and D Type 25 Pin Connectors

Pin Functions Abbreviation Full Name Function TD Transmit Data Serial Data Output (TXD) RD Receive Data Serial Data Input (RXD) CTS Clear to Send This line indicates that the Modem is ready to

exchange data. DCD Data Carrier

Detect When the modem detects a "Carrier" from the modem at the other end of the phone line, this Line becomes active.

DSR Data Set Ready

This tells the UART that the modem is ready to establish a link.

DTR Data Terminal Ready

This is the opposite to DSR. This tells the Modem that the UART is ready to link.

RTS Request To Send

This line informs the Modem that the UART is ready to exchange data.

RI Ring Indicator Goes active when modem detects a ringing signal from the PSTN.

Page 25: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 25 -

Serial Port's Registers : Port Addresses & IRQ's

Name Address IRQ COM 1 3F8 4 COM 2 2F8 3 COM 3 3E8 4 COM 4 2E8 3

Table : Standard Port Addresses Above is the standard port addresses. These should work for most P.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.

Null Modems

A Null Modem is used to connect two DTE's together. This is commonly used as a cheap way to network games or to transfer files between computers using Zmodem Protocol, Xmodem Protocol etc. This can also be used with many Microprocessor Development Systems.

Figure : Null Modem Wiring Diagram

Above is my preferred method of wiring a Null Modem. It only requires 3 wires (TD, RD & SG) to be wired straight through thus is more cost effective to use with long cable runs. The theory of operation is reasonably easy. The aim is to make to computer think it is talking to a modem rather than another computer. Any data transmitted from the first computer must be received by the second thus TD is connected to RD. The second computer must have the same set-up thus RD is connected to TD. Signal Ground (SG) must also be connected so both grounds are common to each computer. The Data Terminal Ready is looped back to Data Set Ready and Carrier Detect on both computers. When the Data Terminal Ready is asserted active, then the Data Set Ready and Carrier Detect immediately become active. At this point the computer thinks the Virtual Modem to which it is connected is ready and has detected the carrier of the other modem.

Page 26: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 26 -

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 to Send high and as it's hooked together with the Clear to Send, It immediately gets a reply that it is ok to send and does so. Notice that the ring indicator is not connected to anything of each end. This line is only used to tell the computer that there is a ringing signal on the phone line. As we don't have a modem connected to the phone line this is left disconnected. DTE / DCE Speeds We have already talked briefly about DTE & DCE. A typical Data Terminal Device is a computer and a typical Data Communications Device is a Modem. Often people will talk about DTE to DCE or DCE to DCE speeds. DTE to DCE is the speed between your modem and computer, sometimes referred to as your terminal speed. This should run at faster speeds than the DCE to DCE speed. DCE to DCE is the link between modems, sometimes called the line speed. Most people today will have 28.8K or 33.6K modems. Therefore we should expect the DCE to DCE speed to be either 28.8K or 33.6K. Considering the high speed of the modem we should expect the DTE to DCE speed to be about 115,200 BPS.(Maximum Speed of the 16550a UART) This is where some people often fall into a trap. The communications program which they use have settings for DCE to DTE speeds. However they see 9.6 KBPS, 14.4 KBPS etc and think it is your modem speed. Today's Modems should have Data Compression build into them. This is very much like PK-ZIP but the software in your modem compresses and decompresses the data. When set up correctly you can expect compression ratios of 1:4 or even higher. 1 to 4 compression would be typical of a text file. If we were transferring that text file at 28.8K (DCE-DCE), then when the modem compresses it you are actually transferring 115.2 KBPS between computers and thus have a DCE-DTE speed of 115.2 KBPS. Thus this is why the DCE-DTE should be much higher than your modem's connection speed. Some modem manufacturers quote a maximum compression ratio as 1:8. Lets say for example its on a new 33.6 KBPS modem then we may get a maximum 268,800 BPS transfer between modem and UART. If you only have a 16550a which can do 115,200 BPS tops, then you would be missing out on a extra bit of performance. Buying a 16C650 should fix your problem with a maximum transfer rate of 230,400 BPS. However don't abuse your modem if you don't get these rates. These are MAXIMUM compression ratios. In some instances if you try to send a already compressed file, your modem can spend more time trying the compress it, thus you get a transmission speed less than your modem's connection speed. If this occurs try turning off your data compression. This should be fixed on newer modems. Some files compress easier than others thus any file which compresses easier is naturally going to have a higher compression ratio.

Page 27: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 27 -

Flow Control So if our DTE to DCE speed is several times faster than our DCE to DCE speed the PC can send data to your modem at 115,200 BPS. Sooner or later data is going to get lost as buffers overflow, thus flow control is used. Flow control has two basic varieties, Hardware or Software. Software flow control, sometimes expressed as Xon/Xoff uses two characters Xon and Xoff. Xon is normally indicated by the ASCII 17 character where as the ASCII 19 character is used for Xoff. The modem will only have a small buffer so when the computer fills it up the modem sends a Xoff character to tell the computer to stop sending data. Once the modem has room for more data it then sends a Xon character and the computer sends more data. This type of flow control has the advantage that it doesn't require any more wires as the characters are sent via the TD/RD lines. However on slow links each character requires 10 bits which can slow communications down. Hardware flow control is also known as RTS/CTS flow control. It uses two wires in your serial cable rather than extra characters transmitted in your data lines. Thus hardware flow control will not slow down transmission times like Xon-Xoff does. When the computer wishes to send data it takes active the Request to Send line. If the modem has room for this data, then the modem will reply by taking active the Clear to Send line and the computer starts sending data. If the modem does not have the room then it will not send a Clear to Send. The UART (8250 and Compatibles)

UART stands for Universal Asynchronous Receiver / Transmitter. Its the little box of tricks found on your serial card which plays the little games with your modem or other connected devices. Most cards will have the UART's integrated into other chips which may also control your parallel port, games port, floppy or hard disk drives and are typically surface mount devices. The 8250 series, which includes the 16450, 16550, 16650, & 16750 UARTS are the most commonly found type in your PC. Later we will look at other types which can be used in your homemade devices and projects.

Page 28: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 28 -

Figure : Pin Diagrams for 16550, 16450 & 8250 UARTs

The 16550 is chip compatible with the 8250 & 16450. The only two differences are pins 24 & 29. On the 8250 Pin 24 was chip select out which functioned only as a indicator to if the chip was active or not. Pin 29 was not connected on the 8250/16450 UARTs. The 16550 introduced two new pins in their place. These are Transmit Ready and Receive Ready which can be implemented with DMA (Direct Memory Access). These Pins have two different modes of operation. Mode 0 supports single transfer DMA where as Mode 1 supports Multi-transfer DMA. Mode 0 is also called the 16450 mode. This mode is selected when the FIFO buffers are disabled via Bit 0 of the FIFO Control Register or When the FIFO buffers are enabled but DMA Mode Select = 0. (Bit 3 of FCR) In this mode RXRDY is active low when at least one character (Byte) is present in the Receiver Buffer. RXRDY will go inactive high when no more characters are left in the Receiver Buffer. TXRDY will be active low when there are no characters in the Transmit Buffer. It will go inactive high after the first character / byte is loaded into the Transmit Buffer. Mode 1 is when the FIFO buffers are active and the DMA Mode Select = 1. In Mode 1, RXRDY will go active low when the trigger level is reached or when 16550 Time Out occurs and will return to inactive state when no more characters are left in the FIFO. TXRDY will be active when no characters are present in the Transmit Buffer and will go inactive when the FIFO Transmit Buffer is completely Full. All the UARTs pins are TTL compatible. That includes TD, RD, RI, DCD, DSR, CTS, DTR and RTS which all interface into your serial plug, typically a D-type connector. Therefore RS232 Level Converters (which we talk about in detail later) are used. These are commonly the DS1489 Receiver and the DS1488 as the PC has +12 and -12 volt rails which can be used by these devices. The RS232 Converters will convert the TTL signal into RS232 Logic Levels.

Page 29: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 29 -

Pin No. Name Notes Pin 1:8 D0:D7 Data Bus Pin 9 RCLK Receiver Clock Input. The frequency of

this input should equal the receivers baud rate * 16

Pin 10 RD Receive Data Pin 11 TD Transmit Data Pin 12 CS0 Chip Select 0 - Active High Pin 13 CS1 Chip Select 1 - Active High Pin 14 nCS2 Chip Select 2 - Active Low Pin 15 nBAUDOUT Baud Output - Output from

Programmable Baud Rate Generator. Frequency = (Baud Rate x 16)

Pin 16 XIN External Crystal Input - Used for Baud Rate Generator Oscillator

Pin 17 XOUT External Crystal Output Pin 18 nWR Write Line - Inverted Pin 19 WR Write Line - Not Inverted Pin 20 VSS Connected to Common Ground Pin 21 RD Read Line - Inverted Pin 22 nRD Read Line - Not Inverted Pin 23 DDIS Driver Disable. This pin goes low when

CPU is reading from UART. Can be connected to Bus Transceiver in case of high capacity data bus.

Pin 24 nTXRDY Transmit Ready Pin 25 nADS Address Strobe. Used if signals are not

stable during read or write cycle Pin 26 A2 Address Bit 2 Pin 27 A1 Address Bit 1 Pin 28 A0 Address Bit 0 Pin 29 nRXRDY Receive Ready Pin 30 INTR Interrupt Output Pin 31 nOUT2 User Output 2 Pin 32 nRTS Request to Send Pin 33 nDTR Data Terminal Ready Pin 34 nOUT1 User Output 1 Pin 35 MR Master Reset Pin 36 nCTS Clear To Send Pin 37 nDSR Data Set Ready Pin 38 nDCD Data Carrier Detect Pin 39 nRI Ring Indicator Pin 40 VDD + 5 Volts

Table : Pin Assignments for 16550A UART

Page 30: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 30 -

Programming with Serial Port Bioscom() is the standard library function declared in the bios.h file.

Declaration: int bioscom(int cmd, char abyte, int port);

Remarks: bioscom use BIOS interrupt 0x14 to perform various RS-232 communications over the I/O port given in port.

Argument What It Is/Does Cmd Specifies the I/O operation to perform

Abyte OR combination of bits that specifies COM port settings (ignored

if cmd = 2 or 3) Port Identifies the I/O port; 0 = COM1, 1 = COM2, etc.

cmd can be one of the following (defined in BIOS.H): 0 Sets the communications parameters to the value in abyte 1 Sends the character in abyte out over the communications line 2 Receives a character from the communications line 3 Returns current status of the communications port When cmd = 2 or 3 (_COM_RECEIVE or _COM_STATUS), the abyte argument is ignored. When cmd = 0 (_COM_INIT), abyte is an OR combination of the following bits (one from each group):

Bioscom Meaning 0x02 0x03

7 data bits 8 data bits

0x00 0x04

1 stop bit 2 stop bits

0x00 0x08 0x18

No parity Odd parity Even parity

0x00 0x20 0x40 0x60 0x80 0xA0 0xC0 0xE0

110 baud 150 baud 300 baud 600 baud 1200 baud 2400 baud 4800 baud 9600 baud

Page 31: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 31 -

For example: abyte = 0xEB = (0xE0 | 0x08 | 0x00 | 0x03) =

(_COM_9600 | _COM_ODDPARITY | _COM_STOP1 | _COM_CHR8) The communications port is set to

9600 baud (0xE0 = _COM_9600) Odd parity (0x08 = _COM_ODDPARITY) 1 stop bit (0x00 = _COM_STOP1) 8 data bits (0x03 = _COM_CHR8)

Return Value: For all values of cmd, both functions return a 16-bit integer.

• The upper 8 bits of the return value are status bits. • If one or more status bits is set to 1, an error has occured. • If no status bits are set to 1, the byte was received without error.

The lower 8 bits of the return value depend on the value of cmd specified:

Value of cmd Lower 8 bits of return value 0 (_COM_INIT) or 3 (_COM_STATUS)

The lower bits are defined as shown below.

1 (_COM_SEND) The byte send to the port. 2 (_COM_RECEIVE) The byte read is in the lower bits of the

return value--if there is no error (no upper bits are set to 1).

Upper 8 bits of the bioscom return value 15 Time out (set to 1 if abyte value could not be sent) 14 Transmit shift register empty 13 Transmit holding register empty 12 Break detect 11 Framing error 10 Parity error 9 Overrun error 8 Data ready Lower 8 bits (these vary, depending on the value of cmd) 0 Received line signal detect 1 Ring indicator 2 Data set ready 3 Clear to send 4 Change in receive line signal detector 5 Trailing edge ring detector 6 Change in data set ready 7 Change in clear to send

Page 32: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 32 -

Example

Our program will display whatever is typed on one computer on the other computer. The two machines are connected through the serial cable & both running the same program. #include <bios.h> #include <conio.h> #include <stdio.h> #define COM1 0 #define DATA_READY 0x100 #define TRUE 1 #define FALSE 0 #define SETTINGS ( 0x80 | 0x02 | 0x00 | 0x00) int main(void) { int in, out, status, DONE = FALSE; bioscom(0, SETTINGS, COM1); printf("... BIOSCOM [ESC] to exit ...\n"); while (!DONE) { status = bioscom(3, 0, COM1); if (status & DATA_READY) if ((out = bioscom(2, 0, COM1) & 0x7F) != 0) putch(out); if (kbhit()) { if ((in = getch()) == '\x1B') DONE = TRUE; bioscom(1, in, COM1); } } return 0; }

Page 33: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 33 -

Page 34: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 34 -

Interrupt No. and Service No.

Interrupt Service How to Use

33h 0

Reset mouse and get status Call with:

AX = 0000h Returns: AX = FFFFh (If mouse support is available)

AX = 0000h (If mouse support is not available)

33h 1

Show mouse pointer Call with:

AX = 0001h Returns:

Nothing

33h 2

Hide mouse pointer Call with:

AX = 0002h

Returns: Nothing

33h 3

Get mouse position and button status Call with:

AX = 0003h Returns:

BX = mouse button status

Bit Significance 0 left button is down 1 right button is down 2 center button is down CX = x coordinate DX = y coordinate

33h 4

Set mouse pointer position Call with:

AX = 0004h CX = x coordinate DX = y coordinate

Returns: Nothing

33h 7

Set horizontal limits for pointer Call with:

AX = 0007h CX = minimum x coordinate DX = maximum x coordinate

Page 35: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 35 -

Interrupt Service Service

33h 8

Set vertical limits for pointer Call with:

AX = 0008h CX = minimum y coordinate DX = maximum y coordinate

Page 36: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 36 -

1) Program to find whether mouse driver is loaded or not.

#include <dos.h> Void main() { union REGS i,o; clrscr(); i.x.ax=0; int86(0x33,&i,&o); if(o.x.ax==0) printf("No Mouse Available....."); else printf("Mouse Available......"); getch(); }

The above program declares two variables of type union REGS.union REGS, which is declared in dos.h, contains two structures(struct WORDREGS x, struct BYTEREGS h).These two structures contain some 1-byte long and 2-byte long variables which indirectly represent CPU's registers. By placing 0 (sub-function) in ax register and invoking mouse interrupt(33h),we can check whether mouse driver is loaded or not.we used int86() function to invoke the interrupt.int86() takes 3 arguements: interrupt no and two union REGS type variables. If mouse driver is not loaded, it returns 0 in ax register. All return values are accessed using 'o' i.e why we have o.x.ax==0 in if statement.

Page 37: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 37 -

2) Program to show the mouse pointer.

Our first program only reported mouse driver loaded or not.Even if driver is avilable,we have no signs of mouse pointer.To view mouse pointer,we have to use sub-function 1.Look at the program presented below.

#include <dos.h> Void main() { union REGS i,o; clrscr(); i.x.ax=0; int86(0x33,&i,&o); if(o.x.ax==0) { printf("No Mouse Available....."); exit(); } i.x.ax=1; int86(0x33,&i,&o); }

The above program is same as our first program except for the last few lines. We have placed 1 in ax register and invoked mouse interrupt to see the pointer. Since we are in text mode, our pointer is a rectangular box. We can observe an arrow if we switch to graphics mode.

Page 38: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 38 -

3) Program to hide the mouse pointer.

Mouse cursor still remains, even after our program is terminated. Look at the following program.

#include <dos.h> Void main() { union REGS i,o; clrscr(); i.x.ax=0; int86(0x33,&i,&o); if(o.x.ax==0) { printf("No Mouse Available....."); exit(); } i.x.ax=1; int86(0x33,&i,&o); gotoxy(24,23); printf("Press any key to hide mouse cursor... "); getch(); i.x.ax=2; int86(0x33,&i,&o); gotoxy(10,23);

printf("Mouse cursor is hidden !! Press any key to terminate the program ...") ;

getch(); }

The above program uses sub-function 2 and invokes mouse interrupt to hide the mouse pointer.This function is quite a useful function,when writing programs that draw a line or rectangle as we move the mouse. While writing those programs we don't want mouse pointer to erase what we draw hence we hide the pointer.

Page 39: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 39 -

4) Program to show the position of the mouse pointer.

For writing any useful program with mouse support,we need to know the (x,y) co-ordinates of the mouse position.The below program prints the position of the mouse,as we mouse the mouse.

#include <dos.h> Void main() { union REGS i,o; clrscr(); i.x.ax=0; int86(0x33,&i,&o); if(o.x.ax==0) { printf("No Mouse Available..."); exit(); } i.x.ax=1; int86(0x33,&i,&o); gotoxy(25,23); printf("Press any key to exit..."); while(!kbhit()) { i.x.ax=3; int86(0x33,&i,&o); gotoxy(2,2); printf("x->co-ordinate=%d \n y->co- ordinate=%d ",o.x.cx,o.x.dx); } i.x.ax=2; int86(0x33,&i,&o); }

In the above program we have a while loop.This loop continues until a key is hit.In loop,we used sub-function 3 and invoked mouse interrupt. Sub-function 3 returns X->co-ordinate in cx register and Y->co-ordinate in dx register.printf statements prints x and y co-ordinates as long as the loop continues.Maximum screen resolution for mouse in text mode is 640x200 and in graphics mode is 640x480.

Page 40: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 40 -

5) Program to print which mouse button is pressed.

Knowing which button is pressed is very important task.The program below prints which button is pressed as soon as we press any button.

#include <dos.h> Void main() { union REGS i,o; int button; clrscr(); i.x.ax=0; int86(0x33,&i,&o); if(o.x.ax==0) { printf("No mouse available...."); exit(); } i.x.ax=1; int86(0x33,&i,&o); gotoxy(24,23); printf("Press any key to exit...."); while(!kbhit()) { i.x.ax=3; int86(0x33,&i,&o); button=o.x.bx&7; gotoxy(23,11); switch(button) { case 1: printf("Left button pressed"); break; case 2: printf("Right button pressed”); break; case 4: printf("Middle button pressed”); break;

Page 41: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 41 -

case 3: printf("Both buttons pressed ”); break; case 5: printf("Left and Middle buttons pressed”); break; case 6: printf("Right and Middle buttons pressed"); break; case 7: printf("All the three buttons pressed”); break; default: printf("No button pressed...."); } } i.x.ax=2; int86(0x33,&i,&o); }

The above program is same as the previous program except we have little extra in while loop.In while we used the same sub-function 3 and invoked mouse interrupt.This subfunction even returns button press information in bx register.Entire button press information is stored in the first 3 bits of the bx register.So we ANDED bx with 7 to separate the first 3 bits and stored them in button variable.

If the first bit's value is 1 then the left button is pressed,if the value is 0 then it is not pressed.If the second bit's value is 1 then the right button is pressed,if value is 0 then it is not pressed.If the last bit's value is 1 then the middle button is pressed,if value is 0 then it is not pressed.

Page 42: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 42 -

6) Program to set the position of the mouse pointer on the screen.

Sometimes we need to set the position of the mouse pointer, just as we set the position of the keyboard's cursor using gotoxy().The following program sets the pointer to (x=150,y=100) position on the screen.

#include <dos.h> Void main() { union REGS i,o; clrscr(); i.x.ax=0; int86(0x33,&i,&o); if(o.x.ax==0) { printf("No mouse available"); exit(); } i.x.ax=1; int86(0x33,&i,&o); i.x.ax=3; int86(0x33,&i,&o); gotoxy(1,1); printf("Current Position:x=%d y=%d”,o.x.cx,o.x .dx); gotoxy(15,23); printf("Press any key to set the mouse pointer to (150,100)..."); getch(); i.x.ax=4; i.x.cx=150; i.x.dx=100; int86(0x33,&i,&o); gotoxy(15,23); printf("Cursor is set ... press a key to exit”) ; getch(); }

In the above program,we use sub-function 4 to set the pointer's position. We set the X->co-ordinate by placing a value in the cx register and Y->co-ordinate by placing a value in the dx register.

Page 43: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 43 -

7) Program to switch to graphics mode.

The program below switches text mode to graphcs mode.After executing this program,observe the mouse pointer.Now,it's in an arrow shape. Try to execute program-4 in graphics mode and observe the maximum screen resolution for mouse is increased to 640x480.

#include <graphics.h> #include <dos.h> Void main() { int gd=DETECT,gm; union REGS i,o; initgraph(&gd,&gm,"c:\\tc\\bgi"); i.x.ax=0; int86(0x33,&i,&o);

if(o.x.ax==0) { printf("No Mouse Avaialable.."); restorecrtmode(); exit(); }

i.x.ax=1; int86(0x33,&i,&o); outtextxy(100,400,"Mouse Pointer in graphics mode!!Press any key to exit"); getch(); i.x.ax=2; int86(0x33,&i,&o); restorecrtmode(); }

In the above program,we used standard library function initgraph() to initialize graphics system.This function takes 3 arguments;graphics driver, graphics mode,path to the driver.By using DETECT,we tell the function to select a suitable driver by itselt.When DETECT is used,no need to assign anything to graphics mode.Path is null since the driver files are located in the current directory.This function initializes graphics system and when the program terminates we come to text mode by using restorecrtmode() function.

Page 44: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 44 -

8) Program to restrict the mouse pointer within a boundary.

Sometimes,in our program,we need to restrict the mouse pointer with in a screen boundary.In order to do that,we need to specify the top,left co-ordinates as well bottom,right co-ordinates.Sub-functions 7,8 are used to limit the pointer within a boundary.Look at the following program.

#include <graphics.h> #include <dos.h> main() { union REGS i,o; int gd=DETECT,gm; initgraph(&gd,&gm,"c:\\tc\\bgi"); i.x.ax=0; int86(0x33,&i,&o);

if(o.x.ax==0) { restorecrtmode(); printf("No Mouse Available....."); exit(); }

rectangle(99,49,501,151); i.x.ax=1; int86(0x33,&i,&o); i.x.ax=7; i.x.cx=100; i.x.dx=500; int86(0x33,&i,&o); i.x.ax=8; i.x.cx=50; i.x.dx=150; int86(0x33,&i,&o); while(!kbhit()) ; i.x.ax=2; int86(0x33,&i,&o); restorecrtmode(); }

Page 45: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 45 -

In the above program,sub-fuction 7 is used to specify two x->co-ordinates and sub-function 8 is used to specify two y->co-ordinates and these co-ordinates form a rectangular boundary within which mouse is restricted.

Page 46: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 46 -

9) Free-hand drawing.

If you ever wonder,how pencil tool in paint works.Then,the following program shows how it can be written in C.The following program makes use of some of the sub-function,which we already disussed above,and shows how they can be used to write useful programs like free-hand drawing.Just,go through the following program.

#include <graphics.h> #include <dos.h> union REGS i,o; main() { int gd=DETECT,gm,button,x1,y1,x2,y2; initgraph(&gd,&gm,""); i.x.ax=0; int86(0x33,&i,&o);

if(o.x.ax==0) { printf("No Mouse is available.."); exit(); restorecrtmode(); }

outtextxy(230,400,"Press any key to exit....");

while(!kbhit()) { show_mouse(); get_mouse_pos(&x1,&y1,&button); x2=x1; y2=y1; while(button==1) { hide_mouse(); line(x1,y1,x2,y2); x1=x2; y1=y2; get_mouse_pos(&x2,&y2,&button); }

Page 47: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 47 -

} restorecrtmode(); } show_mouse() { i.x.ax=1; int86(0x33,&i,&o); } hide_mouse() { i.x.ax=2; int86(0x33,&i,&o); } get_mouse_pos(int *x,int *y,int *button) { i.x.ax=3; int86(0x33,&i,&o); *x=o.x.cx; *y=o.x.dx; *button=o.x.bx&1; }

There is nothing in this program to explain.Since you have gone through the program,you must have understood the logic.

Page 48: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 48 -

10) Line drawing using mouse.

Following program shows how to draw a line interactively using mouse. If you know how to draw a line,there is no big deal in developing a program that draws a square.So,carefully observe and understand the following program.

#include <graphics.h> #include <alloc.h> #include <dos.h> union REGS i,o; char far *p; void main() { Int gd=DETECT,gm,button; Int x1,y1,x2,y2,prevx2,prevy2,x,y; initgraph(&gd,&gm,"c:\\tc\\bgi"); i.x.ax=0; int86(0x33,&i,&o); if(o.x.ax==0) { printf("No Mouse is available.."); exit(); restorecrtmode(); } while(!kbhit()) { show_mouse(); get_mouse_pos(&x1,&y1,&button); if(button==1) { hide_mouse(); x2=x1; y2=y1; save(x1,y1,x2,y2); line(x1,y1,x2,y2); prevx2=x2; prevy2=y2; get_mouse_pos(&x2,&y2,&button);

Page 49: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 49 -

while(button==1) { if(x2!=prevx2 || y2!=prevy2) { setcolor(BLACK); line(x1,y1,prevx2,prevy2); x=x1<prevx2?x1:prevx2; y=y1<prevy2?y1:prevy2; restore(x,y); setcolor(WHITE); save(x1,y1,x2,y2); line(x1,y1,x2,y2); prevx2=x2; prevy2=y2; } get_mouse_pos(&x2,&y2,&button); } farfree(p); } } restorecrtmode(); } show_mouse() { i.x.ax=1; int86(0x33,&i,&o); } hide_mouse() { i.x.ax=2; int86(0x33,&i,&o); } get_mouse_pos(int *x,int *y,int *button) { i.x.ax=3; int86(0x33,&i,&o); *x=o.x.cx; *y=o.x.dx; *button=o.x.bx&1; } save(int x1,int y1,int x2,int y2) { unsigned area;

Page 50: Hardware Interfacing in C - GTUCAMPUS Engineeringniraj9787HARDWARE...complex as the characters represented by the keys on a typewriter keyboard. In this case, the characters or symbols

HARDWARE INTERFACING USING C

Prepared By: Chirag Gohel E-mail: [email protected] - 50 -

area=imagesize(x1,y1,x2,y2); p=farmalloc(area); if(p==NULL) { restorecrtmode(); printf("No Memory..."); exit(); } getimage(x1,y1,x2,y2,p); } restore(int x1,int y1) { putimage(x1,y1,p,OR_PUT); farfree(p); }

When drawing lines interactively,we must make sure that the currently drawn line doesn't wipe off already drawn lines when it intersects them.In order to do that,the above program uses save and restore functions.These two functions captures and restores screen contents.