Example Code for Arduino-Laser Distance Measurement

This project demonstrates how to use the Laser Ranging Sensor (4m) with Arduino to measure distance and view the detected distance value through the serial port. Users can learn how to interface the sensor using the I2C communication protocol and read distance data.

Hardware Preparation

Software Preparation

Wiring Diagram

Connection Diagram

Other Preparation Work

Ensure the Arduino IDE is installed correctly. The Wire library (required for I2C communication) is included with the Arduino IDE by default, so no additional library installation is needed.

Sample Code

#include "Wire.h"
#define address 0x74

uint8_t buf[2] = { 0 };

void setup() {
  Serial.begin(115200);
  Wire.begin();
}

uint8_t dat = 0xB0;
int distance = 0;


void loop() {
  writeReg(0x10, &dat, 1);
  delay(50);
  readReg(0x02, buf, 2);
  distance = buf[0] * 0x100 + buf[1] + 10;
  Serial.print("distance=");
  Serial.print(distance);
  Serial.print("mm");
  Serial.println("\t");
  delay(100);
}

uint8_t readReg(uint8_t reg, const void* pBuf, size_t size) {
  if (pBuf == NULL) {
    Serial.println("pBuf ERROR!! : null pointer");
  }
  uint8_t* _pBuf = (uint8_t*)pBuf;
  Wire.beginTransmission(address);
  Wire.write(®, 1);
  if (Wire.endTransmission() != 0) {
    return 0;
  }
  delay(20);
  Wire.requestFrom(address, (uint8_t)size);
  for (uint16_t i = 0; i < size; i++) {
    _pBuf[i] = Wire.read();
  }
  return size;
}

bool writeReg(uint8_t reg, const void* pBuf, size_t size) {
  if (pBuf == NULL) {
    Serial.println("pBuf ERROR!! : null pointer");
  }
  uint8_t* _pBuf = (uint8_t*)pBuf;
  Wire.beginTransmission(address);
  Wire.write(®, 1);

  for (uint16_t i = 0; i < size; i++) {
    Wire.write(_pBuf[i]);
  }
  if (Wire.endTransmission() != 0) {
    return 0;
  } else {
    return 1;
  }
}

Result

View the distance value detected by the sensor through the serial port.

Result

Was this article helpful?

TOP