【问题标题】:Do while run but not actually running?运行时执行但实际上不运行?
【发布时间】:2021-06-11 16:08:19
【问题描述】:

嗨,我是一名大学生,我试图在 arduino 中将我的程序从 if 转换为 do,但它似乎不起作用。这是我原来的if程序

  if (pot < 200)
  digitalWrite(12,LOW);
  if (pot > 200) 
  digitalWrite(12,HIGH);
  if (pot > 300)
  digitalWrite(11,HIGH);
  if (pot > 400)
  digitalWrite(10,HIGH);
  if (pot > 500)

转换为

  do{ 
  digitalWrite(12,LOW);
  }while (pot < 200);
  do{ 
  digitalWrite(12,HIGH);
  }while (pot > 200); 
  do{ 
  digitalWrite(11,HIGH);
  }while (pot > 300);
  do{ 
  digitalWrite(10,HIGH);
  }while (pot > 400);
  do{ 

我仍然无法弄清楚我的代码有什么问题,任何帮助将不胜感激。

编辑 1

const int eLDeeR = A0;
void setup()
{
  Serial.begin(9600);
  for(int i=5; i<=12; i++) { 
  pinMode(i,OUTPUT);
  }
}

void loop()
{
   int pot = analogRead(eLDeeR);
   // Do a little animation by writing to the same location
   for ( int i = 0; i < 1; i++ )
      for ( int j = 0; j < 1; j++ )
   delay (200);
  Serial.println(pot);
  for(int i=5 ; i<=12; i++){
    digitalWrite(i,LOW);
    }
  do{ 
  digitalWrite(12,LOW);
  }while (pot < 200);
  do{ 
  digitalWrite(12,HIGH);
  }while (pot > 200); 
  do{ 
  digitalWrite(11,HIGH);
  }while (pot > 300);
  do{ 
  digitalWrite(10,HIGH);
  }while (pot > 400);
  do{ 
  digitalWrite(9,HIGH);
  }while(pot > 500);
  do{ 
  digitalWrite(8,HIGH);
  }while (pot > 600);
  do{ 
  digitalWrite(7,HIGH);
  }while (pot > 700);
  do{ 
  digitalWrite(6,HIGH);
  }while(pot > 800);
  do{ 
  digitalWrite(5,HIGH);
  }while (pot > 900);

}

【问题讨论】:

  • 在第二个示例中,您在某处设置了一次pot,但随后您进入了一个无限循环,而从未更新该值。您还可以在测试条件之前更改引脚......似乎倒退了。也许普通的while cond {set pin} 更好?我认为第一个示例没有问题...看起来您正在制作一个小条形图仪表...也许您想在设置/重置引脚 12 时重置引脚 10 和 11???
  • 可怕的代码。为什么要在loop 循环内放置一个do 循环?可怕的想法。您需要阅读您的数据表并遵循 Atmel/Microchip 代码示例。更重要的是,什么“不起作用”?回答这个问题并写下来。您发布的代码不可测试,您期望什么?

标签: arduino arduino-uno arduino-ide


【解决方案1】:

if 语句很好。您尝试将代码更改为 do-while 语句可能会导致无限循环挂起您的程序。我的建议:

1: 您发布的代码片段不完整,因为发布它们无法正常工作。他们在一个循环中吗?它们应该在一个循环中,就像主循环一样。

2:在循环内,变量“pot”必须在循环内更新,否则条件的结果将永远保持不变。

3:当 pot 小于 300 时,您可能希望将引脚 11 和 10 拉低。当 pot 小于 400 时,将引脚 11 拉低。但是您必须添加显式语句才能做到这一点。引脚不会自动恢复到低电平。

4:使用缩进。它将使您的代码更具可读性并且更容易排除故障。

所以尝试类似:

void loop() {
  
  [update pot variable here] 
  
  if (pot > 200)
    digitalWrite(12,HIGH);
  else
    digitalWrite(12,LOW);
  if (pot > 300)
    digitalWrite(11,HIGH);
  else
    digitalWrite(11,LOW);    
  if (pot > 400)
    digitalWrite(10,HIGH);
  else
    digitalWrite(10,LOW);
}

【讨论】:

  • 嗯,我的代码实际上可能处于循环中,但我仍然对 do while 函数摸不着头脑,因为我的任务是 do while 形式。我会尝试你的建议谢谢你的回复。 p.s 我编辑了我在 do while 下面发布了整个程序的帖子。
猜你喜欢
  • 2017-03-26
  • 2015-08-28
  • 1970-01-01
  • 1970-01-01
  • 2016-11-15
  • 1970-01-01
  • 2011-08-06
  • 2015-02-22
  • 1970-01-01
相关资源
最近更新 更多