Serial Port and PC communication code based on AVR (uart8-bit data ),
In order to continue to improve the function based on this code in the future, we will put the code here and learn it with everyone.
/************************************
AVR clock: 8.00 MHz
* 8-bit data with a baud rate of 9600 (51) and 1-bit data is stopped. When the baud rate is set to 19200, UBRR = 25, 4800 = 103
* Note: The best baud rate setting is 9600, and other data is unstable. For more information about the UBRR values corresponding to different baud rates, see the manual.
* The PC sends a character to the Development Board, and the Development Board writes the uppercase letter back to the PC.
***********************************/
# Include <iom16v. h>
# Include <macros. h>
Void USART_Init (unsigned int baud)
{
/* Set the baud rate and baud value query data manual */
UBRRH = (unsigned char) (baud> 8 );
UBRRL = (unsigned char) baud;
/* Enable the receiver and transmitter */
Ucsulfate = (1 <RXEN) | (1 <TXEN );
/* Set the frame format: 8 data bits and 2 Stop bits */
UCSRC = (1 <URSEL) | (1 <USBS) | (3 <UCSZ0 );
}
Void USART_Transmit (unsigned char data)
{
/* Wait for the sending buffer to be empty */
While (! (UCSRA & (1 <UDH )))
;
/* Put the data into the buffer and send the data */
UDR = data;
}
Unsigned char USART_Receive (void)
{
/* Waiting for receiving data */
While (! (UCSRA & (1 <RXC )))
;
/* Obtain and return data from the buffer */
Return UDR;
}
Void main ()
{
Unsigned char cr;
DDRD = 0X02; // port PD2 (TXD) output, port PD1 (RXD) Input pulling
PORTD = 0XFF;
// CLR_PORTD (BUZZER );
USART_Init (51); // The UBRR value corresponding to the baud rate for parameter initialization
While (1)
{
Cr = USART_Receive ();
Cr-= 32;
USART_Transmit (cr );
}
}
// The ASCII code of uppercase and lowercase letters is 32 different. If the PC sends non-lowercase letters, the Development Board may send back garbled characters.