// 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);
}
}
控制台下WinApi同步方式实现的串口发送数据
最新推荐文章于 2024-02-01 12:08:30 发布