So, I'm trying to learn how to code for Arduino and I've been trying to stop a servo using a pushbutton as in you push the button once and it stops and you push it again and it starts moving.
The main code is from the example for the servo, so all I've done is add a "speed" control and tried to add the button.
I've tried a lot of different approaches but none have worked. My current one is trying to use Interrupt and a flag but clearly am doing smth wrong.
Any help is appreciated,
Thank you!
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
int potPin = A0;
volatile byte stopSweep = HIGH;
boolean mode = HIGH;
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
Serial.begin(9600);
pinMode(potPin, INPUT);
attachInterrupt(digitalPinToInterrupt(3),Reset, FALLING);
}
void loop() {
int increment = analogRead(potPin)/100 ; // adjust speed function
Serial.println(increment);
boolean push = digitalRead(stopSweep);
Serial.print("Stop is " );Serial.println(stopSweep);
Serial. print("mode is ");Serial.println(mode);
if (stopSweep == LOW) {
mode = !mode; //If i write mode = LOW, the servo stops but I can't make it start moving again
}
if (mode == LOW) {
myservo.write(0);
}
else {
for (pos = 0; pos <= 180; pos = pos + increment) { // goes from 0 degrees to 180 degrees
// in steps of +increment degree
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 = 180; pos >= 0; pos = pos - increment) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
}
void Reset() {
stopSweep = !stopSweep;
}