[英]Serial I/O functions with Servo
So I've hooked up a Servo motor to digital pin 6 on my Arduino. 因此,我已经在Arduino的数字引脚6上连接了一个伺服电机。 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. 1)询问并从10到170之间的串行端口接收一个数字。询问是否再次输入无效。 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." 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);
}
}
I am still pretty new to c++, and I think it might just be a matter of variables being mixed up. 我对C ++还是很陌生,我认为这可能只是变量混在一起的问题。 Using pointers also seems to be an option but haven't gotten far trying to implement those.
使用指针似乎也是一种选择,但是还没有尝试实现它们。
This should work for you: 这应该为您工作:
Function recieveNum
should return -1
to indicator invalid input: 函数
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.