Добавил:
Mymnan
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:Сборка Часть1 / avmis_labs / неразобрано / 501 / Лаб_СОМ / Кухта В.В / com-port / com-port / com-port
.cpp#include "stdafx.h"
#include <stdio.h>
#include <conio.h>
#include <iostream>
#include <windows.h>
using namespace std;
const int SizeBuffer = 1200;
int main()
{
wchar_t port[] = L"COM1";
char c;
cout << "[1] COM1" << endl << "[2] COM2" << endl;
c = _getch();
if (c == '2')
{
port[3] = '2';
}
//открытие порта
HANDLE handle;
handle = CreateFile(port, GENERIC_READ | GENERIC_WRITE, NULL, NULL, OPEN_EXISTING, 0, NULL);
if (handle)
{
for (int i = 0; i < 4; i++)
{
wcout << port[i];
}
cout << " opened" << endl;
}
//настройка порта
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);
//чистим порт
PurgeComm(handle, PURGE_RXCLEAR);
PurgeComm(handle, PURGE_TXCLEAR);
//
DWORD numbytes, numbytes_ok, temp;
COMSTAT ComState;
char buf_in[2];
char buf_out[] = "\0";
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();
printf(&buf_out[0]);
ClearCommError(handle, &temp, &ComState);
if (!temp)
{
WriteFile(handle, buf_out, 1, &numbytes_ok, 0);
}
}
}
}