Serial.Available question

All:

Appreciate some help, I am sure the solution is simple. Basically in the Loop() I want the code that toggles outputs on and off to run without interruption UNTIL it receives data from the serial port. This doesn't work because the while() is in a endless loop until some data is received, so the port toggling never occurs.

void loop() {
  unsigned long currentMillis = micros(); //for timing
  char inchar;
  
   while (!Serial.available()); //stay here as long as COM port is empty   
    inchar = Serial.read();        // read next available byte

  
  if( inchar == 'd' || inchar == 'D') {
    USARTDisplay(); 
  }
  else if( inchar == 's'|| inchar == 'S') {
    USARTMenu();
  }
 
  

         if((outpin_state == HIGH) && (currentMillis - previousMillis >= co2_ontime)) {
             outpin_state = LOW;
             previousMillis = currentMillis;
            digitalWrite(CO2_OUTPIN, LOW);
          
           }
          else if ((outpin_state == LOW) && (currentMillis - previousMillis >= co2_offtime))
           {
            outpin_state = HIGH;
            previousMillis = currentMillis;
           digitalWrite(CO2_OUTPIN, HIGH);
            
           }
      

   }

Use 'if' instead (but you have to re-work the logic, it's not a drop in replacement). Colloquially, what you want is, "if something do this" not "while not something wait, then do this".

Thanks for the reply, but wouldn’t data be missed as the code is processing something else. I did try some variants of While (Serial.available <0) etc so that if the buffer is empty it continues on. Couldn’t get that to work either.

but wouldn’t data be missed as the code is processing something else

Only if whatever it is you’re doing takes so long the input buffer overflows.

This should work:

void loop() {
  unsigned long currentMillis = micros(); //for timing

  if (Serial.available())  {
    char inchar = Serial.read();        // read next available byte
    if ( inchar == 'd' || inchar == 'D') {
      USARTDisplay();
    }
    else if ( inchar == 's' || inchar == 'S') {
      USARTMenu();
    }
  }
  
  if ((outpin_state == HIGH) && (currentMillis - previousMillis >= co2_ontime)) {
    outpin_state = LOW;
    previousMillis = currentMillis;
    digitalWrite(CO2_OUTPIN, LOW);
  }
  else if ((outpin_state == LOW) && (currentMillis - previousMillis >= co2_offtime))
  {
    outpin_state = HIGH;
    previousMillis = currentMillis;
    digitalWrite(CO2_OUTPIN, HIGH);
  }
}

Thanks so much. That did the trick. :slight_smile: