用C语言写出51单片机串口收发字符串的程序
时间: 2023-04-03 17:02:45 浏览: 119
可以的,以下是一个简单的示例程序:
```c
#include <reg51.h>
#define FOSC 11059200L
#define BAUD 9600
#define DIVIDER (FOSC / 12 / BAUD)
void init_uart() {
SCON = 0x50; // 8-bit data, 1 stop bit, receive enable
TMOD &= 0x0F; // clear timer1 mode bits
TMOD |= 0x20; // timer1 mode 2: 8-bit auto-reload
TH1 = TL1 = 0 - DIVIDER; // set timer1 reload value
TR1 = 1; // start timer1
ES = 1; // enable serial interrupt
EA = 1; // enable global interrupt
}
void send_char(char c) {
SBUF = c;
while (!TI);
TI = 0;
}
void send_string(char *s) {
while (*s) {
send_char(*s++);
}
}
char receive_char() {
while (!RI);
RI = 0;
return SBUF;
}
void receive_string(char *buf, int len) {
int i;
for (i = 0; i < len - 1; i++) {
buf[i] = receive_char();
if (buf[i] == '\r' || buf[i] == '\n') {
break;
}
}
buf[i] = '\0';
}
void main() {
char buf[64];
init_uart();
while (1) {
receive_string(buf, sizeof(buf));
send_string("You said: ");
send_string(buf);
send_string("\r\n");
}
}
void serial_isr() interrupt 4 {
// do nothing
}
```
阅读全文