TModbus.cpp
资源名称:test.rar [点击查看]
上传用户:wuxg88
上传日期:2022-05-28
资源大小:814k
文件大小:2k
源码类别:
通讯编程
开发平台:
C++ Builder
- //---------------------------------------------------------------------------
- #include <vcl.h>
- #pragma hdrstop
- #include "TModbus.h"
- #include "DMT.h"
- #include "winsock2.h"
- #pragma comment(lib, "ws2_32.lib")
- #pragma comment(lib, "DMT.lib")
- //---------------------------------------------------------------------------
- #pragma package(smart_init)
- #pragma resource "*.dfm"
- TForm1 *Form1;
- //---------------------------------------------------------------------------
- __fastcall TForm1::TForm1(TComponent* Owner)
- : TForm(Owner)
- {
- comm_type = 0; // 通讯种类, 0:序列埠, 1:以太网络
- conn_num = 1; // 序列埠编号或联机识别码
- }
- //---------------------------------------------------------------------------
- void __fastcall TForm1::Button1Click(TObject *Sender)
- {
- OpenModbusSerial(1,9600, 8, 'N', 1, 2);
- }
- //---------------------------------------------------------------------------
- void __fastcall TForm1::Button2Click(TObject *Sender)
- {
- CloseSerial(1);
- }
- //---------------------------------------------------------------------------
- void __fastcall TForm1::Button3Click(TObject *Sender)
- {
- modbus_addr = 0x01; // 站号, 0
- modbus_func = 0x03; // 功能码, 0x05
- sendbuf[0] = 0x00; // Modbus起始地址, 0500
- sendbuf[1] = 0x00;
- sendbuf[2] = 0x00; // Coil状态值 , FF00 / 0000 force coil on / off
- sendbuf[3] = 0x70;
- datalen = 4; // Buffer数据长度 (bytes), ex: “0500FF00”
- RequestData(0,1,modbus_addr,modbus_func,sendbuf,datalen);
- }
- //---------------------------------------------------------------------------
- void __fastcall TForm1::Timer1Timer(TObject *Sender)
- {
- AnsiString s = "接收:<-";
- int b = ResponseData(0,1,&modbus_addr,&modbus_func,recvbuf);
- Edit1->Text = b;
- if(b>0)
- {
- s +=IntToHex(modbus_addr,2)+" "+ IntToHex(modbus_func,2)+" "+ IntToHex(b,2)+ " ";
- for(int j = 0;j<b;j++)
- {
- s += IntToHex(recvbuf[j],2)+ " ";
- }
- Memo1->Lines->Add(s);
- }
- }
- //---------------------------------------------------------------------------
- void __fastcall TForm1::Timer2Timer(TObject *Sender)
- {
- Button3Click(NULL);
- }
- //---------------------------------------------------------------------------