Making a servo controlled by a joystick stick to position

Hello. I wrote a script that controls the position of a servo motor with a joystick. This program also includes an if function that detects if the joystick was moved, which might be helpful for the problem. The problem is that when I move the joystick the servo turns but when I turn it back the servo also moves. I know this is supposed to happen, I just need to change it. How would I go about making it so that the amount the joystick is moved on one axis is added to the current servo position? Please help.

#include <Servo.h>
const int servo1 = 3;
Servo myservo1;
const int joyy = 4;
bool movejoy;
void setup() {
  // put your setup code here, to run once:
    myservo1.attach(servo1);  // attaches the servo
    Serial.begin(9600);
    myservo1.write(90);
}

void loop() {
  // put your main code here, to run repeatedly:
    int analogInputy = analogRead(joyy) - 504;
    //Serial.println(analogInputy);
    if (analogInputy > -5 and analogInputy < 5)
    {
      bool movejoy = false;
      Serial.println("Returned");
      myservo1.write(90);
    }
    else
    {
      bool movejoy = true;
      Serial.print("out of range: ");
      Serial.println(analogInputy);
      int highnumber = analogInputy;
      myservo1.write(myservo1.read() + analogInputy / 5.6);
    }
}

You need to think through the action some more. What is the joystick supposed to represent?
If You move the stick and keep it there let the position of the stick represent a certain position. How would any logic understand that the "moving back" of the stick is not a command to move the servo back. How do You supposed to give a "move back" command to the servo.

If I understood you correctly, try the following code.

#include <Servo.h>
const int servo1 = 3;
Servo myservo1;
const int joyy = 4;
int degree = 90;

void setup() {
  // put your setup code here, to run once:
  myservo1.attach(servo1);  // attaches the servo
  Serial.begin(9600);
  myservo1.write(degree);
}

void loop() {
  // put your main code here, to run repeatedly:
  int analogInputy = analogRead(joyy);
  if (analogInputy > 674) {
    degree ++;
    If (degree > 180) {
      degree = 180;
    }
  }
  if (analogInputy < 350) {
    degree --;
    If (degree < 0) {
      degree = 0;
    }
  }
  myservo1.write(degree);
  delay 250);
}

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