Bare Bones Windows Serial Program

Thread Starter

Brownout

Joined Jan 10, 2012
2,390
I want an absolute bare bones windows serial program to use as a base to build my application. I found this code (shamelessly copied from here: http://forums.codeguru.com/showthread.php?442634-Serial-port-program-in-c-language It looks like what I need to get started. I plan to compile it using VCC 2005 and run it on a XP machine. Does anyone see any potential issues?:

NOTE: I;m working to get this code to display better

Rich (BB code):
#include <windows.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
DCB dcb;
HANDLE hCom;
BOOL fSuccess;
char *pcCommPort = "COM2";
 
hCom = CreateFile( pcCommPort,
  GENERIC_READ | GENERIC_WRITE,
  0, // must be opened with exclusive-access
  NULL, // no security attributes
  OPEN_EXISTING, // must use OPEN_EXISTING
  0, // not overlapped I/O
  NULL // hTemplate must be NULL for comm devices
);
if (hCom == INVALID_HANDLE_VALUE) 
  {
  // Handle the error.
  printf ("CreateFile failed with error %d.\n", GetLastError());
  return (1);
}
 // Build on the current configuration, and skip setting the size
 // of the input and output buffers with SetupComm.
 fSuccess = GetCommState(hCom, &dcb);
 if (!fSuccess) 
   {
   // Handle the error.
   printf ("GetCommState failed with error %d.\n", GetLastError());
   return (2);
 }
 // Fill in DCB: 57,600 bps, 8 data bits, no parity, and 1 stop bit.
 dcb.BaudRate = CBR_57600; // set the baud rate
 dcb.ByteSize = 8; // data size, xmit, and rcv
 dcb.Parity = NOPARITY; // no parity bit
 dcb.StopBits = ONESTOPBIT; // one stop bit
 fSuccess = SetCommState(hCom, &dcb);
 if (!fSuccess) 
 {
   // Handle the error.
   printf ("SetCommState failed with error %d.\n", GetLastError());
   return (3);
 }
 printf ("Serial port %s successfully reconfigured.\n", pcCommPort);
 return (0);
}
 
Last edited:

tshuck

Joined Oct 18, 2012
3,534
It looks suspiciously similar to the "Configuring a Communications Resource" article from MSDN, which means it has a little more credibility than most internet-generated code. I haven't used this method, but it seems okay.

The only thing I would point out, and this may, or may not, seem obvious, make sure you set the correct COM port when you compile.
 

Thread Starter

Brownout

Joined Jan 10, 2012
2,390
I got this code to work, but only after dynking around with it all day. I had to make a change to my VC++ configuration to use Multi Byte Character Set for the CreateFile function to work. After exhausting google looking for the answer, I posted on Jan Alexson's Lake View Project forum, and she provided links that got me going :)
 
Top