CW32 UART FIFO例程
时间: 2023-10-05 19:09:57 浏览: 85
以下是一个简单的 CW32 UART FIFO 例程,用于使用 FIFO 缓冲区实现 UART 通信:
```c
#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <windows.h>
#define BUFFER_SIZE 1024
int main(int argc, char *argv[])
{
HANDLE hCom;
DCB dcb;
COMMTIMEOUTS timeouts;
char buffer[BUFFER_SIZE];
DWORD bytesRead, bytesWritten;
BOOL success;
memset(&dcb, 0, sizeof(dcb));
dcb.DCBlength = sizeof(dcb);
hCom = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hCom == INVALID_HANDLE_VALUE) {
fprintf(stderr, "Error opening COM port\n");
return 1;
}
success = GetCommState(hCom, &dcb);
if (!success) {
fprintf(stderr, "Error getting DCB\n");
CloseHandle(hCom);
return 1;
}
dcb.BaudRate = CBR_9600;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
success = SetCommState(hCom, &dcb);
if (!success) {
fprintf(stderr, "Error setting DCB\n");
CloseHandle(hCom);
return 1;
}
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
success = SetCommTimeouts(hCom, &timeouts);
if (!success) {
fprintf(stderr, "Error setting timeouts\n");
CloseHandle(hCom);
return 1;
}
while (1) {
success = ReadFile(hCom, buffer, BUFFER_SIZE, &bytesRead, NULL);
if (!success) {
fprintf(stderr, "Error reading from COM port\n");
CloseHandle(hCom);
return 1;
}
if (bytesRead > 0) {
success = WriteFile(hCom, buffer, bytesRead, &bytesWritten, NULL);
if (!success) {
fprintf(stderr, "Error writing to COM port\n");
CloseHandle(hCom);
return 1;
}
}
}
CloseHandle(hCom);
return 0;
}
```
这个例程使用了 Windows API 中的 CreateFile、GetCommState、SetCommState、SetCommTimeouts、ReadFile 和 WriteFile 函数来与 CW32 的 UART 进行通信。其中,ReadFile 和 WriteFile 函数使用了缓冲区来实现数据的 FIFO 储存。具体实现可以参考上述代码。
阅读全文