控制台下WinApi同步方式实现的串口发送数据

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

#include "stdafx.h"
#include "windows.h"
//using std namespace ;


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

	int rc =0;
	HANDLE hComm=INVALID_HANDLE_VALUE;
	COMMTIMEOUTS commtimeouts;
//	const unsigned short * filename="COM1";

	hComm = CreateFile("COM1", GENERIC_WRITE|GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);//倒数第2个参数控制 是否使用重叠IO,这里不使用。
//	hComm = CreateFile("COM1",						// communication port string (COMX)
//					     GENERIC_READ | GENERIC_WRITE,	// read/write types
//					     0,								// comm devices must be opened with exclusive access
//					     NULL,							// no security attributes
//					     OPEN_EXISTING,					// comm devices must use OPEN_EXISTING
//					     FILE_FLAG_OVERLAPPED,			// Async I/O 这个是重叠IO,就是异步方式
//					     NULL);


	if (hComm == INVALID_HANDLE_VALUE){
		rc = GetLastError();
//		ELOG2("InitUart::CreateFile('%S') FAILED with err = %d \n\r", filename,rc);
		printf("Open Com1 Failed with %d\n",rc);
		return false;
	}else{
		printf("Open success\n");//
//		system("PAUSE");
	};


	///ÅäÖô®¿Ú
    DCB  PortDCB;    
    PortDCB.DCBlength = sizeof(DCB); 
    // ĬÈÏ´®¿Ú²ÎÊý
    GetCommState(hComm, &PortDCB);
    PortDCB.BaudRate = 9600; // baud
    PortDCB.ByteSize = 8;     // Number of bits/byte, 4-8 
    PortDCB.Parity = NOPARITY; 
    PortDCB.StopBits = ONESTOPBIT;  
    if(! SetCommState(hComm, &PortDCB))
    {
		printf("CUartReader::Init -- SetCommState FAILED\n\r");
        return false;
    }

	char * pHelloworld="HelloWorld\r\n";
	unsigned char Helloworld[32];
	memcpy(Helloworld,pHelloworld,strlen(pHelloworld));

	unsigned long BytesSent;
	int result;


//	OpenFile(hComm);

//	result=WriteFile(		hComm,							// Handle to COMM Port
//							Helloworld,					// Pointer to message buffer in calling finction
//							5,	// Length of message to send
//							&BytesSent,			// Where to store the number of bytes sent
//							NULL
//							);				// Overlapped structure)

	DWORD len;
char  data[1024];
memset(data,0,sizeof(data));
strcpy(data,"data to send ");  
result=WriteFile(hComm ,data,strlen(data),&len,0); 
	
	if(result){
		printf("Send Over\n");
	}else{
		rc = GetLastError();
		printf("Send Failed with %d\n",rc);
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值