0
votes

So I've hooked up a Servo motor to digital pin 6 on my Arduino. I want to type a number into the Serial port, and have the Servo rotate to that degree.

I'm trying to make two functions,

1) asks and receives a number from a serial port between 10 & 170. asks for re-entry if invalid. only returns when the number is good.

2) takes in a degree argument, writes the argument as a servo degree, prints out the status: "Servo moved x ticks to y degrees."

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

I am still pretty new to c++, and I think it might just be a matter of variables being mixed up. Using pointers also seems to be an option but haven't gotten far trying to implement those.

1
In recieveNum() you need another return statement at the end of the function. Besides that it's completely unclear what you'r asking. - πάντα ῥεῖ

1 Answers

0
votes

This should work for you:

Function recieveNum should return -1 to indicator invalid input:

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