Serial Communication
I'm trying to read and write from a serial port communication using
the MSComm Object.
I'm having problems reading, and I suspect that I do not write
correctly to it.
I know that MSComm.SetOutput() requires a VARIANT so...
I have this function that creates a VARIANT from an unsigned char
array.
[CODE]
VARIANT* CIFDlg::insertArrayInVariant( unsigned char* data, unsigned
int num_bytes )
{
SAFEARRAYBOUND rgb[1];
rgb[0].lLbound = 0;
rgb[0].cElements = num_bytes;
VARIANT* v = new VARIANT;
v->vt = VT_ARRAY|VT_UI1;
v->parray = SafeArrayCreate( VT_UI1, 1, rgb );
char *regs;
SafeArrayAccessData( v->parray, ( void** )®s );
for( long c=0; c<num_bytes; c++ )
{
switch( SafeArrayPutElement( v->parray, &c, &data[c] ) )
{
case S_OK: break;
case DISP_E_BADINDEX: AfxMessageBox( "Invalid index); break;
case E_INVALIDARG: AfxMessageBox( "Invalid argument."); break;
}
}
SafeArrayUnaccessData( v->parray );
return v;
}
[/CODE]
And this is the code to send to serial:
[CODE]
VARIANT* v = insertArrayInVariant( datos, );
m_Comm.SetOutput( *v );
[/CODE]
I can confirm that I put correctly the data into variant 'cause I
tried to read after I create it.
The problem comes reading:
[CODE]
void CIFDlg::OnCommEvent()
{
// TODO: Add your control notification handler code here
VARIANT input_buff;
input_buff.vt = VT_ARRAY|VT_UI1;
long lLen = 0;
unsigned char byte;
switch( m_Comm.GetCommEvent() )
{
case 2: // RX data
AfxMessageBox("Recieving..");
input_buff = m_Comm.GetInput();
int Count= input_buff.parray-
rgsabound[0].cElements;
unsigned char *p = (unsigned char
*)input_buff.parray->pvData;
for(i=0; i<Count; i++ )
{
byte = *p;
aux.Format( _T("DATA:%x"), byte );
AfxMessageBox( aux );
p++;
}
break;
}
}
[/CODE]
This gives me an infinity loop showing me invalid data.
In my example I'm sending:
af 05 10 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 c4
And I'm receiving:
6e 94 2 2
6f 94 2 2
70 94 2 2
71 94 2 2
72 .....
What I'm doing wrong????