首页 > 解决方案 > 无法使用 Modbus RTU 读取 Arduino 的寄存器

问题描述

我正在尝试使用 rs485 和 Modbus RTU protokoll 在 2 个 arduino 之间建立连接。作为库,我使用<SimpleModbusMaster.h>and <SimpleModbusSlave.h>

我尝试将主寄存器中的 2 个变量写入从寄存器中,并从从寄存器中读取 4 个变量。所以我成功地将变量写入寄存器,并且很可能在两个 arduino 之间建立了基本连接(arduino 的蓝色指示灯同步亮起。

为了更好地可视化这里的代码:大师:

#include <SimpleModbusMaster.h>

#define baud 9600
#define timeout 1000
#define polling 200 // the scan rate
#define retry_count 10
#define TxEnablePin 2 

enum {
  PACKET1,
  PACKET2,
  TOTAL_NO_OF_PACKETS
};

Packet packets[TOTAL_NO_OF_PACKETS]; // Create an array of Packets to be configured

enum {     
  M_DIREC_VAL,     
  M_VELOC_VAL, 
  M_ROTAT_VAL,  
  M_TURBO_VAL,
  M_INDEX_VAL,
  M_BATTL_VAL,     
  TOTAL_NO_OF_REGISTERS // leave this one
};

unsigned int regs[TOTAL_NO_OF_REGISTERS]; // Masters register array

int cDisplayIndex = 0;
int cBatterieLevel = 0;
int cDirec = 0;
int cVeloc = 0;
int cRotation = 0;
int cTurbo = 0;

void setup() {
  Serial.begin(9600);
  modbus_construct(&packets[PACKET1], 1, READ_HOLDING_REGISTERS, 0, 4, 0);
  modbus_construct(&packets[PACKET2], 1, PRESET_MULTIPLE_REGISTERS, 4, 2, 4);
  modbus_configure(&Serial, baud, SERIAL_8N1, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS, regs);
}

void loop() {
  modbus_update();
  
  regs[M_INDEX_VAL] = cDisplayIndex; // update data to be written to arduino slave
  regs[M_BATTL_VAL] = cBatterieLevel;
  
  cDirec = regs[0];
  cVeloc = regs[1];
  cRotation = regs[2];
  cTurbo = regs[3];// read the registers of the slave and write them into variavles
}

和奴隶:

#include <SimpleModbusSlave.h>

#define baud 9600

enum {     
  S_DIREC_VAL,     
  S_VELOC_VAL, 
  S_ROTAT_VAL,  
  S_TURBO_VAL,
  M_INDEX_VAL,
  M_BATTL_VAL,     
  HOLDING_REGS_SIZE // leave this one
};

unsigned int holdingRegs[HOLDING_REGS_SIZE]; // function 3 and 16 register array

int cDirec =100;
int cVeloc = 0;
int cRotation = 0;
int cTurbo = 0;

int cBatterielevel = 128;
int cDisplayIndex = 0;

void setup() {
  modbus_configure(&Serial, baud, SERIAL_8N2, 1, 2, HOLDING_REGS_SIZE, holdingRegs);
  modbus_update_comms(baud, SERIAL_8N1, 1);
}

void loop() {
  modbus_update();
  
  holdingRegs[S_DIREC_VAL] = cDirec;
  holdingRegs[S_VELOC_VAL] = cVeloc;
  holdingRegs[S_ROTAT_VAL] = cRotation;
  holdingRegs[S_TURBO_VAL] = cTurbo;// update data to be read by the master

  cBatterielevel = (holdingRegs[M_BATTL_VAL]);
  cDisplayIndex = (holdingRegs[M_INDEX_VAL]);
}

首先,是的,我确实先断开了 USB

我从其他站点尝试了许多不同的方法和示例,但我从未成功转移任何变量。

请帮忙。它不需要成为这个特殊问题的解决方案,我只需要 2 个 arduino 之间的可靠连接,我可以在其中发送 8 位变量。(我也不应该太难理解)非常感谢

标签: arduino

解决方案


推荐阅读