// read voltage from DDSU666 Power meter
#define DE_RE_PIN 18      // DE and RE pins linked to GPIO 18
#define MODE_SEND HIGH   // HIGH for transmitting
#define MODE_RECV LOW    // LOW for receiving
byte ByteArray[250];int ByteData[20];

unsigned long rawValue = 0;
float finalValue;
float voltage;

void relay_command() {
 
  uint8_t buff[] = {
    0x0a, // Device Address
    0x03, // Function code (Read Input Registers)
    0x20, // start address of voltage byte high
    0x00, // address byte low
    0x00, // data count byte high
    0x02, // data count byte low
    0xce, // CRC high
    0xb0  // CRC low
  };

  digitalWrite(DE_RE_PIN, MODE_SEND); // Enable transmission
  Serial2.write(buff, sizeof(buff));   // Send the command via Serial2
  Serial2.flush();                     // Wait for send to complete
  digitalWrite(DE_RE_PIN, MODE_RECV);  // Enable reception

  int a = 0;

  while(Serial2.available()){
    ByteArray[a] = Serial2.read();
    a++;
  }
  // The sensor should respond with a packet 
  int b = 0;
  String Register;
  Serial.println("Receiving Data...");
  for(b=0;b<a;b++){
    Serial.print("[");
    Serial.print(b);
    Serial.print("]");
    Serial.print("=");

    Register = String(ByteArray[b],HEX);
    Serial.print(Register);
    Serial.print(" ");
  }

// get voltage from byte 3,4,5,6
  Serial.println();
 
      uint32_t valInt = ((uint32_t)ByteArray[3] << 24) | 
                        ((uint32_t)ByteArray[4] << 16) | 
                        ((uint32_t)ByteArray[5] << 8) | 
                        (uint32_t)ByteArray[6];

 memcpy(&voltage, &valInt, 4);
   
}

void setup() {
  pinMode(DE_RE_PIN, OUTPUT);
  digitalWrite(DE_RE_PIN, MODE_RECV); // Start in receive mode
  Serial.begin(115200);               // Serial monitor output
  Serial2.begin(9600, SERIAL_8N1, 19, 21); // Initialize Serial2 with standard Modbus settings
  Serial2.setTimeout(200);            // Set a timeout for response
}

void loop() {
  relay_command();

 Serial.print("Voltage: ");
      Serial.print(voltage, 2);
      Serial.println(" V");
  delay(500);
}
