TModbus.cpp
上传用户:wuxg88
上传日期:2022-05-28
资源大小:814k
文件大小:2k
源码类别:

通讯编程

开发平台:

C++ Builder

  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "TModbus.h"
  5. #include "DMT.h"
  6. #include "winsock2.h"
  7. #pragma comment(lib, "ws2_32.lib")
  8. #pragma comment(lib, "DMT.lib")
  9. //---------------------------------------------------------------------------
  10. #pragma package(smart_init)
  11. #pragma resource "*.dfm"
  12. TForm1 *Form1;
  13. //---------------------------------------------------------------------------
  14. __fastcall TForm1::TForm1(TComponent* Owner)
  15.         : TForm(Owner)
  16. {
  17.      comm_type = 0;               // 通讯种类, 0:序列埠, 1:以太网络
  18.      conn_num = 1;                 // 序列埠编号或联机识别码
  19. }
  20. //---------------------------------------------------------------------------
  21. void __fastcall TForm1::Button1Click(TObject *Sender)
  22. {
  23.    OpenModbusSerial(1,9600, 8, 'N', 1, 2);
  24. }
  25. //---------------------------------------------------------------------------
  26. void __fastcall TForm1::Button2Click(TObject *Sender)
  27. {
  28.     CloseSerial(1);        
  29. }
  30. //---------------------------------------------------------------------------
  31. void __fastcall TForm1::Button3Click(TObject *Sender)
  32. {
  33.     modbus_addr = 0x01;           // 站号, 0
  34.     modbus_func = 0x03;            // 功能码, 0x05
  35.     sendbuf[0] = 0x00;             // Modbus起始地址, 0500
  36.     sendbuf[1] = 0x00;
  37.     sendbuf[2] = 0x00;          // Coil状态值 , FF00 / 0000  force coil on / off
  38.     sendbuf[3] = 0x70;
  39.     datalen = 4;                                                                         // Buffer数据长度 (bytes), ex: “0500FF00”
  40.     RequestData(0,1,modbus_addr,modbus_func,sendbuf,datalen);
  41. }
  42. //---------------------------------------------------------------------------
  43. void __fastcall TForm1::Timer1Timer(TObject *Sender)
  44. {
  45.   AnsiString s = "接收:<-";
  46.   int b = ResponseData(0,1,&modbus_addr,&modbus_func,recvbuf);
  47.   Edit1->Text = b;
  48.   if(b>0)
  49.   {
  50.      s +=IntToHex(modbus_addr,2)+" "+ IntToHex(modbus_func,2)+" "+ IntToHex(b,2)+ " ";
  51.      for(int j = 0;j<b;j++)
  52.      {
  53.        s += IntToHex(recvbuf[j],2)+ " ";
  54.      }
  55.      Memo1->Lines->Add(s);
  56.   }
  57. }
  58. //---------------------------------------------------------------------------
  59. void __fastcall TForm1::Timer2Timer(TObject *Sender)
  60. {
  61.   Button3Click(NULL);
  62. }
  63. //---------------------------------------------------------------------------