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 // include the SoftwareSerial library so we can use it to talk to the LRF #define rxPin 2 // connect to the LRF’s SOUT pin // set up a new serial port void setup() // define pin modes for tx, rx, led pins: // send a U to the LRF so that it will autodetect the speed to communicate with us at (9600) //print splash screen delay(3000); // Print a message to the LCD. void loop() // read what the LRF sends back // set the cursor to column 0, line 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
#include
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
#include
#define txPin 3 // connect to the LRF’s SIN pin thru a 4.7
SoftwareSerial lrfSerial = SoftwareSerial(rxPin, txPin);
{
// set up the LCD’s number of columns and rows:
lcd.begin(16, 4);
pinMode(rxPin, INPUT);
pinMode(txPin, OUTPUT);
// set the data rate for the SoftwareSerial port
lrfSerial.begin(9600);
lrfSerial.print(‘U’);
// the LRF will send back a : and a newline, we just read and ignore those here
lrfSerial.read();
lrfSerial.read();
lcd.print(“Laser”);
lcd.setCursor(0, 1);
lcd.print(” Range”);
lcd.setCursor(0, 2);
lcd.print(” Finder”);
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();
lcd.print(“Distance in mm”);
}
{
// send an R to the LRF telling it to take a measurement
lrfSerial.print(‘R’);
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++;
}
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
lcd.print(lrfData);
delay(200);
int distance = atoi(&lrfData[4]);
//sound the alert if the distance is less than stated
if (distance < 200)
{
tone(5, 440, 200);
delay(200);
}
}