Advertisement
Guest User

WinAPI COM Port Communication

a guest
Jan 15th, 2013
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. #include "windows.h"
  4.  
  5. using namespace std;
  6.  
  7. int main() {
  8.     //create handle to COM-Port
  9.     const char *port = "COM3";
  10.     HANDLE handle = CreateFile(port, GENERIC_ALL, 0, NULL, OPEN_EXISTING, 0, NULL);
  11.     if (handle == INVALID_HANDLE_VALUE) {
  12.         return -1;
  13.     }
  14.  
  15.     //set baud rate to 9600
  16.     DCB configuration;
  17.     DWORD baudrate = CBR_9600;
  18.     if (!GetCommState(handle, &configuration)) {
  19.         return -1;
  20.     }
  21.     configuration.BaudRate = baudrate;
  22.     if (!SetCommState(handle, &configuration)) {
  23.         return -1;
  24.     }
  25.  
  26.     //read as long as data is available
  27.     char buffer;
  28.     DWORD bytesRead = 0;
  29.     DWORD bytesWritten = 0;
  30.     while (ReadFile(handle, &buffer, 1, &bytesRead, 0)) {
  31.         cout << buffer;
  32.         //write every character back to the device
  33.         if (!WriteFile(handle, &buffer, 1, &bytesWritten, 0)) {
  34.             return -1;
  35.         }
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement