简体   繁体   中英

Sending/Receiving serial port (COM) data with C++ Handle

I need some help with understanding how to use ReadFile and WriteFile in C++ while using method shown in this guide:

https://www.delftstack.com/howto/cpp/cpp-serial-communication/

My question is, how to use these two functions to send or receive anything? I don't know how to call them properly

I start with Handle:

// Open serial port
HANDLE serialHandle;

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

Next I did some basic settings like setting baud, bytesize etc. I will skip that. And here we come to my problem. I tried to send some data and receive it (my cable output and input pins are connected). Problem is I don't know how to call ReadFile and WriteFile properly. Here's how I tried to do it:

    char sBuff[n + 1] = { 0 };
    DWORD send = 0;
    cout << "Sent: " << WriteFile(serialHandle, sBuff, n, &send, NULL) << endl;

    DWORD dwRead = 0;
    cout << "Received: " << ReadFile(serialHandle, sBuff, n, &dwRead, NULL) << endl;

    CloseHandle(serialHandle);
}
}

It's just some attempt to guess the correct method. Any example with short explanation will be much appreciated.

Edit: removed useless chunk of code, hope my question is more understandable now

It's all about the handle "serialHandle" being set to the com3 port instead of the file. The first question, in the layer where you write code, you should not worry about the synchronization or interference of sending and receiving. The serial port handler coordinates it. Second question, your data is sent as a string of characters that are ASCII. You have to write a function called extract(reciedData) in receiving and place your variables in integer or double or string. In fact, you need a protocol, for example, NMEA. please search aboat NMEA protocol in google

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