/* Light Sense. A light sensor connected to Port 1 is used to distinguish three colours. Last updated. 2.4.02 */ #include "H8.h" #include "InputPorts.h" #include "LCD.h" #include "Speaker.h" #include "Buttons.h" #include "Math.h" #ifndef LightSense_H_DEFINED #define LightSense_H_DEFINED /* A light sensor is connected to Port 1. A light value is interpreted as one of three colours by means of simple thresholds. The thresholds are determined by means of an initial calibration. If a light value is outside the possible light values, the light value is interpreted as an undefined reading. */ /* Range of possible light values. */ #define MinLightValue 340 #define MaxLightValue 950 /* Minimum and maximum readings for a given colour under calibration. */ static uint16 Colour1Min, Colour1Max; static uint16 Colour2Min, Colour2Max; static uint16 Colour3Min, Colour3Max; /* Thresholds calculated from the max and min readings. */ static uint16 Colour1Threshold; static uint16 Colour2Threshold; static uint16 Colour3Threshold; enum Colour_t { UnDef = 4, Colour1 = 1, Colour2 = 2, Colour3 = 3}; typedef enum Colour_t Colour; #define CALIBRATE_N 32 void EstimateMinMaxValue ( byte id , uint16 * Min, uint16 * Max ) { uint16 i, value, max = 0 , min = 1023; lcd_show_digit(id); while( ! Prgm ) lcd_show_int16(Port1Raw()); for (i=0;i < CALIBRATE_N;i++){ value = Port1Raw(); if ( value < min ) min = value; if ( value > max ) max = value; } * Min = min; * Max = max; lcd_show_int16(min); lcd_show_digit(8); BusyPauseMS(2000); lcd_show_int16(max); lcd_show_digit(9); BusyPauseMS(2000); } void LightSenseCalibrate( void ){ EstimateMinMaxValue( 1, & Colour1Min, & Colour1Max ); EstimateMinMaxValue( 2, & Colour2Min, & Colour2Max ); EstimateMinMaxValue( 3, & Colour3Min, & Colour3Max ); while( ! View ); while( View ); SpeakerPlay(3,150); Colour1Threshold = (Colour2Min + Colour1Max) / 2; Colour2Threshold = (Colour3Min + Colour2Max) / 2; Colour3Threshold = MaxLightValue; lcd_show_int16(Colour1Threshold); lcd_show_digit(1); BusyPauseMS(3000); lcd_show_int16(Colour2Threshold); lcd_show_digit(2); BusyPauseMS(3000); lcd_show_int16(Colour3Threshold); lcd_show_digit(3); BusyPauseMS(3000); } Colour LightSenseColour( void ) { Colour result; uint16 RawValue; result = UnDef; RawValue = Port1Raw(); if ( RawValue < MinLightValue ) result = UnDef; else if ( RawValue < Colour1Threshold ) result = Colour1; else if ( RawValue < Colour2Threshold ) result = Colour2; else if ( RawValue < Colour3Threshold ) result = Colour3; else result = UnDef; return result; } void LightSenseInit( void ) { SpeakerInit(); Port1SetActive(); LightSenseCalibrate(); } void LightSenseClose( void ) { Port1SetPassive(); } #endif /* LightSense_H_DEFINED */