Laser Range Finder Arduino Code

Copy and paste this code into the Arduino compiler and upload it to your Arduino.

Simple LRF Demo
by Roy ELtham and Dino Segovis

// include the library code:

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

// include the SoftwareSerial library so we can use it to talk to the LRF

#define rxPin 2 // connect to the LRF’s SOUT pin
#define txPin 3 // connect to the LRF’s SIN pin thru a 4.7

// set up a new serial port
SoftwareSerial lrfSerial = SoftwareSerial(rxPin, txPin);

void setup()
// set up the LCD’s number of columns and rows:
lcd.begin(16, 4);

// define pin modes for tx, rx, led pins:
pinMode(rxPin, INPUT);
pinMode(txPin, OUTPUT);
// set the data rate for the SoftwareSerial port

// send a U to the LRF so that it will autodetect the speed to communicate with us at (9600)
// the LRF will send back a : and a newline, we just read and ignore those here;;

//print splash screen
lcd.setCursor(0, 1);
lcd.print(” Range”);
lcd.setCursor(0, 2);
lcd.print(” Finder”);

// send an E to the LRF to adjust to current lighting conditions
//tell the user that the LRF is ready
lcd.print(“LRF ready.”);

// Print a message to the LCD.
lcd.print(“Distance in mm”);

void loop()
// send an R to the LRF telling it to take a measurement

// read what the LRF sends back
char lrfData[32];
int offset = 0;
lrfData[0] = 0;
lrfData[offset] =;
// if we get a : character that indicates the end of the read data (and that the LRF is ready for the next command)
if (lrfData[offset] == ‘:’)
lrfData[offset] = 0; // null terminate the string of bytes and break out of the loop

// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);

// print out the data from the LRF (it sends back a string in the form “D = xxxx mm” where xxxx is the distance in milimeters

// delay a tiny bit before the next read

//integer to convert lrfData string to an integer value
int distance = atoi(&lrfData[4]);
//sound the alert if the distance is less than stated
if (distance < 200) { tone(5, 440, 200); delay(200); } }

Leave a Reply