-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathqwiic_vl53l1x.py
1615 lines (1298 loc) · 54.6 KB
/
qwiic_vl53l1x.py
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
#-----------------------------------------------------------------------
# SparkFun Qwiic VL53L1X Library
#-----------------------------------------------------------------------
#
# Ported by SparkFun Electronics, October 2019
# Author: Wes Furuya
#
# Compatibility:
# * Original: https://www.sparkfun.com/products/14722
#
# Do you like this library? Help support SparkFun. Buy a board!
# For more information on Qwiic Distance Sensor, check out the product
# page linked above.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http:www.gnu.org/licenses/>.
#
#=======================================================================
# Copyright (c) 2019 SparkFun Electronics
#
# 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.
#=======================================================================
#
# pylint: disable=line-too-long, bad-whitespace, invalid-name
###############################################################################
###############################################################################
#
# Original License:
#=======================================================================
# @author IMG
# @version V0.0.1
# @date 14-December-2018
# @brief Implementation file for the VL53L1X driver class
#=======================================================================
# COPYRIGHT(c) 2017 STMicroelectronics International N.V. All rights reserved.
#
# This file is part of VL53L1 Core and is dual licensed,
# either 'STMicroelectronics Proprietary license'
# or 'BSD 3-clause "New" or "Revised" License' , at your option.
#=======================================================================
#
# 'STMicroelectronics Proprietary license'
#=======================================================================
#
# License terms: STMicroelectronics Proprietary in accordance with licensing
# terms at www.st.com/sla0081
#
# STMicroelectronics confidential
# Reproduction and Communication of this document is strictly prohibited unless
# specifically authorized in writing by STMicroelectronics.
#
#=======================================================================
#
# Alternatively, VL53L1 Core may be distributed under the terms of
# 'BSD 3-clause "New" or "Revised" License', in which case the following
# provisions apply instead of the ones mentioned above :
#=======================================================================
#
# License terms: BSD 3-clause "New" or "Revised" License.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#=======================================================================
# Load Necessary Modules:
#----------------------------------------------
import time # Time access and conversion package
import math # Basic math package
import qwiic_i2c # I2C bus driver package
# from smbus2 import SMBus, i2c_msg # I2C bus driver package
# From vL53l1x_class.h Header File
###############################################################################
###############################################################################
# if _MSC_VER != None:
# if VL53L1X_API_EXPORTS != None:
# VL53L1X_API = __declspec(dllexport)
# else:
# VL53L1X_API
# else:
# VL53L1X_API
SOFT_RESET = 0x0000
VL53L1_I2C_SLAVE__DEVICE_ADDRESS = 0x0001
VL53L1_VHV_CONFIG__TIMEOUT_MACROP_LOOP_BOUND = 0x0008
ALGO__CROSSTALK_COMPENSATION_PLANE_OFFSET_KCPS = 0x0016
ALGO__CROSSTALK_COMPENSATION_X_PLANE_GRADIENT_KCPS = 0x0018
ALGO__CROSSTALK_COMPENSATION_Y_PLANE_GRADIENT_KCPS = 0x001A
ALGO__PART_TO_PART_RANGE_OFFSET_MM = 0x001E
MM_CONFIG__INNER_OFFSET_MM = 0x0020
MM_CONFIG__OUTER_OFFSET_MM = 0x0022
GPIO_HV_MUX__CTRL = 0x0030
GPIO__TIO_HV_STATUS = 0x0031
SYSTEM__INTERRUPT_CONFIG_GPIO = 0x0046
PHASECAL_CONFIG__TIMEOUT_MACROP = 0x004B
RANGE_CONFIG__TIMEOUT_MACROP_A_HI = 0x005E
RANGE_CONFIG__VCSEL_PERIOD_A = 0x0060
RANGE_CONFIG__VCSEL_PERIOD_B = 0x0063
RANGE_CONFIG__TIMEOUT_MACROP_B_HI = 0x0061
RANGE_CONFIG__TIMEOUT_MACROP_B_LO = 0x0062
RANGE_CONFIG__SIGMA_THRESH = 0x0064
RANGE_CONFIG__MIN_COUNT_RATE_RTN_LIMIT_MCPS = 0x0066
RANGE_CONFIG__VALID_PHASE_HIGH = 0x0069
VL53L1_SYSTEM__INTERMEASUREMENT_PERIOD = 0x006C
SYSTEM__THRESH_HIGH = 0x0072
SYSTEM__THRESH_LOW = 0x0074
SD_CONFIG__WOI_SD0 = 0x0078
SD_CONFIG__INITIAL_PHASE_SD0 = 0x007A
ROI_CONFIG__USER_ROI_CENTRE_SPAD = 0x007F
ROI_CONFIG__USER_ROI_REQUESTED_GLOBAL_XY_SIZE = 0x0080
SYSTEM__SEQUENCE_CONFIG = 0x0081
VL53L1_SYSTEM__GROUPED_PARAMETER_HOLD = 0x0082
SYSTEM__INTERRUPT_CLEAR = 0x0086
SYSTEM__MODE_START = 0x0087
VL53L1_RESULT__RANGE_STATUS = 0x0089
VL53L1_RESULT__DSS_ACTUAL_EFFECTIVE_SPADS_SD0 = 0x008C
RESULT__AMBIENT_COUNT_RATE_MCPS_SD = 0x0090
VL53L1_RESULT__FINAL_CROSSTALK_CORRECTED_RANGE_MM_SD0 = 0x0096
VL53L1_RESULT__PEAK_SIGNAL_COUNT_RATE_CROSSTALK_CORRECTED_MCPS_SD0 = 0x0098
VL53L1_RESULT__OSC_CALIBRATE_VAL = 0x00DE
VL53L1_FIRMWARE__SYSTEM_STATUS = 0x00E5
VL53L1_IDENTIFICATION__MODEL_ID = 0x010F
VL53L1_ROI_CONFIG__MODE_ROI_CENTRE_SPAD = 0x013E
_VL53L1X_DEFAULT_DEVICE_ADDRESS = 0x52
###############################################################################
###############################################################################
_DEFAULT_NAME = "Qwiic 4m Distance Sensor (ToF)"
###############################################################################
###############################################################################
_FULL_ADDRESS_LIST = list(range(0x08,0x77+1)) # Full I2C Address List (excluding resrved addresses)
_FULL_ADDRESS_LIST.remove(_VL53L1X_DEFAULT_DEVICE_ADDRESS >> 1) # Remove Default Address of VL53L1X from list
_AVAILABLE_I2C_ADDRESS = [_VL53L1X_DEFAULT_DEVICE_ADDRESS >> 1] # Initialize with Default Address of VL53L1X
_AVAILABLE_I2C_ADDRESS.extend(_FULL_ADDRESS_LIST) # Add Full Range of I2C Addresses
# From vL53l1x_class.cpp C++ File
###############################################################################
###############################################################################
ALGO__PART_TO_PART_RANGE_OFFSET_MM = 0x001E
MM_CONFIG__INNER_OFFSET_MM = 0x0020
MM_CONFIG__OUTER_OFFSET_MM = 0x0022
# DEBUG_MODE
VL51L1X_DEFAULT_CONFIGURATION = [
0x00, # 0x2d : set bit 2 and 5 to 1 for fast plus mode (1MHz I2C), else don't touch
0x01, # 0x2e : bit 0 if I2C pulled up at 1.8V, else set bit 0 to 1 (pull up at AVDD)
0x01, # 0x2f : bit 0 if GPIO pulled up at 1.8V, else set bit 0 to 1 (pull up at AVDD)
0x01, # 0x30 : set bit 4 to 0 for active high interrupt and 1 for active low (bits 3:0 must be 0x1), use set_interrupt_polarity()
0x02, # 0x31 : bit 1 = interrupt depending on the polarity, use check_for_data_ready()
0x00, # 0x32 : not user-modifiable
0x02, # 0x33 : not user-modifiable
0x08, # 0x34 : not user-modifiable
0x00, # 0x35 : not user-modifiable
0x08, # 0x36 : not user-modifiable
0x10, # 0x37 : not user-modifiable
0x01, # 0x38 : not user-modifiable
0x01, # 0x39 : not user-modifiable
0x00, # 0x3a : not user-modifiable
0x00, # 0x3b : not user-modifiable
0x00, # 0x3c : not user-modifiable
0x00, # 0x3d : not user-modifiable
0xff, # 0x3e : not user-modifiable
0x00, # 0x3f : not user-modifiable
0x0F, # 0x40 : not user-modifiable
0x00, # 0x41 : not user-modifiable
0x00, # 0x42 : not user-modifiable
0x00, # 0x43 : not user-modifiable
0x00, # 0x44 : not user-modifiable
0x00, # 0x45 : not user-modifiable
0x20, # 0x46 : interrupt configuration 0->level low detection, 1-> level high, 2-> Out of window, 3->In window, 0x20-> New sample ready , TBC
0x0b, # 0x47 : not user-modifiable
0x00, # 0x48 : not user-modifiable
0x00, # 0x49 : not user-modifiable
0x02, # 0x4a : not user-modifiable
0x0a, # 0x4b : not user-modifiable
0x21, # 0x4c : not user-modifiable
0x00, # 0x4d : not user-modifiable
0x00, # 0x4e : not user-modifiable
0x05, # 0x4f : not user-modifiable
0x00, # 0x50 : not user-modifiable
0x00, # 0x51 : not user-modifiable
0x00, # 0x52 : not user-modifiable
0x00, # 0x53 : not user-modifiable
0xc8, # 0x54 : not user-modifiable
0x00, # 0x55 : not user-modifiable
0x00, # 0x56 : not user-modifiable
0x38, # 0x57 : not user-modifiable
0xff, # 0x58 : not user-modifiable
0x01, # 0x59 : not user-modifiable
0x00, # 0x5a : not user-modifiable
0x08, # 0x5b : not user-modifiable
0x00, # 0x5c : not user-modifiable
0x00, # 0x5d : not user-modifiable
0x01, # 0x5e : not user-modifiable
0xdb, # 0x5f : not user-modifiable
0x0f, # 0x60 : not user-modifiable
0x01, # 0x61 : not user-modifiable
0xf1, # 0x62 : not user-modifiable
0x0d, # 0x63 : not user-modifiable
0x01, # 0x64 : Sigma threshold MSB (mm in 14.2 format for MSB+LSB), use set_sigma_threshold(), default value 90 mm
0x68, # 0x65 : Sigma threshold LSB
0x00, # 0x66 : Min count Rate MSB (MCPS in 9.7 format for MSB+LSB), use set_signal_threshold()
0x80, # 0x67 : Min count Rate LSB
0x08, # 0x68 : not user-modifiable
0xb8, # 0x69 : not user-modifiable
0x00, # 0x6a : not user-modifiable
0x00, # 0x6b : not user-modifiable
0x00, # 0x6c : Intermeasurement period MSB, 32 bits register, use set_inter_measurement_in_ms()
0x00, # 0x6d : Intermeasurement period
0x0f, # 0x6e : Intermeasurement period
0x89, # 0x6f : Intermeasurement period LSB
0x00, # 0x70 : not user-modifiable
0x00, # 0x71 : not user-modifiable
0x00, # 0x72 : distance threshold high MSB (in mm, MSB+LSB), use SetD:tanceThreshold()
0x00, # 0x73 : distance threshold high LSB
0x00, # 0x74 : distance threshold low MSB ( in mm, MSB+LSB), use SetD:tanceThreshold()
0x00, # 0x75 : distance threshold low LSB
0x00, # 0x76 : not user-modifiable
0x01, # 0x77 : not user-modifiable
0x0f, # 0x78 : not user-modifiable
0x0d, # 0x79 : not user-modifiable
0x0e, # 0x7a : not user-modifiable
0x0e, # 0x7b : not user-modifiable
0x00, # 0x7c : not user-modifiable
0x00, # 0x7d : not user-modifiable
0x02, # 0x7e : not user-modifiable
0xc7, # 0x7f : ROI center, use set_roi()
0xff, # 0x80 : XY ROI (X=Width, Y=Height), use set_roi()
0x9B, # 0x81 : not user-modifiable
0x00, # 0x82 : not user-modifiable
0x00, # 0x83 : not user-modifiable
0x00, # 0x84 : not user-modifiable
0x01, # 0x85 : not user-modifiable
0x00, # 0x86 : clear interrupt, use clear_interrupt()
0x00 # 0x87 : start ranging, use start_ranging() or stop_ranging(), If you want an automatic start after self.init() call, put 0x40 in location 0x87
]
###############################################################################
###############################################################################
# From vL53l1_error_codes.h Header File
###############################################################################
###############################################################################
# @brief Error Code definitions for VL53L1 API.
#=======================================================================
# PRIVATE define do not edit
#=======================================================================
# @defgroup VL53L1_define_Error_group Error and Warning code returned by API
# The following DEFINE are used to identify the PAL ERROR
VL53L1_ERROR_NONE = 0
VL53L1_ERROR_CALIBRATION_WARNING = -1
# """Warning invalid calibration data may be in used
# \a VL53L1_InitData()
# \a VL53L1_GetOffsetCalibrationData
# \a VL53L1_SetOffsetCalibrationData"""
VL53L1_ERROR_MIN_CLIPPED = -2
# """Warning parameter passed was clipped to min before to be applied"""
VL53L1_ERROR_UNDEFINED = -3
# """Unqualified error"""
VL53L1_ERROR_INVALID_PARAMS = -4
# """Parameter passed is invalid or out of range"""
VL53L1_ERROR_NOT_SUPPORTED = -5
# """Function is not supported in current mode or configuration"""
VL53L1_ERROR_RANGE_ERROR = -6
# """Device report a ranging error interrupt status"""
VL53L1_ERROR_TIME_OUT = -7
# """Aborted due to time out"""
VL53L1_ERROR_MODE_NOT_SUPPORTED = -8
# """Asked mode is not supported by the device"""
VL53L1_ERROR_BUFFER_TOO_SMALL = -9
# """..."""
VL53L1_ERROR_COMMS_BUFFER_TOO_SMALL = -10
# """Supplied buffer is larger than I2C supports"""
VL53L1_ERROR_GPIO_NOT_EXISTING = -11
# """User tried to setup a non-existing GPIO pin"""
VL53L1_ERROR_GPIO_FUNCTIONALITY_NOT_SUPPORTED = -12
# """unsupported GPIO functionality"""
VL53L1_ERROR_CONTROL_INTERFACE = -13
# """error reported from IO functions"""
VL53L1_ERROR_INVALID_COMMAND = -14
# """The command is not allowed in the current device state (power down)"""
VL53L1_ERROR_DIVISION_BY_ZERO = -15
# """In the function a division by zero occurs"""
VL53L1_ERROR_REF_SPAD_INIT = -16
# """Error during reference SPAD initialization"""
VL53L1_ERROR_GPH_SYNC_CHECK_FAIL = -17
# """GPH sync interrupt check fail - API out of sync with device"""
VL53L1_ERROR_STREAM_COUNT_CHECK_FAIL = -18
# """Stream count check fail - API out of sync with device"""
VL53L1_ERROR_GPH_ID_CHECK_FAIL = -19
# """GPH ID check fail - API out of sync with device"""
VL53L1_ERROR_ZONE_STREAM_COUNT_CHECK_FAIL = -20
# """Zone dynamic config stream count check failed - API out of sync"""
VL53L1_ERROR_ZONE_GPH_ID_CHECK_FAIL = -21
# """Zone dynamic config GPH ID check failed - API out of sync"""
VL53L1_ERROR_XTALK_EXTRACTION_NO_SAMPLE_FAI = -22
# """Thrown when run_xtalk_extraction fn has 0 succesful samples when using
# the full array to sample the xtalk. In this case there is not enough
# information to generate new Xtalk parm info. The function will exit and
# leave the current xtalk parameters unaltered"""
VL53L1_ERROR_XTALK_EXTRACTION_SIGMA_LIMIT_FAIL = -23
# """Thrown when run_xtalk_extraction fn has found that the avg sigma
# estimate of the full array xtalk sample is > than the maximal limit
# allowed. In this case the xtalk sample is too noisy for measurement.
# The function will exit and leave the current xtalk parameters unaltered."""
VL53L1_ERROR_OFFSET_CAL_NO_SAMPLE_FAIL = -24
# """Thrown if there one of stages has no valid offset calibration
# samples. A fatal error calibration not valid"""
VL53L1_ERROR_OFFSET_CAL_NO_SPADS_ENABLED_FAIL = -25
# """Thrown if there one of stages has zero effective SPADS Traps the case
# when MM1 SPADs is zero. A fatal error calibration not valid"""
VL53L1_ERROR_ZONE_CAL_NO_SAMPLE_FAIL = -26
# """Thrown if then some of the zones have no valid samples. A fatal error
# calibration not valid"""
VL53L1_ERROR_TUNING_PARM_KEY_MISMATCH = -27
# """Thrown if the tuning file key table version does not match with
# expected value. The driver expects the key table version to match the
# compiled default version number in the define
# #VL53L1_TUNINGPARM_KEY_TABLE_VERSION_DEFAULT*"""
VL53L1_WARNING_REF_SPAD_CHAR_NOT_ENOUGH_SPADS = -28
# """Thrown if there are less than 5 good SPADs are available."""
VL53L1_WARNING_REF_SPAD_CHAR_RATE_TOO_HIGH = -29
# """Thrown if the final reference rate is greater than the upper reference
# rate limit - default is 40 Mcps. Implies a minimum Q3 (x10) SPAD (5)
# selected"""
VL53L1_WARNING_REF_SPAD_CHAR_RATE_TOO_LOW = -30
# """Thrown if the final reference rate is less than the lower reference
# rate limit - default is 10 Mcps. Implies maximum Q1 (x1) SPADs selected"""
VL53L1_WARNING_OFFSET_CAL_MISSING_SAMPLES = -31
# """Thrown if there is less than the requested number of valid samples."""
VL53L1_WARNING_OFFSET_CAL_SIGMA_TOO_HIGH = -32
# """Thrown if the offset calibration range sigma estimate is greater than
# 8.0 mm. This is the recommended min value to yield a stable offset
# measurement"""
VL53L1_WARNING_OFFSET_CAL_RATE_TOO_HIGH = -33
# """Thrown when VL53L1_run_offset_calibration() peak rate is greater than
# that 50.0Mcps. This is the recommended max rate to avoid pile-up
# influencing the offset measurement"""
VL53L1_WARNING_OFFSET_CAL_SPAD_COUNT_TOO_LOW = -34
# """Thrown when VL53L1_run_offset_calibration() when one of stages range
# has less that 5.0 effective SPADS. This is the recommended min value to
# yield a stable offset"""
VL53L1_WARNING_ZONE_CAL_MISSING_SAMPLES = -35
# """Thrown if one of more of the zones have less than the requested number
# of valid samples"""
VL53L1_WARNING_ZONE_CAL_SIGMA_TOO_HIGH = -36
# """Thrown if one or more zones have sigma estimate value greater than
# 8.0 mm. This is the recommended min value to yield a stable offset
# measurement"""
VL53L1_WARNING_ZONE_CAL_RATE_TOO_HIGH = -37
# """Thrown if one of more zones have peak rate higher than that 50.0Mcps.
# This is the recommended max rate to avoid pile-up influencing the offset
# measurement"""
VL53L1_WARNING_XTALK_MISSING_SAMPLES = -38
# """Thrown to notify that some of the xtalk samples did not yield valid
# ranging pulse data while attempting to measure the xtalk signal in
# vl53l1_run_xtalk_extract(). This can signify any of the zones are missing
# samples, for further debug information the xtalk_results struct should be
# referred to. This warning is for notification only, the xtalk pulse and
# shape have still been generated"""
VL53L1_WARNING_XTALK_NO_SAMPLES_FOR_GRADIENT = -39
# """Thrown to notify that some of teh xtalk samples used for gradient
# generation did not yield valid ranging pulse data while attempting to
# measure the xtalk signal in vl53l1_run_xtalk_extract(). This can signify
# that any one of the zones 0-3 yielded no successful samples. The
# xtalk_results struct should be referred to for further debug info. This
# warning is for notification only, the xtalk pulse and shape have still
# been generated."""
VL53L1_WARNING_XTALK_SIGMA_LIMIT_FOR_GRADIENT = -40
# """Thrown to notify that some of the xtalk samples used for gradient
# generation did not pass the sigma limit check while attempting to
# measure the xtalk signal in vl53l1_run_xtalk_extract(). This can signify
# that any one of the zones 0-3 yielded an avg sigma_mm value > the limit.
# The xtalk_results struct should be referred to for further debug info.
# This warning is for notification only, the xtalk pulse and shape have
# still been generated."""
VL53L1_ERROR_NOT_IMPLEMENTED = -41
# """Tells requested functionality has not been implemented yet or not
# compatible with the device"""
VL53L1_ERROR_PLATFORM_SPECIFIC_START = -60
# """Tells the starting code for platform
# @} VL53L1_define_Error_group"""
# _VL53L1_ERROR_CODES_H_
###############################################################################
###############################################################################
###############################################################################
# Classes ------------------------------------------------
# Class representing a VL53L1 sensor component
###############################################################################
class QwiicVL53L1X(object):
"""
SparkFunVL53L1X
Initialise the VL53L1X chip at ``address`` with ``i2c_driver``.
:param address: The I2C address to use for the device.
* If not provided, the default address is used.
:param i2c_driver: An existing i2c driver object.
* If not provided a driver object is created.
:return: **Constructor Initialization** -
* True- Successful
* False- Issue loading I2C driver
:rtype: Bool
"""
# Software Version Information
VL53L1X_IMPLEMENTATION_VER_MAJOR= 1
VL53L1X_IMPLEMENTATION_VER_MINOR= 0
VL53L1X_IMPLEMENTATION_VER_SUB= 1
VL53L1X_IMPLEMENTATION_VER_REVISION= 0000
#----------------------------------------------
# Device Name:
device_name = _DEFAULT_NAME
#----------------------------------------------
# Available Addresses:
available_addresses = _AVAILABLE_I2C_ADDRESS
#----------------------------------------------
# Constructor
def __init__(self, address = None, debug = None, i2c_driver = None):
"""
This method initializes the class object. If no 'address' or
'i2c_driver' are inputed or 'None' is specified, the method will
use the defaults.
:param address: The I2C address to use for the device.
If not provided, the method will default to
the first address in the
'available_addresses' list.
Default = 0x29
:param debug: Designated whether or not to print debug
statements.
0- Don't print debug statements
1- Print debug statements
:param i2c_driver: An existing i2c driver object. If not
provided a driver object is created from the
'qwiic_i2c' I2C driver of the SparkFun Qwiic
library.
"""
# Did the user specify an I2C address?
# Defaults to 0x52 if unspecified.
self.address = address if address != None else self.available_addresses[0]
# Load the I2C driver if one isn't provided
if i2c_driver == None:
self._i2c = qwiic_i2c.getI2CDriver()
if self._i2c == None:
print("Unable to load I2C driver for this platform.")
return
else:
self._i2c = i2c_driver
# Do you want debug statements?
if debug == None:
self.debug = 0 # Debug Statements Disabled
else:
self.debug = debug # Debug Statements Enabled (1)
def _begin(self):
"""
One time device initialization
:return: 0 on success
#CALIBRATION_WARNING if failed
"""
return self.sensor_init()
def _read_id(self):
"""
Read function of the ID device. (Verifies id ID matches factory number).
:return: 0- Correct
-1- Failure
"""
if (self.get_sensor_id() == 0xEEAC):
return 0
return -1
def get_distance(self):
"""
This function returns the distance measured by the sensor in mm
:return: Distance measured by the sensor in mm
:rtype: Integer
"""
self.status = 0
distance = self.__i2cRead(self.address,
VL53L1_RESULT__FINAL_CROSSTALK_CORRECTED_RANGE_MM_SD0, 2)
return distance
def init_sensor(self, address):
"""
Initialize the sensor with default values
:param address: Device address
:return: 0 on Success
"""
self.status = 0
sensorState = 0
# VL53L1_Off()
# VL53L1_On()
self.status = self.set_i2c_address(address)
if self.debug == 1:
byteData = self.__i2cRead(self.address, 0x010F, 1)
print("VL53L1X Model_ID: %s", byteData)
byteData = self.__i2cRead(self.address, 0x0110, 1)
print("VL53L1X Module_Type: %s", byteData)
wordData = self.__i2cRead(self.address, 0x010F, 2)
print("VL53L1X: %s", wordData)
while (not sensorState and not self.status):
sensorState = self.boot_state()
time.sleep(2/1000)
if (not self.status):
self.status = self.sensor_init()
return self.status
# VL53L1X_api.h functions
###############################################################################
###############################################################################
def get_sw_version(self):
"""
This function returns the SW driver version
:return: [major, minor, build, revision] numbers
:rtype: List
"""
self.status = 0
major = self.VL53L1X_IMPLEMENTATION_VER_MAJOR
minor = self.VL53L1X_IMPLEMENTATION_VER_MINOR
build = self.VL53L1X_IMPLEMENTATION_VER_SUB
revision = self.VL53L1X_IMPLEMENTATION_VER_REVISION
return [major, minor, build, revision]
def set_i2c_address(self, new_address):
"""
This function sets the sensor I2C address used in case multiple devices application, default address **0x29** (0x52 >> 1)
:param new_address: I2C address to change device to
"""
self.status = 0
self.status = self.__i2cWrite(self.address, VL53L1_I2C_SLAVE__DEVICE_ADDRESS, new_address, 1)
self.address = new_address
return self.status
def sensor_init(self):
"""
This function loads the 135 bytes default values to initialize the sensor.
:return: * 0:success
* != 0:failed
"""
self.status = 0
Addr = 0x00
tmp = 0
timeout = 0
for Addr in range(0x2D, 0x87 + 1):
self.status = self.__i2cWrite(self.address, Addr, VL51L1X_DEFAULT_CONFIGURATION[Addr - 0x2D], 1)
self.status = self.start_ranging()
while(tmp == 0):
tmp = self.check_for_data_ready()
timeout = timeout + 1
if (timeout > 50):
self.status = VL53L1_ERROR_TIME_OUT
return self.status
tmp = 0
self.status = self.clear_interrupt()
self.status = self.stop_ranging()
self.status = self.__i2cWrite(self.address, VL53L1_VHV_CONFIG__TIMEOUT_MACROP_LOOP_BOUND, 0x09, 1) # two bounds VHV
self.status = self.__i2cWrite(self.address, 0x0B, 0, 1) # start VHV from the previous temperature
return self.status
def clear_interrupt(self):
"""
This function clears the interrupt, to be called after a ranging data reading to arm the interrupt for the next data ready event.
"""
self.status = 0
self.status = self.__i2cWrite(self.address, SYSTEM__INTERRUPT_CLEAR, 0x01, 1)
return self.status
def set_interrupt_polarity(self, NewPolarity):
"""
This function programs the interrupt polarity
:param NewPolarity: * 1 = active high (**default**)
* 0 = active low
"""
self.status = 0
Temp = self.__i2cRead(self.address, GPIO_HV_MUX__CTRL, 1)
Temp = Temp & 0xEF
self.status = self.__i2cWrite(self.address, GPIO_HV_MUX__CTRL, Temp | (not (NewPolarity & 1)) << 4, 1)
return self.status
def get_interrupt_polarity(self):
"""
This function returns the current interrupt polarity
:return: * 1 = active high (**default**)
* 0 = active low
:rtypye: Integer
"""
self.status = 0
Temp = self.__i2cRead(self.address, GPIO_HV_MUX__CTRL, 1)
Temp = Temp & 0x10
pInterruptPolarity = not (Temp >> 4)
return pInterruptPolarity
def start_ranging(self):
"""
This function starts the ranging distance operation
The ranging operation is continuous. The clear interrupt has to be done after each get data to allow the interrupt to raise when the next data is ready
1=active high (**default**), 0=active low, use set_interrupt_polarity() to change the interrupt polarity if required.
"""
self.status = 0
self.status = self.__i2cWrite(self.address, SYSTEM__MODE_START, 0x40, 1) # Enable VL53L1X
return self.status
def stop_ranging(self):
"""
This function stops the ranging.
"""
self.status = 0
self.status = self.__i2cWrite(self.address, SYSTEM__MODE_START, 0x00, 1) # Disable VL53L1X
return self.status
def check_for_data_ready(self):
"""
This function checks if the new ranging data is available by polling the dedicated register.
:return isDataReady: * 0 -> not ready
* 1 -> ready
"""
self.status = 0
IntPol = self.get_interrupt_polarity()
Temp = self.__i2cRead(self.address, GPIO__TIO_HV_STATUS, 1)
# Read in the register to check if a new value is available
if (self.status == 0):
if ((Temp & 1) == IntPol):
isDataReady = 1
else:
isDataReady = 0
return isDataReady
def set_timing_budget_in_ms(self, TimingBudgetInMs):
"""
This function programs the timing budget in ms.
:param TimingBudgetInMs: Predefined values = 15, 20, 33, 50, 100 (**default**), 200, 500.
"""
self.status = 0
DM = self.get_distance_mode()
if (DM == 0):
return 1
elif (DM == 1): # Short DistanceMode
if TimingBudgetInMs == 15: # only available in short distance mode
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_A_HI, 0x01D, 2)
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_B_HI, 0x0027, 2)
elif TimingBudgetInMs == 20:
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_A_HI, 0x0051, 2)
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_B_HI, 0x006E, 2)
elif TimingBudgetInMs == 33:
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_A_HI, 0x00D6, 2)
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_B_HI, 0x006E, 2)
elif TimingBudgetInMs == 50:
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_A_HI, 0x1AE, 2)
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_B_HI, 0x01E8, 2)
elif TimingBudgetInMs == 100:
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_A_HI, 0x02E1, 2)
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_B_HI, 0x0388, 2)
elif TimingBudgetInMs == 200:
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_A_HI, 0x03E1, 2)
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_B_HI, 0x0496, 2)
elif TimingBudgetInMs == 500:
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_A_HI, 0x0591, 2)
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_B_HI, 0x05C1, 2)
else:
self.status = 1
else:
if TimingBudgetInMs == 20:
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_A_HI, 0x001E, 2)
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_B_HI, 0x0022, 2)
elif TimingBudgetInMs == 33:
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_A_HI, 0x0060, 2)
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_B_HI, 0x006E, 2)
elif TimingBudgetInMs == 50:
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_A_HI, 0x00AD, 2)
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_B_HI, 0x00C6, 2)
elif TimingBudgetInMs == 100:
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_A_HI, 0x01CC, 2)
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_B_HI, 0x01EA, 2)
elif TimingBudgetInMs == 200:
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_A_HI, 0x02D9, 2)
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_B_HI, 0x02F8, 2)
elif TimingBudgetInMs == 500:
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_A_HI, 0x048F, 2)
self.__i2cWrite(self.address, RANGE_CONFIG__TIMEOUT_MACROP_B_HI, 0x04A4, 2)
else:
self.status = 1
return self.status
def get_timing_budget_in_ms(self):
"""
This function returns the current timing budget in ms.
"""
self.status = 0
Temp = self.__i2cRead(self.address, RANGE_CONFIG__TIMEOUT_MACROP_A_HI, 2)
def get_timing_budget_in_ms_switch(var):
switcher = {
0x001D:15,
0x0051:20,
0x001E:20,
0x00D6:33,
0x0060:33,
0x1AE :50,
0x00AD:50,
0x02E1:100,
0x01CC:100,
0x03E1:200,
0x02D9:200,
0x0591:500,
0x048F:500}
return switcher.get(var,0)
pTimingBudget = get_timing_budget_in_ms_switch(Temp)
return pTimingBudget
def set_distance_mode(self, DM):
"""
This function programs the distance mode (1=short, 2=long(default)).
:param DM: * 1- Short mode max distance is limited to 1.3 m but better ambient immunity.
* 2- Long mode can range up to 4 m in the dark with 200 ms timing budget (**default**).
"""
self.status = 0
TB = self.get_timing_budget_in_ms()
if DM == 1:
self.status = self.__i2cWrite(self.address, PHASECAL_CONFIG__TIMEOUT_MACROP, 0x14, 1)
self.status = self.__i2cWrite(self.address, RANGE_CONFIG__VCSEL_PERIOD_A, 0x07, 1)
self.status = self.__i2cWrite(self.address, RANGE_CONFIG__VCSEL_PERIOD_B, 0x05, 1)
self.status = self.__i2cWrite(self.address, RANGE_CONFIG__VALID_PHASE_HIGH, 0x38, 1)
self.status = self.__i2cWrite(self.address, SD_CONFIG__WOI_SD0, 0x0705, 2)
self.status = self.__i2cWrite(self.address, SD_CONFIG__INITIAL_PHASE_SD0, 0x0606, 2)
elif DM == 2:
self.status = self.__i2cWrite(self.address, PHASECAL_CONFIG__TIMEOUT_MACROP, 0x0A, 1)
self.status = self.__i2cWrite(self.address, RANGE_CONFIG__VCSEL_PERIOD_A, 0x0F, 1)
self.status = self.__i2cWrite(self.address, RANGE_CONFIG__VCSEL_PERIOD_B, 0x0D, 1)
self.status = self.__i2cWrite(self.address, RANGE_CONFIG__VALID_PHASE_HIGH, 0xB8, 1)
self.status = self.__i2cWrite(self.address, SD_CONFIG__WOI_SD0, 0x0F0D, 2)
self.status = self.__i2cWrite(self.address, SD_CONFIG__INITIAL_PHASE_SD0, 0x0E0E, 2)
else:
if self.debug == 1:
print("Invalid DIstance Mode")
self.status = self.set_timing_budget_in_ms(TB)
return self.status
def get_distance_mode(self):
"""
This function returns the current distance mode (1=short, 2=long).
:return: * 1- Short mode max distance is limited to 1.3 m but better ambient immunity.
* 2- Long mode can range up to 4 m in the dark with 200 ms timing budget (**default**).
"""
self.status = 0
TempDM = self.__i2cRead(self.address,PHASECAL_CONFIG__TIMEOUT_MACROP, 1)
if (TempDM == 0x14):
DM=1
if(TempDM == 0x0A):
DM=2
return DM
def set_inter_measurement_in_ms(self, InterMeasMs):
"""
This function programs the Intermeasurement period in ms.
:param InterMeasMs: Intermeasurement period must be >/= timing budget. This condition is not checked by the API,
the customer has the duty to check the condition. **Default = 100 ms**
"""
self.status = 0
ClockPLL = self.__i2cRead(self.address, VL53L1_RESULT__OSC_CALIBRATE_VAL, 2)
ClockPLL = ClockPLL&0x3FF
self.status = self.__i2cWrite(self.address, VL53L1_SYSTEM__INTERMEASUREMENT_PERIOD,
int(ClockPLL * InterMeasMs * 1.075), 4)
return self.status
def get_inter_measurement_in_ms(self):
"""
This function returns the Intermeasurement period in ms.
:return: Intermeasurement period in ms
:rtype: Integer
"""
tmp = 0
ClockPLL = 0
pIM = 0
tmp = self.__i2cRead(self.address, VL53L1_SYSTEM__INTERMEASUREMENT_PERIOD, 4)
ClockPLL = self.__i2cRead(self.address, VL53L1_RESULT__OSC_CALIBRATE_VAL, 2)
ClockPLL = ClockPLL&0x3FF
pIM= (tmp/(ClockPLL*1.065))
return pIM
def boot_state(self):
"""
This function returns the boot state of the device (1:booted, 0:not booted)
:return: * 1- booted
* 0- not booted
:rtype: Integer
"""
self.status = 0
state = 0
state = self.__i2cRead(self.address,VL53L1_FIRMWARE__SYSTEM_STATUS, 1)
return state
def get_sensor_id(self):
"""
This function returns the sensor id, sensor Id must be 0xEEAC
:return: Sensor ID
:rtype: Integer
"""
self.status = 0
sensorId = 0
sensorId = self.__i2cRead(self.address, VL53L1_IDENTIFICATION__MODEL_ID, 2)
return sensorId
def get_signal_per_spad(self):
"""
This function returns the returned signal per SPAD in kcps/SPAD (kcps stands for Kilo Count Per Second).
:return: Signal per SPAD (Kilo Count Per Second/SPAD).
"""
self.status = 0
SpNb=1
signal = self.__i2cRead(self.address,
VL53L1_RESULT__PEAK_SIGNAL_COUNT_RATE_CROSSTALK_CORRECTED_MCPS_SD0, 2)
SpNb = self.__i2cRead(self.address,
VL53L1_RESULT__DSS_ACTUAL_EFFECTIVE_SPADS_SD0, 2)
signalRate = (2000.0*signal/SpNb)
return signalRate
def get_ambient_per_spad(self):
"""
This function returns the ambient per SPAD in kcps/SPAD
:return: Ambient per SPAD
"""
self.status = 0
SpNb=1
AmbientRate = self.__i2cRead(self.address, RESULT__AMBIENT_COUNT_RATE_MCPS_SD, 2)
SpNb = self.__i2cRead(self.address, VL53L1_RESULT__DSS_ACTUAL_EFFECTIVE_SPADS_SD0, 2)
ambPerSp=(2000.0 * AmbientRate / SpNb)
return ambPerSp
def get_signal_rate(self):
"""
This function returns the returned signal in kcps.