串口通讯
来源:互联网 发布:无经验程序员 编辑:程序博客网 时间:2024/04/29 22:01
声明:
HANDLE m_hCom; // 串口句柄
OVERLAPPED m_osRead,m_osWrite; // 指向重叠结构变量的指针
打开串口:
CString strCom;
m_Com.GetWindowText(strCom);
m_hCom=CreateFile(strCom,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
NULL);
if(m_hCom==INVALID_HANDLE_VALUE)
{
MessageBox("打开串口失败!","错误",MB_OK|MB_ICONERROR);
return;
}
SetupComm(m_hCom,1024,512);
发送数据:
bool fState;
DWORD length=dwlength;// 数据长度
byte bytSendAddress;
byte bytSendData[32];
int i, j;
j = 0;
bytSendAddress = buf[0];
for(i=1;i<=length;i++)
{
bytSendData[j] = buf[i];
j++;
}
DCB myDCB;
GetCommState(m_hCom,&myDCB);
myDCB.BaudRate = CBR_4800;
myDCB.fBinary = TRUE;
myDCB.fParity = TRUE;
myDCB.ByteSize = 8;
myDCB.Parity = MARKPARITY;
myDCB.StopBits = ONESTOPBIT;
SetCommState(m_hCom,&myDCB);
fState=WriteFile(m_hCom,&bytSendAddress,1,NULL,&m_osWrite);
for(int x=0;x<1000000;x++)
{
for(int y=0;y<2.5;y++){} // 延迟
}
GetCommState(m_hCom,&myDCB);
myDCB.Parity = SPACEPARITY;
fState=WriteFile(m_hCom,&bytSendData,length-1,NULL,&m_osWrite);
SetCommState(m_hCom,&myDCB);
fWriteAdr = true;
Sleep(iSleep);
if(!fState)
{
if (GetLastError()==ERROR_IO_PENDING)
{
GetOverlappedResult(m_hCom,&m_osWrite,&length,TRUE);//wait
}
}
接收数据:
DWORD length=0;
COMSTAT ComStat;
DWORD dwErrorFlags;
ClearCommError(m_hCom,&dwErrorFlags,&ComStat);
length=min(dwlength, ComStat.cbInQue);
ReadFile(m_hCom,&receiveLSControl,length,&length,&m_osRead);//receiveLSControl byte数组
关闭串口:
CloseHandle(m_hCom);
- 串口通讯
- 串口通讯
- 串口通讯
- 串口通讯
- 串口通讯
- 串口通讯
- 串口通讯
- 串口通讯
- 串口通讯
- 串口通讯
- 串口通讯
- 串口通讯
- 串口通讯
- 通讯串口
- 串口通讯
- 串口通讯
- 串口通讯
- 串口通讯
- 膨胀防火涂料与不膨胀防火涂料区别
- 偶然发现asp.net中使用script的小区别
- 路径规划(最短路径)算法C#实现[转]
- 安装SQL Server 遇到错误提示的解决
- [转帖]《EVE》主策划畅谈游戏创意与玩家乐趣
- 串口通讯
- JProfiler连接Weblogic使用说明(转)
- 多猫宠物游戏
- 關于ClickOnce
- openser配置
- struts tag 运用
- java读取xml配置文件(sax)
- 烟雾测试
- IDES ECC 6.0 Copy Client SAP* 无法登陆解决方法