:::: MENU ::::

Windows com port — C++

Код под катом.

#include <windows.h>
#include <iostream>
using namespace std;

typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;

// typedef void *HANDLE; указатель на пустую структуру
HANDLE hPort; // структура для управления com-port (h_port - адрес)
LPCTSTR sPortName = L"COM1";
DCB dcbSerialParams = {0};

void WriteComPort(void);
void ReadComPort(void);

int main(void) {
  std::cout << "test" << '\n';

  WriteComPort();
  ReadComPort();

  return 0;
}

void WriteComPort(void) {
  char data[] = "Hello World";
  DWORD dwSize = sizeof(data);
  DWORD dwBytesWritten;

  hPort = CreateFile(sPortName, GENERIC_READ | GENERIC_WRITE, 0, 0,
  OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

  if(hPort == INVALID_HANDLE_VALUE) {
    if(GetLastError() == ERROR_FILE_NOT_FOUND) {
      cout << "serial port does not exist \n";
    } else {
      cout << "other error \n";
    }
  }

  dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
  if(!GetCommState(hPort, &dcbSerialParams)) {
    cout << "getting state error\n";
  }
  dcbSerialParams.BaudRate = CBR_19200;
  dcbSerialParams.ByteSize = 8;
  dcbSerialParams.StopBits = ONESTOPBIT;
  dcbSerialParams.Parity = NOPARITY;

  if(!SetCommState(hPort, &dcbSerialParams)) {
    cout << "error setting serial port state \n"; 
  } 
  WriteFile(hPort, data, dwSize,       &dwBytesWritten, NULL); 
} 

void ReadComPort(void) { 
  DWORD iSize; 
  char sReceivedChar; 
  while(1) { 
    ReadFile(hPort, &sReceivedChar, 1, &iSize, 0); 
    if(iSize > 0) {
      cout << sReceivedChar;
    }
  }
}