Example Code for Arduino-I2C Mode Distance Measurement

This project uses the TF-NOVA Line Laser LiDAR Sensor in I2C mode to measure the distance to a target object and the current frame rate, then outputs these values via the Arduino’s serial port.

Hardware Preparation

  • DFRduino UNO R3 (or similar) x 1
  • Gravity: IO Expansion Shield for Arduino V7.1 x 1
  • TF-NOVA Line Laser LiDAR Sensor x 1
  • 1.25mm-to-2.54mm Dupont Cable (20cm) x 1

Software Preparation

Wiring Diagram

Other Preparation Work

TF-NOVA switches the output mode through instructions and registers. Ensure the sensor is configured to I2C output mode (refer to the user manual for instructions).

To modify the frame rate, uncomment the following line in the setup() function:

// i2c_writeN(0x26, COM3, 1);

To switch back to UART mode, uncomment the following lines:

// i2c_writeN(0x1E, COM1, 1);
// delay(200);
// i2c_writeN(0x20, COM2, 2);

Sample Code

#include <Wire.h> //I2C library
#define deviceaddress 0x10
uint16_t data;
uint8_t COM[4] = { 0 };
uint8_t COM1[1] = { 0x00 }; //Serial port mode
uint8_t COM2[2] = { 0x01, 0x02 }; //Save, restart
uint8_t COM3[1] = { 0x64 }; //Frame rate value, default 0x64 (100hz)
uint8_t COM4[1] = { 0 };
void i2c_writeN(uint8_t registerAddress, uint8_t *buf, size_t len) {
Wire.beginTransmission(deviceaddress);
Wire.write(registerAddress);
Wire.write(buf, len);
Wire.endTransmission();
}

int16_t i2c_readN(uint8_t registerAddress, uint8_t *buf, size_t len) {
uint8_t i = 0;
Wire.beginTransmission(deviceaddress);
Wire.write(registerAddress);
if (Wire.endTransmission(false) != 0) {
return -1;
}
Wire.requestFrom(deviceaddress, len);
delay(100);
while (Wire.available()) {
buf[i++] = Wire.read();
}
return i;
}

void setup() {
Wire.begin();
Serial.begin(9600);
/*
* Write to register, open when you need to modify the frame rate
*/
// i2c_writeN(0x26, COM3, 1);

/*
* Write register, open when switching to UART mode
*/
// i2c_writeN(0x1E, COM1, 1);
// delay(200);
// i2c_writeN(0x20, COM2, 2);
}

void loop() {
i2c_readN(0x00, COM, 2);
data = COM[1] << 8 | COM[0];
i2c_readN(0x26, COM4, 1);
Serial.print("Distance =");
Serial.print(data);
Serial.print(" cm");
Serial.print(" FPS =");
Serial.print(COM4[0]);
Serial.println(" hz");
delay(100);
}

Result

Print the collected distance value and frame rate value.

Was this article helpful?

TOP