Скачиваний:
34
Добавлен:
15.09.2014
Размер:
2.53 Кб
Скачать
// comport.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 << "1 - COM4 port." << endl;
	 cout << "2 - COM5 port." << endl;
	 

	 do{
		c = _getch();
		if (c == '1'){
			strcpy(port,"COM4");
			break;
		}else if (c == '2'){
			strcpy(port,"COM5");
			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;
		 for (int i = 0; i < 4; i++){
               cout << port[i];
		 }
          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, byte_num = 1; 
     COMSTAT ComState; 
     char buf_in[2]; 
     char buf_out[2] = "";
     
     while (1){
          ClearCommError(handle, &temp, &ComState); 
		  if (!temp)
		  {
               ReadFile(handle, buf_in, byte_num, &numbytes_ok, 0);
			   byte_num = 1;
		  }
		  if (numbytes_ok > 0)
		  {
			  cout << buf_in[0];
			  if(numbytes_ok == 2)
			  cout << buf_in[1];
		  }
          if (_kbhit()){
               buf_out[0] = _getch();
			   cout << buf_out[0];
			   if(buf_out[0] == 13)
			   {
				   buf_out[1] = 10;
				   byte_num = 2;
				   cout<<buf_out[1];
			   }
               ClearCommError(handle, &temp, &ComState); 
			   if (!temp){
                    WriteFile(handle, buf_out, byte_num, &numbytes_ok, 0);
				}
          }
     }
}