如何停止串行输入的循环

时间:2019-07-19 05:51:54

标签: c++ loops arduino-uno

如何使用串行输入停止或退出此循环? 这是我一直在使用的简单代码

#define stimulation 4
#define led 13

void setup() {
  Serial.begin(57600);
  pinMode(stimulation,OUTPUT);       
  pinMode(led, OUTPUT);
  digitalWrite(stimulation, LOW);    
  digitalWrite(led, LOW);
  Serial.println("Press any Key");
  while (!Serial.available()){}       
}

void loop() {    
  digitalWrite(stimulation, HIGH);   
  digitalWrite(led, HIGH); 
  delay(20);                         
  digitalWrite(stimulation, LOW);    
  digitalWrite(led, LOW);
  delay(30);                          
}

我正在寻找一个串行输入字符串来退出循环

void loop() {    
  digitalWrite(stimulation, HIGH);   
  digitalWrite(led, HIGH); 
  delay(20);                         
  digitalWrite(stimulation, LOW);    
  digitalWrite(led, LOW);
  delay(30);                          
}

谢谢!

2 个答案:

答案 0 :(得分:0)

由于您的代码无需串行监视器即可工作,因此您可以尝试以下代码段:

void setup() {
  /* other codes */
  Serial.begin(57600);
  int numTries = 0;
  while (!Serial.available()){
    if( ++numTries >= 10) break;
    delay(100);
  }       
}

已编辑:我假设您在Serial显示器无响应的初始设置阶段陷入困境。由于您只希望LED闪烁一次,因此可以使用static关键字来这样做。当变量声明为静态变量时,将在程序生命周期内为其分配空间。

void loop() {    
  static bool done = false; // will initialize only once
  digitalWrite(stimulation, HIGH);   
  digitalWrite(led, HIGH); 
  delay(20);                         
  digitalWrite(stimulation, LOW);    
  digitalWrite(led, LOW);
  delay(30);
  if(!done && Serial.available()) {
     Serial.println("Stimulation Done :)");
     done = true;
  }                          
}

答案 1 :(得分:0)

#define stimulation 4
#define led 13
unsigned long startMillis;
unsigned long currentMillis;
const unsigned long stimTime = 20*60000;  // Stimulation Time (60s = 60000ms)

void setup() {
  Serial.begin(115200);
  pinMode(stimulation,OUTPUT);       
  pinMode(led, OUTPUT);
  digitalWrite(stimulation, LOW);   // force laser OFF before starting 
  digitalWrite(led, LOW);
  Serial.println("Standby:");
  Serial.println("Press any key to start stimulation");
  while (!Serial.available()){}     // do absolutely nothing until serial input received
  startMillis = millis();           // time (ms) when input received
  Serial.println("Now you wait 20min :)");       
}  
void loop() {
  currentMillis = millis();         // time (ms) beginning of the loop
  if (currentMillis - startMillis <= stimTime) {  
  digitalWrite(stimulation, HIGH);  // Laser ON
  digitalWrite(led, HIGH);          // Internal Led ON 
  delay(20);                        // Keep laser ON for 20ms
  digitalWrite(stimulation, LOW);   // Laser OFF
  digitalWrite(led, LOW);           // Internal Led OFF
  delay(30);                        // Keep laser OFF for 30ms
}   
  else {                            // After 20min do nothing (stop stimulation)
    }                          
}