STC8单片机串口的多字节通过数组的收发程序
时间: 2024-03-20 11:44:29 浏览: 21
好的,下面是基于STC8单片机的串口多字节收发程序:
```c
#include <reg52.h>
#include <stdio.h>
#define UART_BAUDRATE 9600
#define UART_STOP_BITS 1
#define UART_PARITY 'N'
#define BUFFER_SIZE 16
#define DELAY_TIME 1000
unsigned char tx_buffer[BUFFER_SIZE];
unsigned char rx_buffer[BUFFER_SIZE];
unsigned char tx_index = 0;
unsigned char rx_index = 0;
void UART_Init() {
TMOD |= 0x20;
SCON = 0x50;
TH1 = 256 - (11059200 / 12 / 32 / UART_BAUDRATE);
TL1 = TH1;
TR1 = 1;
}
void UART_SendChar(unsigned char ch) {
SBUF = ch;
while (!TI);
TI = 0;
}
void UART_SendString(unsigned char *str) {
while (*str) {
UART_SendChar(*str++);
}
}
void UART_Receive() {
if (RI) {
RI = 0;
rx_buffer[rx_index++] = SBUF;
if (rx_index >= BUFFER_SIZE) {
rx_index = 0;
}
}
}
void UART_SendBuffer(unsigned char *buffer, unsigned char length) {
for (unsigned char i = 0; i < length; i++) {
UART_SendChar(buffer[i]);
}
}
void UART_ReceiveBuffer(unsigned char *buffer, unsigned char length) {
unsigned char i = 0;
while (i < length) {
UART_Receive();
if (rx_index != i) {
buffer[i++] = rx_buffer[rx_index];
}
}
}
void main() {
UART_Init();
EA = 1;
ES = 1;
unsigned char data[] = {'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!'};
unsigned char length = sizeof(data) / sizeof(data[0]);
while (1) {
UART_SendBuffer(data, length);
for (unsigned int i = 0; i < DELAY_TIME; i++);
UART_ReceiveBuffer(tx_buffer, length);
UART_SendString("\r\nReceived: ");
UART_SendBuffer(tx_buffer, length);
UART_SendString("\r\n");
for (unsigned int i = 0; i < DELAY_TIME; i++);
}
}
```
在这个程序中,我们定义了一个缓冲区 `tx_buffer` 和 `rx_buffer`,分别用于存储发送和接收的数据。我们还定义了两个索引变量 `tx_index` 和 `rx_index`,分别用于指向缓冲区中下一个要发送或接收的数据。
程序中的 `UART_SendBuffer` 函数用于向串口发送多个字节数据,`UART_ReceiveBuffer` 函数用于从串口接收多个字节数据。在 `UART_ReceiveBuffer` 函数中,我们会不断调用 `UART_Receive` 函数来判断是否有新的数据到达。如果有新的数据到达,我们就将其存储到缓冲区中,直到接收到足够的字节为止。
在主函数中,我们首先定义了一个要发送的数据数组 `data`,并且计算出了它的长度。然后我们通过循环不断地向串口发送该数组中的数据,并且在每次发送后暂停一段时间。接着我们调用 `UART_ReceiveBuffer` 函数来接收从串口返回的数据,并且将其打印出来。
注意,由于串口是异步通信的,我们需要在发送和接收之间加入一定的延时,以确保数据能够被正确地发送和接收。在这个程序中,我们使用了一个简单的 `for` 循环来实现延时,但是实际上更好的方法是使用定时器来实现延时。