Ultrasonic sensor URM04 V2.0 Tutorial


URM04 V2.0

The URM04 V2.0 uses RS485 to communicate. It can be plugged into a Xbee IO Expansion shield V5 using a 4 pin cable. The Xbee shield itself can be plugged into an Arduino board:

Xbee IO Expansion V5:
xbee io expansion v5
Arduino Uno:
Arduino Uno


The URM04 V2.0 ultrasonic sensor needs a few tricks to use. The information from this Wiki (as of 2012-2-12) is not correct.
The main problem is that after a distance measurement, sometimes one cannot retrieve the result.

After a few experiments, it turns out that sometimes, after the measurement, the sensor does not return any result, so if your program waits for the answer forever, it may get blocked. I use the following adapted program to wait only for certain amount of time. If it times out, the program gives up and continue to the next measurement.

// Measure distance using the URM04V2 ultrasonic sensor.  
void measureDistance(byte device) {  
  digitalWrite(EN, HIGH);  
  // Trigger distance measurement.  
  uint8_t DScmd[6]={0x55,0xaa,device,0x00,0x01,0x00};    
  for(int i=0; i<6; i++) {  
    Serial.write(DScmd[i]);  
    DScmd[5] += DScmd[i];  
  }  
  delay(30);  
  // Send command to read measured distance.  
  uint8_t STcmd[6]={0x55,0xaa,device,0x00,0x02,0x00};    
  for(int i=0; i<6; i++) {  
    Serial.write(STcmd[i]);  
    STcmd[5] += STcmd[i];  
  }    
  delay(3);  
}  
 
// Return last measured distance by the URM04V2 ultrasonic sensor.  
// -1 means the last measurement is out of range or unsuccessful.  
int readDistance() {  
  uint8_t data[8];  
  digitalWrite(EN,LOW);  
  boolean done = false;  
  int counter = 0;  
  int result = -1;  
   
  while(!done){  
    int bytes = Serial.available();  
    if(bytes==8) {    
      for(int i=0; i<8; i++) {  
        data[i] = Serial.read();  
      }  
      result = (int)data[5] * 256 + data[6];  
      done = true;  
    } else {  
      delay(10);  
      counter++;  
      if(counter==5) { // If failed to read measured data for 5 times, give up and return -1.  
        done = true;  
      }  
    }  
  }  
  return result;  
}  

// Usage code sample:  
int EN = 2; // Pin number to enable XBee expansion board V5  
 
void setup() {  
  pinMode(EN, OUTPUT);  
  Serial.begin(19200);  
  delay(200);  
  digitalWrite(EN,HIGH);  
  delay(2000);    
}  
 
void loop() {  
  measureDistance(0x11);  
  int distance = readDistance();  
  delay(1000);  
}  

In the above program, function measureDistance triggers a distance measurement. Its argument specifies the device ID. The default device ID is 0x11. If you only have one such sensor, 0x11 is what you should write here. Function readDistance is used to retrieve measured distance. If the measurement failed or the distance is beyond the capacity of the sensor, this function returns -1.

A few things to note when using this URM04 V2.0 ultrasonic sensor: