How to make a servo sweep once back and forth with the same keyboard key.

I’m trying to make a servo sweep once when I press a keyboard key, say ‘d’, and then sweep back when I press ‘d’ again.

This is the code I’ve tried to write:

#include<Servo.h> // include server library
Servo ser; // create servo object to control a servo
int poser = 0; // initial position of server
int val; // initial value of input

void setup() {
  Serial.begin(9600); // Serial comm begin at 9600bps
  ser.attach(9);// server is connected at pin 9
}

void loop() {
  if (Serial.available()) // if serial value is available 
  {
    val = Serial.read();// then read the serial value
    if (val == 'd' && poser == 0) //if value input is equals to d and the position is 0
    {
      poser += 180; //than position of servo motor increases by 180 ( anti clockwise)
      ser.write(poser);// the servo will move according to position 
      delay(15);//delay for the servo to get to the position
     }
    if (val == 'd' && poser > 0) //if value input is equals to d and the position is greater than 0
    {
      poser -= 180; //than position of servo motor decreases by 180 (clockwise)
      ser.write(poser);// the servo will move according to position 
      delay(15);//delay for the servo to get to the position
    }
  }
}

This only moves the servo once and then nothing else when I press ‘d’.

This code is my attempt at modifying this code:

#include<Servo.h> // include server library
Servo ser; // create servo object to control a servo
int poser = 0; // initial position of server
int val; // initial value of input

void setup() {
  Serial.begin(9600); // Serial comm begin at 9600bps
  ser.attach(9);// server is connected at pin 9
}

void loop() {
  if (Serial.available()) // if serial value is available 
  {
    val = Serial.read();// then read the serial value
    if (val == 'd') //if value input is equals to d
    {
      poser += 180; //than position of servo motor increases by 180 ( anti clockwise)
      ser.write(poser);// the servo will move according to position 
      delay(10);//delay for the servo to get to the position
     }
    if (val == 'a') //if value input is equals to a
    {
      poser -= 180; //than position of servo motor decreases by 180 (clockwise)
      ser.write(poser);// the servo will move according to position 
      delay(10);//delay for the servo to get to the position
    }
  }
}

This code works when I press ‘d’ for one direction and ‘a’ for the other direction. I just want to be able to do this with one key though.

Thanks for the help.

In your first program change this

if (val == 'd' && poser > 0)

to this

else if (val == 'd' && poser > 0)

so that it only applies one of the options at any one time

…R

Robin2:
In your first program change this

if (val == 'd' && poser > 0)

to this

else if (val == 'd' && poser > 0)

so that it only applies one of the options at any one time

...R

That worked perfectly, Thank you!! :slight_smile: