Example Code for Arduino-UART Mode
Last revision 2025/12/30
Test the SRF02 ultrasonic sensor using UART mode with Arduino Leonardo (or Arduino UNO with Software Serial). Users can learn how to communicate with the SRF02 via UART and read distance measurements in centimeters.
Hardware Preparation
- SRF02 Ultrasonic Sensor, SKU:SEN0005, Quantity:1, Purchase Link
- Arduino Leonardo (or Arduino UNO), Quantity:1
Software Preparation
- Development Tool: Arduino IDE (version 1.8.x or later). Download link
- Library: SoftwareSerial library (included with Arduino IDE for Arduino UNO; no additional installation needed for Leonardo)
Wiring Diagram
For Arduino Leonardo:
| SRF02 | Arduino |
|---|---|
| 5v Vcc | 5V |
| Rx | 1(TX) |
| Tx | 0(RX) |
| Mode | GND |
| 0v Ground | GND |
For Arduino UNO (Software Serial):
Change "Serial1" to "mySerial" and add #include <SoftwareSerial.h> and SoftwareSerial mySerial(10, 11); // RX, TX to the code. Connect SRF02's Rx to Arduino UNO's TX (pin 11) and Tx to Arduino UNO's RX (pin 10).
Other Preparation Work
For UART mode, connect the "Mode" pin of the SRF02 to GND. For Arduino UNO, use Software Serial and adjust the pin connections accordingly.
Sample Code
/*
Sample code for test the SRF02 with the UART mode based on Leonardo!
Command for reference:http://robot-electronics.co.uk/htm/srf02techSer.htm
Connection:
SRF02 Arduino
5v Vcc -> 5V
Rx -> 1(TX)
Tx -> 0(RX)
Mode -> GND
0v Ground -> GND
*/
void SendCmd(unsigned char address,unsigned char cmd)
{
Serial1.write(address);//set the address of SRF02(factory default is 0)
delayMicroseconds(100);//serial data is fixed at 9600,N,8,2,so we need some time to creat the sencond stop bit
Serial1.write(cmd);//send the command to SRF02
delayMicroseconds(100);//serial data is fixed at 9600,N,8,2,so we need some time to creat the sencond stop bit
}
void setup(void)
{
Serial.begin(9600);
Serial1.begin(9600);
Serial.println("SRF02 TEST!");
}
void loop(void)
{
unsigned int reading;
SendCmd(0x00,0x51);//Real Ranging Mode - Result in centimeters
delay(70);//time for SRF02 to measure the range
SendCmd(0x00,0x5E);//Get Range, returns two bytes (high byte first) from the most recent ranging.
delay(10);//wait for some time,let the Arduino receive 2 bytes data from the TX pin of SRF02
if(Serial1.available()>=2)//if two bytes were received
{
reading = Serial1.read()<<8;//receive high byte (overwrites previous reading) and shift high byte to be high 8 bits
reading |= Serial1.read(); // receive low byte as lower 8 bits
Serial.print(reading); // print the reading
Serial.println("cm");
}
delay(250); // wait a bit since people have to read the output :)
}
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
Result
Open the Serial Monitor in Arduino IDE with baud rate 9600. You should see the distance measured by the SRF02 in centimeters printed continuously.
Additional Information
Command reference link: http://robot-electronics.co.uk/htm/srf02techSer.htm
Was this article helpful?
