Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade
UART (Universal Asynchronous Receiver/Transmitter) is a critical communication protocol used in many embedded systems for serial communication. UART1 refers to the first UART module in a microcontroller. Initializing UART1 correctly is essential for ensuring reliable data transmission and reception between devices. In the context of Microchip microcontrollers, such as those from the PIC and AVR families, initializing UART1 involves configuring various registers to set the baud rate, data bits, parity, and stop bits.
This article will guide you through the process of initializing UART1 on a Microchip microcontroller. We will use the MPLAB X IDE and the XC8 compiler for our examples. The steps and code provided will be specifically for a PIC18F4550 microcontroller, but the concepts can be adapted to other Microchip microcontrollers as well.
Examples:
Setting Up the Environment:
Configuring UART1:
main.c
) and include the necessary header files.#include <xc.h>
// Configuration bits
#pragma config FOSC = HS // Oscillator Selection bits (HS oscillator)
#pragma config WDT = OFF // Watchdog Timer Enable bit (WDT disabled)
#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)
#define _XTAL_FREQ 20000000 // Define the system clock frequency (20MHz)
void UART1_Initialize(void) {
// Set the baud rate
unsigned int baudrate = 9600;
unsigned int spbrg = (_XTAL_FREQ / (16 * baudrate)) - 1;
SPBRG = spbrg;
// Configure the TXSTA and RCSTA registers
TXSTAbits.BRGH = 1; // High-speed baud rate
TXSTAbits.SYNC = 0; // Asynchronous mode
TXSTAbits.TXEN = 1; // Enable transmitter
TXSTAbits.TX9 = 0; // 8-bit transmission
RCSTAbits.SPEN = 1; // Enable serial port
RCSTAbits.RX9 = 0; // 8-bit reception
RCSTAbits.CREN = 1; // Enable continuous reception
// Configure the TRIS register for TX and RX pins
TRISCbits.TRISC6 = 0; // TX pin as output
TRISCbits.TRISC7 = 1; // RX pin as input
}
void main(void) {
UART1_Initialize();
while (1) {
// Main loop
}
}
Explanation of the Code:
UART1_Initialize
function sets the baud rate by calculating the value for the SPBRG
register.TXSTA
(Transmit Status and Control) and RCSTA
(Receive Status and Control) registers are configured for 8-bit asynchronous communication.TRISC
register is configured to set the TX pin (RC6) as output and the RX pin (RC7) as input.Testing the UART1 Initialization: