I am working on a project at the moment that deploy a model rockets parachute. I am not very skilled at coding so I thought I would ask here. The code is designed to press a button on the ground with a timer and then the parachute is deployed by the servo moving to 90 degrees. I would like the servo to return to 0 degrees after ward without having to press the button again. Would this code work?
#include <Servo.h>
// constants won't change
const int BUTTON_PIN = 7;
const int SERVO_PIN = 9;
Servo servo;
int angle = 0;
int lastButtonState;
int currentButtonState;
void setup() {
Serial.begin(9600);
pinMode(BUTTON_PIN, INPUT_PULLUP);
servo.attach(SERVO_PIN);
servo.write(angle);
currentButtonState = digitalRead(BUTTON_PIN);
}
void loop() {
lastButtonState = currentButtonState;
currentButtonState = digitalRead(BUTTON_PIN);
if(lastButtonState == HIGH && currentButtonState == LOW) {
Serial.println("The button is pressed");
delay(10000);
if(angle == 0)
angle = 90;
else
if(angle == 90)
angle = 0;
delay(5000);
servo.write(0);
}
}
Currently you are waiting for 10 seconds (10 000ms) after the button has been pressed. After the button has been pressed nothing is done except for the Serial.println(...). You then check the if/else statement once. For your code to work you would want something like
if (buttonPressed == true) {
// Wait for 10 seconds
delay(10000);
// Turn servo to 90 degrees
servo.write(90);
// Wait for 5 seconds
delay(5000);
// Turn servo to 0 degrees
servo.write(0);
}
To detect that your button is pressed you will probably want to add a debounce (check https://www.arduino.cc/en/Tutorial/BuiltInExamples/Debounce), but the debounce should not change the logic when the button is detected to be pressed. The debounce only prevents triggering multiple button pressed detections.