串口通信的实现不算难,尤其是有了控件之后就更加的简单了,这里个人主要用的是PCOMM.DLL。
下载地址:http://pan.baidu.com/s/1ntoRRGP
电脑和仪器进行串口通信主要是以下几个过程:
①设置正确的串口号
http://blog.csdn.net/supersonico/article/details/44241201
这里面写的很清楚获得串口的方法。
②向串口发送命令字
一般和搞硬件的沟通就行了,如果是别人的。那么可以通过串口工具获得:
http://blog.csdn.net/supersonico/article/details/44062709
发送的命令字用char数组:
char sOut[5];
sOut[0] = 170;
sOut[1] = 2;
sOut[2] = 5;
sOut[3] = 0;
sOut[4] = 0xf9;
③串口返回字节
返回的字节一般是16进制的
④获取串口返回的字节进行转换
一般用来保存字节的是char数组,可以将数组转换相应的 short,int,float,一般通过指针进行强制转换
这里一定要清楚各种类型保存的字节数:
32位操作系统:
char 1 个字节
short 2个字节
int 4个字节
char c[4] = {0x30,0x00,0x00,0x00};
int* d = (int *)c;
float 4个字节
char a[4] = {0x30,0xC6,0xA4,0x43};
float * b = (float *)a;
double 8个字节
⑤关闭串口
以下是用PCOMM.DLL控件的代码主体:
bool ReadData(int iPort, //串口号
char *pWriteCmd, //发送的数据
DWORD dwWriteCmdBytes, //发送数据的字节数
char* pRcvBuffer, //接收的数据
DWORD dwRcvCmdByte, //接收数据的字节数
int iBaud = B9600, //波特率
int iBit= BIT_8, //数据位
int iParity = P_NONE, //奇偶校验
int iStopBit = STOP_1 //停止位
)
{
DWORD dwReadByte = 0; //记录读取的字节数
if ( ::sio_open(iPort) != SIO_OK )
{
AfxMessageBox(_T("串口打开失败,请先设置正确串口号!"));
return false;
}
int iIoCtl = ::sio_ioctl(iPort, iBaud, iBit | iParity | iStopBit );
int iWriteReturn = ::sio_write(iPort, pWriteCmd, dwWriteCmdBytes);
//读取数据
int iCount = 0;
const int IREADTIMES = 10;
int iCurReadBytes = 0;
dwReadByte = 0;
memset(pRcvBuffer,0,RSVBFRSIZE);
while(iCount <= IREADTIMES)
{
iCurReadBytes = sio_read(iPort, (char*)pRcvBuffer+ dwReadByte, RSVBFRSIZE);
dwReadByte += iCurReadBytes;
iCount++;
if (iCount > IREADTIMES-1 && iCurReadBytes > 0)
{
iCount--;
}
Sleep(100);
}
::sio_close(iPort);
return ( true );
}