@@ -37,6 +37,8 @@ def __init__(self):
37
37
self .red = None
38
38
self .green = None
39
39
self .blue = None
40
+ self ._white_cal = None
41
+ self ._black_cal = None
40
42
self .left_line = None
41
43
self .center_line = None
42
44
self .right_line = None
@@ -83,6 +85,7 @@ def begin(self) -> int:
83
85
sleep_ms (2000 )
84
86
self .set_illuminator (True )
85
87
self .set_behaviour (1 )
88
+ self ._set_color_reference ()
86
89
return 0
87
90
88
91
def _begin_update_thread (self ):
@@ -530,6 +533,71 @@ def get_touch_right(self) -> bool:
530
533
"""
531
534
return bool (self .touch_bits & 0b10000000 )
532
535
536
+ def _set_color_reference (self ):
537
+ try :
538
+ from color_calibration import BLACK_CAL as _B
539
+ except ImportError :
540
+ _B = BLACK_CAL
541
+ try :
542
+ from color_calibration import WHITE_CAL as _W
543
+ except ImportError :
544
+ _W = WHITE_CAL
545
+
546
+ self ._black_cal = _B
547
+ self ._white_cal = _W
548
+
549
+ def color_calibration (self , background : str = 'white' ) -> None :
550
+ """
551
+ Calibrates the color sensor
552
+ :param background: str white or black
553
+ :return:
554
+ """
555
+ if background not in ['black' , 'white' ]:
556
+ return
557
+
558
+ red_avg = green_avg = blue_avg = 0
559
+
560
+ for _ in range (0 , 100 ):
561
+ red , green , blue = self .get_color_raw ()
562
+ red_avg += red
563
+ green_avg += green
564
+ blue_avg += blue
565
+ sleep_ms (10 )
566
+
567
+ red_avg = int (red_avg / 100 )
568
+ green_avg = int (green_avg / 100 )
569
+ blue_avg = int (blue_avg / 100 )
570
+
571
+ if background == 'white' :
572
+ self ._white_cal = [red_avg , green_avg , blue_avg ]
573
+ elif background == 'black' :
574
+ self ._black_cal = [red_avg , green_avg , blue_avg ]
575
+
576
+ file_path = './color_calibration.py'
577
+
578
+ try :
579
+ with open (file_path , 'r' ) as file :
580
+ content = file .read ().split ('\n ' )
581
+ lines = [l + '\n ' for l in content if l ]
582
+ except OSError :
583
+ open (file_path , 'a' ).close ()
584
+ lines = []
585
+
586
+ found_param_line = False
587
+
588
+ for i , line in enumerate (lines ):
589
+ if line .startswith (background .upper ()):
590
+ lines [i ] = f'{ background .upper ()} _CAL = [{ red_avg } , { green_avg } , { blue_avg } ]\n '
591
+ found_param_line = True
592
+ break
593
+
594
+ if not found_param_line :
595
+ lines .extend ([f'{ background .upper ()} _CAL = [{ red_avg } , { green_avg } , { blue_avg } ]\n ' ])
596
+
597
+ with open (file_path , 'w' ) as file :
598
+ for line in lines :
599
+ file .write (line )
600
+
533
601
def get_color_raw (self ) -> (int , int , int ):
534
602
"""
535
603
Returns the color sensor's raw readout
0 commit comments