Skip to content

Instantly share code, notes, and snippets.

@uilianries
Created January 22, 2018 00:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uilianries/2a5ee873f1064efb192a6f4ea016a3c0 to your computer and use it in GitHub Desktop.
Save uilianries/2a5ee873f1064efb192a6f4ea016a3c0 to your computer and use it in GitHub Desktop.
Read Serial port on Windows
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
const char reboot = 'R';
const char ack = 6;
HANDLE hSerial = NULL;
DCB dcbSerialParams = {0};
COMMTIMEOUTS timeouts = {0};
DWORD bytes_written = 0;
DWORD bytes_read = 0;
BOOL status = FALSE;
char buffer = 0;
fprintf(stderr, "Opening serial port...");
hSerial = CreateFile("\\\\.\\COM1", GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hSerial == INVALID_HANDLE_VALUE) {
fprintf(stderr, "Error: Could not open serial port.\n");
return EXIT_FAILURE;
} else {
fprintf(stderr, "OK\n");
}
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
if (GetCommState(hSerial, &dcbSerialParams) == 0) {
fprintf(stderr, "Error getting device state\n");
CloseHandle(hSerial);
return EXIT_FAILURE;
}
dcbSerialParams.BaudRate = CBR_115200;
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity = NOPARITY;
if(SetCommState(hSerial, &dcbSerialParams) == 0) {
fprintf(stderr, "Error setting device parameters\n");
CloseHandle(hSerial);
return EXIT_FAILURE;
}
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
if(SetCommTimeouts(hSerial, &timeouts) == 0) {
fprintf(stderr, "Error setting timeouts\n");
CloseHandle(hSerial);
return EXIT_FAILURE;
}
do {
status = ReadFile(hSerial, &buffer, sizeof(buffer), &bytes_read, NULL);
if (!status) {
fprintf(stderr, "Error: Could not read serial port.\n");
CloseHandle(hSerial);
return EXIT_FAILURE;
}
} while (read_buffer != reboot);
fprintf(stderr, "Sending ACK...");
if(!WriteFile(hSerial, &ack, 1, &bytes_written, NULL)) {
fprintf(stderr, "Error: Could not send ACK.\n");
CloseHandle(hSerial);
return EXIT_FAILURE;
}
fprintf(stderr, "Closing serial port...");
if (CloseHandle(hSerial) == 0) {
fprintf(stderr, "Error: Could not close serial port.\n");
return EXIT_FAILURE;
}
fprintf(stderr, "OK\n");
status = ExitWindowsEx(EWX_REBOOT, 0);
if (!status) {
fprintf(stderr, "Error: Could not reboot the system.\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
@edsonrequena
Copy link

Very useful, I modified by eliminating the loop. The variable read_buffer was not declared.It served me perfect for reading the weight of a truck scale. Thank you very much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment