我遇到了编程线跟踪机器人(带电机和使用Arduino Uno)并使用开关语句来声明电机的不同运动的麻烦。
到目前为止,我有:
void loop() {
int sensorValueright = analogRead(A0);
int sensorValuecentre = analogRead(A1);
int sensorValueleft = analogRead(A2);
switch (direction1) {
case "right":
digitalWrite(12, HIGH); //Establishes forward direction of Channel A
digitalWrite(9, LOW); //Disengage the Brake for Channel A
analogWrite(3, 60); //Motor A at quarter speed
digitalWrite(13, HIGH); //Establishes forward direction of Channel B
digitalWrite(8, LOW); //Disengage the Brake for Channel B
analogWrite(11, 125); //Motor B at half speed
delay(1000);
break;
case "centre":
digitalWrite(12, HIGH); //Forward A
digitalWrite(9, LOW); //Disengage the Brake for Channel A
analogWrite(3, 100); //Motor A = Motor B speed
digitalWrite(13, HIGH); //Forward B
digitalWrite(8, LOW); //Disengage the Brake for Channel B
analogWrite(11, 100); //Motor A = Motor B speed
delay(500);
break;
case "left":
digitalWrite(12, HIGH); //Establishes forward direction of Channel A
digitalWrite(9, LOW); //Disengage the Brake for Channel A
analogWrite(3, 125); //Motor A at Half Speed
digitalWrite(13, HIGH); //Establishes forward direction of Channel B
digitalWrite(8, LOW); //Disengage the Brake for Channel B
analogWrite(11, 60); //Motor B at Quarter Speed
delay(1000);
break;
}
if (sensorValuecentre < 1){
direction1 == "centre"
}
else if (sensorValueright < 1){
direction1 == "right"
}
else if (sensorValueleft < 1){
direction1 == "left"
}
else{
digitalWrite(12, HIGH); //Establishes forward direction of Channel A
digitalWrite(9, LOW); //Disengage the Brake for Channel A
analogWrite(3, 50); //Motor A at low speed
digitalWrite(13, HIGH); //Establishes forward direction of Channel B
digitalWrite(8, LOW); //Disengage the Brake for Channel B
analogWrite(11, 50); //Motor B at low speed
delay(500);
}
delay(1);
}
但是我在编译时遇到以下错误:
line_tracker_test_switch.ino: In function 'void loop()':
line_tracker_test_switch.ino:20:9: error: 'direction1' was not declared in this scope
line_tracker_test_switch.ino:60:3: error: expected ';' before '}' token
line_tracker_test_switch.ino:64:3: error: expected ';' before '}' token
line_tracker_test_switch.ino:68:3: error: expected ';' before '}' token
Error compiling.
非常感谢任何帮助!
答案 0 :(得分:2)
“direction1”尚未在您粘贴的代码中的任何位置声明。
某处需要有一行表格
type direction1;
例如char *direction1;
或int direction1;
告诉编译器什么是direction1。
其他3个错误表明这些行在结尾处缺少分号。
direction1 == "left";
这也不太可能是你想要的。 ==
是相等运算符。 =
是赋值运算符。这也是使用这些运算符的一种奇怪方式,因为字符串与int
和float
等基本类型的工作方式不同。您无法直接比较或分配它们。您将改为访问指针值。
标准C中不允许使用带有switch语句的字符串。
改为创建整数常量
enum {LEFT, RIGHT, CENTRE};
并将“左”替换为LEFT,依此类推。