-
Notifications
You must be signed in to change notification settings - Fork 3
/
vl53l0x.go
1707 lines (1464 loc) · 45.8 KB
/
vl53l0x.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//--------------------------------------------------------------------------------------------------
//
// This code is an adaptation and translation of well-formed C++ library to GOLANG for the distance
// measure sensor's family VL53L0X taken from https://github.com/pololu/vl53l0x-arduino:
// https://github.com/pololu/vl53l0x-arduino/blob/master/VL53L0X.cpp
// https://github.com/pololu/vl53l0x-arduino/blob/master/VL53L0X.h
//
// Some portion of code taken from Adafruit https://github.com/adafruit/Adafruit_VL53L0X:
// https://github.com/adafruit/Adafruit_VL53L0X/blob/master/src/core/src/vl53l0x_api.cpp
// https://github.com/adafruit/Adafruit_VL53L0X/blob/master/src/vl53l0x_def.h
// https://github.com/adafruit/Adafruit_VL53L0X/blob/master/src/vl53l0x_device.h
//
//
// Copyright (c) 2018 Denis Dyakov
// Copyright (c) 2017 Pololu Corporation
// Copyright (c) 2016 Adafruit Industries
// Copyright (c) 2016 STMicroelectronics International N.V.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
// associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial
// portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//--------------------------------------------------------------------------------------------------
package vl53l0x
import (
"errors"
"time"
i2c "github.com/d2r2/go-i2c"
"github.com/davecgh/go-spew/spew"
)
// Registers from sensor hardware.
const (
SYSRANGE_START = 0x00
SYSTEM_THRESH_HIGH = 0x0C
SYSTEM_THRESH_LOW = 0x0E
SYSTEM_SEQUENCE_CONFIG = 0x01
SYSTEM_RANGE_CONFIG = 0x09
SYSTEM_INTERMEASUREMENT_PERIOD = 0x04
SYSTEM_INTERRUPT_CONFIG_GPIO = 0x0A
GPIO_HV_MUX_ACTIVE_HIGH = 0x84
SYSTEM_INTERRUPT_CLEAR = 0x0B
RESULT_INTERRUPT_STATUS = 0x13
RESULT_RANGE_STATUS = 0x14
RESULT_CORE_AMBIENT_WINDOW_EVENTS_RTN = 0xBC
RESULT_CORE_RANGING_TOTAL_EVENTS_RTN = 0xC0
RESULT_CORE_AMBIENT_WINDOW_EVENTS_REF = 0xD0
RESULT_CORE_RANGING_TOTAL_EVENTS_REF = 0xD4
RESULT_PEAK_SIGNAL_RATE_REF = 0xB6
ALGO_PART_TO_PART_RANGE_OFFSET_MM = 0x28
I2C_SLAVE_DEVICE_ADDRESS = 0x8A
MSRC_CONFIG_CONTROL = 0x60
PRE_RANGE_CONFIG_MIN_SNR = 0x27
PRE_RANGE_CONFIG_VALID_PHASE_LOW = 0x56
PRE_RANGE_CONFIG_VALID_PHASE_HIGH = 0x57
PRE_RANGE_MIN_COUNT_RATE_RTN_LIMIT = 0x64
FINAL_RANGE_CONFIG_MIN_SNR = 0x67
FINAL_RANGE_CONFIG_VALID_PHASE_LOW = 0x47
FINAL_RANGE_CONFIG_VALID_PHASE_HIGH = 0x48
FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT = 0x44
PRE_RANGE_CONFIG_SIGMA_THRESH_HI = 0x61
PRE_RANGE_CONFIG_SIGMA_THRESH_LO = 0x62
PRE_RANGE_CONFIG_VCSEL_PERIOD = 0x50
PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI = 0x51
PRE_RANGE_CONFIG_TIMEOUT_MACROP_LO = 0x52
SYSTEM_HISTOGRAM_BIN = 0x81
HISTOGRAM_CONFIG_INITIAL_PHASE_SELECT = 0x33
HISTOGRAM_CONFIG_READOUT_CTRL = 0x55
FINAL_RANGE_CONFIG_VCSEL_PERIOD = 0x70
FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI = 0x71
FINAL_RANGE_CONFIG_TIMEOUT_MACROP_LO = 0x72
CROSSTALK_COMPENSATION_PEAK_RATE_MCPS = 0x20
MSRC_CONFIG_TIMEOUT_MACROP = 0x46
SOFT_RESET_GO2_SOFT_RESET_N = 0xBF
IDENTIFICATION_MODEL_ID = 0xC0
IDENTIFICATION_REVISION_ID = 0xC2
OSC_CALIBRATE_VAL = 0xF8
GLOBAL_CONFIG_VCSEL_WIDTH = 0x32
GLOBAL_CONFIG_SPAD_ENABLES_REF_0 = 0xB0
GLOBAL_CONFIG_SPAD_ENABLES_REF_1 = 0xB1
GLOBAL_CONFIG_SPAD_ENABLES_REF_2 = 0xB2
GLOBAL_CONFIG_SPAD_ENABLES_REF_3 = 0xB3
GLOBAL_CONFIG_SPAD_ENABLES_REF_4 = 0xB4
GLOBAL_CONFIG_SPAD_ENABLES_REF_5 = 0xB5
GLOBAL_CONFIG_REF_EN_START_SELECT = 0xB6
DYNAMIC_SPAD_NUM_REQUESTED_REF_SPAD = 0x4E
DYNAMIC_SPAD_REF_EN_START_OFFSET = 0x4F
POWER_MANAGEMENT_GO1_POWER_FORCE = 0x80
VHV_CONFIG_PAD_SCL_SDA__EXTSUP_HV = 0x89
ALGO_PHASECAL_LIM = 0x30
ALGO_PHASECAL_CONFIG_TIMEOUT = 0x30
)
// VcselPeriodType is a type of VCSEL (vertical cavity surface emitting laser) pulse period.
type VcselPeriodType int
const (
// pre-range pulse period
VcselPeriodPreRange VcselPeriodType = iota + 1
// final range pulse period
VcselPeriodFinalRange
)
// RangeSpec used to configure sensor for expected distance to measure.
type RangeSpec int
const (
// Signal rate limit = 0.25 MCPS, laser pulse periods = (14, 10).
RegularRange RangeSpec = iota + 1
// Signal rate limit = 0.10 MCPS, laser pulse periods = (18, 14).
// Use "long range" mode only when "regular" can't detect distance
// (returned distance value is 8190 mm or more). It's ordinary
// happens, when distance exceed something about a meter.
LongRange
)
// String implement Stringer interface.
func (v RangeSpec) String() string {
switch v {
case RegularRange:
return "RegularRange"
case LongRange:
return "LongRange"
default:
return "<unknown>"
}
}
// SpeedAccuracySpec used to configure sensor for accuracy/measure time.
// It's clear that to improve accuracy, you should increase
// measure time.
type SpeedAccuracySpec int
const (
// HighSpeed distance measurement takes 20 ms.
HighSpeed SpeedAccuracySpec = iota + 1
// RegularAccuracy distance measurement takes 33 ms.
RegularAccuracy
// GoodAccuracy distance measurement takes 66 ms.
GoodAccuracy
// HighAccuracy distance measurement takes 100 ms.
HighAccuracy
// HighestAccuracy distance measurement takes 200 ms.
HighestAccuracy
)
// String implement Stringer interface.
func (v SpeedAccuracySpec) String() string {
switch v {
case HighSpeed:
return "HighSpeed"
case RegularAccuracy:
return "RegularAccuracy"
case GoodAccuracy:
return "GoodAccuracy"
case HighAccuracy:
return "HighAccuracy"
case HighestAccuracy:
return "HighestAccuracy"
default:
return "<unknown>"
}
}
// Vl53l0x contains sensor data and corresponding methods.
type Vl53l0x struct {
// read by init and used when starting measurement;
// is StopVariable field of VL53L0X_DevData_t structure in API
stopVariable uint8
// total measurement timing budget in microseconds
measurementTimingBudgetUsec uint32
// default timeout value
ioTimeout time.Duration
}
// NewVl53l0x creates sensor instance.
func NewVl53l0x() *Vl53l0x {
v := &Vl53l0x{}
return v
}
// Config configure sensor expected distance range and time to make a measurement.
func (v *Vl53l0x) Config(i2c *i2c.I2C, rng RangeSpec, speed SpeedAccuracySpec) error {
lg.Debug("Start config")
switch rng {
case RegularRange:
// default is 0.25 MCPS
err := v.SetSignalRateLimit(i2c, 0.25)
if err != nil {
return err
}
// defaults are 14 and 10 PCLKs)
err = v.SetVcselPulsePeriod(i2c, VcselPeriodPreRange, 14)
if err != nil {
return err
}
err = v.SetVcselPulsePeriod(i2c, VcselPeriodFinalRange, 10)
if err != nil {
return err
}
case LongRange:
// lower the return signal rate limit (default is 0.25 MCPS)
err := v.SetSignalRateLimit(i2c, 0.1)
if err != nil {
return err
}
// increase laser pulse periods (defaults are 14 and 10 PCLKs)
err = v.SetVcselPulsePeriod(i2c, VcselPeriodPreRange, 18)
if err != nil {
return err
}
err = v.SetVcselPulsePeriod(i2c, VcselPeriodFinalRange, 14)
if err != nil {
return err
}
}
switch speed {
case HighSpeed:
// reduce timing budget to 20 ms (default is about 33 ms)
err := v.SetMeasurementTimingBudget(i2c, 20000)
if err != nil {
return err
}
case RegularAccuracy:
// default is about 33 ms
err := v.SetMeasurementTimingBudget(i2c, 33000)
if err != nil {
return err
}
case GoodAccuracy:
// increase timing budget to 66 ms
err := v.SetMeasurementTimingBudget(i2c, 66000)
if err != nil {
return err
}
case HighAccuracy:
// increase timing budget to 100 ms
err := v.SetMeasurementTimingBudget(i2c, 100000)
if err != nil {
return err
}
case HighestAccuracy:
// increase timing budget to 200 ms
err := v.SetMeasurementTimingBudget(i2c, 200000)
if err != nil {
return err
}
}
lg.Debug("End config")
return nil
}
// Reset soft-reset the sensor.
// Based on VL53L0X_ResetDevice().
func (v *Vl53l0x) Reset(i2c *i2c.I2C) error {
// Set reset bit
lg.Debug("Set reset bit")
err := v.writeRegU8(i2c, SOFT_RESET_GO2_SOFT_RESET_N, 0x00)
if err != nil {
return err
}
// Wait for some time
err = v.waitUntilOrTimeout(i2c, IDENTIFICATION_MODEL_ID,
func(checkReg byte, err error) (bool, error) {
return checkReg == 0, err
})
if err != nil {
return err
}
// Release reset
lg.Debug("Release reset bit")
err = v.writeRegU8(i2c, SOFT_RESET_GO2_SOFT_RESET_N, 0x01)
if err != nil {
return err
}
// Wait for some time
err = v.waitUntilOrTimeout(i2c, IDENTIFICATION_MODEL_ID,
func(checkReg byte, err error) (bool, error) {
// Skip error like "read /dev/i2c-x: no such device or address"
// for a while, because sensor in reboot has temporary
// no connection to I2C-bus. So, that is why we are
// returning nil instead of err, suppressing this.
return checkReg != 0, nil
})
if err != nil {
return err
}
return nil
}
// GetProductMinorRevision takes revision from sensor hardware.
// Based on VL53L0X_GetProductRevision.
func (v *Vl53l0x) GetProductMinorRevision(i2c *i2c.I2C) (byte, error) {
u8, err := v.readRegU8(i2c, IDENTIFICATION_REVISION_ID)
if err != nil {
return 0, err
}
return (u8 & 0xF0) >> 4, nil
}
// SetAddress change default address of sensor and reopen I2C-connection.
func (v *Vl53l0x) SetAddress(i2cRef **i2c.I2C, newAddr byte) error {
err := v.writeRegU8(*i2cRef, I2C_SLAVE_DEVICE_ADDRESS, newAddr&0x7F)
if err != nil {
return err
}
*i2cRef, err = i2c.NewI2C(newAddr, (*i2cRef).GetBus())
return err
}
// Init initialize sensor using sequence based on VL53L0X_DataInit(),
// VL53L0X_StaticInit(), and VL53L0X_PerformRefCalibration().
// This function does not perform reference SPAD calibration
// (VL53L0X_PerformRefSpadManagement()), since the API user manual says that it
// is performed by ST on the bare modules; it seems like that should work well
// enough unless a cover glass is added.
func (v *Vl53l0x) Init(i2c *i2c.I2C) error {
v.setTimeout(time.Millisecond * 1000)
// VL53L0X_DataInit() begin
// "Set I2C standard mode"
err := v.writeRegU8(i2c, 0x88, 0x00)
if err != nil {
return err
}
err = v.writeRegValues(i2c, []RegBytePair{
{Reg: 0x80, Value: 0x01},
{Reg: 0xFF, Value: 0x01},
{Reg: 0x00, Value: 0x00},
}...)
if err != nil {
return err
}
v.stopVariable, err = v.readRegU8(i2c, 0x91)
if err != nil {
return err
}
err = v.writeRegValues(i2c, []RegBytePair{
{Reg: 0x00, Value: 0x01},
{Reg: 0xFF, Value: 0x00},
{Reg: 0x80, Value: 0x00},
}...)
if err != nil {
return err
}
// disable SIGNAL_RATE_MSRC (bit 1) and SIGNAL_RATE_PRE_RANGE (bit 4) limit checks
u8, err := v.readRegU8(i2c, MSRC_CONFIG_CONTROL)
if err != nil {
return err
}
err = v.writeRegU8(i2c, MSRC_CONFIG_CONTROL, u8|0x12)
if err != nil {
return err
}
// set final range signal rate limit to 0.25 MCPS (million counts per second)
err = v.SetSignalRateLimit(i2c, 0.25)
if err != nil {
return err
}
err = v.writeRegU8(i2c, SYSTEM_SEQUENCE_CONFIG, 0xFF)
if err != nil {
return err
}
// VL53L0X_DataInit() end
// VL53L0X_StaticInit() begin
spadInfo, err := v.getSpadInfo(i2c)
if err != nil {
return err
}
// The SPAD map (RefGoodSpadMap) is read by VL53L0X_get_info_from_device() in
// the API, but the same data seems to be more easily readable from
// GLOBAL_CONFIG_SPAD_ENABLES_REF_0 through _6, so read it from there
spadMap := make([]byte, 6)
err = v.readRegBytes(i2c, GLOBAL_CONFIG_SPAD_ENABLES_REF_0, spadMap)
if err != nil {
return err
}
// -- VL53L0X_set_reference_spads() begin (assume NVM values are valid)
err = v.writeRegValues(i2c, []RegBytePair{
{Reg: 0xFF, Value: 0x01},
{Reg: DYNAMIC_SPAD_REF_EN_START_OFFSET, Value: 0x00},
{Reg: DYNAMIC_SPAD_NUM_REQUESTED_REF_SPAD, Value: 0x2C},
{Reg: 0xFF, Value: 0x00},
{Reg: GLOBAL_CONFIG_REF_EN_START_SELECT, Value: 0xB4},
}...)
if err != nil {
return err
}
var firstSpadToEnable byte
if spadInfo.TypeIsAperture {
// 12 is the first aperture spad
firstSpadToEnable = 12
}
var spadsEnabled byte
var i byte
for i = 0; i < 48; i++ {
if i < firstSpadToEnable || spadsEnabled == spadInfo.Count {
// This bit is lower than the first one that should be enabled, or
// (reference_spad_count) bits have already been enabled, so zero this bit
spadMap[i/8] &= ^(1 << (i % 8))
} else if (spadMap[i/8]>>(i%8))&0x1 != 0 {
spadsEnabled++
}
}
err = v.writeBytes(i2c, GLOBAL_CONFIG_SPAD_ENABLES_REF_0, spadMap)
if err != nil {
return err
}
// -- VL53L0X_set_reference_spads() end
// -- VL53L0X_load_tuning_settings() begin
// DefaultTuningSettings from vl53l0x_tuning.h
err = v.writeRegValues(i2c, []RegBytePair{
{Reg: 0xFF, Value: 0x01},
{Reg: 0x00, Value: 0x00},
}...)
if err != nil {
return err
}
err = v.writeRegValues(i2c, []RegBytePair{
{Reg: 0xFF, Value: 0x00},
{Reg: 0x09, Value: 0x00},
{Reg: 0x10, Value: 0x00},
{Reg: 0x11, Value: 0x00},
}...)
if err != nil {
return err
}
err = v.writeRegValues(i2c, []RegBytePair{
{Reg: 0x24, Value: 0x01},
{Reg: 0x25, Value: 0xFF},
{Reg: 0x75, Value: 0x00},
}...)
if err != nil {
return err
}
err = v.writeRegValues(i2c, []RegBytePair{
{Reg: 0xFF, Value: 0x01},
{Reg: 0x4E, Value: 0x2C},
{Reg: 0x48, Value: 0x00},
{Reg: 0x30, Value: 0x20},
}...)
if err != nil {
return err
}
err = v.writeRegValues(i2c, []RegBytePair{
{Reg: 0xFF, Value: 0x00},
{Reg: 0x30, Value: 0x09},
{Reg: 0x54, Value: 0x00},
{Reg: 0x31, Value: 0x04},
{Reg: 0x32, Value: 0x03},
{Reg: 0x40, Value: 0x83},
{Reg: 0x46, Value: 0x25},
{Reg: 0x60, Value: 0x00},
{Reg: 0x27, Value: 0x00},
{Reg: 0x50, Value: 0x06},
{Reg: 0x51, Value: 0x00},
{Reg: 0x52, Value: 0x96},
{Reg: 0x56, Value: 0x08},
{Reg: 0x57, Value: 0x30},
{Reg: 0x61, Value: 0x00},
{Reg: 0x62, Value: 0x00},
{Reg: 0x64, Value: 0x00},
{Reg: 0x65, Value: 0x00},
{Reg: 0x66, Value: 0xA0},
}...)
if err != nil {
return err
}
err = v.writeRegValues(i2c, []RegBytePair{
{Reg: 0xFF, Value: 0x01},
{Reg: 0x22, Value: 0x32},
{Reg: 0x47, Value: 0x14},
{Reg: 0x49, Value: 0xFF},
{Reg: 0x4A, Value: 0x00},
}...)
if err != nil {
return err
}
err = v.writeRegValues(i2c, []RegBytePair{
{Reg: 0xFF, Value: 0x00},
{Reg: 0x7A, Value: 0x0A},
{Reg: 0x7B, Value: 0x00},
{Reg: 0x78, Value: 0x21},
}...)
if err != nil {
return err
}
err = v.writeRegValues(i2c, []RegBytePair{
{Reg: 0xFF, Value: 0x01},
{Reg: 0x23, Value: 0x34},
{Reg: 0x42, Value: 0x00},
{Reg: 0x44, Value: 0xFF},
{Reg: 0x45, Value: 0x26},
{Reg: 0x46, Value: 0x05},
{Reg: 0x40, Value: 0x40},
{Reg: 0x0E, Value: 0x06},
{Reg: 0x20, Value: 0x1A},
{Reg: 0x43, Value: 0x40},
}...)
if err != nil {
return err
}
err = v.writeRegValues(i2c, []RegBytePair{
{Reg: 0xFF, Value: 0x00},
{Reg: 0x34, Value: 0x03},
{Reg: 0x35, Value: 0x44},
}...)
if err != nil {
return err
}
err = v.writeRegValues(i2c, []RegBytePair{
{Reg: 0xFF, Value: 0x01},
{Reg: 0x31, Value: 0x04},
{Reg: 0x4B, Value: 0x09},
{Reg: 0x4C, Value: 0x05},
{Reg: 0x4D, Value: 0x04},
}...)
if err != nil {
return err
}
err = v.writeRegValues(i2c, []RegBytePair{
{Reg: 0xFF, Value: 0x00},
{Reg: 0x44, Value: 0x00},
{Reg: 0x45, Value: 0x20},
{Reg: 0x47, Value: 0x08},
{Reg: 0x48, Value: 0x28},
{Reg: 0x67, Value: 0x00},
{Reg: 0x70, Value: 0x04},
{Reg: 0x71, Value: 0x01},
{Reg: 0x72, Value: 0xFE},
{Reg: 0x76, Value: 0x00},
{Reg: 0x77, Value: 0x00},
}...)
if err != nil {
return err
}
err = v.writeRegValues(i2c, []RegBytePair{
{Reg: 0xFF, Value: 0x01},
{Reg: 0x0D, Value: 0x01},
}...)
if err != nil {
return err
}
err = v.writeRegValues(i2c, []RegBytePair{
{Reg: 0xFF, Value: 0x00},
{Reg: 0x80, Value: 0x01},
{Reg: 0x01, Value: 0xF8},
}...)
if err != nil {
return err
}
err = v.writeRegValues(i2c, []RegBytePair{
{Reg: 0xFF, Value: 0x01},
{Reg: 0x8E, Value: 0x01},
{Reg: 0x00, Value: 0x01},
{Reg: 0xFF, Value: 0x00},
{Reg: 0x80, Value: 0x00},
}...)
if err != nil {
return err
}
// -- VL53L0X_load_tuning_settings() end
// "Set interrupt config to new sample ready"
// -- VL53L0X_SetGpioConfig() begin
err = v.writeRegU8(i2c, SYSTEM_INTERRUPT_CONFIG_GPIO, 0x04)
if err != nil {
return err
}
u8, err = v.readRegU8(i2c, GPIO_HV_MUX_ACTIVE_HIGH)
if err != nil {
return err
}
err = v.writeRegValues(i2c, []RegBytePair{
{Reg: GPIO_HV_MUX_ACTIVE_HIGH, Value: u8 & ^byte(0x10)}, // active low
{Reg: SYSTEM_INTERRUPT_CLEAR, Value: 0x01},
}...)
if err != nil {
return err
}
// -- VL53L0X_SetGpioConfig() end
u32, err := v.getMeasurementTimingBudget(i2c)
if err != nil {
return err
}
v.measurementTimingBudgetUsec = u32
// "Disable MSRC and TCC by default"
// MSRC = Minimum Signal Rate Check
// TCC = Target CentreCheck
// -- VL53L0X_SetSequenceStepEnable() begin
err = v.writeRegU8(i2c, SYSTEM_SEQUENCE_CONFIG, 0xE8)
if err != nil {
return err
}
// -- VL53L0X_SetSequenceStepEnable() end
// "Recalculate timing budget"
err = v.SetMeasurementTimingBudget(i2c, v.measurementTimingBudgetUsec)
if err != nil {
return err
}
// VL53L0X_StaticInit() end
// VL53L0X_PerformRefCalibration() begin (VL53L0X_perform_ref_calibration())
// -- VL53L0X_perform_vhv_calibration() begin
err = v.writeRegU8(i2c, SYSTEM_SEQUENCE_CONFIG, 0x01)
if err != nil {
return err
}
err = v.performSingleRefCalibration(i2c, 0x40)
if err != nil {
return err
}
// -- VL53L0X_perform_vhv_calibration() end
// -- VL53L0X_perform_phase_calibration() begin
err = v.writeRegU8(i2c, SYSTEM_SEQUENCE_CONFIG, 0x02)
if err != nil {
return err
}
err = v.performSingleRefCalibration(i2c, 0x00)
if err != nil {
return err
}
// -- VL53L0X_perform_phase_calibration() end
// "restore the previous Sequence Config"
err = v.writeRegU8(i2c, SYSTEM_SEQUENCE_CONFIG, 0xE8)
if err != nil {
return err
}
// VL53L0X_PerformRefCalibration() end
return nil
}
// SetSignalRateLimit set the return signal rate limit check value in units of MCPS
// (mega counts per second). "This represents the amplitude of the signal reflected
// from the target and detected by the device"; setting this limit presumably determines
// the minimum measurement necessary for the sensor to report a valid reading.
// Setting a lower limit increases the potential range of the sensor but also
// seems to increase the likelihood of getting an inaccurate reading because of
// unwanted reflections from objects other than the intended target.
// Defaults to 0.25 MCPS as initialized by the ST API and this library.
func (v *Vl53l0x) SetSignalRateLimit(i2c *i2c.I2C, limitMcps float32) error {
if limitMcps < 0 || limitMcps > 511.99 {
return errors.New("out of MCPS range")
}
// Q9.7 fixed point format (9 integer bits, 7 fractional bits)
err := v.writeRegU16(i2c, FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT,
uint16(limitMcps*(1<<7)))
return err
}
// GetSignalRateLimit gets the return signal rate limit check value in MCPS.
func (v *Vl53l0x) GetSignalRateLimit(i2c *i2c.I2C) (float32, error) {
u16, err := v.readRegU16(i2c, FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT)
if err != nil {
return 0, err
}
limit := float32(u16) / (1 << 7)
return limit, nil
}
// TCC: Target CentreCheck
// MSRC: Minimum Signal Rate Check
// DSS: Dynamic Spad Selection
type SequenceStepEnables struct {
TCC bool
MSRC bool
DSS bool
PreRange bool
FinalRange bool
}
type SequenceStepTimeouts struct {
PreRangeVcselPeriodPclks uint16
FinalRangeVcselPeriodPclks uint16
MsrcDssTccMclks uint16
PreRangeMclks uint16
FinalRangeMclks uint16
MsrcDssTccUsec uint32
PreRangeUsec uint32
FinalRangeUsec uint32
}
// Get sequence step enables.
// Based on VL53L0X_GetSequenceStepEnables().
func (v *Vl53l0x) getSequenceStepEnables(i2c *i2c.I2C) (*SequenceStepEnables, error) {
lg.Debug("Start getting sequence step enables")
sequenceConfig, err := v.readRegU8(i2c, SYSTEM_SEQUENCE_CONFIG)
if err != nil {
return nil, err
}
se := &SequenceStepEnables{
TCC: (sequenceConfig>>4)&0x1 != 0,
DSS: (sequenceConfig>>3)&0x1 != 0,
MSRC: (sequenceConfig>>2)&0x1 != 0,
PreRange: (sequenceConfig>>6)&0x1 != 0,
FinalRange: (sequenceConfig>>7)&0x1 != 0,
}
return se, nil
}
// Decode VCSEL (vertical cavity surface emitting laser) pulse period in PCLKs
// from register value. Based on VL53L0X_decode_vcsel_period().
func (v *Vl53l0x) decodeVcselPeriod(value byte) byte {
return (value + 1) << 1
}
// Encode VCSEL pulse period register value from period in PCLKs.
// Based on VL53L0X_encode_vcsel_period().
func (v *Vl53l0x) encodeVcselPeriod(periodPclks byte) byte {
return periodPclks>>1 - 1
}
// Calculate macro period in *nanoseconds* from VCSEL period in PCLKs.
// Based on VL53L0X_calc_macro_period_ps().
// PLL_period_ps = 1655; macro_period_vclks = 2304.
func (v *Vl53l0x) calcMacroPeriod(vcselPeriodPclks uint16) uint32 {
return (uint32(vcselPeriodPclks)*2304*1655 + 500) / 1000
}
// Convert sequence step timeout from MCLKs to microseconds with given VCSEL period in PCLKs.
// Based on VL53L0X_calc_timeout_us().
func (v *Vl53l0x) timeoutMclksToMicroseconds(timeoutPeriodMclks uint16, vcselPeriodPclks uint16) uint32 {
macroPeriodNsec := v.calcMacroPeriod(vcselPeriodPclks)
return (uint32(timeoutPeriodMclks)*macroPeriodNsec + macroPeriodNsec/2) / 1000
}
// Convert sequence step timeout from microseconds to MCLKs with given VCSEL period in PCLKs.
// Based on VL53L0X_calc_timeout_mclks().
func (v *Vl53l0x) timeoutMicrosecondsToMclks(timeoutPeriodUsec uint32, vcselPeriodPclks uint16) uint32 {
macroPeriodNsec := v.calcMacroPeriod(vcselPeriodPclks)
return (timeoutPeriodUsec*1000 + macroPeriodNsec/2) / macroPeriodNsec
}
// SetVcselPulsePeriod set the VCSEL (vertical cavity surface emitting laser) pulse period
// for the given period type (pre-range or final range) to the given value in PCLKs.
// Longer periods seem to increase the potential range of the sensor.
// Valid values are (even numbers only):
// pre: 12 to 18 (initialized default: 14),
// final: 8 to 14 (initialized default: 10).
// Based on VL53L0X_set_vcsel_pulse_period().
func (v *Vl53l0x) SetVcselPulsePeriod(i2c *i2c.I2C, tpe VcselPeriodType, periodPclks uint8) error {
vcselPeriodReg := v.encodeVcselPeriod(periodPclks)
enables, err := v.getSequenceStepEnables(i2c)
if err != nil {
return err
}
timeouts, err := v.getSequenceStepTimeouts(i2c, *enables)
if err != nil {
return err
}
// "Apply specific settings for the requested clock period"
// "Re-calculate and apply timeouts, in macro periods"
// "When the VCSEL period for the pre or final range is changed,
// the corresponding timeout must be read from the device using
// the current VCSEL period, then the new VCSEL period can be
// applied. The timeout then must be written back to the device
// using the new VCSEL period.
//
// For the MSRC timeout, the same applies - this timeout being
// dependant on the pre-range vcsel period."
if tpe == VcselPeriodPreRange {
// "Set phase check limits"
switch periodPclks {
case 12:
err := v.writeRegU8(i2c, PRE_RANGE_CONFIG_VALID_PHASE_HIGH, 0x18)
if err != nil {
return err
}
case 14:
err := v.writeRegU8(i2c, PRE_RANGE_CONFIG_VALID_PHASE_HIGH, 0x30)
if err != nil {
return err
}
case 16:
err := v.writeRegU8(i2c, PRE_RANGE_CONFIG_VALID_PHASE_HIGH, 0x40)
if err != nil {
return err
}
case 18:
err := v.writeRegU8(i2c, PRE_RANGE_CONFIG_VALID_PHASE_HIGH, 0x50)
if err != nil {
return err
}
default:
// invalid period
return errors.New("invalid period")
}
err = v.writeRegU8(i2c, PRE_RANGE_CONFIG_VALID_PHASE_LOW, 0x08)
if err != nil {
return err
}
// apply new VCSEL period
err = v.writeRegU8(i2c, PRE_RANGE_CONFIG_VCSEL_PERIOD, vcselPeriodReg)
if err != nil {
return err
}
// update timeouts
// set_sequence_step_timeout() begin
// (SequenceStepId == VL53L0X_SEQUENCESTEP_PRE_RANGE)
newPreRangeTimeoutMclks := v.timeoutMicrosecondsToMclks(timeouts.PreRangeUsec,
uint16(periodPclks))
err = v.writeRegU16(i2c, PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI,
v.encodeTimeout(uint16(newPreRangeTimeoutMclks)))
if err != nil {
return err
}
// set_sequence_step_timeout() end
// set_sequence_step_timeout() begin
// (SequenceStepId == VL53L0X_SEQUENCESTEP_MSRC)
newMsrcTimeoutMclks := v.timeoutMicrosecondsToMclks(timeouts.MsrcDssTccUsec,
uint16(periodPclks))
if newMsrcTimeoutMclks > 256 {
newMsrcTimeoutMclks = 255
} else {
newMsrcTimeoutMclks--
}
err = v.writeRegU8(i2c, MSRC_CONFIG_TIMEOUT_MACROP, uint8(newMsrcTimeoutMclks))
if err != nil {
return err
}
// set_sequence_step_timeout() end
} else if tpe == VcselPeriodFinalRange {
switch periodPclks {
case 8:
err := v.writeRegValues(i2c, []RegBytePair{
{Reg: FINAL_RANGE_CONFIG_VALID_PHASE_HIGH, Value: 0x10},
{Reg: FINAL_RANGE_CONFIG_VALID_PHASE_LOW, Value: 0x08},
{Reg: GLOBAL_CONFIG_VCSEL_WIDTH, Value: 0x02},
{Reg: ALGO_PHASECAL_CONFIG_TIMEOUT, Value: 0x0C},
{Reg: 0xFF, Value: 0x01},
{Reg: ALGO_PHASECAL_LIM, Value: 0x30},
{Reg: 0xFF, Value: 0x00},
}...)
if err != nil {
return err
}
case 10:
err := v.writeRegValues(i2c, []RegBytePair{
{Reg: FINAL_RANGE_CONFIG_VALID_PHASE_HIGH, Value: 0x28},
{Reg: FINAL_RANGE_CONFIG_VALID_PHASE_LOW, Value: 0x08},
{Reg: GLOBAL_CONFIG_VCSEL_WIDTH, Value: 0x03},
{Reg: ALGO_PHASECAL_CONFIG_TIMEOUT, Value: 0x09},
{Reg: 0xFF, Value: 0x01},
{Reg: ALGO_PHASECAL_LIM, Value: 0x20},
{Reg: 0xFF, Value: 0x00},
}...)
if err != nil {
return err
}
case 12:
err := v.writeRegValues(i2c, []RegBytePair{
{Reg: FINAL_RANGE_CONFIG_VALID_PHASE_HIGH, Value: 0x38},
{Reg: FINAL_RANGE_CONFIG_VALID_PHASE_LOW, Value: 0x08},
{Reg: GLOBAL_CONFIG_VCSEL_WIDTH, Value: 0x03},
{Reg: ALGO_PHASECAL_CONFIG_TIMEOUT, Value: 0x08},
{Reg: 0xFF, Value: 0x01},
{Reg: ALGO_PHASECAL_LIM, Value: 0x20},
{Reg: 0xFF, Value: 0x00},
}...)
if err != nil {
return err
}
case 14:
err := v.writeRegValues(i2c, []RegBytePair{
{Reg: FINAL_RANGE_CONFIG_VALID_PHASE_HIGH, Value: 0x48},
{Reg: FINAL_RANGE_CONFIG_VALID_PHASE_LOW, Value: 0x08},
{Reg: GLOBAL_CONFIG_VCSEL_WIDTH, Value: 0x03},
{Reg: ALGO_PHASECAL_CONFIG_TIMEOUT, Value: 0x07},
{Reg: 0xFF, Value: 0x01},
{Reg: ALGO_PHASECAL_LIM, Value: 0x20},
{Reg: 0xFF, Value: 0x00},
}...)
if err != nil {
return err
}
default:
// invalid period
return errors.New("invalid period")
}
// apply new VCSEL period
err = v.writeRegU8(i2c, FINAL_RANGE_CONFIG_VCSEL_PERIOD, vcselPeriodReg)
if err != nil {
return err
}
// update timeouts
// set_sequence_step_timeout() begin
// (SequenceStepId == VL53L0X_SEQUENCESTEP_FINAL_RANGE)