Skip to content

Instantly share code, notes, and snippets.

@upsilun
Created July 10, 2024 00:32
Show Gist options
  • Save upsilun/910eb9a5e138f08bb89f88cf49e5f893 to your computer and use it in GitHub Desktop.
Save upsilun/910eb9a5e138f08bb89f88cf49e5f893 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <windows.h>
void sendSerialData(const wchar_t* portName, const char* data) {
HANDLE hSerial;
DCB dcbSerialParams = { 0 };
COMMTIMEOUTS timeouts = { 0 };
// Open the serial port
hSerial = CreateFileW(portName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hSerial == INVALID_HANDLE_VALUE) {
DWORD dwError = GetLastError();
if (dwError == ERROR_FILE_NOT_FOUND) {
std::cerr << "Serial port does not exist." << std::endl;
}
else {
std::cerr << "Error opening serial port. Error code: " << dwError << std::endl;
}
return;
}
// Set device parameters
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
if (!GetCommState(hSerial, &dcbSerialParams)) {
std::cerr << "Error getting device state." << std::endl;
CloseHandle(hSerial);
return;
}
dcbSerialParams.BaudRate = CBR_9600; // Example baud rate
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity = NOPARITY;
if (!SetCommState(hSerial, &dcbSerialParams)) {
std::cerr << "Error setting device parameters." << std::endl;
CloseHandle(hSerial);
return;
}
// Set timeouts
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
if (!SetCommTimeouts(hSerial, &timeouts)) {
std::cerr << "Error setting timeouts." << std::endl;
CloseHandle(hSerial);
return;
}
// Write data to serial port
DWORD bytesWritten;
if (!WriteFile(hSerial, data, strlen(data), &bytesWritten, NULL)) {
std::cerr << "Error writing to serial port." << std::endl;
}
else {
std::cout << "Data sent successfully." << std::endl;
}
// Close serial port
CloseHandle(hSerial);
}
int main() {
const wchar_t* portName = L"\\\\.\\COM3"; // COM port name for COM3
const char* data = "0"; // Data to send
sendSerialData(portName, data);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment