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

// Define software serial pins (use any digital pins if not using hardware serial)
#define RX_PIN 13
#define TX_PIN 12
#define DE_PIN 3
#define RE_PIN 4

SoftwareSerial s1(RX_PIN, TX_PIN);
ModbusMaster node;
uint16_t holdingRegisters[20]; 

void setup() {
  // Start the software serial port
  s1.begin(9600 );
 
  //pinMode(RX_PIN, INPUT);
  //pinMode(TX_PIN, OUTPUT);
  pinMode(DE_PIN, OUTPUT);
  pinMode(RE_PIN, OUTPUT);

  digitalWrite(DE_PIN, LOW);
  digitalWrite(RE_PIN, LOW);

  //node.setTimeout(2000);
  // Optionally, start the Serial monitor for debugging
  Serial.begin(9600);

  while (!s1) {
  }
  node.begin(101, s1); 
  node.preTransmission(preTransmission);
  node.postTransmission(postTransmission);

}

void preTransmission()
{
  digitalWrite(DE_PIN, HIGH); // Enable RS485 transmit
  digitalWrite(RE_PIN, HIGH);

 
}

void postTransmission()
{
  digitalWrite(DE_PIN, LOW); // Disable RS485 transmit
  digitalWrite(RE_PIN, LOW);
}

static unsigned long lastRefreshTime = 0;
#define ReadSize 4
void loop() {
  static uint16_t count = 0; 
  uint8_t result;
  int16_t data[ReadSize];


  //delay(100); // Wait a second before the next loop

  // digitalWrite(RE_PIN, HIGH);
  // s1.print("Hello");   
  // digitalWrite(RE_PIN, LOW);

  if(millis() - lastRefreshTime >= 1000)
	{

		lastRefreshTime += 1000;
    Serial.print("Cycle\n\n");


    result = node.readHoldingRegisters(29 , 70);

    // Check if the read was successful
    if (result == node.ku8MBSuccess)
    {
      Serial.print("Read successful: ");
      for (uint8_t j = 0; j < 70; j++)
      {
        uint8_t v = node.getResponseBuffer(j);
        char a = v;
        if (v == 0) {
          continue;
        }
        Serial.print(a);
      }
   
 
   

    } else {
      Serial.print("Read error: ");
      Serial.println(result, HEX);
    }

	}
  
}
