windows串口通信

#include 
#include 
HANDLE hCom;
int main(void)
{
        hCom = CreateFile(TEXT("COM1"),//COM1口
                GENERIC_READ | GENERIC_WRITE, //允许读和写
                0, //独占方式
                NULL,
                OPEN_EXISTING, //打开而不是创建
                0, //同步方式
                NULL);
        if (hCom == (HANDLE)-1)
        {
                printf("COM open fail!\n");
                return FALSE;
        }
        else
        {
                printf("COM open success1!\n");
        }
        SetupComm(hCom, 1024, 1024); //输入缓冲区和输出缓冲区的大小都是1024
        COMMTIMEOUTS TimeOuts;
        //设定读超时
        TimeOuts.ReadIntervalTimeout=1000;
        TimeOuts.ReadTotalTimeoutMultiplier=500;
        TimeOuts.ReadTotalTimeoutConstant=5000;
        //设定写超时
        TimeOuts.WriteTotalTimeoutMultiplier=500;
        TimeOuts.WriteTotalTimeoutConstant=2000;
        SetCommTimeouts(hCom,&TimeOuts); //设置超时
        DCB dcb;
        GetCommState(hCom, &dcb);
        dcb.BaudRate = 9600; //波特率为9600
        dcb.ByteSize = 8; //每个字节有8位
        dcb.Parity = NOPARITY; //无奇偶校验位
        dcb.StopBits = ONE5STOPBITS; //1个停止位
        SetCommState(hCom, &dcb);
        DWORD wCount;//读取的字节数
        //printf("wCount", wCount);
        BOOL bReadStat;
        BOOL bWriteStat;
        printf("COM open success2!\n");
        while (1)
        {
                PurgeComm(hCom, PURGE_TXCLEAR | PURGE_RXCLEAR); //清空缓冲区
                char str[9] = { 0 };
                char str1[9] = { 0 };
                bReadStat = ReadFile(hCom, str, 9, &wCount, NULL);
                //ReadFile (HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped);
                //printf("%d\n", bReadStat);
                if (!bReadStat)
                {
                        printf("Failed to read serial port!");
                        return FALSE;
                }
                else
                {
                        //WriteFile (HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped);
                        bWriteStat=WriteFile(hCom,str,9,&wCount,NULL);
                        //printf("%d\n", bWriteStat);
                        //printf("%s\n", str1);
                        //printf("%s\n", str1);
                        str[8] = '\0';
                        printf("%s\n", str);
                }
                //Sleep(100);
                Sleep(10);
        }
}

在这里插入代码片


你可能感兴趣的:(windows,c语言)