/** xmas tree worm full working edition 02 completed at 19hrs 23/10/2008 Created by pete-rogers.co.uk Connectors: Servo to pin 10 Analog sensor to pin 2 Things you can change: Threshold (int) changes the level at which the sensor triggers the servo if it is higher than threshold servo triggered... timerLength(int) changes the timer that holds in the worm... inExtreme(int) the in amount of the servo. Needs to be callibrated outExtreme(int)the out amount of the servo. Needs to be callibrated alpha controls the amount of smoothing needed for the analog signal, higher the smoother **/ //constants int servoPin = 10; int oldRot = 500; int sensorPin = 2; int sec = 0; // this timer is for the delay for the worm to keep hiding int timer = 0; //configerable int timerLength = 100; int alpha = 15; int threshold = 50; int inExtreme = 2500; int outExtreme = 500; //vars boolean extended; boolean retracted; int smoothed; int sensorNum; void setup(){ Serial.begin(9600); Serial.println("initialised"); servoIn(2500); } void loop (){ sensorNum = checkSensor(); sec = sec + 1; if(sec > 1000){ Serial.println(sensorNum); timer = timer + 1; sec = 0; } if (sensorNum < threshold){ timer = 0; if (retracted == false){ Serial.println("go in"); servoIn(inExtreme); } } if (timer > timerLength && extended == false){ Serial.println("go out"); servoOut(outExtreme); timer = 0; } }//end loop //checks the sensor int checkSensor(){ int rawValue = analogRead(sensorPin); if (rawValue > smoothed){ smoothed = smoothed + (rawValue - smoothed)/alpha; }else{ smoothed = smoothed -(smoothed - rawValue)/alpha; } int i = smoothed; return i; } void servoOut(int rot){ retracted = false; Serial.println("out started"); while (true){ if (oldRot == rot){ Serial.println(oldRot); extended = true; break; } //check to see if sensor has detected anything whilst worm is extending sensorNum = checkSensor(); if( sensorNum < threshold){ Serial.println(sensorNum); servoIn(inExtreme); break; } digitalWrite(servoPin, HIGH); // Turn the motor on delayMicroseconds(oldRot); // Length of the pulse sets the motor position digitalWrite(servoPin, LOW); // Turn the motor off oldRot = oldRot - 1; delay(20); } Serial.println("out completed"); }//end servoOut void servoIn(int rot){ extended = false; Serial.println("in started"); for (int i = 0; i < 1000; i ++){ digitalWrite(servoPin, HIGH); // Turn the motor on delayMicroseconds(rot); // Length of the pulse sets the motor position digitalWrite(servoPin, LOW); // Turn the motor off } oldRot = rot; timer = 0; Serial.println("in completed"); retracted = true; }//end servoIn