#include #include // Define the pins for SoftwareSerial communication #define RX_PIN 7 // RX pin for SoftwareSerial #define TX_PIN 6 // TX pin for SoftwareSerial #define TX_ENABLE_PIN 4 // 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 } void postTransmission() { digitalWrite(TX_ENABLE_PIN, LOW); // Disable RS485 transmit } 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]; // Read 6 holding registers starting at address 0x0000 result = node.readHoldingRegisters(0x0000, 6); // Check if the read was successful if (result == node.ku8MBSuccess) { Serial.print("Read successful: "); for (uint8_t j = 0; j < 6; j++) { data[j] = node.getResponseBuffer(j); Serial.print(data[j], HEX); Serial.print(" "); } Serial.println(); } else { Serial.print("Read error: "); Serial.println(result, HEX); } // 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); }