Example Code for Arduino-I2C Ranging
This article provides example code for Arduino-I2C ranging, detailing how to print collected distance and frame rate values, making it an essential read for those interested in sensor integration and electronics projects.
Hardware Preparation
- DFRduino UNO R3 (or similar) x 1
- Gravity: IO Expansion Shield for Arduino V7.1 x1
- TFS20-L LiDAR x1
- 0.8mm-to-2.54mm Dupont Cable (20cm) x1
Software Preparation
- Arduino IDE
- Download the DFRobot_TFmini library, which is a general library for TF series single-point LiDAR.
Wiring Diagram
Leave pin 5 of TFS20-L unconnected for I2C mode. Adjust the VCC voltage of Arduino UNO R3 development board to 3.3V. Do not use 5V power supply for TFS20-L. It will get hot if powered by 5V for a long time.
Other Preparation Work
Adjust the VCC voltage of Arduino UNO R3 development board to 3.3V. Do not use 5V power supply for TFS20-L. It will get hot if powered by 5V for a long time.
Sample Code
#include <Wire.h>
#define deviceaddress 0x10
uint16_t data;
uint8_t COM[4] = { 0 };
uint8_t COM1[1] = { 0 };
uint8_t COM2[1] = { 0x64 }; //Frame rate value, default 100hz
uint8_t COM3[1] = { 0x01}; //Save register
uint8_t COM4[1] = { 0x02}; //Restart register
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);
/*
* Modify and save registers, open when you need to modify the frame rate
*/
// i2c_writeN(0x26, COM2, 1);
// delay(200);
// i2c_writeN(0x20, COM3, 1);
// delay(200);
// i2c_writeN(0x21, COM4, 1);
}
void loop() {
i2c_readN(0x00, COM, 2);
data = COM[1] << 8 | COM[0];
delay(200);
i2c_readN(0x26, COM1, 1);
Serial.print("Distance=");
Serial.print(data);
Serial.print("cm");
Serial.print(" FPS =");
Serial.print(COM1[0]);
Serial.println("hz");
delay(100);
}
Result
Print the collected distance value and frame rate value.
Was this article helpful?
