简体   繁体   中英

C++ Reading from a serial port with CreateFile

I am writing a C++ program to read from a serial port (in my case COM6). To open the COM-Port. I always found this code in the internet:

HANDLE serialHandle;

serialHandle = CreateFile(L"COM6", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

My Problem is that I get the following errors:

  • 'HANDLE': identifier not found
  • 'CreateFile': identifier not found
  • 'GENERIC_READ': undeclared identifier
  • 'INVALID_HANDLE_VALUE': undeclared identifier
  • ...

My code:

#include <windows.h>
#include "stdafx.h"
#include <iostream>
#include <string>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
using namespace std;


int main()
{
    /*int comPortNmr = 6, speed = 115200;
    cout << "Serial Line: > ";
    cin >> comPortNmr;
    cout << endl;
    cout << "Speed: > ";
    cin >> speed;
    cout << endl; */

    HANDLE serialHandle;
    // Open serial port
    serialHandle = CreateFile(L"COM6", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

    if (serialHandle == INVALID_HANDLE_VALUE)
    {
        cout << "Error." << endl;
    }
    else
    {
        cout << "Opend." << endl;
    }

    return 0;
}

What am I doing wrong?

If you install VS'17 without adjusting the settings, the Windows SDK will NOT install.

Please re-check your VS'17 installation and install the appropiate Windows SDK.

If you are using precompiled headers, anything up to and including the line #include "stdafx.h" is supposed to already be part of the precompiled header. And so will be skipped by the compiler.

So make sure that #include "stdafx.h" always is the first #include .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM