// // LED-based proximity switch demonstration. // White LED is connected to P1_7 // Red LED is connected to P1_4 // Both of these LEDs are external to the Launchpad (not the built-in LEDs). // They are arranged so that they are right next to one another. // This lets the white LED illuminate anything in front of it. // The red LED is used as a sensor, to detect anything close enough to the white LED to be brightly lit. // // When you place your finger or a white card in front of the two LEDs, the program turns on the on-board green LED, // and sends text to the development computer telling what the light level was. // // This version of the program gets better distance and accuracy by collecting 64 samples and throwing out the high and // low 8 samples, then averaging the remaining center samples. This allows us to turn the green LED on when we reach // 90% of the "no signal" value, instead of the 50% we had to use in the simple version (the noise level is such that // without smoothing we need to wait for a lot of change or we get spurious events). // enum { NUM_VALUES=64, NOISE=8 }; int values[ NUM_VALUES ]; void sort( int *list, int left, int right ) { int i = left; int j = right; int pivot = list[ (left + right) / 2 ]; while( i <= j ) { while( list[ i ] < pivot ) i++; while( list[ j ] > pivot ) j--; if( i <= j ) { unsigned int tmp = list[ i ]; list[ i++ ] = list[ j ]; list[ j-- ] = tmp; } } if( left < j ) sort( list, left, j ); if( i < right ) sort( list, i, right ); } unsigned int average( unsigned int which_pin ) { for( unsigned int x = 0; x < NUM_VALUES; x++ ) values[ x ] = analogRead( which_pin ); sort( values, 0, NUM_VALUES-1 ); unsigned int val = 0; for( unsigned int x = NOISE; x < NUM_VALUES-NOISE; x++ ) val += values[ x ]; val /= NUM_VALUES - (2*NOISE); return val; } unsigned int no_signal; void setup( void ) { analogReference( INTERNAL1V5 ); pinMode( A4, INPUT ); pinMode( P1_7, OUTPUT ); pinMode( GREEN_LED, OUTPUT ); digitalWrite( P1_7, HIGH ); for( int x = 0; x < 100; x++ ) { delay( 10 ); // spread the samples out for a better average int val = average( A4 ); if( val > no_signal ) no_signal = val; } Serial.begin( 9600 ); } void loop( void ) { unsigned int percent = (100 * average( A4 )) / no_signal; Serial.print( percent ); if( percent < 90 ) { digitalWrite( GREEN_LED, HIGH ); Serial.println( "% ON" ); } else { digitalWrite( GREEN_LED, LOW ); Serial.println( "% OFF" ); } }