#include <Windows.h>
#include <tchar.h>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <cstring>
using namespace std;
HANDLE OpenDevice(TCHAR*);
void PrintCommState(DCB dcb);
int _tmain(int argc, TCHAR *argv[])
{
TCHAR *pComName = TEXT("COM1");
HANDLE device = OpenDevice(pComName);
DCB dcb;
if (device == INVALID_HANDLE_VALUE)
{
cout << "Error Creating File: " << GetLastError() << endl;
return 1;
}
SecureZeroMemory(&dcb, sizeof(DCB));
dcb.DCBlength = sizeof(DCB);
if ( !GetCommState(device, &dcb) )
{
cout << "Error Getting CommState " << endl;
return 1;
}
PrintCommState(dcb);
// set your baud rate and stuff
dcb.BaudRate = CBR_9600;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
if (!SetCommState(device, &dcb) )
{
cout << "Can't Set CommState!" << endl;
return 1;
}
if ( !GetCommState(device, &dcb) )
{
cout << "Error Getting CommState " << endl;
return 1;
}
PrintCommState(dcb);
cout << "Listening on CommDevice " << endl;
UINT8 bufferS[2];
UINT8 buffer[7];
UINT8 x0=0,x1=0,y0=0,y1=0,z0=0,z1=0;
UINT16 x=0, y=0, z=0;
DWORD i=0,bytesReturned = 0;
stringstream ss;
string temp;
while (1)
{
ReadFile(device, &bufferS, 1, &bytesReturned, NULL);
if(bufferS[0]==0x73){
printf("it found the s string\n");
break;
}
}
i=0;
while (ReadFile(device, &bufferS, 1, &bytesReturned, NULL) > 0)
{
if(bytesReturned==1){
buffer[i]=bufferS[0];
cout <<bytesReturned;
printf(" %6d ",buffer[i]);
i++;
}
if(i==6){
x=(buffer[1]<<8)| buffer[0];
y=(buffer[3]<<8)| buffer[2];
z=(buffer[5]<<8)| buffer[4];
printf("\n%6d %6d %6d\n",x,y,z);
i=0;
}
//cout << hex << temp;
}
cout << endl;
cout << "Device is Gone" << endl;
system("pause");
return 0;
}
HANDLE OpenDevice(TCHAR* t)
{
return CreateFile(t, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
}
void PrintCommState(DCB dcb)
{ _tprintf( TEXT("\nBaudRate: %d, ByteSize: %d, Parity: %d, StopBits: %d\n"), dcb.BaudRate, dcb.ByteSize, dcb.Parity, dcb.ByteSize); }