Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <SoftwareSerial.h>
- #include <ModbusMaster.h>
- // SoftwareSerial pins for RS485 communication
- #define RX_PIN 2
- #define TX_PIN 3
- // Modbus settings
- #define BAUD_RATE 4800
- #define START_ADDRESS 0x0000
- #define READ_COUNT 2 // Number of registers to read
- SoftwareSerial modbusSerial(RX_PIN, TX_PIN); // RX, TX
- ModbusMaster node;
- void setup() {
- Serial.begin(9600); // Arduino Serial Monitor
- delay(1000);
- Serial.println();
- Serial.println("Arduino Nano Modbus Address Scanner");
- Serial.println("--------------------------------");
- // Initialize SoftwareSerial for RS485
- modbusSerial.begin(BAUD_RATE);
- // Initialize ModbusMaster node and link serial stream
- node.begin(1, modbusSerial);
- delay(500);
- }
- void loop() {
- // Adjust range as needed (1 to 247 for full scan)
- for (uint8_t slaveID = 1; slaveID <= 10; slaveID++) {
- node.begin(slaveID, modbusSerial);
- uint8_t result = node.readHoldingRegisters(START_ADDRESS, READ_COUNT);
- //uint8_t result = node.readInputRegisters(START_ADDRESS, READ_COUNT);
- if (result == node.ku8MBSuccess) {
- Serial.print("FOUND device at Modbus ID: ");
- Serial.println(slaveID);
- Serial.print(" Registers: ");
- for (uint8_t i = 0; i < READ_COUNT; i++) {
- Serial.print(node.getResponseBuffer(i));
- Serial.print(" ");
- }
- Serial.println();
- } else {
- Serial.print("Failed ID ");
- Serial.print(slaveID);
- Serial.print(" - Error: 0x");
- Serial.println(result, HEX);
- }
- delay(50); // Avoid bus congestion
- }
- Serial.println("--------------------------------");
- Serial.println("Scan complete. Restarting in 3 seconds...");
- Serial.println();
- delay(3000);
- }
Advertisement
Add Comment
Please, Sign In to add comment