Sending and receiving binary data with MSComm32.ocx
After much efort I have been able to read and write binary data (
including NULLs ) in the serial port with BCB5
and the MSComm32 component from VB6.
Here there is an example of reading :
/* This is the function called on Comm event.
*/
void __fastcall Tdiso::CommPortComm(TObject *Sender)
{
switch ( CommPort->CommEvent )
{
/* You may place code to take care of eache event.
*/
case comBreak
case comEventCDTO :
case comEventCTST:.
case comEventDSRTO:
case comEventFrame
case comEventOverrun:
case comEventRxOver:
case comEventRxParity:
case comEventTxFull:
case comEventDCB:
Received->Caption = "Communication error";
break;
/* Data received take it ( if you can )
*/
case comEvReceive:
{
OleVariant Hope;
AnsiString One;
int ReceivedBytes = CommPort->InBufferCount;
int ReadedBytes = 1;
CommPort->InputLen = ReadedBytes;
unsigned char raw_data[BUFFER_SIZE];
/* You must take the data out one by one or you
will lose all the data after first null caracter.
*/
for ( int i = 0;i < ReceivedBytes;i++ )
{
Hope = CommPort->Input;
WideString Needed = Hope;
One = Needed;
memcpy ( (char *)&raw_data[i], ( char *
)One.c_str(), 1 );
}
Although it may seem a bit complicated you must do it in this way or
risk to hung the BCB or even the windows.
Here there is an example of writing :
SendBuffer[0] = 0x01;
SendBuffer[0] = 0x03;
SendBuffer[0] = 0x0a;
SendBuffer[0] = 0xd1;
SendBuffer[0] = 0x00;
SendBuffer[0] = 0x00;
SendBuffer[0] = 0x02;
.
.
.
AnsiString OutData = "";;
SendBuffer[num_bytes] = 0x00;
/* This is very tricky but you must do it or no caracter will be
send after the first NULL.
*/
OutData..SetLength ( num_bytes+1 );
memcpy ( (char * )OutData.c_str (),(char *)&SendBuffer[0],
num_bytes+1 );
OutData.SetLength ( num_bytes );
CommPort->Output = OutData;
Although it may seem a bit complicated you must do it in this way or
risk to hung the BCB or even the windows.
I have tested this example and has been working sending and reciving 24
hours without a problem.
To find this solution I researched the borlands newsgroup and taked some
hint here and there,
so I think it fair to post it here may it help someone.