![]() | ![]() |
Description
This applet demonstrates the
RS-232 Serial-Communications Receiver and Transmitter
modules of the PIC16F628 microcontroller.
The circuit consists of the microcontroller
connected to a serial terminal.
The program running on the microcontroller (see below) first sets the input/output direction of the ports A and B and initializes the on-chip serial receiver and transmitter registers. Default parameters are 600 baud, 8N1 communication. Afterwards, the program enters an endless idle loop.
Due to the setup of the receiver control registers, an interrupt is generated whenever the microcontroller detects an incoming character on the receive pin (port B1/RX). The interrupt service routine (see below) then simply copied the received character into the TXREG transmission register and starts sending this character via TXEN=1 onto the transmitter output pin (port B2/TX). As a result, all incoming characters are echoed via the TX pin, and appear on the serial terminal.
To see the program in action, just type characters into the terminal window (if necessary, use the popup-menu 'edit' command to open the serial terminal window). The character is then sent from the terminal to the PIC microprocessor, detected and stored into the RCREG register, copied to the TXREG register, sent back to the terminal, and finally displayed by the terminal.
The program running on the microcontroller is based on the following C source code:
/* demonstration of the PIC16F628 serial-communications module.
* Characters received via the RX pin are echoed to the TX pin,
* at 600 baud 8N1.
*/
#include "pic.h"
void main() {
TRISB1 = 1;
TRISB2 = 0;
RB2 = 1;
// configura baud rate
SPBRG = 23;
SYNC = 0;
BRGH = 0;
RX9 = 0; // nao receber nono bit
RCIF = 0; // zera flag de interrupcao de recepcao na USART
RCIE = 1; // habilita interrupcao de recepcao na USART
SPEN = 1; // habilita USART
CREN = 1; // habilita recepcao na USART
PEIE = 1; // habilita interrupcao em perifericos
GIE = 1; // habilita todas as interrupcoes
while( 1 )
;
}
static void interrupt isr( void ) {
if ( RCIF ) { // se dado chegou na USART
TXREG = RCREG; // pega dado recebido em RCREG e transfere
// para TXREG para ser transmitido via USART
TXEN = 1; // habilita envio na USART
}
}
Run the applet | Run the editor (via Webstart)