带伺服的串行I / O功能

时间:2016-03-07 06:59:17

标签: c++ function arduino

所以我把一个伺服电机连接到我的Arduino上的数字引脚6。 我想在串口输入一个数字,让伺服旋转到那个程度。

我正在尝试制作两个函数,

1)从10和10之间的串行端口询问并接收号码。 170.如果无效则要求重新入境。 只有在数字良好时才会返回。

2)接受度数论证,将论证写为伺服度, 打印出状态:“伺服将x刻度移动到y度。”

#include <Servo.h>

Servo myServo;

int deg;
int degree;
int inputDeg;

int ang;
int angle;
int inputAng;

int servoMin = 10;
int servoMax = 175;

int recieveNum(int inputDeg) {
  inputDeg = Serial.parseInt();
  if (inputDeg >= 0 && inputDeg <= 180) {
     Serial.println("You did great!");
     return degree;
  } else {
     Serial.println("Hey! Try giving me a number between 0 and 180 this time.");
  }
 }

int servoTranslate(int inputAng) {
  angle = map(degree, 0, 180, servoMin, servoMax);
  return angle;
}

void setup() {
  Serial.begin(9600);
  myServo.attach(6);
}

void loop() {
  if (Serial.available() == 0) {}
  else {
    recieveNum(deg);

    int finalAng = servoTranslate(degree);

    Serial.print("  Servo moved ");
    Serial.print(degree);
    Serial.print(" tick(s) to ");
    Serial.print(finalAng);
    Serial.println("º");

    myServo.write(finalAng);
  }
}

我仍然是c ++的新手,我认为这可能仅仅是变量混乱的问题。使用指针似乎也是一种选择,但还没有尝试实现这些。

1 个答案:

答案 0 :(得分:0)

这应该适合你:

函数recieveNum应该将-1返回到指标无效输入:

int recieveNum(int inputDeg) 
{
  inputDeg = Serial.parseInt();
  if (inputDeg >= 0 && inputDeg <= 180) {
    Serial.println("You did great!");
    return degree;
  } else {
    Serial.println("Hey! Try giving me a number between 0 and 180 this time.");
  }
  return -1; 
  ^^^^^^^^^
}

void loop() 
{
  if (Serial.available() != 0) 
  {
     if(-1 != recieveNum(deg))
     { // Valid 'deg'
       int finalAng = servoTranslate(degree);
       Serial.print("  Servo moved ");
       Serial.print(degree);
       Serial.print(" tick(s) to ");
       Serial.print(finalAng);
       Serial.println("º");
     }
  } 
  myServo.write(finalAng);
}
相关问题