Arduino Example Code – Address Scan

The N20 UART motor is a Modbus-RTU slave device. Multiple motors can be connected on a single bus, and each motor has a unique slave address (1~247). This example scans the Modbus bus to quickly identify the addresses of online N20 motors on the bus. It applies to scenarios where the motor address is forgotten or addresses of multiple motors cannot be distinguished.

Hardware Preparation

Software Preparation

Wiring Diagram

DFR1277-Wiring Diagram

Connection Description:

Motor Pin: + Connect to Main Controller Pin: VCC
Motor Pin: - Connect to Main Controller Pin: GND
Motor Pin: R Connect to Main Controller Pin: 26/TX
Motor Pin: T Connect to Main Controller Pin: 25/RX

Sample Code

#include "DFRobot_N20SerialMotor.h"

/* Baud rate and scan range can be changed */
#define MOTOR_BAUD     9600
#define SCAN_START_ADDR N20SERIAL_ADDR_MIN
#define SCAN_END_ADDR   N20SERIAL_ADDR_MAX
#define SCAN_BUF_LEN    (N20SERIAL_ADDR_MAX - N20SERIAL_ADDR_MIN + 1)

DFRobot_N20SerialMotor scanner(SCAN_START_ADDR, &Serial1);

void setup()
{
  uint8_t scanBuf[SCAN_BUF_LEN] = { 0 };
  uint8_t foundCount = 0;
  uint8_t j = 0;

  Serial.begin(115200);
  // Serial1: baud 9600, 8N1, TX pin 25, RX pin 26
  Serial1.begin(MOTOR_BAUD, SERIAL_8N1, 25, 26);

  delay(1000);
  Serial.println();
  Serial.println(F("========================================"));
  Serial.println(F("  DFRobot N20 Serial Motor"));
  Serial.println(F("  Address Scan Example"));
  Serial.println(F("========================================"));

  Serial.print(F("[SCAN] Range: "));
  Serial.print(SCAN_START_ADDR);
  Serial.print(F("~"));
  Serial.println(SCAN_END_ADDR);
  Serial.println(F("[SCAN] Scanning bus..."));
  Serial.println(F("Full range scan may take a while. Please be patient and wait."));

  foundCount = scanner.scanAddress(scanBuf, sizeof(scanBuf), SCAN_START_ADDR, SCAN_END_ADDR);

  if (foundCount == 0) {
    Serial.println(F("[SCAN] No device found on bus."));
  } else {
    Serial.print(F("[SCAN] Found "));
    Serial.print(foundCount);
    Serial.println(F(" device(s), address:"));
    for (j = 0; j < foundCount; j++) {
      Serial.print(scanBuf[j]);
      Serial.print(F(" "));
    }
    Serial.println();
  }
  Serial.println(F("[SCAN] Done."));
}

void loop()
{
}

Result

Compile and upload the code, then open the Serial Monitor (Baud rate: 115200). The program automatically scans the address range from 1 to 247. Once the scan completes, it outputs the addresses of detected motor devices on the bus via serial port. The log output is shown in the figure below.

DFR1277-Result

Was this article helpful?

TOP