//* sample C program that access a serial port com3 under Win32 *

#include<windows.h> #include<stdio.h> #include<string.h> int main() { // declare a variable that describes com device parameters DCB dcbCOM; int OK; // declare the structure that describes a file or a device HANDLE hCOM = CreateFile( TEXT("COM3"), // file or device name GENERIC_READ|GENERIC_WRITE, // access mode: can read and/or write 0, // sharing mode NULL, // security attributes OPEN_EXISTING, // whether to create a new file 0, // file attributes to set, NULL); // template file handle if (hCOM==INVALID_HANDLE_VALUE) { fprintf(stderr, "ERROR: cannot create COM device handle\n"); return(0); } // initialize COM port // get the current COM device parameters OK=GetCommState(hCOM, &dcbCOM); if (OK) { // modify the parameters to suit our needs dcbCOM.BaudRate = 9600; dcbCOM.ByteSize = 8; dcbCOM.Parity = NOPARITY; dcbCOM.StopBits = ONESTOPBIT; // set the COM device parameters according to that variable OK=SetCommState(hCOM, &dcbCOM); if (OK) { // set the internal input and output buffer OK=SetupComm(hCOM, 2048, 1024); if (OK) { // setup area to keep data char buffer[1024]; DWORD size=0; DWORD done; for (;;) { fgets(buffer, sizeof(buffer), stdin); if (strcmp(buffer,".\n")==0) break; buffer[strlen(buffer)]=0; strcat(buffer, "\r\n"); /* */ // SAMPLE WRITE // write some data to the file or device OK=WriteFile(hCOM, // file or device handle &buffer, // address of buffer with data to send strlen(buffer), // how many bytes should be sent &done, // how many bytes were actually written NULL); // NULL or Overlapped structure if used if (!OK) fprintf(stderr, "ERROR: cannot write to COM port\n"); // make sure that everything from internal buffer is sent OK=FlushFileBuffers(hCOM); if (!OK) fprintf(stderr, "ERROR: cannot flush COM port\n"); // they may be actually sent after flushing // because of the non-full buffer of 1024 bytes // buffers speed your program in general though fprintf(stdout, "%d bytes sent\n", done); /* end of comment */ Sleep(500); // allow for processing by the embedded device /* */ // SAMPLE READ - !!this will return whatevedr is in the buffer as long as there is at least one byte, otherwise, it waits!! ReadFile(hCOM, // file or device handle &buffer, // address of buffer to put received data strlen(buffer), // how many bytes are expected &done, // how many bytes were actually received NULL); // must be NULL, not supported buffer[done]=0; // Note: last byte in [done-1] fprintf(stdout, "%s\n", buffer); /* end of comment */ } } else fprintf(stderr, "ERROR: cannot set buffer size for COM port\n"); } else fprintf(stderr, "ERROR: cannot initialize COM port parameters\n"); } else fprintf(stderr, "ERROR: cannot create COM port parameters record \n"); // release device back to the Operating System CloseHandle(hCOM); return(0); }