Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

help with serial port programming

Status
Not open for further replies.

ShawnCoutts

Programmer
Jul 4, 2006
74
CA
Hey guys

Ive been recently assigned a new task that requires me to be able to open, read, and write to a serial port. Ive been googling this for about 2 hours now, and as of yet have come up with nothing. I am using turbo C++ explorer, as my IDE.
Supposedly serial IO is just like File IO, but thats of no use to me, until I can open the serial port. Has anyone the knowledge of how to do this?

Shawn
 
I have done that. It's as simple as opening a file with the name "COM1" (or "COM2"...).

char Text[10];
// Check out COM1 - COM8 if they are available
for(int Counter = 1;Counter <= 8;Counter++)
{
sprintf(Text,"COM%u",Counter);
Handle = CreateFile(Text,GENERIC_READ | GENERIC_WRITE,0,0,OPEN_EXISTING,0,0);
if(Handle != INVALID_HANDLE_VALUE)
{
COMM_Select->Items->Add(Text); // Into the selector box
PurgeComm(Comm_Handle,PURGE_RXABORT); // Flush everything
CloseHandle(Handle); // Done, thank you
Available++; // The number of availables
}
else
{
if(GetLastError() == 5) // Existing but used by other
{
COMM_Select->Items->Add(Text);
Available++;
}
}
}


Totte
Keep making it perfect and it will end up broken.
 
thanks a lot. This is very helpful and should allow me to start working on my project now.

Shawn
 
Hi

I wrote an application to read / write data from a handheld terminal that communicated via RS232 port. My code is now very specialized within the app but essentially my starting block was this :

void __fastcall TForm1::Button1Click(TObject *Sender)
{
HANDLE hCom = CreateFile("COM1",
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL );

if(hCom)
{

DCB dcb;
ZeroMemory(&dcb, sizeof(dcb));
dcb.DCBlength = sizeof(dcb);

dcb.BaudRate = 57600;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY; // NOPARITY and friends are
dcb.StopBits = ONESTOPBIT; // #defined in windows.h

// Set the port properties and write the string out the port.
if(SetCommState(hCom,&dcb))
{
DWORD ByteCount;
const char *msg = "Hello world!";
WriteFile(hCom,msg, strlen(msg),&ByteCount,NULL);
}
CloseHandle(hCom);
}
}


Again you need to use threads to do the actual reading and writing to the port.



Hope this helps!

Regards

BuilderSpec
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top