I am trying to increment a servo from 0 to 180 and hold at 180 until a sound sensor reads above a certain level. If the sound sensor reads above that level, I want the servo to return to 0, and the loop begins again.
my code is below, but my main question is how to hold the servo to increment the servo and then hold it at a desired position until a threshold is met.
Is this an example where millis() should be used? Hope my questions make sense. Gratitude in advance for your help.
//include Servo Library
#include <Servo.h>
//create servo object
Servo nServo;
//create variable to store servo position
int pos = 0;
//create analog sound sensor
int sound = 0;
int soundlevel = A0;
int val;
void setup() {
// attach servo
nServo.attach(9);
//initialize serial communication
Serial.begin(9600);
}
void loop() {
//constantly check to see if threshold is met
int val = analogRead(A0);
Serial.println(val);
//make servo increment from 0 to 180 by 20 degrees every 30 seconds then stay at 180 until sensor threshold is met
if (val <= 200){
for (pos = 0; pos <= 180; pos += 20)
noahServo.write(pos);
delay(1000);
if (pos == 180 && val < 100){
noahServo.write(180);
}
if (val > 200){
noahServo.write(0);
}
}
}