I attempting to make a basic set up that opens and closes a lid to a trash can (variable sizes) with a push of a button using the servo library. I think my code is close but I have a feeling that I'm missing something obvious. Specifically, do I even need a If/Else setup? When I change the value in the else section and re-upload, the servo moves to that designated value without even considering the value in the "If" section.
#include <Servo.h>
Servo LidServo;
const int LidTrig = 2;
int buttonState = 0;
void setup() {
pinMode(LidTrig, INPUT);
LidServo.attach(9);
Serial.begin(9600);
}
void loop() {
buttonState = digitalRead(LidTrig);
if (LidTrig == HIGH) {
LidServo.write(30);
delay(3000);
}
else {
LidServo.write(90);
}
}
Thanks for your help!
I bet that it IS considering it. Your button is not pushed so it executes the else portion.
I see what you're saying. Before I change anything, I should note that pushing the tactile button (with pull down) doesn't do anything. I then changed the "if" statement to read
if (LidTrig == LOW) {
Nothing changed....or rather, pushing the button still doesn't do anything. I have the button wired up as in this example:
The "output" of the button is going to pin 2 on the Arduino (UNO). I know the servo is wired properly since I can get it to move by changing the values in the "else" segment. Am I missing something in the wiring of the button?
As I see it, every time through the loop, if the button is pushed, the servo moves to 30 and waits for 3 seconds. If the button is not pushed, the servo moves to 90.
Is that what happens?
If you change the value used by the servo.Write in the 'else' portion then instead of moving to 90 it will move to the angle for that value.
Is that what happens?
When you first run the sketch, it very likely moves to the position indicated in the 'else' portion because the button is not pressed.
const int LidTrig = 2;
...
if (LidTrig == HIGH)
It usually works better to compare the state of a pin rather than the pin number!
Steve
slipstick:
const int LidTrig = 2;
...
if (LidTrig == HIGH)
It usually works better to compare the state of a pin rather than the pin number!
Steve
Bingo! Thank your for your help! Karma added 