Hardware Required:
- PIC16F84A microcontroller
- 8MHz crystal
- 2 x 22pF ceramic capacitors
- 10K ohm resistor
- MAX232 -- datasheet
- 4 x 10uF polarized capacitor
- Female RS232 connector
- Breadboard
- 5V power source
- Jumper wires
To interface the PIC16F84A MCU with the PC we need MAX232 signal level converter as shown in the circuit diagram. There are 2 lines between the PIC16F84A and the MAX232 and also two lines between the MAX232 and the female COM connector. One line for data transmit and the other one for data receive.
The female COM connector is connected to the PC using RS232 cable, this cable has to be male-female because the PC RS232 port type is male.
In this example the PIC16F84A MCU runs with 8MHz crystal oscillator.
UART Example for PIC16F84A microcontroller C code:
The function #use rs232(xmit = PIN_B4, rcv = PIN_B5, baud = 2400) is used to configure the UART protocol. Here software UART is used.
where:
xmit is the transmit pin (RB4)
rcv is the receive pin (RB5)
2400 is the baud rate.
The functions used in the C code are:
printf: sends a string of characters over RS232 transmission pin (TX).
putc: send a character over RS232 transmission pin (TX).
getc(): read character if available.
Complete C code for CCS C compiler is below.
// Software UART example for PIC16F84A. // http://ccspicc.blogspot.com/ // electronnote@gmail.com #include <16F84A.h> #fuses HS, NOWDT, PUT, NOPROTECT #use delay(clock = 8000000) #use fast_io(B) #use rs232(xmit = PIN_B4, rcv = PIN_B5, baud = 2400) const char message[] = "***** PIC16F84A microcontroller UART example *****" ; int8 i = 0, j; void main(){ output_drive(PIN_B4); delay_ms(2000); // Wait 2 seconds // Print text printf("Hello world!"); // Print list of characters printf("\n\r"); // Start new line while(message[i] != '\0'){ // Loop until the end of the string putc(message[i]); // Write character delay_ms(100); // Wait 100 ms i++; // Increment i } // Print numbers printf("\n\r"); // Start new line for(i = 0; i < 21; i++){ printf("%u\n\r", i); // Print i and start new line delay_ms(500); } // Receive and send character via UART while(TRUE){ j = getc(); // UART read character putc(j); // Send it back } }