#include <ModbusMaster.h>
#include <SoftwareSerial.h>

// Define the pins for SoftwareSerial communication
#define RX_PIN 3  // RX pin for SoftwareSerial
#define TX_PIN 4  // TX pin for SoftwareSerial
#define TX_ENABLE_PIN 2 // Pin to control RS485 direction
#define DE_ENABLE_PIN 5  

// Create a SoftwareSerial object
SoftwareSerial modbusSerial(RX_PIN, TX_PIN);

// Create an instance of the ModbusMaster class
ModbusMaster node;

// Function to control RS485 transmit enable
void preTransmission()
{
  digitalWrite(TX_ENABLE_PIN, HIGH); // Enable RS485 transmit
  digitalWrite(DE_ENABLE_PIN, HIGH);
}

void postTransmission()
{
  digitalWrite(TX_ENABLE_PIN, LOW); // Disable RS485 transmit
  digitalWrite(DE_ENABLE_PIN, LOW);
}

void setup()
{
  // Initialize the built-in serial port for debugging
  Serial.begin(9600);

  // Initialize SoftwareSerial for Modbus communication
  modbusSerial.begin(9600);

  pinMode(DE_ENABLE_PIN, OUTPUT);
  digitalWrite(DE_ENABLE_PIN, HIGH);


  // Set the pin mode for the RS485 control pin
  pinMode(TX_ENABLE_PIN, OUTPUT);
  digitalWrite(TX_ENABLE_PIN, LOW);
  

  // Modbus communication setup
  node.begin(1, modbusSerial); // Slave ID = 1, use modbusSerial for RS485 communication

  // Set callbacks to handle RS485 flow control
  node.preTransmission(preTransmission);
  node.postTransmission(postTransmission);
}

void loop()
{
  static uint16_t count = 0; 
  uint8_t result;
  uint16_t data[6];
  Serial.print("Loop:");
 Serial.println(count);
   // Write the count value to the holding register at address 0x0001
  result = node.writeSingleRegister(0x0001, count);


  // Check if the write was successful
  if (result == node.ku8MBSuccess)
  {
    Serial.print("Write successful: ");
    Serial.println(count);
  }
  else
  {
    Serial.print("Write error: ");
    Serial.println(result, HEX);
  }

  // Increment the count value
  count++;
  // Delay before the next read cycle
  delay(1000);
}
