Ardurino UNO - 伺服控制

问题描述 投票:0回答:1

我在设计 ardurino 代码时遇到问题,该代码根据 10kOhm 电位计的位置转动迷你伺服器。

这是我的代码:

#include <Servo.h>

Servo myservo;       // create servo object to control a servo
int potpin = 0;      // analog pin used to connect the potentiometer
int val;             // variable to read the value from the analog pin

void setup() {
 myservo.attach(9); // attaches the servo on pin 9 to the servo object
}

void loop() {
    val = analogRead(potpin); // reads the value of the potentiometer (0 to 1023)

    // Map the potentiometer readings to the servo's range
    int servoPosition = map(val, 0, 1023, 0, 180);

    // Ensure servo stops moving when potentiometer is at its extremes
    if (servoPosition == 0 || servoPosition == 180) {
        myservo.write(servoPosition); // sets servo position
    } else {
        myservo.write(servoPosition - 90);
    }

    delay(15); // waits for the servo to get there
}

我希望当电位计值为 1023(最大值)时,舵机旋转 1 整圈并在那里等待。当电位计值为 0(最小)时,舵机将返回完整旋转。

arduino arduino-uno arduino-ide arduino-c++ servo
1个回答
0
投票

我不确定我是否理解你的问题以及你的意思

“确保电位器处于极值时舵机停止移动”

我的猜测是,当电位计处于极端位置时,伺服器会接触机械挡块,并且可能会弹跳。

为了避免这种情况,只需缩小角度范围,留一点余量即可。 例如 5..175 而不是完整的 0..180 范围。

那我不明白为什么你对他0和180的情况区别对待。

#include <Servo.h>

Servo myservo;       // create servo object to control a servo
int potpin = 0;      // analog pin used to connect the potentiometer
int val;             // variable to read the value from the analog pin

void setup() {
 myservo.attach(9); // attaches the servo on pin 9 to the servo object
}

void loop() {
    // this value will probably not reach 1023. 
    // what you can do is read what maximum value you get when the potentiomenter 
    // at max position. eg: Suppose you get 950
    val = analogRead(potpin); 
   
    // Then the 1023 here for the max Value you read
    // I also limited here the angle adding a 5 degree margin
    int servoPosition = map(val, 0, 950, 5, 175);

    then just write the value to the servo.
    myservo.write(servoPosition); // sets servo position
   

    delay(15); // waits for the servo to get there
}
© www.soinside.com 2019 - 2024. All rights reserved.