C++ 使用 CreateFile 从串行端口读取

C++ Reading from a serial port with CreateFile

我正在编写一个 C++ 程序来从串行端口(在我的例子中是 COM6)读取数据。打开 COM 端口。我总是在互联网上找到这段代码:

HANDLE serialHandle;

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

我的问题是出现以下错误:

我的代码:

#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;
}

我做错了什么?

如果您在不调整设置的情况下安装 VS'17,Windows SDK 将不会安装。

请重新检查您的 VS'17 安装并安装适当的 Windows SDK。

如果您使用的是预编译头文件,则 #include "stdafx.h" 行之前的任何内容都应该是预编译头文件的一部分。因此将被编译器跳过。

因此请确保 #include "stdafx.h" 始终是 第一个 #include