Move servo from A-B-A with microswitch

Super newbie here:

I have a servo being activated by a microswitch. I need to the servo to move from A to B and back to A, all while the microswitch is still pressed. Nothing needs to happen when the switch is released (for now).

Currrently, when I press the switch, it moves from A to B, but then stays there until I release the switch. Then it goes back to A. How can I get it to move through the whole cycle and then wait until the switch is pressed again? I'm using a Teensy 4.0. Thanks!

#include <Arduino.h>
#include <Servo.h>

Servo myservo;

void setup() {
  myservo.attach(9);  

  pinMode(11, INPUT);
  pinMode(13, OUTPUT);
}

void loop() {
  if( digitalRead(11) == LOW){
    digitalWrite(13, HIGH);
    myservo.write(180);
    delay(500);
    myservo.write(0);
  }else{
    digitalWrite(13, LOW);
  }
  }

Do you suppose you could draw a diagram of you circuit and make a picture and post it on the forum? With what you told us, no one can help.

PAul

Perhaps you modified the original post in response to the reply, thanks for the code tags and additional information if that was the case. I think mainly, your problem is that you look at the state of the button, not the change in state (a button press event):
StateChangeDetection
The "state only" method simply mimics the button pin at the output, and that is exactly what you are seeing.

FYI if you did edit the original post, careful that you don't edit posts so as to make the thread seem illogical, thanks...

Oh, and one more thing, please give names to your pins. For one thing, LED_ONBOARD is already defined as (guess what) the on board LED on pretty much any Arduino. So use it instead of just '13'. Also give a name to '11', poor '11' has just been dying to be given a more personal name like, 'buttonPin' or whatever. '9' could be 'servoPin'.

Example:

const int buttonPin = 11;
...
blah = digitalRead(buttonPin);

That did it! Thanks for the help on my first (of many) question(s)!

Hi,
Can you please put your working code in a new post so it will complete this thread for others using it for assistance?

Thanks.. Tom.. :slight_smile:

For context I'm using platformio in vs code and running a teensy 4.0:

#include <Arduino.h>
#include <Servo.h>

Servo myservo;

const int buttonPin = 11;

int buttonState = 0;
int lastButtonState = 0;

void setup() {
  myservo.attach(9);  

  pinMode(buttonPin, INPUT);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {

  buttonState = digitalRead(buttonPin); 

  if (buttonState != lastButtonState) {
    if (buttonState == HIGH) {
      digitalWrite(LED_BUILTIN, HIGH);
      myservo.write(40);
      delay(500);
      myservo.write(90);
    } else {
      digitalWrite(LED_BUILTIN, LOW);
    }
    delay(50);
  }
  lastButtonState = buttonState;

}

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.