arduino - 无法使用 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 位变量。(我也不应该太难理解)非常感谢
解决方案
推荐阅读
- javascript - 使用 vue.js 动态加载(可插入)组件
- azure-devops - 如何为构建失败时引发的错误指定迭代路径?
- node.js - MongoDB - 使用多个查找的 $gruop、辅助 $group、$sum 字段
- ssl - BizTalk Server 中的 Microsoft MQ 客户端绑定导致与 IBM MQ 的 SSL 连接握手失败
- javascript - 悬停下划线的边距问题
- spring-boot - 具有单个属性文件的 Spring 配置文件属性继承
- java - 如何按降序对 Java ArrayList 进行排序?
- java - 如何使用通用函数解析 json?
- javascript - 如何更改 bootstrap-datetimepicker 的视图以显示格式包含时间的日期?
- c# - 如何使用 NLog 记录所有 EF 查询