This is the code that does not work because both includes use pins 2 and 3 for communication:
pin 3 is not used by ModbusRTU in that example. Why do you connect the TXEN to pin 2? You have plenty of other pins to connect that to and you're free in the software to define any pin for that function.
I understand that the wiegand protocol is simpler to implement if you can use the hardware interrupts and don't have to fiddle with pin change interrupts, so I would leave that functionality on pins 2 and 3.
void loop() {
slave.poll( au16data, 16 );
Wire.begin(SlaveDeviceId);
Wire.onReceive(receiveEvent);//interrupt handler for incoming message
if (newReceiveEvent == true)
{ Serial.println("Got some data");
for (byte j = 0; j < 2; j++)
{
Serial.println(receiveInts[j]);
}
newReceiveEvent = false;
}
if (errorEvent == true)
{
Serial.println("I2C Receive Error");
errorEvent = false;
}
au16data[0] = receiveInts[1];
au16data[1] = receiveInts[0];
delay(500);
}
It's a bad idea to have an RS-485 driver connected to the serial interface and while listening for some ModBus commands print any debugging garbage to that interface. Either use that interface for ModBus or for debugging. I suggest the former.
Also remove that delay(500) call because it ruins the ModBus interface response time.
The Wire.onReceive() call should be in the setup() routine (needs to be called only once) as should be the Wire.begin().
In that code you also use Wire.readBytes(), which uses timedRead() to get it's bytes. Keep in mind that the timeout feature of that method is not available inside the receiveEvent() function (interrupt context).
void loop() {
if(wg.available())
{
Wire.begin();
Wire.beginTransmission(SlaveDeviceId);
Wire.write((uint8_t*)&sendInts, sizeof(sendInts));
Serial.print("Wiegand HEX = ");
Serial.print(wg.getCode(),HEX);
Serial.print(", DECIMAL = ");
Serial.print(wg.getCode());
Serial.print(", Type W");
Serial.println(wg.getWiegandType());
byte myArray[4];
long reader1 = wg.getCode();
myArray[0] = (reader1 >> 24) & 0xFF;
myArray[1] = (reader1 >> 16) & 0xFF;
myArray[2] = (reader1 >> 8) & 0xFF;
myArray[3] = reader1 & 0xFF;
sendInts[0] = (reader1 >> 16) & 0xFFFF;;
sendInts[1] = reader1 & 0xFFFF;;
Serial.println(reader1 & 0xffffffff);
Serial.println(sendInts[0]);
Serial.println(sendInts[1]);
Serial.println(reader1 & 0xffffffff);
delay(1000);
Wire.endTransmission(); // stop transmitting Serial.println(" Reader 1 High Part");
}
}
In this code Wire.begin() should be in the setup() routine too.
I don't understand why you have the delay() there. You know that nothing is sent over the I2C until the Wire.endTransmission() is called, do you? The way the code is currently structured you're sending the data of the previous wiegand read when the next chunk of data arrives. I guess that is not what you wanted to achieve.