Arduino到RS-485的Arduino Modbus RTU

时间:2018-02-08 09:41:19

标签: arduino serial-port embedded modbus rs485

我在RS-485中使用Modbus RTU协议尝试Arduino与Arduino(主从)通信。我正在使用Arduino Mega 2560进行项目并使用此library Modbus RTU。截至目前,master只读取数据slave并在Serial monitor中打印。

我尝试了以下代码:

从站

#include <ModbusRtu.h>
#define ID   3

Modbus slave(ID, 0, 0);
boolean led;
int8_t state = 0;
unsigned long tempus;
// data array for modbus network sharing
uint16_t au16data[9];

void setup() {
  // define i/o
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  pinMode(4, INPUT);
  pinMode(5, INPUT);

  // start communication
  slave.begin(19200);
  tempus = millis() + 100;
  digitalWrite(13, HIGH);
}

void loop() {
  // poll messages
  // blink led pin on each valid message
  state = slave.poll( au16data, 9 );
  if (state > 4) {
    tempus = millis() + 50;
    digitalWrite(13, HIGH);
  }
  if (millis() > tempus) digitalWrite(13, LOW );
  // get digital inputs -> au16data[0]
  bitWrite( au16data[0], 0, digitalRead( 2 ));
  bitWrite( au16data[0], 1, digitalRead( 3 ));
  bitWrite( au16data[0], 2, digitalRead( 4 ));
  bitWrite( au16data[0], 3, digitalRead( 5 ));

  // diagnose communication
  au16data[6] = slave.getInCnt();
  au16data[7] = slave.getOutCnt();
  au16data[8] = slave.getErrCnt();
}

#include <ModbusRtu.h>

// data array for modbus network sharing
uint16_t au16data[16];
uint8_t u8state;

/**
 *  Modbus object declaration
 *  u8id : node id = 0 for master, = 1..247 for slave
 *  u8serno : serial port (use 0 for Serial)
 *  u8txenpin : 0 for RS-232 and USB-FTDI 
 *               or any pin number > 1 for RS-485
 */
Modbus master(0,1,1); // this is master and RS-485

/**
 * This is an structe which contains a query to an slave device
 */
modbus_t telegram;

unsigned long u32wait;

void setup() {
  master.begin(19200); // baud-rate at 19200
  master.setTimeOut(2000); // if there is no answer in 2000 ms, roll over
  u32wait = millis() + 1000;
  u8state = 0; 
  Serial.begin(9600);
}

void loop() {
  Serial.print(u8state);
  switch(u8state) {
  case 0:
    if (millis() > u32wait) u8state++; // wait state
    break;
  case 1: 
    telegram.u8id = 1; // slave address
    telegram.u8fct = 3; // function code (this one is registers read)
    telegram.u16RegAdd = 1; // start address in slave
    telegram.u16CoilsNo = 4; // number of elements (coils or registers) to read
    telegram.au16reg = au16data; // pointer to a memory array in the Arduino
    master.query(telegram); // send query (only once)
    u8state++;
    break;
  case 2:
    master.poll(); // check incoming messages
    if (master.getState() == COM_IDLE) {
      u8state = 0;
      u32wait = millis() + 100; 
    }
    break;
  }
  Serial.println(au16data[0])
}

当从站2中的引脚输入为高电平时,串行监视器中的输出不会改变。

20
00

有人可以告诉我可能的原因和解决方案吗?如果我错过了任何内容,过分强调或不足以强调某个特定点,请在评论中告诉我。

0 个答案:

没有答案