#include <SoftwareSerial.h> 
#include <SimpleModbusSlaveSoftwareSerial.h>

#define RX 3      // Arduino defined pin (PB0, package pin #5)
#define TX 1      // Arduino defined pin (PB1, package pin #6)
#define RS485_EN 13 // Pin to set transmission mode on RS485 chip (PB2, package pin #7)
#define BAUD_RATE 9600  // Baud rate for serial communication
#define deviceID 22      // This device address

// Modbus Register Addresses
enum {
    BUTTON0,
    HI,
    LO,
    TOTAL_REGS_SIZE // Total number of registers for function 3 and 16
};

// Holding Registers
unsigned int holdingRegs[TOTAL_REGS_SIZE];
uint16_t val = 20;

SoftwareSerial mySerial(RX, TX);

void setup() {
    mySerial.begin(BAUD_RATE);
    modbus_configure(&mySerial, BAUD_RATE, deviceID, RS485_EN, TOTAL_REGS_SIZE);

    val++; // Increment val
    holdingRegs[BUTTON0] = val;
    holdingRegs[HI] = 0;
    holdingRegs[LO] = 0;

    modbus_update(holdingRegs); // Initial Modbus update
}

void loop() {
    // Update Modbus registers continuously
    modbus_update(holdingRegs);

    if (mySerial.available()) { // If data is available on serial port
        val++;
        holdingRegs[BUTTON0] = val; // Update register with new value
    }
}
