« LED as light sensors | Main | comics »

range finder + night rider

To make the range finder work (better), I had to first calibrate it to find the initial state of things. When there's a change in value that exceeds this initial value, I know something REALLY moved infront of it (instead of just noise).

Code is below

// pin definitions
int range_pin = 0; // where the range pin is
int range_value = 0; // range value
int switch_pin = 2; // pull switch - re-calibrate

// output pins
int led1 = 4;
int led2 = 5;
int led3 = 6;
int led4 = 7;

#define TOTAL_OUTPUT_PINS 4
#define BASE_PIN 4

// some global values we need
int base_value = 0;
int was_on = 0;
int calibrated = 0;

// scale of base value
#define SCALE 50

// turn on debug
#define DEBUG 1

void setup() {

pinMode(switch_pin,INPUT);

// outputs
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);
pinMode(led3,OUTPUT);
pinMode(led4,OUTPUT);

// initialize serial communications
Serial.begin(9600);
}

void loop() {

// calibration
if ( digitalRead(switch_pin) == HIGH ) {

// pull range and convert it to a base value
range_value = analogRead(range_pin);
base_value = scale_value(range_value);

#ifdef DEBUG
Serial.print("range value ");
Serial.println(range_value);
Serial.print("base value ");
Serial.println(base_value);
#endif

calibrated = 1; // mark as calibrated
}

if ( calibrated ) {

int new_value = 0;

// pull value again
range_value = analogRead(range_pin); // read the pot value
new_value = scale_value(range_value);

#ifdef DEBUG
Serial.print("new value is ");
Serial.println(new_value);
Serial.print("base value is ");
Serial.println(base_value);
#endif

// check the change in scaled value
if ( base_value < new_value ) {
digital_constant();
was_on = 1;
Serial.println("digital constant");
} else if ( base_value == new_value && was_on == 1 ) {
digital_end();
was_on = 0;
Serial.println("digital off");
}
}
}

// how to scale the values
int scale_value ( int value ) {
return value / SCALE;
}

// digital light ending
int digital_end() {

int ii;
int jj;
for ( ii = 0; ii < TOTAL_OUTPUT_PINS; ii++ ) {
for ( jj = 0; jj < TOTAL_OUTPUT_PINS; jj++ ) {

if ( jj == ii )
digitalWrite(BASE_PIN + jj,HIGH);
else
digitalWrite(BASE_PIN + jj,LOW);

delay(10); // give it some time
}
}

// ending condition
digitalWrite(led4,LOW);

}


// digital light sequence - need to make this have fading effect
int digital_constant() {

int ii;
for ( ii = 0; ii < TOTAL_OUTPUT_PINS; ii++ ) {
digitalWrite(BASE_PIN + ii,HIGH);
}
}