串口发送数据不对的问题
wince串口程序,用wince开发板和计算机互连,用串口助手调试,在计算机端用串口接收数据不正确,但是计算机发,程序收显示正常。但是单步跟踪调试数据显示都正确啊,苦找不到原因,难道是宽字符需要转换么?怎么转求解答
代码如:
void CSerialPortDlg::OnSend()
{
DWORD dwCharToWrite=0;
DWORD dwBytesWritten=0;
int i,j;
GetDlgItemText(IDC_TRANSMIT,m_strTransmit);//cstring m_strTransmit
if(!HexSend)//十六进制
{
dwCharToWrite=(DWORD)m_strTransmit.GetLength();
}
else
{
for(i=0;i<m_strTransmit.GetLength()/2;i++)
{
if(((m_strTransmit.GetAt(i*2)>='0'&&m_strTransmit.GetAt(i*2)<='9')||(m_strTransmit.GetAt(i*2)>='A'&&m_strTransmit.GetAt(i*2)<='F'))&&((m_strTransmit.GetAt(i*2+1)>='0'&&m_strTransmit.GetAt(i*2+1)<='9')||(m_strTransmit.GetAt(i*2+1)>='A'&&m_strTransmit.GetAt(i*2+1)<='F')))
{
dwCharToWrite++;
}
}
}
dwBytesWritten=0;
if(Open&&dwCharToWrite!=0)
{
char* buf=new char[dwCharToWrite];
if(!HexSend)
{
for(i=0;i<(int)dwCharToWrite;i++)
{
buf[i]=(char)m_strTransmit.GetAt(i);
}
}
else
{
j=0;
for(i=0;i<m_strTransmit.GetLength()/2;i++)
{
if(((m_strTransmit.GetAt(i*2)>='0'&&m_strTransmit.GetAt(i*2)<='9')||(m_strTransmit.GetAt(i*2)>='A'&&m_strTransmit.GetAt(i*2)<='F'))&&((m_strTransmit.GetAt(i*2+1)>='0'&&m_strTransmit.GetAt(i*2+1)<='9')||(m_strTransmit.GetAt(i*2+1)>='A'&&m_strTransmit.GetAt(i*2+1)<='F')))
{
if(m_strTransmit.GetAt(i*2+1)>='0'&&m_strTransmit.GetAt(i*2+1)<='9')
{
buf[j]=m_strTransmit.GetAt(i*2+1)-48;
}
else
{
buf[j]=m_strTransmit.GetAt(i*2+1)-55;
}
if(m_strTransmit.GetAt(i*2)>='0'&&m_strTransmit.GetAt(i*2)<='9')
{
buf[j]+=(m_strTransmit.GetAt(i*2)-48)*16;
}
else
{
buf[j]+=(m_strTransmit.GetAt(i*2)-55)*16;
}
j++;
}
}
}
dwBytesWritten=m_pSerial->WritePort(buf,dwCharToWrite);
if(dwBytesWritten==0)
{
AfxMessageBox(_T("无法向端口写入数据!"));
}
delete[] buf;
}
}
DWORD CPSerialPort::WritePort(char *data,int length)
{
if(m_hComm==INVALID_HANDLE_VALUE)
{
return 0;
}
BOOL fWriteState;
DWORD dwBytesWritten=0;
fWriteState=WriteFile(m_hComm,data,length*sizeof(char),&dwBytesWritten,NULL);
return dwBytesWritten;
}
[解决办法]
CE上也有串口工具的,找一个试一下,测试一下收发,如果都正常就是你程序的问题。
如果两个工具互通都不对,有可能是你驱动的问题
[解决办法]
HRESULT __fastcall UnicodeToAnsi(LPCOLESTR pszW, LPSTR* ppszA)
{
ULONG cbAnsi, cCharacters;
DWORD dwError;
// If input is null then just return the same.
if (pszW == NULL)
{
*ppszA = NULL;
return NOERROR;
}
cCharacters = wcslen(pszW)+1;
// Determine number of bytes to be allocated for ANSI string. An
// ANSI string can have at most 2 bytes per character (for Double
// Byte Character Strings.)
cbAnsi = cCharacters*2;
// Use of the OLE allocator is not required because the resultant
// ANSI string will never be passed to another COM component. You
// can use your own allocator.
*ppszA = (LPSTR) CoTaskMemAlloc(cbAnsi);
if (NULL == *ppszA)
return E_OUTOFMEMORY;
// Convert to ANSI.
if (0 == WideCharToMultiByte(CP_ACP, 0, pszW, cCharacters, *ppszA,
cbAnsi, NULL, NULL))
{
dwError = GetLastError();
CoTaskMemFree(*ppszA);
*ppszA = NULL;
return HRESULT_FROM_WIN32(dwError);
}
return NOERROR;
}