Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade
Serial communication is a fundamental feature in embedded systems, allowing microcontrollers to communicate with other devices such as computers, sensors, and other microcontrollers. In the Arduino environment, the Serial.begin
function is commonly used to initialize serial communication. However, in the microchip environment, particularly with PIC microcontrollers, the process differs and requires a more hands-on approach to configure the Universal Synchronous Asynchronous Receiver Transmitter (USART) module.
This article will guide you through the steps to initialize serial communication on a PIC microcontroller using MPLAB X IDE and the XC8 compiler. Understanding how to set up serial communication is crucial for debugging, data logging, and interfacing with various peripherals.
Examples:
Setting Up the USART Module:
To initialize serial communication on a PIC microcontroller, you need to configure the USART module. Below is an example of how to set up the USART for a PIC16F877A microcontroller.
#include <xc.h>
// Configuration bits
#pragma config FOSC = HS // Oscillator Selection bits (HS oscillator)
#pragma config WDTE = OFF // Watchdog Timer Enable bit (WDT disabled)
#pragma config PWRTE = OFF // Power-up Timer Enable bit (PWRT disabled)
#pragma config BOREN = ON // Brown-out Reset Enable bit (BOR enabled)
#pragma config LVP = OFF // Low-Voltage (Single-Supply) In-Circuit Serial Programming Enable bit (RB3 is digital I/O, HV on MCLR must be used for programming)
#pragma config CPD = OFF // Data EEPROM Memory Code Protection bit (Data EEPROM code protection off)
#pragma config WRT = OFF // Flash Program Memory Write Enable bits (Write protection off)
#pragma config CP = OFF // Flash Program Memory Code Protection bit (Code protection off)
void USART_Init(long baud_rate) {
// Set the baud rate
unsigned int x;
x = (_XTAL_FREQ - baud_rate*64)/(baud_rate*64); // For low baud rates
if(x > 255) {
x = (_XTAL_FREQ - baud_rate*16)/(baud_rate*16); // For high baud rates
BRGH = 1;
}
if(x < 256) {
SPBRG = x; // Set the baud rate generator register
SYNC = 0; // Asynchronous mode
SPEN = 1; // Enable serial port pins
TXEN = 1; // Enable transmission
CREN = 1; // Enable reception
TX9 = 0; // 8-bit transmission
RX9 = 0; // 8-bit reception
}
}
void USART_TxChar(char out) {
while(!TRMT); // Wait until the transmit buffer is empty
TXREG = out; // Transmit the character
}
char USART_RxChar() {
while(!RCIF); // Wait until data is received
return RCREG; // Return the received character
}
void main() {
USART_Init(9600); // Initialize USART with 9600 baud rate
while(1) {
USART_TxChar('H'); // Transmit 'H'
__delay_ms(1000); // Wait 1 second
}
}
Explanation:
_XTAL_FREQ
).