Skip to content

Instantly share code, notes, and snippets.

@Lif3line
Last active August 29, 2015 14:04
Show Gist options
  • Save Lif3line/2feb9cd482fe51278ed6 to your computer and use it in GitHub Desktop.
Save Lif3line/2feb9cd482fe51278ed6 to your computer and use it in GitHub Desktop.
C code to open, configure and sit listening to a serial port under Windows. Simply edit the port and its parameters (defaults to COM6, 9600 baud, 8 data bits, no parity checking, no flow control and a single stop bit). NOTE if your COM port is already set up you can remove lines 21-42.
#include <windows.h>
#include <stdio.h>
#include <conio.h>
int main(void) {
char port[] = "COM6", buffer[100];
int i;
DCB dcb;
HANDLE hCOM;
DWORD bytesRead;
hCOM = CreateFile(port,
GENERIC_READ | GENERIC_WRITE,
0, // REQUIRED
NULL, // Default security
OPEN_EXISTING, // REQUIRED
0, // Non-overlapped I/O
NULL // REQUIRED
);
if (hCOM == INVALID_HANDLE_VALUE) {
printf ("CreateFile error, code: %d.\n", GetLastError());
return -1;
}
if (!GetCommState(hCOM, &dcb)) {
printf ("GetCommState error, code: %d.\n", GetLastError());
return -2;
}
/* Port parameters */
dcb.BaudRate = CBR_9600;
dcb.ByteSize = DATABITS_8; // Number of data bits
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
dcb.fRtsControl = 0; // Flow control
if (!SetCommState(hCOM, &dcb)) {
printf("SetCommState error, code: %d.\n", GetLastError());
return -3;
}
printf("Serial Port %s configured.\n", port);
printf("Reading will begin in a moment (press any key to finish)..\n");
sleep(3000);
/* Reading loop */
while(1) {
if (ReadFile(hCOM, &buffer, sizeof(buffer), &bytesRead, NULL)) {
for(i = 0; i < bytesRead; i++) {
printf("%c", buffer[i]);
}
} else {
printf("Error reading from serial port, code: %d.\n", GetLastError());
CloseHandle(hCOM);
return -4;
}
if (kbhit()) { // Exit on any keypress
break;
}
}
CloseHandle(hCOM); // Clean up
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment