How to limit a servo which is designed to 360 degrees while keeping the purpuse of this code?

354 Views Asked by At

So i took michael reeves turret video and wanted to limit the servo rotation to **180 **degrees so the cables wont do loops o themselves.(the servos are mg996r)

I tried using if and couple other things but no sucsses(I am new to arduino and c# with arduino) and I just expect that I will still be able to control the servos with the mouse but when it hits 180 it will stop until it switches sides.

the setup in c#:

public Stopwatch watch { get; set; }
        private Point previousMousePosition; // Store the previous mouse position
        private bool servoMoving; // Flag to track if the servo is currently moving

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            watch = Stopwatch.StartNew();
            port.Open();
            previousMousePosition = Cursor.Position; // Initialize with the current mouse position
            servoMoving = false;
        }

the mouse and rotation control:

 private void Form1_MouseMove(object sender, MouseEventArgs e) 
        { 
            writeToPort(new Point(e.X, e.Y)); 
        }

        public void writeToPort(Point coordinates)
        {
            if (watch.ElapsedMilliseconds > 15)
            {
                watch = Stopwatch.StartNew();

                int servoX = (int)(coordinates.X * 180.0 / Size.Width); // Map X to 0-180 degrees
                int servoY = (int)(coordinates.Y * 180.0 / Size.Height); // Map Y to 0-180 degrees

                // Ensure servoX and servoY are within the valid range (0-180)
                servoX = Math.Max(0, Math.Min(180, servoX));
                servoY = Math.Max(0, Math.Min(180, servoY));
                port.Write(String.Format("X{0}Y{1}", servoX, servoY));

                servoMoving = true; // Set the flag to indicate the servo is moving
            }
            else
            {
                servoMoving = false; // Set the flag to indicate the servo has stopped moving
            }
        }
1

There are 1 best solutions below

0
Delta_G On

If you have the continuous rotation type of servo that can rotate 360 degrees then these are most likely not the type of servos that afford positional control. For continuous rotation servos, usually writing a value less than 9 causes them to spin one direction and a value greater than 90 causes them to spin the other way. Writing them to 90 degrees will cause them to stop. They don't work like the 180 degree positional type of hobby servo where you can write them to a given angle and expect them to go to that angle. Unless you add some sort of way to measure the position of these servos then you really won't be able to control where they stop.