Setting speed of servomotor controlled by joystick

Hello! I am new to this forum, sorry if I posted this thread in the wrong category.

I designed the mechanism for a wing elevator which I intend to actuate using a DS3240 servomotor, controlled by joystick through Arduino Nano. I was wondering if there is any method of setting the speed of the servo motor, without it varying with different loads.

I know about the "delay" trick, but it won't work as the reading of the joystick is a loop itself and the loads on the servomotor will varry. This is the code I have:

#include <Servo.h>

const int servoPin = 9;
const int joystickPin = A0;
const int numSamples = 5; 
const int deadzone = 10; 

Servo servoMotor;

void setup() {
  servoMotor.attach(servoPin);
  servoMotor.write(90);
  Serial.begin(9600);
}

void loop() {
  int joystickSamples[numSamples]; 
  
  for (int i = 0; i < numSamples; i++) {
    joystickSamples[i] = analogRead(joystickPin);
    delay(5); 
  }
  
  int joystickFilteredValue = 0;
  for (int i = 0; i < numSamples; i++) {
    joystickFilteredValue += joystickSamples[i];
  }
  joystickFilteredValue /= numSamples;
  

  int servoAngle = map(joystickFilteredValue, 0, 1023, 0, 180);
  

  if (joystickFilteredValue > (512 - deadzone) && joystickFilteredValue < (512 + deadzone)) {
   
    servoMotor.write(90); 
  } else if (joystickFilteredValue >= 512 + deadzone && joystickFilteredValue <= 1023) {
    
    servoAngle = map(joystickFilteredValue, 512 + deadzone, 1023, 90, 110);
    servoMotor.write(servoAngle);
  } else if (joystickFilteredValue <= 512 - deadzone && joystickFilteredValue >= 0) {
 
    servoAngle = map(joystickFilteredValue, 0, 512 - deadzone, 80, 90);
    servoMotor.write(servoAngle)
    ;
  }
  

  Serial.print("Angle: ");
  Serial.print(servoAngle);
  Serial.print("Joystick: ");
  Serial.println(joystickFilteredValue);
  
  delay(15); 
}

Why not simply sum the readings as you make them?
You don't need to save them, unless you're doing something like filtering.

Yeah, I tried to do a sampling filter as the servomotor had some "noisy" moves.

You change the setting in small steps, with the time between the steps equivalent to the servo speed. See the BlinkWithoutDelay example.

You can bump it from position to position with a variable delay between each bump, but the actual speed that the servo moves from position to position probably won't change.

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