SHENG-HEN HSIEH / Mbed 2 deprecated VL53L0X_STM32compatible

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers VL53L0X_SH.cpp Source File

VL53L0X_SH.cpp

00001 // Most of the functionality of this library is based on the VL53L0X API
00002 // provided by ST (STSW-IMG005), and some of the explanatory comments are quoted
00003 // or paraphrased from the API source code, API user manual (UM2039), and the
00004 // VL53L0X datasheet.
00005 
00006 #include <VL53L0X_SH.h>
00007 #include "mbed.h"
00008 // Defines /////////////////////////////////////////////////////////////////////
00009 
00010 // The Arduino two-wire interface uses a 7-bit number for the address,
00011 // and sets the last bit correctly based on reads and writes
00012 #define ADDRESS_DEFAULT 0b0101001
00013 
00014 // Record the current time to check an upcoming timeout against
00015 //#define startTimeout() (timeout_start_ms = millis())
00016 
00017 // Check if timeout is enabled (set to nonzero value) and has expired
00018 //#define checkTimeoutExpired() (io_timeout > 0 && ((short)millis() - timeout_start_ms) > io_timeout)
00019 
00020 // Decode VCSEL (vertical cavity surface emitting laser) pulse period in PCLKs
00021 // from register value
00022 // based on VL53L0X_decode_vcsel_period()
00023 #define decodeVcselPeriod(reg_val)      (((reg_val) + 1) << 1)
00024 
00025 // Encode VCSEL pulse period register value from period in PCLKs
00026 // based on VL53L0X_encode_vcsel_period()
00027 #define encodeVcselPeriod(period_pclks) (((period_pclks) >> 1) - 1)
00028 
00029 // Calculate macro period in *nanoseconds* from VCSEL period in PCLKs
00030 // based on VL53L0X_calc_macro_period_ps()
00031 // PLL_period_ps = 1655; macro_period_vclks = 2304
00032 #define calcMacroPeriod(vcsel_period_pclks) ((((long)2304 * (vcsel_period_pclks) * 1655) + 500) / 1000)
00033 
00034 // Constructors ////////////////////////////////////////////////////////////////
00035 I2C         i2c(D14, D15);      //I2C reg(SDA, SCL)
00036 
00037 VL53L0X::VL53L0X(void)
00038     : address(ADDRESS_DEFAULT)
00039     , io_timeout(0) // no timeout
00040     , did_timeout(false)
00041 {
00042 }
00043 
00044 // Public Methods //////////////////////////////////////////////////////////////
00045 
00046 void VL53L0X::setAddress(char new_addr)
00047 {
00048     writeReg(I2C_SLAVE_DEVICE_ADDRESS, new_addr & 0x7F);
00049     address = new_addr;
00050 }
00051 
00052 // Initialize sensor using sequence based on VL53L0X_DataInit(),
00053 // VL53L0X_StaticInit(), and VL53L0X_PerformRefCalibration().
00054 // This function does not perform reference SPAD calibration
00055 // (VL53L0X_PerformRefSpadManagement()), since the API user manual says that it
00056 // is performed by ST on the bare modules; it seems like that should work well
00057 // enough unless a cover glass is added.
00058 // If io_2v8 (optional) is true or not given, the sensor is configured for 2V8
00059 // mode.
00060 bool VL53L0X::init(bool io_2v8)
00061 {
00062     if (io_2v8) {
00063         writeReg(VHV_CONFIG_PAD_SCL_SDA__EXTSUP_HV,
00064                  readReg(VHV_CONFIG_PAD_SCL_SDA__EXTSUP_HV) | 0x01); // set bit 0
00065     }
00066     // "Set I2C standard mode"
00067     writeReg(0x88, 0x00);
00068     writeReg(0x80, 0x01);
00069     writeReg(0xFF, 0x01);
00070     writeReg(0x00, 0x00);
00071     stop_variable = readReg(0x91);
00072     writeReg(0x00, 0x01);
00073     writeReg(0xFF, 0x00);
00074     writeReg(0x80, 0x00);
00075 
00076     // disable SIGNAL_RATE_MSRC (bit 1) and SIGNAL_RATE_PRE_RANGE (bit 4) limit checks
00077     writeReg(MSRC_CONFIG_CONTROL, readReg(MSRC_CONFIG_CONTROL) | 0x12);
00078 
00079     // set final range signal rate limit to 0.25 MCPS (million counts per second)
00080     setSignalRateLimit(0.25);
00081 
00082     writeReg(SYSTEM_SEQUENCE_CONFIG, 0xFF);
00083 
00084     // VL53L0X_DataInit() end
00085 
00086     // VL53L0X_StaticInit() begin
00087 
00088     char spad_count;
00089     bool spad_type_is_aperture;
00090     if (!getSpadInfo(&spad_count, &spad_type_is_aperture)) {
00091         return false;
00092     }
00093 
00094     // The SPAD map (RefGoodSpadMap) is read by VL53L0X_get_info_from_device() in
00095     // the API, but the same data seems to be more easily readable from
00096     // GLOBAL_CONFIG_SPAD_ENABLES_REF_0 through _6, so read it from there
00097     char ref_spad_map[6];
00098     readMulti(GLOBAL_CONFIG_SPAD_ENABLES_REF_0, ref_spad_map, 6);
00099 
00100     // -- VL53L0X_set_reference_spads() begin (assume NVM values are valid)
00101 
00102     writeReg(0xFF, 0x01);
00103     writeReg(DYNAMIC_SPAD_REF_EN_START_OFFSET, 0x00);
00104     writeReg(DYNAMIC_SPAD_NUM_REQUESTED_REF_SPAD, 0x2C);
00105     writeReg(0xFF, 0x00);
00106     writeReg(GLOBAL_CONFIG_REF_EN_START_SELECT, 0xB4);
00107 
00108     char first_spad_to_enable = spad_type_is_aperture ? 12 : 0; // 12 is the first aperture spad
00109     char spads_enabled = 0;
00110 
00111     for (char i = 0; i < 48; i++) {
00112         if (i < first_spad_to_enable || spads_enabled == spad_count) {
00113             // This bit is lower than the first one that should be enabled, or
00114             // (reference_spad_count) bits have already been enabled, so zero this bit
00115             ref_spad_map[i / 8] &= ~(1 << (i % 8));
00116         } else if ((ref_spad_map[i / 8] >> (i % 8)) & 0x1) {
00117             spads_enabled++;
00118         }
00119     }
00120 
00121     writeMulti(GLOBAL_CONFIG_SPAD_ENABLES_REF_0, ref_spad_map, 6);
00122 
00123     // -- VL53L0X_set_reference_spads() end
00124 
00125     // -- VL53L0X_load_tuning_settings() begin
00126     // DefaultTuningSettings from vl53l0x_tuning.h
00127 
00128     writeReg(0xFF, 0x01);
00129     writeReg(0x00, 0x00);
00130 
00131     writeReg(0xFF, 0x00);
00132     writeReg(0x09, 0x00);
00133     writeReg(0x10, 0x00);
00134     writeReg(0x11, 0x00);
00135 
00136     writeReg(0x24, 0x01);
00137     writeReg(0x25, 0xFF);
00138     writeReg(0x75, 0x00);
00139 
00140     writeReg(0xFF, 0x01);
00141     writeReg(0x4E, 0x2C);
00142     writeReg(0x48, 0x00);
00143     writeReg(0x30, 0x20);
00144 
00145     writeReg(0xFF, 0x00);
00146     writeReg(0x30, 0x09);
00147     writeReg(0x54, 0x00);
00148     writeReg(0x31, 0x04);
00149     writeReg(0x32, 0x03);
00150     writeReg(0x40, 0x83);
00151     writeReg(0x46, 0x25);
00152     writeReg(0x60, 0x00);
00153     writeReg(0x27, 0x00);
00154     writeReg(0x50, 0x06);
00155     writeReg(0x51, 0x00);
00156     writeReg(0x52, 0x96);
00157     writeReg(0x56, 0x08);
00158     writeReg(0x57, 0x30);
00159     writeReg(0x61, 0x00);
00160     writeReg(0x62, 0x00);
00161     writeReg(0x64, 0x00);
00162     writeReg(0x65, 0x00);
00163     writeReg(0x66, 0xA0);
00164 
00165     writeReg(0xFF, 0x01);
00166     writeReg(0x22, 0x32);
00167     writeReg(0x47, 0x14);
00168     writeReg(0x49, 0xFF);
00169     writeReg(0x4A, 0x00);
00170 
00171     writeReg(0xFF, 0x00);
00172     writeReg(0x7A, 0x0A);
00173     writeReg(0x7B, 0x00);
00174     writeReg(0x78, 0x21);
00175 
00176     writeReg(0xFF, 0x01);
00177     writeReg(0x23, 0x34);
00178     writeReg(0x42, 0x00);
00179     writeReg(0x44, 0xFF);
00180     writeReg(0x45, 0x26);
00181     writeReg(0x46, 0x05);
00182     writeReg(0x40, 0x40);
00183     writeReg(0x0E, 0x06);
00184     writeReg(0x20, 0x1A);
00185     writeReg(0x43, 0x40);
00186 
00187     writeReg(0xFF, 0x00);
00188     writeReg(0x34, 0x03);
00189     writeReg(0x35, 0x44);
00190 
00191     writeReg(0xFF, 0x01);
00192     writeReg(0x31, 0x04);
00193     writeReg(0x4B, 0x09);
00194     writeReg(0x4C, 0x05);
00195     writeReg(0x4D, 0x04);
00196 
00197     writeReg(0xFF, 0x00);
00198     writeReg(0x44, 0x00);
00199     writeReg(0x45, 0x20);
00200     writeReg(0x47, 0x08);
00201     writeReg(0x48, 0x28);
00202     writeReg(0x67, 0x00);
00203     writeReg(0x70, 0x04);
00204     writeReg(0x71, 0x01);
00205     writeReg(0x72, 0xFE);
00206     writeReg(0x76, 0x00);
00207     writeReg(0x77, 0x00);
00208 
00209     writeReg(0xFF, 0x01);
00210     writeReg(0x0D, 0x01);
00211 
00212     writeReg(0xFF, 0x00);
00213     writeReg(0x80, 0x01);
00214     writeReg(0x01, 0xF8);
00215 
00216     writeReg(0xFF, 0x01);
00217     writeReg(0x8E, 0x01);
00218     writeReg(0x00, 0x01);
00219     writeReg(0xFF, 0x00);
00220     writeReg(0x80, 0x00);
00221 
00222     // -- VL53L0X_load_tuning_settings() end
00223 
00224     // "Set interrupt config to new sample ready"
00225     // -- VL53L0X_SetGpioConfig() begin
00226 
00227     writeReg(SYSTEM_INTERRUPT_CONFIG_GPIO, 0x04);
00228     writeReg(GPIO_HV_MUX_ACTIVE_HIGH, readReg(GPIO_HV_MUX_ACTIVE_HIGH) & ~0x10); // active low
00229     writeReg(SYSTEM_INTERRUPT_CLEAR, 0x01);
00230 
00231     // -- VL53L0X_SetGpioConfig() end
00232 
00233     measurement_timing_budget_us = getMeasurementTimingBudget();
00234 
00235     // "Disable MSRC and TCC by default"
00236     // MSRC = Minimum Signal Rate Check
00237     // TCC = Target CentreCheck
00238     // -- VL53L0X_SetSequenceStepEnable() begin
00239 
00240     writeReg(SYSTEM_SEQUENCE_CONFIG, 0xE8);
00241 
00242     // -- VL53L0X_SetSequenceStepEnable() end
00243 
00244     // "Recalculate timing budget"
00245     setMeasurementTimingBudget(measurement_timing_budget_us);
00246 
00247     // VL53L0X_StaticInit() end
00248 
00249     // VL53L0X_PerformRefCalibration() begin (VL53L0X_perform_ref_calibration())
00250 
00251     // -- VL53L0X_perform_vhv_calibration() begin
00252 
00253     writeReg(SYSTEM_SEQUENCE_CONFIG, 0x01);
00254     if (!performSingleRefCalibration(0x40)) {
00255         return false;
00256     }
00257 
00258     // -- VL53L0X_perform_vhv_calibration() end
00259 
00260     // -- VL53L0X_perform_phase_calibration() begin
00261 
00262     writeReg(SYSTEM_SEQUENCE_CONFIG, 0x02);
00263     if (!performSingleRefCalibration(0x00)) {
00264         return false;
00265     }
00266 
00267     // -- VL53L0X_perform_phase_calibration() end
00268 
00269     // "restore the previous Sequence Config"
00270     writeReg(SYSTEM_SEQUENCE_CONFIG, 0xE8);
00271 
00272     // VL53L0X_PerformRefCalibration() end
00273 
00274     return true;
00275 }
00276 
00277 // Write an 8-bit register
00278 void VL53L0X::writeReg(char reg, char value)
00279 {
00280     data_w_2[0] = reg;
00281     data_w_2[1] = value;
00282     i2c.write( address<<1 | 0x00, data_w_2, 2, 0);
00283 }
00284 
00285 // Write a 16-bit register
00286 void VL53L0X::writeReg16Bit(char reg, short value)
00287 {
00288     data_w_3[0] = reg;
00289     data_w_3[1] = (value >> 8) & 0xFF;
00290     data_w_3[2] = (value     ) & 0xFF;
00291     i2c.write( address<<1 | 0x00, data_w_3, 3, 0);
00292 }
00293 
00294 // Write a 32-bit register
00295 void VL53L0X::writeReg32Bit(char reg, long value)
00296 {
00297     data_w_5[0] = reg;
00298     data_w_5[1] = (value >> 24) & 0xFF;
00299     data_w_5[2] = (value >> 16) & 0xFF;
00300     data_w_5[3] = (value >>  8) & 0xFF;
00301     data_w_5[4] = (value      ) & 0xFF;
00302     i2c.write( address<<1 | 0x00, data_w_5, 5, 0);
00303 }
00304 
00305 // Read an 8-bit register
00306 char VL53L0X::readReg(char reg)
00307 {
00308     char value[1];
00309     data_r_1[0] = reg;
00310     i2c.write( address<<1 | 0x00, data_r_1, 1, 0);
00311     i2c.read ( address<<1 | 0x01, value, 1, 0);
00312     return value[0];
00313 }
00314 
00315 // Read a 16-bit register
00316 short VL53L0X::readReg16Bit(char reg)
00317 {
00318     short value;
00319     data_r_1[0] = reg;
00320     i2c.write( address<<1 | 0x00, data_r_1, 1, 0);
00321     i2c.read ( address<<1 | 0x01, data_r_2, 2, 0);
00322     value = data_r_2[0] << 8 | data_r_2[1];
00323     return value;
00324 }
00325 
00326 // Read a 32-bit register
00327 long VL53L0X::readReg32Bit(char reg)
00328 {
00329     long value;
00330     data_r_1[0] = reg;
00331     i2c.write( address<<1 | 0x00, data_r_1, 1, 0);
00332     i2c.read ( address<<1 | 0x01, data_r_4, 4, 0);
00333     value  = data_r_4[0] << 24;
00334     value |= data_r_4[1] << 16;
00335     value |= data_r_4[2] <<  8;
00336     value |= data_r_4[3]      ;
00337     return value;
00338 }
00339 
00340 // Write an arbitrary number of bytes from the given array to the sensor,
00341 // starting at the given register
00342 void VL53L0X::writeMulti(char reg, char const * src, char count)
00343 {
00344     char data_w_n[count];
00345     data_w_n[0] = reg;
00346     for(int i=0; i<count; i++) {
00347         data_w_n[i+1] = *(src+i);
00348     }
00349     i2c.write( address<<1 | 0x00, data_w_n, count, 0);
00350 }
00351 
00352 // Read an arbitrary number of bytes from the sensor, starting at the given
00353 // register, into the given array
00354 void VL53L0X::readMulti(char reg, char * dst, char count)
00355 {
00356     char data_r_n[count];
00357     data_r_1[0] = reg;
00358     i2c.write( address<<1 | 0x00, data_r_1, 1, 0);
00359     i2c.read ( address<<1 | 0x01, data_r_n, count, 0);
00360     for(int i=0; i<count; i++) {
00361         *(dst+i) = data_r_n[i];
00362     }
00363 }
00364 
00365 // Set the return signal rate limit check value in units of MCPS (mega counts
00366 // per second). "This represents the amplitude of the signal reflected from the
00367 // target and detected by the device"; setting this limit presumably determines
00368 // the minimum measurement necessary for the sensor to report a valid reading.
00369 // Setting a lower limit increases the potential range of the sensor but also
00370 // seems to increase the likelihood of getting an inaccurate reading because of
00371 // unwanted reflections from objects other than the intended target.
00372 // Defaults to 0.25 MCPS as initialized by the ST API and this library.
00373 bool VL53L0X::setSignalRateLimit(float limit_Mcps)
00374 {
00375     if (limit_Mcps < 0 || limit_Mcps > 511.99f) {
00376         return false;
00377     }
00378 
00379     // Q9.7 fixed point format (9 integer bits, 7 fractional bits)
00380     writeReg16Bit(FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT, limit_Mcps * (1 << 7));
00381     return true;
00382 }
00383 
00384 // Get the return signal rate limit check value in MCPS
00385 float VL53L0X::getSignalRateLimit(void)
00386 {
00387     return (float)readReg16Bit(FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT) / (1 << 7);
00388 }
00389 
00390 // Set the measurement timing budget in microseconds, which is the time allowed
00391 // for one measurement; the ST API and this library take care of splitting the
00392 // timing budget among the sub-steps in the ranging sequence. A longer timing
00393 // budget allows for more accurate measurements. Increasing the budget by a
00394 // factor of N decreases the range measurement standard deviation by a factor of
00395 // sqrt(N). Defaults to about 33 milliseconds; the minimum is 20 ms.
00396 // based on VL53L0X_set_measurement_timing_budget_micro_seconds()
00397 bool VL53L0X::setMeasurementTimingBudget(long budget_us)
00398 {
00399     SequenceStepEnables enables;
00400     SequenceStepTimeouts timeouts;
00401 
00402     short const StartOverhead      = 1320; // note that this is different than the value in get_
00403     short const EndOverhead        = 960;
00404     short const MsrcOverhead       = 660;
00405     short const TccOverhead        = 590;
00406     short const DssOverhead        = 690;
00407     short const PreRangeOverhead   = 660;
00408     short const FinalRangeOverhead = 550;
00409 
00410     long const MinTimingBudget = 20000;
00411 
00412     if (budget_us < MinTimingBudget) {
00413         return false;
00414     }
00415 
00416     long used_budget_us = StartOverhead + EndOverhead;
00417 
00418     getSequenceStepEnables(&enables);
00419     getSequenceStepTimeouts(&enables, &timeouts);
00420 
00421     if (enables.tcc) {
00422         used_budget_us += (timeouts.msrc_dss_tcc_us + TccOverhead);
00423     }
00424 
00425     if (enables.dss) {
00426         used_budget_us += 2 * (timeouts.msrc_dss_tcc_us + DssOverhead);
00427     } else if (enables.msrc) {
00428         used_budget_us += (timeouts.msrc_dss_tcc_us + MsrcOverhead);
00429     }
00430 
00431     if (enables.pre_range) {
00432         used_budget_us += (timeouts.pre_range_us + PreRangeOverhead);
00433     }
00434 
00435     if (enables.final_range) {
00436         used_budget_us += FinalRangeOverhead;
00437 
00438         // "Note that the final range timeout is determined by the timing
00439         // budget and the sum of all other timeouts within the sequence.
00440         // If there is no room for the final range timeout, then an error
00441         // will be set. Otherwise the remaining time will be applied to
00442         // the final range."
00443 
00444         if (used_budget_us > budget_us) {
00445             // "Requested timeout too big."
00446             return false;
00447         }
00448 
00449         long final_range_timeout_us = budget_us - used_budget_us;
00450 
00451         // set_sequence_step_timeout() begin
00452         // (SequenceStepId == VL53L0X_SEQUENCESTEP_FINAL_RANGE)
00453 
00454         // "For the final range timeout, the pre-range timeout
00455         //  must be added. To do this both final and pre-range
00456         //  timeouts must be expressed in macro periods MClks
00457         //  because they have different vcsel periods."
00458 
00459         short final_range_timeout_mclks =
00460             timeoutMicrosecondsToMclks(final_range_timeout_us,
00461                                        timeouts.final_range_vcsel_period_pclks);
00462 
00463         if (enables.pre_range) {
00464             final_range_timeout_mclks += timeouts.pre_range_mclks;
00465         }
00466 
00467         writeReg16Bit(FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI,
00468                       encodeTimeout(final_range_timeout_mclks));
00469 
00470         // set_sequence_step_timeout() end
00471 
00472         measurement_timing_budget_us = budget_us; // store for internal reuse
00473     }
00474     return true;
00475 }
00476 
00477 // Get the measurement timing budget in microseconds
00478 // based on VL53L0X_get_measurement_timing_budget_micro_seconds()
00479 // in us
00480 long VL53L0X::getMeasurementTimingBudget(void)
00481 {
00482     SequenceStepEnables enables;
00483     SequenceStepTimeouts timeouts;
00484 
00485     short const StartOverhead     = 1910; // note that this is different than the value in set_
00486     short const EndOverhead        = 960;
00487     short const MsrcOverhead       = 660;
00488     short const TccOverhead        = 590;
00489     short const DssOverhead        = 690;
00490     short const PreRangeOverhead   = 660;
00491     short const FinalRangeOverhead = 550;
00492 
00493     // "Start and end overhead times always present"
00494     long budget_us = StartOverhead + EndOverhead;
00495 
00496     getSequenceStepEnables(&enables);
00497     getSequenceStepTimeouts(&enables, &timeouts);
00498 
00499     if (enables.tcc) {
00500         budget_us += (timeouts.msrc_dss_tcc_us + TccOverhead);
00501     }
00502 
00503     if (enables.dss) {
00504         budget_us += 2 * (timeouts.msrc_dss_tcc_us + DssOverhead);
00505     } else if (enables.msrc) {
00506         budget_us += (timeouts.msrc_dss_tcc_us + MsrcOverhead);
00507     }
00508 
00509     if (enables.pre_range) {
00510         budget_us += (timeouts.pre_range_us + PreRangeOverhead);
00511     }
00512 
00513     if (enables.final_range) {
00514         budget_us += (timeouts.final_range_us + FinalRangeOverhead);
00515     }
00516 
00517     measurement_timing_budget_us = budget_us; // store for internal reuse
00518     return budget_us;
00519 }
00520 
00521 // Set the VCSEL (vertical cavity surface emitting laser) pulse period for the
00522 // given period type (pre-range or final range) to the given value in PCLKs.
00523 // Longer periods seem to increase the potential range of the sensor.
00524 // Valid values are (even numbers only):
00525 //  pre:  12 to 18 (initialized default: 14)
00526 //  final: 8 to 14 (initialized default: 10)
00527 // based on VL53L0X_set_vcsel_pulse_period()
00528 bool VL53L0X::setVcselPulsePeriod(vcselPeriodType type, char period_pclks)
00529 {
00530     char vcsel_period_reg = encodeVcselPeriod(period_pclks);
00531 
00532     SequenceStepEnables enables;
00533     SequenceStepTimeouts timeouts;
00534 
00535     getSequenceStepEnables(&enables);
00536     getSequenceStepTimeouts(&enables, &timeouts);
00537 
00538     // "Apply specific settings for the requested clock period"
00539     // "Re-calculate and apply timeouts, in macro periods"
00540 
00541     // "When the VCSEL period for the pre or final range is changed,
00542     // the corresponding timeout must be read from the device using
00543     // the current VCSEL period, then the new VCSEL period can be
00544     // applied. The timeout then must be written back to the device
00545     // using the new VCSEL period.
00546     //
00547     // For the MSRC timeout, the same applies - this timeout being
00548     // dependant on the pre-range vcsel period."
00549 
00550 
00551     if (type == VcselPeriodPreRange) {
00552         // "Set phase check limits"
00553         switch (period_pclks) {
00554             case 12:
00555                 writeReg(PRE_RANGE_CONFIG_VALID_PHASE_HIGH, 0x18);
00556                 break;
00557 
00558             case 14:
00559                 writeReg(PRE_RANGE_CONFIG_VALID_PHASE_HIGH, 0x30);
00560                 break;
00561 
00562             case 16:
00563                 writeReg(PRE_RANGE_CONFIG_VALID_PHASE_HIGH, 0x40);
00564                 break;
00565 
00566             case 18:
00567                 writeReg(PRE_RANGE_CONFIG_VALID_PHASE_HIGH, 0x50);
00568                 break;
00569 
00570             default:
00571                 // invalid period
00572                 return false;
00573         }
00574         writeReg(PRE_RANGE_CONFIG_VALID_PHASE_LOW, 0x08);
00575 
00576         // apply new VCSEL period
00577         writeReg(PRE_RANGE_CONFIG_VCSEL_PERIOD, vcsel_period_reg);
00578 
00579         // update timeouts
00580 
00581         // set_sequence_step_timeout() begin
00582         // (SequenceStepId == VL53L0X_SEQUENCESTEP_PRE_RANGE)
00583 
00584         short new_pre_range_timeout_mclks =
00585             timeoutMicrosecondsToMclks(timeouts.pre_range_us, period_pclks);
00586 
00587         writeReg16Bit(PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI,
00588                       encodeTimeout(new_pre_range_timeout_mclks));
00589 
00590         // set_sequence_step_timeout() end
00591 
00592         // set_sequence_step_timeout() begin
00593         // (SequenceStepId == VL53L0X_SEQUENCESTEP_MSRC)
00594 
00595         short new_msrc_timeout_mclks =
00596             timeoutMicrosecondsToMclks(timeouts.msrc_dss_tcc_us, period_pclks);
00597 
00598         writeReg(MSRC_CONFIG_TIMEOUT_MACROP,
00599                  (new_msrc_timeout_mclks > 256) ? 255 : (new_msrc_timeout_mclks - 1));
00600 
00601         // set_sequence_step_timeout() end
00602     } else if (type == VcselPeriodFinalRange) {
00603         switch (period_pclks) {
00604             case 8:
00605                 writeReg(FINAL_RANGE_CONFIG_VALID_PHASE_HIGH, 0x10);
00606                 writeReg(FINAL_RANGE_CONFIG_VALID_PHASE_LOW,  0x08);
00607                 writeReg(GLOBAL_CONFIG_VCSEL_WIDTH, 0x02);
00608                 writeReg(ALGO_PHASECAL_CONFIG_TIMEOUT, 0x0C);
00609                 writeReg(0xFF, 0x01);
00610                 writeReg(ALGO_PHASECAL_LIM, 0x30);
00611                 writeReg(0xFF, 0x00);
00612                 break;
00613 
00614             case 10:
00615                 writeReg(FINAL_RANGE_CONFIG_VALID_PHASE_HIGH, 0x28);
00616                 writeReg(FINAL_RANGE_CONFIG_VALID_PHASE_LOW,  0x08);
00617                 writeReg(GLOBAL_CONFIG_VCSEL_WIDTH, 0x03);
00618                 writeReg(ALGO_PHASECAL_CONFIG_TIMEOUT, 0x09);
00619                 writeReg(0xFF, 0x01);
00620                 writeReg(ALGO_PHASECAL_LIM, 0x20);
00621                 writeReg(0xFF, 0x00);
00622                 break;
00623 
00624             case 12:
00625                 writeReg(FINAL_RANGE_CONFIG_VALID_PHASE_HIGH, 0x38);
00626                 writeReg(FINAL_RANGE_CONFIG_VALID_PHASE_LOW,  0x08);
00627                 writeReg(GLOBAL_CONFIG_VCSEL_WIDTH, 0x03);
00628                 writeReg(ALGO_PHASECAL_CONFIG_TIMEOUT, 0x08);
00629                 writeReg(0xFF, 0x01);
00630                 writeReg(ALGO_PHASECAL_LIM, 0x20);
00631                 writeReg(0xFF, 0x00);
00632                 break;
00633 
00634             case 14:
00635                 writeReg(FINAL_RANGE_CONFIG_VALID_PHASE_HIGH, 0x48);
00636                 writeReg(FINAL_RANGE_CONFIG_VALID_PHASE_LOW,  0x08);
00637                 writeReg(GLOBAL_CONFIG_VCSEL_WIDTH, 0x03);
00638                 writeReg(ALGO_PHASECAL_CONFIG_TIMEOUT, 0x07);
00639                 writeReg(0xFF, 0x01);
00640                 writeReg(ALGO_PHASECAL_LIM, 0x20);
00641                 writeReg(0xFF, 0x00);
00642                 break;
00643 
00644             default:
00645                 // invalid period
00646                 return false;
00647         }
00648 
00649         // apply new VCSEL period
00650         writeReg(FINAL_RANGE_CONFIG_VCSEL_PERIOD, vcsel_period_reg);
00651 
00652         // update timeouts
00653 
00654         // set_sequence_step_timeout() begin
00655         // (SequenceStepId == VL53L0X_SEQUENCESTEP_FINAL_RANGE)
00656 
00657         // "For the final range timeout, the pre-range timeout
00658         //  must be added. To do this both final and pre-range
00659         //  timeouts must be expressed in macro periods MClks
00660         //  because they have different vcsel periods."
00661 
00662         short new_final_range_timeout_mclks =
00663             timeoutMicrosecondsToMclks(timeouts.final_range_us, period_pclks);
00664 
00665         if (enables.pre_range) {
00666             new_final_range_timeout_mclks += timeouts.pre_range_mclks;
00667         }
00668 
00669         writeReg16Bit(FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI,
00670                       encodeTimeout(new_final_range_timeout_mclks));
00671 
00672         // set_sequence_step_timeout end
00673     } else {
00674         // invalid type
00675         return false;
00676     }
00677 
00678     // "Finally, the timing budget must be re-applied"
00679 
00680     setMeasurementTimingBudget(measurement_timing_budget_us);
00681 
00682     // "Perform the phase calibration. This is needed after changing on vcsel period."
00683     // VL53L0X_perform_phase_calibration() begin
00684 
00685     char sequence_config = readReg(SYSTEM_SEQUENCE_CONFIG);
00686     writeReg(SYSTEM_SEQUENCE_CONFIG, 0x02);
00687     performSingleRefCalibration(0x0);
00688     writeReg(SYSTEM_SEQUENCE_CONFIG, sequence_config);
00689 
00690     // VL53L0X_perform_phase_calibration() end
00691 
00692     return true;
00693 }
00694 
00695 // Get the VCSEL pulse period in PCLKs for the given period type.
00696 // based on VL53L0X_get_vcsel_pulse_period()
00697 char VL53L0X::getVcselPulsePeriod(vcselPeriodType type)
00698 {
00699     if (type == VcselPeriodPreRange) {
00700         return decodeVcselPeriod(readReg(PRE_RANGE_CONFIG_VCSEL_PERIOD));
00701     } else if (type == VcselPeriodFinalRange) {
00702         return decodeVcselPeriod(readReg(FINAL_RANGE_CONFIG_VCSEL_PERIOD));
00703     } else {
00704         return 255;
00705     }
00706 }
00707 
00708 // Start continuous ranging measurements. If period_ms (optional) is 0 or not
00709 // given, continuous back-to-back mode is used (the sensor takes measurements as
00710 // often as possible); otherwise, continuous timed mode is used, with the given
00711 // inter-measurement period in milliseconds determining how often the sensor
00712 // takes a measurement.
00713 // based on VL53L0X_StartMeasurement()
00714 void VL53L0X::startContinuous(long period_ms)
00715 {
00716     writeReg(0x80, 0x01);
00717     writeReg(0xFF, 0x01);
00718     writeReg(0x00, 0x00);
00719     writeReg(0x91, stop_variable);
00720     writeReg(0x00, 0x01);
00721     writeReg(0xFF, 0x00);
00722     writeReg(0x80, 0x00);
00723 
00724     if (period_ms != 0) {
00725         // continuous timed mode
00726 
00727         // VL53L0X_SetInterMeasurementPeriodMilliSeconds() begin
00728 
00729         short osc_calibrate_val = readReg16Bit(OSC_CALIBRATE_VAL);
00730 
00731         if (osc_calibrate_val != 0) {
00732             period_ms *= osc_calibrate_val;
00733         }
00734 
00735         writeReg32Bit(SYSTEM_INTERMEASUREMENT_PERIOD, period_ms);
00736 
00737         // VL53L0X_SetInterMeasurementPeriodMilliSeconds() end
00738 
00739         writeReg(SYSRANGE_START, 0x04); // VL53L0X_REG_SYSRANGE_MODE_TIMED
00740     } else {
00741         // continuous back-to-back mode
00742         writeReg(SYSRANGE_START, 0x02); // VL53L0X_REG_SYSRANGE_MODE_BACKTOBACK
00743     }
00744 }
00745 
00746 // Stop continuous measurements
00747 // based on VL53L0X_StopMeasurement()
00748 void VL53L0X::stopContinuous(void)
00749 {
00750     writeReg(SYSRANGE_START, 0x01); // VL53L0X_REG_SYSRANGE_MODE_SINGLESHOT
00751 
00752     writeReg(0xFF, 0x01);
00753     writeReg(0x00, 0x00);
00754     writeReg(0x91, 0x00);
00755     writeReg(0x00, 0x01);
00756     writeReg(0xFF, 0x00);
00757 }
00758 
00759 // Returns a range reading in millimeters when continuous mode is active
00760 // (readRangeSingleMillimeters() also calls this function after starting a
00761 // single-shot range measurement)
00762 short VL53L0X::readRangeContinuousMillimeters(void)
00763 {
00764 //    startTimeout();
00765 //    while ((readReg(RESULT_INTERRUPT_STATUS) & 0x07) == 0) {
00766 //        if (checkTimeoutExpired()) {
00767 //            did_timeout = true;
00768 //            return 32767;
00769 //        }
00770 //    }
00771 
00772     // assumptions: Linearity Corrective Gain is 1000 (default);
00773     // fractional ranging is not enabled
00774     short range = readReg16Bit(RESULT_RANGE_STATUS + 10);
00775 
00776     writeReg(SYSTEM_INTERRUPT_CLEAR, 0x01);
00777 
00778     return range;
00779 }
00780 
00781 // Performs a single-shot range measurement and returns the reading in
00782 // millimeters
00783 // based on VL53L0X_PerformSingleRangingMeasurement()
00784 short VL53L0X::readRangeSingleMillimeters(void)
00785 {
00786     writeReg(0x80, 0x01);
00787     writeReg(0xFF, 0x01);
00788     writeReg(0x00, 0x00);
00789     writeReg(0x91, stop_variable);
00790     writeReg(0x00, 0x01);
00791     writeReg(0xFF, 0x00);
00792     writeReg(0x80, 0x00);
00793 
00794     writeReg(SYSRANGE_START, 0x01);
00795 
00796     // "Wait until start bit has been cleared"
00797 //    startTimeout();
00798 //    while (readReg(SYSRANGE_START) & 0x01) {
00799 //        if (checkTimeoutExpired()) {
00800 //            did_timeout = true;
00801 //            return 32767;
00802 //        }
00803 //    }
00804 
00805     return readRangeContinuousMillimeters();
00806 }
00807 
00808 // Did a timeout occur in one of the read functions since the last call to
00809 // timeoutOccurred()?
00810 bool VL53L0X::timeoutOccurred()
00811 {
00812     bool tmp = did_timeout;
00813     did_timeout = false;
00814     return tmp;
00815 }
00816 
00817 // Private Methods /////////////////////////////////////////////////////////////
00818 
00819 // Get reference SPAD (single photon avalanche diode) count and type
00820 // based on VL53L0X_get_info_from_device(),
00821 // but only gets reference SPAD count and type
00822 bool VL53L0X::getSpadInfo(char * count, bool * type_is_aperture)
00823 {
00824     char tmp;
00825 
00826     writeReg(0x80, 0x01);
00827     writeReg(0xFF, 0x01);
00828     writeReg(0x00, 0x00);
00829 
00830     writeReg(0xFF, 0x06);
00831     writeReg(0x83, readReg(0x83) | 0x04);
00832     writeReg(0xFF, 0x07);
00833     writeReg(0x81, 0x01);
00834 
00835     writeReg(0x80, 0x01);
00836 
00837     writeReg(0x94, 0x6b);
00838     writeReg(0x83, 0x00);
00839 //    startTimeout();
00840     wait_ms(1);
00841     while (readReg(0x83) == 0x00) {
00842 //        if (checkTimeoutExpired()) {
00843 //            return false;
00844 //        }
00845     }
00846     writeReg(0x83, 0x01);
00847     tmp = readReg(0x92);
00848 
00849     *count = tmp & 0x7f;
00850     *type_is_aperture = (tmp >> 7) & 0x01;
00851 
00852     writeReg(0x81, 0x00);
00853     writeReg(0xFF, 0x06);
00854     writeReg(0x83, readReg( 0x83  & ~0x04));
00855     writeReg(0xFF, 0x01);
00856     writeReg(0x00, 0x01);
00857 
00858     writeReg(0xFF, 0x00);
00859     writeReg(0x80, 0x00);
00860 
00861     return true;
00862 }
00863 
00864 // Get sequence step enables
00865 // based on VL53L0X_GetSequenceStepEnables()
00866 void VL53L0X::getSequenceStepEnables(SequenceStepEnables * enables)
00867 {
00868     char sequence_config = readReg(SYSTEM_SEQUENCE_CONFIG);
00869 
00870     enables->tcc          = (sequence_config >> 4) & 0x1;
00871     enables->dss          = (sequence_config >> 3) & 0x1;
00872     enables->msrc         = (sequence_config >> 2) & 0x1;
00873     enables->pre_range    = (sequence_config >> 6) & 0x1;
00874     enables->final_range  = (sequence_config >> 7) & 0x1;
00875 }
00876 
00877 // Get sequence step timeouts
00878 // based on get_sequence_step_timeout(),
00879 // but gets all timeouts instead of just the requested one, and also stores
00880 // intermediate values
00881 void VL53L0X::getSequenceStepTimeouts(SequenceStepEnables const * enables, SequenceStepTimeouts * timeouts)
00882 {
00883     timeouts->pre_range_vcsel_period_pclks = getVcselPulsePeriod(VcselPeriodPreRange);
00884 
00885     timeouts->msrc_dss_tcc_mclks = readReg(MSRC_CONFIG_TIMEOUT_MACROP) + 1;
00886     timeouts->msrc_dss_tcc_us =
00887         timeoutMclksToMicroseconds(timeouts->msrc_dss_tcc_mclks,
00888                                    timeouts->pre_range_vcsel_period_pclks);
00889 
00890     timeouts->pre_range_mclks =
00891         decodeTimeout(readReg16Bit(PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI));
00892     timeouts->pre_range_us =
00893         timeoutMclksToMicroseconds(timeouts->pre_range_mclks,
00894                                    timeouts->pre_range_vcsel_period_pclks);
00895 
00896     timeouts->final_range_vcsel_period_pclks = getVcselPulsePeriod(VcselPeriodFinalRange);
00897 
00898     timeouts->final_range_mclks =
00899         decodeTimeout(readReg16Bit(FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI));
00900 
00901     if (enables->pre_range) {
00902         timeouts->final_range_mclks -= timeouts->pre_range_mclks;
00903     }
00904 
00905     timeouts->final_range_us =
00906         timeoutMclksToMicroseconds(timeouts->final_range_mclks,
00907                                    timeouts->final_range_vcsel_period_pclks);
00908 }
00909 
00910 // Decode sequence step timeout in MCLKs from register value
00911 // based on VL53L0X_decode_timeout()
00912 // Note: the original function returned a long, but the return value is
00913 // always stored in a short.
00914 short VL53L0X::decodeTimeout(short reg_val)
00915 {
00916     // format: "(LSByte * 2^MSByte) + 1"
00917     return (short)((reg_val & 0x00FF) <<
00918                    (short)((reg_val & 0xFF00) >> 8)) + 1;
00919 }
00920 
00921 // Encode sequence step timeout register value from timeout in MCLKs
00922 // based on VL53L0X_encode_timeout()
00923 // Note: the original function took a short, but the argument passed to it
00924 // is always a short.
00925 short VL53L0X::encodeTimeout(short timeout_mclks)
00926 {
00927     // format: "(LSByte * 2^MSByte) + 1"
00928 
00929     long ls_byte = 0;
00930     short ms_byte = 0;
00931 
00932     if (timeout_mclks > 0) {
00933         ls_byte = timeout_mclks - 1;
00934 
00935         while ((ls_byte & 0xFFFFFF00) > 0) {
00936             ls_byte >>= 1;
00937             ms_byte++;
00938         }
00939 
00940         return (ms_byte << 8) | (ls_byte & 0xFF);
00941     } else {
00942         return 0;
00943     }
00944 }
00945 
00946 // Convert sequence step timeout from MCLKs to microseconds with given VCSEL period in PCLKs
00947 // based on VL53L0X_calc_timeout_us()
00948 long VL53L0X::timeoutMclksToMicroseconds(short timeout_period_mclks, char vcsel_period_pclks)
00949 {
00950     long macro_period_ns = calcMacroPeriod(vcsel_period_pclks);
00951 
00952     return ((timeout_period_mclks * macro_period_ns) + (macro_period_ns / 2)) / 1000;
00953 }
00954 
00955 // Convert sequence step timeout from microseconds to MCLKs with given VCSEL period in PCLKs
00956 // based on VL53L0X_calc_timeout_mclks()
00957 long VL53L0X::timeoutMicrosecondsToMclks(long timeout_period_us, char vcsel_period_pclks)
00958 {
00959     long macro_period_ns = calcMacroPeriod(vcsel_period_pclks);
00960 
00961     return (((timeout_period_us * 1000) + (macro_period_ns / 2)) / macro_period_ns);
00962 }
00963 
00964 
00965 // based on VL53L0X_perform_single_ref_calibration()
00966 bool VL53L0X::performSingleRefCalibration(char vhv_init_byte)
00967 {
00968     writeReg(SYSRANGE_START, 0x01 | vhv_init_byte); // VL53L0X_REG_SYSRANGE_MODE_START_STOP
00969 
00970 //    startTimeout();
00971     wait_ms(1);
00972     while ((readReg(RESULT_INTERRUPT_STATUS) & 0x07) == 0) {
00973 //        if (checkTimeoutExpired()) {
00974 //            return false;
00975 //        }
00976     }
00977 
00978     writeReg(SYSTEM_INTERRUPT_CLEAR, 0x01);
00979 
00980     writeReg(SYSRANGE_START, 0x00);
00981 
00982     return true;
00983 }