栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Win32 串口通讯简单示例程序

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Win32 串口通讯简单示例程序

重叠I/O操作

回传接收到的数据

#include 
#include 
#include "comtest.h"

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

HANDLE hComm;
OVERLAPPED osReader = {0};
OVERLAPPED osWrite = {0};
char* gszPort ="COM1";
COMMPROP lpCommProp;


int main(int argc,char *argv[])
{


	DWORD dwRead=0;
	DWORD dwWritten=0;
	DWORD error=0;

	BOOL fWaitingonRead = 0;
	char lpBuf[READ_BUF_SIZE]="";
    DCB dcb={0};
	COMMTIMEOUTS timeouts;
	DWORD dwRes=0;
    int stopFlag =0;
	DWORD dwCommEvent;
    DWORD dwStoredFlags;



	hComm = CreateFile(gszPort,
		GENERIC_READ | GENERIC_WRITE,
		0,
		0,
		OPEN_EXISTING,
		FILE_FLAG_OVERLAPPED,
		//FILE_ATTRIBUTE_NORMAL,
		0);
	if (hComm == INVALID_HANDLE_VALUE)
		printf("error opening port; abort n");


    if (!SetupComm(hComm, 1024, 0))
		printf("Error in SetupComm %d n",GetLastError());
    if (!GetCommProperties(hComm,&lpCommProp))
	printf("Error GetCommProperties.n");

    //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_9600;
	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");
    


	// 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 (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 = %s n",lpBuf);
                          printf("read data number = %d n",dwRead);
				          //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,lpBuf, dwRead, 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;

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/630652.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号