Keil Logo

C51: 8051 Serial I/O in C


Information in this article applies to:

  • C51 Version 5.50

QUESTION

How do I write a C program to echo characters coming in the 8051's serial port?

ANSWER

The functions _getkey and putchar perform serial I/O using the on-chip serial port. These routines are included in the C51 libraries and source for each is included in the \C51\LIB directory. Refer to your C51 User's Guide for complete documentation on these routines.

The following example program sets up the on-chip serial port, sets the baud rate, and waits for a character (using the _getkey function). When a character is received, it is output using the putchar function.

#include "reg51.h"
#include "stdio.h"

void main (void)
{
SCON  = 0x50;                   /* SCON: mode 1, 8-bit UART, enable rcvr    */
TMOD |= 0x20;                   /* TMOD: timer 1, mode 2, 8-bit reload      */
TH1   = 0xf3;                   /* TH1:  reload value for 2400 baud         */
TR1   = 1;                      /* TR1:  timer 1 run                        */
TI    = 1;                      /* TI:   set TI to send first char of UART  */

while(1)
  {
  unsigned char aaa;
  aaa = _getkey();
  putchar(aaa);
  }
}

MORE INFORMATION

  • Refer to _getkey in the Cx51 User's Guide.

Last Reviewed: Thursday, February 25, 2021


Did this article provide the answer you needed?
 
Yes
No
Not Sure
 
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.