我使用C++ Builder 6.0调用Win32 API实现的。
首先开一个线程。
void __fastcall TForm1::FormCreate(TObject *Sender)
{
ReadComm =new TRead232(true);
ReadComm->FreeOnTerminate = true;
}
通过一个按钮实现打开/关闭串口
void __fastcall TForm1::Button1Click(TObject *Sender)
{
if(Button1->Caption == "打开通讯端口") //按钮名称是"打开通讯端口"?
{
char *ComNo;
DCB dcb;
String Temp;
Temp = "COM"+IntToStr(rdCom->ItemIndex+1);
// TRadioGroup *rdCom; 定义要选择的串口
ComNo = Temp.c_str();
hComm =CreateFile(ComNo,GENERIC_READ|GENERIC_WRITE,
0,NULL,OPEN_EXISTING,0,0);
if(hComm == INVALID_HANDLE_VALUE)
{
MessageBox(0,"打开串口失败!!","Set Error",MB_OK);
return;
}
GetCommState(hComm,&dcb);
dcb.BaudRate = CBR_9600;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
if(!SetCommState(hComm,&dcb))
{
MessageBox(0,"打通讯端口设置错误!!","Set Error",MB_OK);
CloseHandle(hComm);
return;
}
Timer1->Enabled = True;
Button1->Caption = "关闭串口";
Shape1->Brush->Color = clRed;
//启动接收线程
ReadComm->Resume();
}
else
{
Button1->Caption = "打开通讯端口";
CloseHandle(hComm);
Shape1->Brush->Color = clBlack;
Timer1->Enabled = False;
ReadComm->Terminate();
}
}
接收由线程TRead232完成
void __fastcall TRead232::Execute()
{
SetName();
//---- Place thread code here ----
if(!Terminated) Synchronize(ReadData);
}
//---------------------------------------------------------------------------
void __fastcall TRead232::ReadData()
{
Form1->Caption = "Updated in a thread";
String Temp;
char inbuff[1024];
DWORD nBytesRead,dwEvent,dwError;
COMSTAT cs;
if(hComm == INVALID_HANDLE_VALUE)
{
MessageBox(0,"串口失败!!","Set Error",MB_OK);
return;
}
ClearCommError(hComm,&dwError,&cs);
Form1->Edit1->Text = cs.cbInQue;
if(cs.cbInQue > sizeof(inbuff))
{
PurgeComm(hComm,PURGE_RXCLEAR);
return;
}
ReadFile(hComm,inbuff,cs.cbInQue,&nBytesRead,NULL);
inbuff[cs.cbInQue]='\0';
Form1->Memo1->Text =Form1->Memo1->Text+inbuff;
}
发送是定时器TIMER1触发,定时发送的。
void __fastcall TForm1::Timer1Timer(TObject *Sender)
{
char SendData[20];
byte ch;
int i;
unsigned long lrc,BS;
if (hComm==0) return;
SendData[0] = 0x41;
SendData[1] = 0x03;
SendData[2] = 0x00;
SendData[3] = 0x01;
SendData[4] = 0x00;
SendData[5] = 0x04;
SendData[6] = 0x1b;
SendData[7] = 0x09;
SendData[8] = '\0';
// BS = 8; // StrLen(SendData);
for(i=0;i<=7;i++)
{
ch = SendData[i];
WriteFile(hComm,&ch,1,&lrc,NULL);
}
}
共1条
1/1 1 跳转至页
modbus协议-PC端的实现(ZZ)

只看楼主 1楼
关键词: modbus 协议 实现 hComm SendDa
共1条
1/1 1 跳转至页
回复
有奖活动 | |
---|---|
发原创文章 【每月瓜分千元赏金 凭实力攒钱买好礼~】 | |
【EEPW在线】E起听工程师的声音! | |
“我踩过的那些坑”主题活动——第001期 | |
高校联络员开始招募啦!有惊喜!! | |
【工程师专属福利】每天30秒,积分轻松拿!EEPW宠粉打卡计划启动! | |
送您一块开发板,2025年“我要开发板活动”又开始了! | |
打赏了!打赏了!打赏了! |
打赏帖 | |
---|---|
【我踩过的那些坑】工作那些年踩过的记忆深刻的坑被打赏10分 | |
【我踩过的那些坑】DRC使用位置错误导致的问题被打赏100分 | |
我踩过的那些坑之混合OTL功放与落地音箱被打赏50分 | |
汽车电子中巡航控制系统的使用被打赏10分 | |
【我踩过的那些坑】工作那些年踩过的记忆深刻的坑被打赏100分 | |
分享汽车电子中巡航控制系统知识被打赏10分 | |
分享安全气囊系统的检修注意事项被打赏10分 | |
分享电子控制安全气囊计算机知识点被打赏10分 | |
【分享开发笔记,赚取电动螺丝刀】【OZONE】使用方法总结被打赏20分 | |
【分享开发笔记,赚取电动螺丝刀】【S32K314】芯片启动流程分析被打赏40分 |