First of all i should establish I'm a complete novice at code, I have barely any understanding of it whatsoever.
That being said, I've found code which should let me move a servo from 0 to 180, and from 180 to 0 in separate button presses (one press should open the visor, one should close it). However when I push the button, the visor opens, then closes after a second. The code is down below, if anyone would be able to help out it would be greatly appreciated!
The code:
const int servoPin = 2;
const int buttonPin = 3;
#include <Servo.h>
Servo visorServo;
void setup() {
visorServo.write(180); // Initial position
visorServo.attach(servoPin);
pinMode(buttonPin, INPUT_PULLUP); // Connect button between pin and GROUND. LOW when pushed.
}
void loop() {
static unsigned long lastPushedTime = 0;
static boolean visorClosed = true;
static boolean lastButtonState = HIGH;
boolean newButtonState = digitalRead(buttonPin);
// If the button is down and it has been a while since it was last down...
if (newButtonState == LOW && lastButtonState == HIGH && millis() - lastPushedTime > 100) {
lastPushedTime = millis();
if (visorClosed) {
visorServo.write(0); // Open visor
visorClosed = false;
}
else { // Viso is open
visorServo.write(180); // Close visor
visorClosed = true;
}
}
lastButtonState = newButtonState;
}