Hi,

I am writing a simple program to read and write a serial port. I only have access to one serial port on my pc so I am using a HugePine RS-232 to USB convertor. The driver is installed and windows recognizes it is attached. My question is what comm port is the USB and can I treat it as if it was a second serial port on my PC. Thanks!!

Dave

I think I solved my first issue but the following code does not work. It seems to write (though I have no proof), but just sits at the readfile (doesnt fail, just sits). Any suggestions on why this may be?

// Testrs232.cpp : Defines the entry point for the console application.
//


#include "stdafx.h"


DCB    dcb;
HANDLE myCom;


BOOL  InitializeDevice();
BOOL  SetupPort(int BaudRate);
char *Recieve();
void  Send(char txchar);


BOOL InitializeDevice()
{
BOOL isInitialized = TRUE;


myCom = CreateFile(TEXT("COM1"), GENERIC_READ | GENERIC_WRITE, 0,    NULL, OPEN_EXISTING, 0, NULL);


if(myCom == INVALID_HANDLE_VALUE)
{
isInitialized = FALSE;
cout << "Could not initialize the port." << endl;
return isInitialized;
}


isInitialized = SetupPort(1200);


return isInitialized;
}



BOOL SetupPort(int BaudRate)
{
BOOL isSetup = TRUE;


if(!SetupComm(myCom, 4096, 4096))
{
isSetup = FALSE;
cout << "Setup comm error." << endl;
}


if(!GetCommState(myCom, &dcb))
{
isSetup = FALSE;
cout << "Get comm state error." << endl;
}


dcb.BaudRate = BaudRate;
dcb.ByteSize = 8;


if(!SetCommState(myCom, &dcb))
{
isSetup = FALSE;
cout << "Set comm state error." << endl;
}


return isSetup;
}


char *Recieve()
{
//DWORD myReadEvent;
DWORD bytesRead;
char *myReadByte;
//char *myIncomingMessage = "";


if(!SetupPort(1200))
cout << "Error setting up the port." << endl;


else
{
//if(!SetCommMask(myCom, EV_RXCHAR))
//cout << "Could not set read mask." << endl;


//if(WaitCommEvent(myCom, &myReadEvent, NULL))
//{
//do
//{
if(ReadFile(myCom, &myReadByte, 1, &bytesRead, NULL))
//strncat_s(myIncomingMessage, sizeof(myIncomingMessage), myReadByte, 1);
cout << "Reading..." << endl;
else
cout << "Read message error." << endl;


//}while(bytesRead);
//}
}


//return myIncomingMessage;
return myReadByte;
}


void Send(char myWriteByte)
{
DWORD bytesWritten;


if(!SetupPort(1200))
cout << "Error setting up the port." << endl;
else
{
if(WriteFile(myCom, &myWriteByte, 1, &bytesWritten, NULL))
cout << "Writing..." << endl;
else
cout << "Write message error." << endl;
}


return;
}


int _tmain(int argc, _TCHAR* argv[])
{
//char *letter;


if(!InitializeDevice())
cout << "Could not Setup port for comm" << endl;
else
{
Send('c');


//letter = Recieve();
}


Sleep(8000);


CloseHandle(myCom);


return 0;
}

Just to clarify I have another console running the read on 'com3' which is usb emulating rs232.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.