Скачиваний:
34
Добавлен:
15.09.2014
Размер:
2.29 Кб
Скачать
// com.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <stdio.h>
#include <conio.h>
#include <iostream>
#include <windows.h>

using namespace std;

const int sizeBuffer = 1200;

int main(){
     char port[4];
     char c;
   
	 cout << "COM port #1." << endl;
	 cout << "COM port #2." << endl;
	 cout << "Enter '1' or '2' to make a choice" << endl;
	 

	 do{
		c = _getch();
		if (c == '2'){
			strcpy(port,"COM2");
			break;
		}else if (c == '1'){
			strcpy(port,"COM3");
			break;
		}
	 }
	 while(1);
	 cout << endl;

     //Open port
     HANDLE handle; 
	 handle = CreateFileA(port, GENERIC_READ | GENERIC_WRITE, NULL, NULL, OPEN_EXISTING, 0, NULL); 
     if (handle){
		 cout << "Well, well, well..." << endl;
		 cout << port;
		 cout << " has opened successfully." << endl;
		 cout << "Enjoy my greatness." << endl << endl;
     }

     //Customize port
     SetupComm(handle, sizeBuffer, sizeBuffer); 

     DCB dcb; 
     GetCommState(handle, &dcb);

     dcb.ByteSize = 8;
     dcb.BaudRate = CBR_57600;
     dcb.Parity = NOPARITY;
     dcb.StopBits = ONESTOPBIT;
     SetCommState(handle, &dcb);

     COMMTIMEOUTS CommTimeOuts;
     CommTimeOuts.ReadIntervalTimeout= 10; 
     CommTimeOuts.ReadTotalTimeoutMultiplier = 1; 
     CommTimeOuts.ReadTotalTimeoutConstant = 100; 
     CommTimeOuts.WriteTotalTimeoutMultiplier = 0; 
     CommTimeOuts.WriteTotalTimeoutConstant = 0; 
     SetCommTimeouts(handle, &CommTimeOuts);

     //Purge port
     PurgeComm(handle, PURGE_RXCLEAR); 
     PurgeComm(handle, PURGE_TXCLEAR);

     DWORD numbytes;
     DWORD numbytes_ok;
     DWORD temp; 
     COMSTAT ComState; 
     char buf_in[2]; 
     char buf_out[2] = "";
     
     while (1){
          ClearCommError(handle, &temp, &ComState); 
		  if (!temp){
               ReadFile(handle, buf_in, 1, &numbytes_ok, 0);
		  }
		  if (numbytes_ok > 0){
               cout << buf_in[0];
		  }
          if (_kbhit()){
               buf_out[0] = _getch();
			   cout << buf_out[0];

               ClearCommError(handle, &temp, &ComState); 
			   if (!temp){
                    WriteFile(handle, buf_out, 1, &numbytes_ok, 0);
				}
          }
     }
}