Hello:)
I am trying to make a circuit where when my touch sensor is activated (touched) the servo motor does its rotations and two LEDs light up.
So far I have been able to make this work, except it works in the opposite way from how I want. Right now the LEDs and servo are on from the start and turn off whenever I touch the sensor.
I have searched up examples on Google and here, and I have tried to follow ones that helped others. But nothing has seemed to work for me.
Any code or help is appreciated!
Thank you,
myyarduino
Here is my code:
#include <Servo.h>
Servo myservo;
int pos = 0; // position of servo motor
int pinLED = 13;
int pinLED2 = 5;
int pinServo = 9;
int pinTouch = 12;
int sensorValue; // a variable to store the current state of the sensor in
int prevState = HIGH;
//int currState;
void setup() {
// servo motor
myservo.attach(9); // attach servo motor to pin 9
// touch sensor
pinMode(pinServo, OUTPUT);
pinMode(pinLED, OUTPUT);
pinMode(pinLED2, OUTPUT);
pinMode(pinTouch, INPUT);
}
void loop() {
// touch sensor
sensorValue = digitalRead(pinTouch); // read the sensors value (either high or low) and store in sensorValue
digitalWrite(pinLED, sensorValue); // write that value to pinLed
digitalWrite(pinLED2, sensorValue);
digitalWrite(pinLED, digitalRead(pinTouch)); // led should read signal from the sensor
digitalWrite(pinLED2, digitalRead(pinTouch));
if (sensorValue != prevState)
{
digitalWrite(pinServo, LOW); // turn off
digitalWrite(pinLED, LOW); // turn off
digitalWrite(pinLED2, LOW);
} else {
digitalWrite(pinServo, HIGH); // turn on
digitalWrite(pinLED, HIGH); // turn on
digitalWrite(pinLED2, HIGH);
// servo motor
for (pos = 0; pos <= 50; pos += 1) // change from 0 degrees to 50 degrees
{
myservo.write(pos); // go to position defined in for loop
delay(20); // take 20 miliseconds to complete rotation
}
for (pos = 50; pos >= 0; pos -= 1) { // change from 0 degrees to 50 degrees
myservo.write(pos); // go to position defined in for loop
delay(20);
}
}
}