Dear community members,
I hope this is the right place to post this, and I really hope that someone here will be able to look at my code and tell me where I'm going wrong. Thanks in advance for any advice/ aid offered.
Basically, my little girl is building a lighthouse for a show and tell project at school and whilst looking for a spinning light to stick in the top I came across arduino and decide that It would be the most practical way to implement the electronics, whilst also being fun and educational (for both me and her).
Anyway, my code so far looks like this.
#include<Servo.h> // Include servo library
const int button = 2; // Button is attached to pin 2
const int led = A0; // LED is on pin A0
Servo servo; // Create a servo object
int buttonPresses = 0; // Declare a variable to hold number of button pushes
int buttonState = 0; // Variable holds present state of button
int prevButtonState = 0; // Variable holds previous button state
int servoPos = 0; // Variable stores the position of the servo
void setup() {
servo.attach(3); // Servo is on pin 3
pinMode(button, INPUT); // Declare button (pin 2) as input
pinMode(led, OUTPUT); // Declare LED (pin A0) as output
}
void loop() {
buttonState = digitalRead(button); // Set the value of buttonState to current value of button (pin 2)
if(buttonState != prevButtonState) { // if buttonState is not the same as prevButtonState, then...
if(buttonState == HIGH) { // and if the current button state is high ...
buttonPresses = buttonPresses + 1; // Increase the press counter by 1
}
delay(60);
}
if (buttonPresses % 2 == 0) {
digitalWrite(led, HIGH);
}
else {
digitalWrite(led, LOW);
}
}
for(servoPos = 0; servoPos <= 180; servoPos++) {
servo.write(servoPos);
delay(80);
}
for(servoPos = 180; servoPos>=0; servoPos--) {
servo.write(servoPos);
delay(80);
}
}
else if (buttonPresses % 2 != 0) {
digitalWrite(led, LOW);
servo.write(0);
delay(20);
}
while (buttonPresses % 2 == 0) {
for(servoPos = 0; servoPos <= 180; servoPos++) {
servo.write(servoPos);
delay(20);
}
for(servoPos = 180; servoPos>=0; servoPos--) {
servo.write(servoPos);
delay(20);
}
break;
}
prevButtonState = buttonState; // Update lastButtonState for the next loop
}
I assume I'm getting stuck in a loop somewhere or that possibly my use of delay() is interrupting the flow. However I'm uncertain of how to go about fixing it.
What I'd like to happen it that a momentary push button attached to pin 2 is pressed counted and then the button press counter is an even number the servo on pin 9 sweeps back and forth continuously and the led lights.
Any and all help and suggestions welcome. Thanks again!
LH_test.ino (1.75 KB)