WIN32 串口通信程序

// win_uart.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <stdio.h>
#include <windows.h>

#define WRITE_BUF_SIZE 255
#define READ_BUF_SIZE  255
#define READ_TIMEOUT   5000      // milliseconds

HANDLE hComm;

DWORD dwRead=0;
DWORD dwWritten=0;
DWORD error=0;
 
BOOL fWaitingOnRead = 0;
char lpBuf[READ_BUF_SIZE]="";
char lpsendBuf[READ_BUF_SIZE] = "w";
DCB dcb={0};
COMMTIMEOUTS timeouts;
DWORD dwRes=0;
int stopFlag =0;
DWORD dwCommEvent;
DWORD dwStoredFlags;

OVERLAPPED osReader = {0};
OVERLAPPED osWrite = {0};
COMMPROP lpCommProp;


int _tmain(int argc, _TCHAR* argv[])
{
        
    hComm = CreateFile(L"COM3",  // CreateFile(L"COM3",
        GENERIC_READ | GENERIC_WRITE,
        0,
        0,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,//0,
        NULL);


    if (hComm == INVALID_HANDLE_VALUE)
        printf("error opening port; abort \n");
    else
        printf("ok opening port \n");
 
 
    if (!SetupComm(hComm, 1024, 0))
        printf("Error in SetupComm %d \n",GetLastError());
#if 1
    if (!GetCommProperties(hComm,&lpCommProp))
        printf("Error GetCommProperties.\n");
#endif
 
    //printf("dwCurrentTxQueue = %d \n",lpCommProp.dwMaxRxQueue);
    //printf("dwCurrentRxQueue = %d \n",lpCommProp.dwCurrentRxQueue);
 
 
    if (!GetCommState(hComm, &dcb))     // get current DCB
       // Error in GetCommState
        printf("Error in GetCommState \n");
    // Update DCB rate.
    dcb.BaudRate = CBR_115200;
    dcb.ByteSize = 8;
    dcb.StopBits = ONESTOPBIT;
    dcb.Parity = NOPARITY;
    // Set new state.
    if (!SetCommState(hComm, &dcb))
        //Error in SetCommState. Possibly a problem with the communications
        // port handle or a problem with the DCB structure itself.
        printf("Error in SetCommState \n");
 
 
    timeouts.ReadIntervalTimeout = 20;
    timeouts.ReadTotalTimeoutMultiplier = 1;
    timeouts.ReadTotalTimeoutConstant = 0;
    timeouts.WriteTotalTimeoutMultiplier = 1;
    timeouts.WriteTotalTimeoutConstant = 2000;
    if (!SetCommTimeouts(hComm, &timeouts))
        // Error setting time-outs.
        printf("Error setting time-outs.\n");
    /*
    dwStoredFlags = EV_BREAK | EV_CTS   | EV_DSR | EV_ERR | EV_RING |\
                EV_RLSD | EV_RXCHAR | EV_RXFLAG | EV_TXEMPTY ;
    if (!SetCommMask(hComm, dwStoredFlags))
   // error setting communications mask
   printf("Error SetCommMask.\n");
   */
 
 
    // Create the overlapped event. Must be closed before exiting
    // to avoid a handle leak.
    osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (osReader.hEvent == NULL)
       printf("CreateEvent (Reader Event)\n");
 
    osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (osWrite.hEvent == NULL)
       printf("CreateEvent (Writer Event)\n");
 
    while (!stopFlag) 
    {
        if (!fWaitingOnRead) {
            // Issue read operation.
            if (!ReadFile(hComm, lpBuf, READ_BUF_SIZE, &dwRead, &osReader))
            {
 
                error=GetLastError();
                //printf("GetLastError = %d \n",error);
                if (error != ERROR_IO_PENDING)     // read not delayed?
                   // Error in communications; report it.
                    {
                      if(error == ERROR_NOACCESS)
                        printf("ERROR_NOACCESS \n");
                    }
                else
                    fWaitingOnRead=TRUE;
 
 
            }
            else
            {
                // read completed immediately
            
                if(dwRead)
                    {
                        printf("immediately read data = %s ",lpBuf);
                        printf("immediately read data number = %d \n",dwRead);
                    }
                
            }
        }
 
        if (fWaitingOnRead) {
            dwRes = WaitForSingleObject(osReader.hEvent,READ_TIMEOUT);
            switch (dwRes)
            {
            case WAIT_TIMEOUT:
                // Operation isn't complete yet. fWaitingOnRead flag isn't
                // changed since I'll loop back around, and I don't want
                // to issue another read until the first one finishes.
                //
                // This is a good time to do some background work.
                printf("read data WAIT_TIMEOUT \n");
                break;
 
            case WAIT_OBJECT_0:
                if (!GetOverlappedResult(hComm, &osReader, &dwRead, FALSE))
                    // Error in communications; report it.
                        ;
                else
                    {
                        // Read completed successfully.
                        //printf("Read completed successfully \n");
                        if(dwRead)
                        {
                          printf("read data number = %d \n", dwRead);
                          printf("read data = %s \n",lpBuf);
                          
                          //if (!PurgeComm(hComm,PURGE_RXABORT))
                          //printf("PurgeComm error \n");
                        }
                    }
 
                //  Reset flag so that another opertion can be issued.
                fWaitingOnRead = FALSE;
                //ResetEvent(osReader.hEvent);
                break;
 
            default:
                // Error in the WaitForSingleObject; abort.
                // This indicates a problem with the OVERLAPPED structure's
                // event handle.
                break;
            }
        }

        //WRITE DATA
        if (dwRead)
        {
            if (!WriteFile(hComm, lpsendBuf, 1, NULL, &osWrite))
            {
                if (GetLastError() != ERROR_IO_PENDING) {
                    // WriteFile failed, but it isn't delayed. Report error and abort.
                    dwRead = 0;
                }
                else {
                    // Write is pending.
                    if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE))
                        ;
                    else
                    {// Write operation completed successfully.
                        printf("Write operation completed successfully \n");
                        dwRead = 0;
                    }
                }
            }
            else
            {// WriteFile completed immediately.
                //WriteFile(hComm,lpBuf, dwRead, NULL, &osWrite);
                printf("WriteFile completed immediately \n");
                dwRead = 0;
            }
        }
 
    }
 

    return 0;
}

串口通信--CSerialport类_atrouble的博客-CSDN博客_cserialport

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值