andresarmento / modbus-arduino

A library that allows your Arduino to communicate via Modbus protocol, acting as a slave (master in development). Supports serial (RS-232, RS-485) and IP via Ethernet (Modbus IP).
BSD 3-Clause "New" or "Revised" License
453 stars 267 forks source link

Switch state not changing #24

Closed blddk closed 7 years ago

blddk commented 7 years ago

I am currently trying to get this to work with the Universal Robots software, but I am having some problems with the inputs.

When I send the command from the robot to turn the coil on, it does that perfectly. But reading status of a input always returns it as HIGH, even when arduino reports it as low.

Anyone got an idea to why that is happening?

#include <SPI.h>
#include <Ethernet.h>
#include <Modbus.h>
#include <ModbusIP.h>

//Modbus Registers Offsets (0-9999)
const int DO1_COIL = 1;
//Used Pins
const int DO1_PIN = 9;

const int DI1_ISTS = 16;
const int DI1_PIN = 3;

//ModbusIP object
ModbusIP mb;

unsigned long statusLast = 0;

void setup()
{
  Serial.begin(9600);

  // The media access control (ethernet hardware) address for the shield
  byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

  // The IP address for the shield
  byte ip[] = { 192, 168, 1, 12 };

  //Config Modbus IP
  mb.config(mac, ip);

  //Set ledPin mode
  pinMode(DO1_PIN, OUTPUT);
  pinMode(DI1_PIN, INPUT);

  // Add LAMP1_COIL register - Use addCoil() for digital outputs
  mb.addCoil(DO1_COIL);

  // Add SWITCH_ISTS register - Use addIsts() for digital inputs
  mb.addIsts(DI1_ISTS);
}

void loop()
{
  //Call once inside loop() - all magic here
  mb.task();

  //Attach switchPin to SWITCH_ISTS register
  mb.Ists(DI1_ISTS, digitalRead(DI1_PIN));

  //Attach ledPin to LAMP1_COIL register
  digitalWrite(DO1_PIN, mb.Coil(DO1_COIL));

  if (millis() - statusLast >= 1000)
  {
    statusLast = millis();
    Serial.print("DI1 = ");
    Serial.println(digitalRead(DI1_PIN));
  }
}