// comconsole.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string>
#include <windows.h>
void set_up_serial_port(HANDLE h, long baud);
int main(int argc, char* argv[])
{ char str[100]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
char str1[100]={'0','0','0','0',0,0,0,0,0,0,0,0,0,0,0,0,0};
char* pChar=&str[0];
DWORD nNumberOfBytesToRead=100;
DWORD wCount;//读取的字节数
LPDWORD lpEvtMask=NULL;
LPOVERLAPPED lpOverlapped=NULL;
HANDLE hCom;
DWORD dwError;
hCom = CreateFile("COM4", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hCom == (HANDLE)0xFFFFFFFF)
{
dwError = GetLastError();
MessageBox(NULL, "dwError", NULL, MB_OK);
}
set_up_serial_port(hCom, 9600);
if(FALSE==ReadFile(hCom,str, nNumberOfBytesToRead, &wCount,0))
{
dwError = GetLastError();
printf("%d",dwError);
MessageBox(NULL, "dwError", NULL, MB_OK);
}
for(int i=0; i<wCount; i++)
{
printf("%s/n",str);
}
printf("Hello World!/n");
CloseHandle(hCom);
return 0;
}
void set_up_serial_port(HANDLE h, long baud)
{
DCB properties; /* Properties of serial port */
/* Get the properties */
GetCommState(h, &properties);
/* Set the baud rate */
switch(baud)
{
case 1200:
properties.BaudRate = CBR_1200;
break;
case 2400:
properties.BaudRate = CBR_2400;
break;
case 4800:
properties.BaudRate = CBR_4800;
break;
case 9600:
properties.BaudRate = CBR_9600;
break;
case 14400:
properties.BaudRate = CBR_14400;
break;
case 19200:
properties.BaudRate = CBR_19200;
break;
case 38400:
properties.BaudRate = CBR_38400;
break;
default:
fprintf(stderr, "Invalid baud rate: %ld/n", baud);
exit(0);
break;
}
/* Set the other properties */
properties.Parity = NOPARITY;
properties.ByteSize = 8;
properties.StopBits = ONESTOPBIT;
SetCommState(h, &properties);
return;
}