PDA

View Full Version : [Question(s)] Cannot figure out how to write to the serial port in C++



Superlaxstar112
07-23-2008, 04:26 PM
I've spent 2 days trying to figure out how to write to the serial port in C++. Here is what I've been trying. I'm compiling in Dev-C++ on windows vista.

CODE:

#include <cstdlib>
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <tchar.h>


using namespace std;

int main(int argc, char *argv[])
{
HANDLE hComm;
char DataBuffer[] = "#31 P1500 T1000 \r\n";
DWORD dwBytesToWrite = (DWORD)strlen(DataBuffer);
DWORD dwBytesWritten = 0;
hComm=CreateFile( "COM1",
GENERIC_READ | GENERIC_WRITE, //bidirectional
0,
NULL, //no security
OPEN_EXISTING, //this must be set; the ports are already created
FILE_ATTRIBUTE_NORMAL, // maybe with | FILE_FLAG_OVERLAPPED
NULL );
if (hComm == INVALID_HANDLE_VALUE)
{
printf("Could not open COM1 \n", GetLastError());
return 0;
}
else
{
printf("COM1 Succesfully opened \n");
}
DCB dcb;

FillMemory(&dcb, sizeof(dcb), 0);
if (!GetCommState(hComm, &dcb)) // get current DCB
// Error in GetCommState
return FALSE;

// Update DCB rate.
dcb.BaudRate = CBR_115200 ;

// Set new state.
if (!SetCommState(hComm, &dcb))
printf("Error in SetCommState. Possibly a problem with the communications port handle or a problem with the DCB structure itself. \n");

COMMTIMEOUTS timeouts;

timeouts.ReadIntervalTimeout = 20;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.ReadTotalTimeoutConstant = 100;
timeouts.WriteTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 100;
if (!SetCommTimeouts(hComm, &timeouts))

//THIS IS WHERE I TRY TO WRITE TO hComm or "COM1" as its supposed to be
WriteFile(hComm, // open file handle
DataBuffer + dwBytesWritten, // start of data to write
dwBytesToWrite - dwBytesWritten, // number of bytes to write
&dwBytesWritten, // number of bytes that were written
NULL); // no overlapped structure WriteFile(hComm,x,100);

return 0;
}


EndCode

I don't get any errors, but it won't write to my SSC-32 cause the light stays on which means it is not recieving. :-(

Basically what I want for now (So I can teach myself based it) is some code that allows me to input a string and then send that string to COM1. I really have very little experience with C++ so this is all very confusing to me. Please help :-D

Adrenalynn
07-23-2008, 04:47 PM
Is your SSC32 set for 115kbaud, and you're sure your com port can handle it, right?

Superlaxstar112
07-23-2008, 04:50 PM
yes and yes. I've got the SSC-32 working with my realbasic program and the lynxmotion terminal. I've made sure the comport is not in use when running this program and what not.

Adrenalynn
07-23-2008, 04:57 PM
Looks like the code sample you found is deprecated. I don't believe you can write to the com port in Vista (or XP) directly that way anymore.

Look-up the MSCOMM Control.

Superlaxstar112
07-23-2008, 05:02 PM
sweet. Ill look into that later tonight. Thanks!