1. 首页
  2. 编程语言
  3. C
  4. C语言232串口通讯源码示例

C语言232串口通讯源码示例

上传者: 2023-03-05 12:20:54上传 DOCX文件 11.89KB 热度 11次

以下是一个示例C语言源码,可以用于实现通过232串口进行通信的应用程序。该代码实现了串口初始化、数据读取和写入等基本功能,并包含了详细的注释和说明,方便开发者进行理解和使用。

#include

#include

#include

int main()

{

HANDLE hCom;

DCB dcb;

COMMTIMEOUTS timeouts;

char data[] = "Hello, Serial Port!";

DWORD dwBytesWrite = 0;

DWORD dwBytesRead = 0;

char readBuf[1024] = { 0 };

int i = 0;

hCom = CreateFile("COM1",

GENERIC_READ | GENERIC_WRITE,

0,

NULL,

OPEN_EXISTING,

0,

NULL);

if (hCom == INVALID_HANDLE_VALUE)

{

printf("Open serial port failed!\n");

return 0;

}

dcb.DCBlength = sizeof(dcb);

GetCommState(hCom, &dcb);

dcb.BaudRate = CBR_9600;

dcb.ByteSize = 8;

dcb.Parity = NOPARITY;

dcb.StopBits = ONESTOPBIT;

SetCommState(hCom, &dcb);

timeouts.ReadIntervalTimeout = 50;

timeouts.ReadTotalTimeoutMultiplier = 10;

timeouts.ReadTotalTimeoutConstant = 100;

timeouts.WriteTotalTimeoutMultiplier = 10;

timeouts.WriteTotalTimeoutConstant = 100;

SetCommTimeouts(hCom, &timeouts);

WriteFile(hCom, data, strlen(data), &dwBytesWrite, NULL);

ReadFile(hCom, readBuf, sizeof(readBuf), &dwBytesRead, NULL);

for (i = 0; i < dwBytesRead; i++)

{

printf("%c", readBuf[i]);

}

CloseHandle(hCom);

return 0;

}

用户评论