I want to modify my code to move a servo motor only for the duration of time that the sensor is touched and stop moving immediately when the sensor is no longer touched. The code I have moves the sensor from 0 to 90 and back. That motion is completed even when you remove your finger. I want it to be such that if you remove your finger before the servo reaches 90 degrees the servo stops. And the servo starts up again toward 90 when touch resumes. This is the code I currently have:
//when signal output is high the sensor is being pressed
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
int sensor=11; //initialises component to arduino digital pins
led=13;
void setup() {
myservo.attach(9);
pinMode(led,OUTPUT);
pinMode(sensor,INPUT);
Serial.begin(9600);
}
void loop() {
int value=digitalRead(sensor);
if(value == HIGH){
digitalWrite(led, HIGH);
for (pos = 0; pos <= 90; pos += 1) {
myservo.write(pos); // tell servo to go to position in
variable 'pos'
delay(15); // waits 15ms for the servo to reach the
position
}
for (pos = 90; pos >= 0; pos -= 1) { // goes from 90 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in
variable 'pos'
delay(15);
}
Serial.println("TOUCHED ");
}else{
digitalWrite(led, LOW);
Serial.println("NOT TOUCHED ");
delay(500);
}
}