PROJECT 23 – Input/Output Example Using the RS232 Port
Function
This project shows how we can input and output serial data using the built-in C functions. In this example, the user is prompted to enter a character through the RS232 terminal. The program then finds the next character (i.e. increments the character by one) and outputs it to the user’s terminal.
Circuit Diagram
The circuit diagram of this project is the same as in Project 22 (i.e. Fig. 6.5).
Program Description
The RS232 serial port is initialized to operate at 2400 baud. The user is then prompted to enter a character. This character is incremented by one and sent to the serial output port.
The following PDL describes the functions of the program:
Program Listing
The program listing is shown in Fig. 6.8. Function serial_init initializes the serial port for operation at 2400 baud with a 12 MHz crystal. Built-in function printf is used toprompt the user to enter a character. A character is then read from the user’s terminal using the standard C built-in function getchar and this character is stored in a variable called c. Finally, this character is incremented by one and is output to the RS232 port using function printf. The above process is repeated indefinitely. This program occupies 1164 bytes of memory.
Input/Output Without Using the Built-in Functions
The above program uses the standard C built-in functions printf and getchar. As a result the program is big. An example program is given in Fig. 6.9 which does not use these built-in functions and thus occupies much less space in memory.
Function serial_init is the same as before but note that the serial port interrupts are enabled (EA = 1 and ES = 1). Function send_serial sends a null-terminated string to the serial output port. Similarly, function send_l_char sends a single character to the serial port. Serial data is read in via the serial port interrupt service routine (serial). Whenever a character is transmitted or received, the interrupt service routine is activated automatically. The interrupt number of the serial port is 4. Here, the receive interrupt register (RI) is checked and a character is assumed to be received from the serial port if RI is non-zero. The received character is copied from SBUF to a variable called received_character.
The main program calls function send_serial todisplay the message ‘Enter a character’. If a character is received, this character is echoed on the user’s terminal and the next character is displayed by incrementing and outputting the variable received_character. Function send_l_char is then used tosend a carriage return and line feed after each output.