如何将设计为360度的舵机限制在360度,同时保持此代码的用途?

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

提问人:havi hugot 提问时间:9/6/2023 更新时间:9/6/2023 访问量:65

问:

所以我拍了迈克尔·里夫斯(Michael Reeves)的炮塔视频,并希望将伺服旋转限制在**180**度,这样电缆就不会自己循环。(舵机为MG996R)

我尝试使用 if 和其他一些东西,但没有成功(我是 arduino 和 c# 和 arduino 的新手),我只是希望我仍然能够用鼠标控制舵机,但当它达到 180 时,它会停止直到它换边。

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;
        }

鼠标和旋转控件:

 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
            }
        }
C# 数学 Arduino 传感器 伺服

评论


答:

0赞 Delta_G 9/6/2023 #1

如果您有可以 360 度旋转的连续旋转类型的伺服器,那么这些很可能不是提供位置控制的伺服器类型。对于连续旋转舵机,通常写入小于 9 的值会导致它们向一个方向旋转,而大于 90 的值会导致它们向另一个方向旋转。将它们写入 90 度会导致它们停止。它们不像 180 度位置类型的爱好伺服那样工作,您可以在其中将它们写入给定的角度并期望它们转到该角度。除非你添加某种方法来测量这些伺服系统的位置,否则你真的无法控制它们停止的位置。