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 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
.