未声明的范围(Arduino 中的 Switch 语句)

Undeclared Scope (Switch Statement in Arduino)

我在为线跟踪机器人(带电机并使用 Arduino Uno)编程以及使用 switch 语句声明电机的不同运动时遇到了问题。
到目前为止,我有:

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.

如有任何帮助,我们将不胜感激!

"direction1" 尚未在您粘贴的代码中的任何位置声明。 某处需要有一行表格 type direction1; 例如 char *direction1;int direction1; 告诉编译器 direction1 是什么。

其他 3 个错误表明这些行末尾缺少分号。 direction1 == "left"; 这也不太可能是您想要的。 == 是相等运算符。 = 是赋值运算符。这也是使用这些运算符的一种奇怪方式,因为字符串与 intfloat 等基本类型的工作方式不同。您不能直接比较或分配它们。您将改为访问指针值。

标准 C 中不允许将字符串与 switch 语句一起使用。

改为创建整数常量 enum {LEFT, RIGHT, CENTRE}; 并将 "left" 替换为 LEFT 等。