Hello, I'm new to Arduino programming and I needed your help. I'm working on a project where I have a servomotor making an infinite pulsating cycle. But I would like to control, through a push button, when the servomotor starts and when it stops. For example, when I click the button once it starts the loop, when I double click it stops. I already have this code done, but it only assumes clicking on the button to start the loop, I can't stop it.
#include <Servo.h>
#include <ezButton.h>
Servo servo1; // Create a servo object to control a servo
#define LOOP_STATE_STOPPED 0
#define LOOP_STATE_STARTED 1
// Variable to store the servo position
int pos = 0;
int ciclos=0;
int loopState = LOOP_STATE_STOPPED;
ezButton button(2);
void setup()
{
// Attaches the servo on pin 6 to the servo object
servo1.attach(6);
Serial.begin(9600);
}
void loop() {
button.loop();
if(button.isPressed())
if (loopState == LOOP_STATE_STOPPED) loopState = LOOP_STATE_STARTED;
else loopState = LOOP_STATE_STOPPED;
if (loopState == LOOP_STATE_STARTED) {
for(pos = 0; pos < 180; pos += 1) // Goes from 0 degrees to 180 degrees in steps of 1 degree
{
servo1.write(pos); // Tell servo to go to position in variable 'pos'
delay(20); // Waits 20ms for the servo reach the position
}
delay(2000);
for(pos = 179; pos > 1; pos = pos-1) // Goes from 179 degrees to 1 degree in steps of 1 degree
{
servo1.write(pos); // Tell servo to go to position in variable 'pos'
delay(20); // Waits 200ms for the servo reach the position
}
delay(2000);
ciclos++;
Serial.println(ciclos);
}
}