Example code AN4545
20/27 DocID026571 Rev 1
7 Example code
Below is example code on how to perform ranging with VL6180X using single shot mode.
The code is based on the STM32 F401 Nucleo board and can be compiled using the mbed
Compiler.
///////////////////////////////////////////////////////////////////
// Beginning of code
///////////////////////////////////////////////////////////////////
#include "mbed.h"
Serial pc(SERIAL_TX, SERIAL_RX); // set-up serial to pc
I2C i2c(I2C_SDA, I2C_SCL); // Set up I²C on the STM32 NUCLEO-401RE
#define addr (0x52) // I²C address of VL6180X shifted by 1 bit
//(0x29 << 1) so the R/W command can be added
///////////////////////////////////////////////////////////////////
// Split 16-bit register address into two bytes and write
// the address + data via I²C
///////////////////////////////////////////////////////////////////
void WriteByte(wchar_t reg,char data) {
char data_write[3];
data_write[0] = (reg >> 8) & 0xFF;; // MSB of register address
data_write[1] = reg & 0xFF; // LSB of register address
data_write[2] = data & 0xFF;
i2c.write(addr, data_write, 3);
}
///////////////////////////////////////////////////////////////////
// Split 16-bit register address into two bytes and write
// required register address to VL6180X and read the data back
///////////////////////////////////////////////////////////////////
char ReadByte(wchar_t reg) {
char data_write[2];
char data_read[1];
data_write
[0] = (reg >> 8) & 0xFF; // MSB of register address
data_write[1] = reg & 0xFF; // LSB of register address
i2c.write(addr, data_write, 2);
i2c.read(addr, data_read, 1);
return data_read[0];
}
///////////////////////////////////////////////////////////////////
// load settings