Serial Port and PC communication code based on AVR (uart8-bit data ),

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.