Quantcast
Channel: Arduino Forum - Latest topics
Viewing all articles
Browse latest Browse all 15238

Servo Motor not working

$
0
0

I have a servo motor and i think it's not working. How can i understand if it is working or not? My servo motor is: SM-S2309S.

I have connected it with an arduino uno and a joystick so i can control the servo motor with the joystick. Here is the code

#include <Servo.h>

// Define the pins for the joystick and servo
#define JOYSTICK_X A0
#define JOYSTICK_Y A1
#define SERVO_PIN 9

// Define the range of values for the joystick
#define JOYSTICK_MIN 0
#define JOYSTICK_MAX 1023

// Define the range of angles for the servo motor
#define ANGLE_MIN 0
#define ANGLE_MAX 180

// Define the angle increment
#define ANGLE_INCREMENT 5 // Adjust this value as needed

Servo servoMotor;
int currentAngle = 90; // Start from the center position
int lastJoystickX = JOYSTICK_MIN; // Initialize the last joystick position

void setup() {
  // Initialize serial communication for debugging
  Serial.begin(9600);

  // Attach the servo to its pin
  servoMotor.attach(SERVO_PIN);
}

void loop() {
  // Read the values from the joystick
  int joystickX = analogRead(JOYSTICK_X);

  // Only update the servo position if the joystick position has changed
  if (joystickX != lastJoystickX) {
    // Map the joystick values to the range of servo angles
    int angleChange = map(joystickX, JOYSTICK_MIN, JOYSTICK_MAX, -ANGLE_INCREMENT, ANGLE_INCREMENT);

    // Calculate the new angle
    int newAngle = currentAngle + angleChange;

    // Ensure the new angle is within the allowed range
    if (newAngle < ANGLE_MIN) {
      newAngle = ANGLE_MIN;
    } else if (newAngle > ANGLE_MAX) {
      newAngle = ANGLE_MAX;
    }

    // Update the servo position
    servoMotor.write(newAngle);

    // Update the current angle and last joystick position
    currentAngle = newAngle;
    lastJoystickX = joystickX;

    // Print the joystick value and mapped angle for debugging
    Serial.print("Joystick X: ");
    Serial.print(joystickX);
    Serial.print(", Angle Change: ");
    Serial.print(angleChange);
    Serial.print(", New Angle: ");
    Serial.println(newAngle);
  }

  // Add a short delay to avoid reading the joystick too frequently
  delay(50);
}

7 posts - 2 participants

Read full topic


Viewing all articles
Browse latest Browse all 15238

Trending Articles