串口通信的实现不算难,尤其是有了控件之后就更加的简单了,这里个人主要用的是PCOMM.DLL。
下载地址:
电脑和仪器进行串口通信主要是以下几个过程:
①设置正确的串口号
这里面写的很清楚获得串口的方法。
②向串口发送命令字
一般和搞硬件的沟通就行了,如果是别人的。那么可以通过串口工具获得:
发送的命令字用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 );
}
本文发布于:2024-02-01 10:31:39,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170675469936000.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |