Problem with while loop.

I need help with this code.
What I am trying to do is when the sensor is detected and during the time it is detected, variable counter1 should only count once.

void loop() {
   Serial.begin(9600);
   
   lego.SingleOutput(PWM, PWM_FWD6,BLUE,CH4); // Passanger train starts

  detected = digitalRead(stationSensor1);
  
   if (detected == LOW){
    Serial.write("Testning!");
    do {
      Serial.write("Test");
    }while(detected == LOW);
     
     Serial.write("Testning22!");
      counter1 = counter1 + 1;
    }
}

Can someone help me?

Firstly Serial.begin() belongs in the setup() function, not loop()

Your 'detected' variable is not updated in the loop so it can never change. There's no magic link
between a variable and a pin - you have to call digitalRead each and every time you want to
test a pin.

The State Change Detection tutorial in the Arduino IDE may be helpful once you overcome the more basic issues.

Also
http://snippets-r-us.com

A person with 5 posts should know better.

READ THE LOCKED TOPICS ABOUT HOW TO POST.