Skip to content

Commit 20a492a

Browse files
committed
feat: b/w color calibration with defaults
1 parent d960ee2 commit 20a492a

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

arduino_alvik.py

+68
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ def __init__(self):
3737
self.red = None
3838
self.green = None
3939
self.blue = None
40+
self._white_cal = None
41+
self._black_cal = None
4042
self.left_line = None
4143
self.center_line = None
4244
self.right_line = None
@@ -83,6 +85,7 @@ def begin(self) -> int:
8385
sleep_ms(2000)
8486
self.set_illuminator(True)
8587
self.set_behaviour(1)
88+
self._set_color_reference()
8689
return 0
8790

8891
def _begin_update_thread(self):
@@ -530,6 +533,71 @@ def get_touch_right(self) -> bool:
530533
"""
531534
return bool(self.touch_bits & 0b10000000)
532535

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+
533601
def get_color_raw(self) -> (int, int, int):
534602
"""
535603
Returns the color sensor's raw readout

constants.py

+2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11

22
# COLOR SENSOR
33
COLOR_FULL_SCALE = 4097
4+
WHITE_CAL = [444, 342, 345]
5+
BLACK_CAL = [153, 135, 123]

0 commit comments

Comments
 (0)