Using 'while (Serial) { ;} does not stop when serial monitor closes

Hey everyone, I’m creating a schoolproject (PC Cooler). Now my code is basically finished but I have one problem. I’m using While (Serial) { ;} for when the serial monitor opens the code would be intercepted to be able to put data in ‘gemetenTemperatuur’ which stands for measured temperature. This works absolutely fine but the problem is, when I close my serial monitor the normal code doesn’t start running again. The code inside the while keeps running untill I reopen the serial monitor.

Anyone knows how to fix this?

#include <LiquidCrystal.h>
#define LM_35 A0
#define rode_led 6
#define blauwe_led 5
#define groene_led 3
#define startTemperatuur 85
#define fan 10
#define fan2 11
float gemetenTemperatuur;

LiquidCrystal lcd(12, 2, 9, 8, 5, 7);

void setup() {
  // put your setup code here, to run once:
  pinMode(rode_led, OUTPUT);
  pinMode(blauwe_led, OUTPUT);
  pinMode(groene_led, OUTPUT);
  pinMode(fan, OUTPUT);
  pinMode(fan2, OUTPUT);
  analogWrite(13, 100);
  lcd.setCursor(0, 0);

void loop() {
  if (Serial.available()){
    while(Serial) {
      gemetenTemperatuur = leesWaarde();
  else {
    int waardeTemperatuurSensor = analogRead(LM_35);
    gemetenTemperatuur = waardeInCelcius(waardeTemperatuurSensor);

The used methods and functions in my code are not needed to be posted because they are unrelated to the problem imo.

Thanks for helping!

The Arduino has no knowledge of whether anything is connected to Serial.

The statement

while (!Serial) ;

is used on the Leonardo and Micro (which use the 32U4 MCU) to allow time for the internal serial connection to be initialised at startup.


while(Serial) only works once. You can not use it to determine if an Arduino is connected to a serial port.

while(Serial) has absolutely no effect if you use an Arduino without native USB (e.g. Uno). So if it has an effect, you're using e.g. a Leonardo. Please tell us which Arduino you use.

If it's one of those, please be aware that you can bring your Arduino to a near-grinding halt once you break the connection to the PC; see Serial.print on Leonardo very slow after disconnection from serial for analysis and solution.

    if (Serial.available()){
        while(Serial) {
            gemetenTemperatuur = leesWaarde();

it's not clear what the above code is trying to do.

available() indicates that something has be received and waiting to be read(). There's no need to to wait for something to be received before sending something using Serial.println()

while(Serial) serves no purpose