求助,一个串口类
我在网上找了一个API写的串口类,详情请点 http://ticktick.blog.51cto.com/823160/286603/
运行如下代码时:
- C/C++ code
#include "stdafx.h"#include "SerialPort.h"#include <iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){ CSerialPort mySerialPort; char temp; while(1) { mySerialPort.ReadChar(temp);//类里面说 ReadChar()读取缓存区里一个字节数据 cout<<temp<<endl;//这里我特意加了换行 } return 0;}
用串口调试助手向它发送一传字符串 abcdefg
显示的结果是:
ab
cde
fg
我很奇怪temp只是一个字符,结果不应该是:
a
b
c
d
这样一个字符一个字符的输出吗? 难道temp可以同时存"ab"?
[解决办法]
试试
char temp[2] = {/0};
另外ReadChar能否把代码打开看看
[解决办法]
没有看到初始化的部分,比如波特率和Buffer等配置;另外从串口读取数据的话,最好中间有些延迟,以免遗漏;串口数据的接收最好用中断的方式,在CSerialPort中应该是一个类似于Monitor的过程;这里有一篇文章(http://ishare.iask.sina.com.cn/f/20898699.html)值得参考。
[解决办法]
[解决办法]
- C/C++ code
DWORD CSerialPort::SerialRead(char* pszbuf, DWORD dwLength){ COMSTAT ComStat; DWORD dwErrorFlags; DWORD length = 0; memset(m_szbuf, 0, sizeof(m_szbuf)); ClearCommError(m_hCom, &dwErrorFlags, &ComStat); if(ComStat.cbInQue) { length = ComStat.cbInQue; if (length>dwLength) { length = dwLength+1; } if (!m_OsFlag) { ReadFile(m_hCom, m_szbuf, length, &length, &m_osRead); } else ReadFile(m_hCom, m_szbuf, length, &length, NULL); strcpy(pszbuf,m_szbuf); } return length;}
[解决办法]
还是boost里面的asio牛,支持windows和linux