Rusty_Gunn

Nano_Modbus_Address_Scanner

Sep 6th, 2026
14
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. #include <SoftwareSerial.h>
  2. #include <ModbusMaster.h>
  3.  
  4. // SoftwareSerial pins for RS485 communication
  5. #define RX_PIN 2
  6. #define TX_PIN 3
  7.  
  8. // Modbus settings
  9. #define BAUD_RATE 4800
  10. #define START_ADDRESS 0x0000
  11. #define READ_COUNT 2 // Number of registers to read
  12.  
  13. SoftwareSerial modbusSerial(RX_PIN, TX_PIN); // RX, TX
  14. ModbusMaster node;
  15.  
  16. void setup() {
  17. Serial.begin(9600); // Arduino Serial Monitor
  18. delay(1000);
  19.  
  20. Serial.println();
  21. Serial.println("Arduino Nano Modbus Address Scanner");
  22. Serial.println("--------------------------------");
  23.  
  24. // Initialize SoftwareSerial for RS485
  25. modbusSerial.begin(BAUD_RATE);
  26.  
  27. // Initialize ModbusMaster node and link serial stream
  28. node.begin(1, modbusSerial);
  29.  
  30. delay(500);
  31. }
  32.  
  33. void loop() {
  34. // Adjust range as needed (1 to 247 for full scan)
  35. for (uint8_t slaveID = 1; slaveID <= 10; slaveID++) {
  36. node.begin(slaveID, modbusSerial);
  37.  
  38. uint8_t result = node.readHoldingRegisters(START_ADDRESS, READ_COUNT);
  39. //uint8_t result = node.readInputRegisters(START_ADDRESS, READ_COUNT);
  40.  
  41. if (result == node.ku8MBSuccess) {
  42. Serial.print("FOUND device at Modbus ID: ");
  43. Serial.println(slaveID);
  44.  
  45. Serial.print(" Registers: ");
  46. for (uint8_t i = 0; i < READ_COUNT; i++) {
  47. Serial.print(node.getResponseBuffer(i));
  48. Serial.print(" ");
  49. }
  50. Serial.println();
  51. } else {
  52. Serial.print("Failed ID ");
  53. Serial.print(slaveID);
  54. Serial.print(" - Error: 0x");
  55. Serial.println(result, HEX);
  56. }
  57.  
  58. delay(50); // Avoid bus congestion
  59. }
  60.  
  61. Serial.println("--------------------------------");
  62. Serial.println("Scan complete. Restarting in 3 seconds...");
  63. Serial.println();
  64. delay(3000);
  65. }
Advertisement
Add Comment
Please, Sign In to add comment