IMHO a short "use millis()" is wayy too lesss instruction to make this understandable
I will explain in comments inside the code what your code is doing
#include <Servo.h>
const int LED = 12;
const int buttonPin2 = 7;
const int buttonPin1 = 8;
const int servo1Pin = 9;
const int servo2Pin = 10;
Servo servo1;
Servo servo2;
int state = LOW;
void setup() {
servo1.attach(servo1Pin);
servo2.attach(servo2Pin);
pinMode(buttonPin1, INPUT);
pinMode(buttonPin2, INPUT);
pinMode(LED, OUTPUT);
}
void loop() {
delay(150); // processor is absorbed for 150 milliseconds in twiddling his thumbs unable to do anything else
if (digitalRead(buttonPin1) == LOW) {
servo1.write(0);
servo2.write(0);
delay(1000); // processor is absorbed for 1 second in twiddling his thumbs unable to do anything else
servo1.write(180);
servo2.write(180);
delay(1000); // processor is absorbed for 1 second in twiddling his thumbs unable to do anything else
servo1.write(90);
servo2.write(90);
delay(1000); // processor is absorbed for 1 second in twiddling his thumbs unable to do anything else
}
delay(150); // processor is absorbed for 150 milliseconds in twiddling his thumbs unable to do anything else
// you have to hold down your button until all the delaying has been finished
// only them your code will react on the button press
if (digitalRead(buttonPin2) == LOW) {
state = !state;
digitalWrite(LED, state);
}
}
now the question is how to solve this?
delay() is blocking. Your code has to be re-written in a non-blocking way
This is based on the following basic rule
let do function loop() ALL looping and use ZERO delay()'s
all other functions work in a quickly jump in / quickly jump out manner
If really all functions can rely on
"the code will call me in about 100 microseconds again and again and again"
These functions do not need any inner while-loop or for-loop
zero delay(), zero while-loops and zero-for-loops are allowed
This is a totally different approach than
- switch LED on
- wait for 2 seconds // processor is absorbed for 2 second in twiddling his thumbs unable to do anything else
- switch LED off
Still you need to "delay" executing parts of your code.
This is done in a different way by a very often repeated checking how much time has passed by
This needs thinking new. And this will need some time to learn
I have written a little tutorial that eplains how to use non-blocking timing
best regards Stefan