第一次发帖 新手小白求大佬指教,遇到的问题是在串口中只能进入switch中的第一层,而其他的都进入不了,这是为什么呢?程序如下,求大佬指教
#include<Servo.h>
Servo base, fArm, rArm, claw;
int i;
const int baseMin = 0;
const int baseMax = 180;
const int fArmMin = 40;
const int fArmMax = 110;
const int rArmMin = 30;
const int rArmMax = 170;
const int clawMin = 0;
const int clawMax = 100;
void setup() {
Serial.begin(9600);
Serial.println("请输入要控制的电机与到达角度");
base.attach(11);
fArm.attach(9);
rArm.attach(10);
claw.attach(6);
base.write(90);
fArm.write(90);
rArm.write(90);
claw.write(90);
}
void loop() {
if(Serial.available()>0){
char DJM = Serial.read();
int pos = Serial.parseInt();
servoCmd(DJM, pos); //(电机名, 到达角度)
}
}
void servoCmd(char DJM, int pos){
int dqBData;
int dqFData;
int dqRData;
int dqCData;
switch(DJM){
case 'b':
int dqBData = base.read();
if(pos>=baseMin && pos<=baseMax){
if(pos >= dqBData){
for(i = dqBData; i <= pos; i++){
base.write(i);
delay(15);
}
}else{
for(i = dqBData; i >= pos; i--){
base.write(i);
delay(15);
}
}
Serial.print("接收指令的电机为");
Serial.print(DJM);
Serial.print(", ");
Serial.print("电机转动到");
Serial.print(pos);
Serial.println("°");
}else{
Serial.println("您输入的转动角度超出安全范围,请查正后重试");
}
break;
case 'f':
if(pos>=fArmMin && pos<=fArmMax){
if(pos >= dqFData){
for(i = dqFData; i <= pos; i++){
fArm.write(i);
delay(15);
}
}else{
for(i = dqFData; i >= pos; i--){
fArm.write(i);
delay(15);
}
}
Serial.print("接收指令的电机为");
Serial.print(DJM);
Serial.print(", ");
Serial.print("电机转动到");
Serial.print(pos);
Serial.println("°");
}else{
Serial.println("您输入的转动角度超出安全范围,请查正后重试");
}
break;
case 'r':
int dqRData = base.read();
if(pos>=baseMin && pos<=baseMax){
if(pos >= dqRData){
for(i = dqRData; i <= pos; i++){
rArm.write(i);
delay(15);
}
}else{
for(i = dqRData; i >= pos; i--){
rArm.write(i);
delay(15);
}
}
Serial.print("接收指令的电机为");
Serial.print(DJM);
Serial.print(", ");
Serial.print("电机转动到");
Serial.print(pos);
Serial.println("°");
}else{
Serial.println("您输入的转动角度超出安全范围,请查正后重试");
}
break;
case 'c':
int dqCData = base.read();
if(pos>=baseMin && pos<=baseMax){
if(pos >= dqCData){
for(i = dqCData; i <= pos; i++){
claw.write(i);
delay(15);
}
}else{
for(i = dqCData; i >= pos; i--){
claw.write(i);
delay(15);
}
}
Serial.print("接收指令的电机为");
Serial.print(DJM);
Serial.print(", ");
Serial.print("电机转动到");
Serial.print(pos);
Serial.println("°");
}else{
Serial.println("您输入的转动角度超出安全范围,请查正后重试");
}
break;
case 'o':
int bb = base.read();
int ff = fArm.read();
int rr = rArm.read();
int cc = claw.read();
Serial.print("基座电机base当前角度为");
Serial.print(bb);
Serial.println("°");
Serial.print("前臂电机fArm当前角度为");
Serial.print(ff);
Serial.println("°");
Serial.print("后臂电机rArm当前角度为");
Serial.print(rr);
Serial.println("°");
Serial.print("钳爪claw当前角度为");
Serial.print(cc);
Serial.println("°");
break;
}
}
|