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:
#include

// 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
#include

#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
lrfSerial.begin(9600);

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

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

delay(3000);
lcd.clear();
// send an E to the LRF to adjust to current lighting conditions
lrfSerial.print(‘E’);
delay(1000);
//tell the user that the LRF is ready
lcd.print(“LRF ready.”);
delay(1000);
lcd.clear();

// 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
lrfSerial.print(‘R’);

// read what the LRF sends back
char lrfData[32];
int offset = 0;
lrfData[0] = 0;
while(1)
{
lrfData[offset] = lrfSerial.read();
// 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
break;
}
offset++;
}

// 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
lcd.print(lrfData);

// delay a tiny bit before the next read
delay(200);

//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