Unreliable 'WHILE' loop -

Here's nearly all the sketch. I've removed the bits that don't do anything yet.

// 009 reverse loop
// 10/09/2023 v010






// SERVO LIBRARY - loads servo control library
    #include <Servo.h>
    


// ASSIGN PINS

    int servoPinL = 38; Servo ServoL; // Yellow
    int servoPinU = 30; Servo ServoU; // Yellow
    
    int LOOPL_IR = 47; // White
    int LOOPU_IR = 39; // White
    int HILLTOP_IR = 13; // White 
    int HILLBOT_IR = 12; // yellow
    
    int LOOPS_PWM = 3; // PWM output to loops is on pin 3 MOTOR B Grey ENABLE B
    int LOOPS_CW = 22; // pin 22 controls direction of travel on loops Purple (input 4)
    int LOOPS_ACW = 2; // pin 2 controls direction of travel on loops Blue (input 3)
    
    int TWOWAY_PWM = 5; // PWM output to 2-way section is on pin 5 Motor A Green ENABLE A
    int TWOWAY_UP = 8; // pin 8 controls polarity on two-way section. Yellow (Input 1) 
    int TWOWAY_DOWN = 46; // pin 46 controls polarity on two-way section. Orange (Input 2)

    int FROGU = 23; // pin 23 switches upper frog to yellow (outer rail)
    int FROGL = 31; // pin 31 switches lower frog to white (inner rail)
    

    int SERVO_ISO = 48; // pin 48 relay L1 to isolate servos (yellow)
    


// ASSIGN NUMERIC VALUES
    
    int TRAINSPEED = 90;
    int UPSPEED = 120;
    int DOWNSPEED = 55;
    int SPEEDUP = (((TRAINSPEED-DOWNSPEED)/2)+DOWNSPEED);
    int dec = 70;
    int acc = 70;


void setup() {
  
      Serial.begin(9600); 
      
      // INITIALISE PINS
      ServoL.attach(servoPinL); // Sets up 'servoPinL' as output for LOWER POINT
      ServoU.attach(servoPinU); // Sets up 'servoPinU' as output for UPPER POINT
      
      pinMode(LOOPL_IR, INPUT);
      pinMode(LOOPU_IR, INPUT);
      pinMode(HILLTOP_IR, INPUT_PULLUP); //NOTE: I called this SENSOR2 in my example
      pinMode(HILLBOT_IR, INPUT_PULLUP); //NOTE: I called this SENSOR1 in my example
      
      pinMode(LOOPS_PWM, OUTPUT); // Output to loops PWM 'ENABLE B'
      pinMode(LOOPS_CW, OUTPUT);  // Output to loops polarity input 1
      pinMode(LOOPS_ACW, OUTPUT); // Output to loops polarity input 2
      
      pinMode(TWOWAY_PWM, OUTPUT); // Output to 2-way PWM 'ENABLE A'
      pinMode(TWOWAY_UP, OUTPUT); // Output to 2-way polarity input 3
      pinMode(TWOWAY_DOWN, OUTPUT); // Output to 2-way polarity input 4

      pinMode(FROGL, OUTPUT); // Output to RELAY 1
      pinMode(FROGU, OUTPUT); // Output to RELAY 8

      pinMode(SERVO_ISO, OUTPUT); // output to relay L1 (yellow)
      
      

      // DEFAULTS - the list below is part of setup - define defaults before programe code loop begins
      
      analogWrite(LOOPS_PWM, 0); // loops PWM OFF
      analogWrite(TWOWAY_PWM, 0); // 2-way PWM OFF
      ENDSCW(); // sets loops polarity to CW
      digitalWrite(TWOWAY_UP, LOW); digitalWrite(TWOWAY_DOWN, HIGH); // sets 2-way section to UP
      digitalWrite(FROGL, HIGH); 
      digitalWrite(FROGU, LOW); // Sets lower frog to right white, Sets upper frog to left yellow
      digitalWrite(SERVO_ISO, 1); //turns off power to servos


      
      
      
}

//____________________________________ MAIN LOOP ______________________________________

void loop() {
  


    
 
      
      ENDSCW(); // Both loops set to CW
      
      GOINGUP(); // Prep points etc to go UP
      delay(500);
      UP(); delay(500); // sets polarity & speed to go UP
      Serial.println("HILLBOT UP");
      HILLBOTup(); delay(500);
      Serial.println("HILLTOP UP");
      HILLTOPup();
      LOOPU(); // waits for upper sensor to be tripped
      
      

      GOINGDOWN(); // Prep points etc to go down
      delay(500);
      DOWN(); // sets polarity & speed to go down
      Serial.println("HILLTOP DOWN");
      HILLTOPdown(); delay(500);
      Serial.println("HILLBOT DOWN");
      HILLBOTdown();
      LOOPL(); // waits for lower sensor to be tripped
      
  
  
                            
      }




// ____________________ SUBROUTINES _______________________
void STOP() {
      analogWrite(LOOPS_PWM, 0); // loops PWM OFF
      analogWrite(TWOWAY_PWM, 0); // 2-way PWM OFF
}

// Sets LOOPS polarity to CW
void ENDSCW(){
      analogWrite(LOOPS_PWM, TRAINSPEED);  
      digitalWrite(LOOPS_CW, LOW); digitalWrite(LOOPS_ACW, HIGH); // sets loops polarity to CW
}

// This sub sets points to go UP
void GOINGUP(){
    TWOWAYOFF(); // 2-way power off
    digitalWrite(FROGL, HIGH); // sets frog
    digitalWrite(FROGU, LOW); // relay ON sets frog LEFT **********
    digitalWrite(SERVO_ISO, 0); //turns on power to servos
    ServoU.write(115);delay(500); // upper point LEFT
    ServoL.write(105);delay(500); // changes  lower point 
    digitalWrite(SERVO_ISO, 1); //turns off power to servos
    
}

void UP(){ 
      TWOWAYOFF(); // two-way power OFF 
      digitalWrite(TWOWAY_UP, LOW); digitalWrite(TWOWAY_DOWN, HIGH); // sets 2-way section to UP
      analogWrite(TWOWAY_PWM, TRAINSPEED); // two-way power ON
}

void HILLBOTup(){
  // Checks HILLBOT sensor (HILLBOT SENSOR is SENSOR1)
  Serial.println(digitalRead(HILLBOT_IR));
  while (digitalRead(HILLBOT_IR) == 1){delay(50);}
  analogWrite(TWOWAY_PWM, UPSPEED); // two-way power ON
}



void HILLTOPup(){
  // Checks HILLTOP sensor (HILLTOP is SENSOR2)
  Serial.println(digitalRead(HILLTOP_IR));
  while (digitalRead(HILLTOP_IR) == 1){delay(50);}
  analogWrite(TWOWAY_PWM, TRAINSPEED); // two-way power ON
}



void LOOPU(){
  while (digitalRead(LOOPU_IR) == 1){delay(20);} // waits until upper loop IR is tripped
  
  
}

// This sub sets points to go DOWN
void GOINGDOWN(){
    TWOWAYOFF(); // 2-way power off
    digitalWrite(SERVO_ISO, 0); //turns on power to servos
    ServoU.write(125);delay(500); //sets point RIGHT
    digitalWrite(FROGU, HIGH); // sets frog
    digitalWrite(FROGL, LOW); // sets frog
    ServoL.write(85);delay(500);
    digitalWrite(SERVO_ISO, 1); //turns off power to servos
  
    }

void DOWN(){
     TWOWAYOFF(); 
     digitalWrite(TWOWAY_UP, HIGH); digitalWrite(TWOWAY_DOWN, LOW); // sets 2-way section to DOWN
     analogWrite(TWOWAY_PWM, TRAINSPEED);
     delay(1000);
     }


void HILLTOPdown(){
  // checks HILLTOP sensor 
  Serial.println(digitalRead(HILLTOP_IR));
  while (digitalRead(HILLTOP_IR) == 1){delay(50);}
  analogWrite(TWOWAY_PWM, DOWNSPEED); // slows train on descent
      
}

void HILLBOTdown(){
  Serial.println(digitalRead(HILLBOT_IR));
  while (digitalRead(HILLBOT_IR) ==1){delay(10);}
  analogWrite(TWOWAY_PWM, TRAINSPEED); // increases voltage after descent
      
}



void LOOPL(){
   while (digitalRead(LOOPL_IR) == 1){delay(50);} 
}


// _______________________________________________

void TWOWAYOFF() {
      analogWrite(TWOWAY_PWM, 0); // 2-way PWM OFF
}


void LOOPSACW(){
      analogWrite(LOOPS_PWM, TRAINSPEED); 
      digitalWrite(LOOPS_CW, HIGH); digitalWrite(LOOPS_ACW, LOW); // sets loops polarity to ACW
}










No.
From the sensor output (D12) to +5.
Maybe a 0.1uF capacitor from sensor output to GND.

Okay :slight_smile:
An image will be difficult. The 'thing' I'm building has 4 Arduinos and the wiring us built in over quite a large area. Everything works except this one sensor. There are 12 of these sensors, all using the same basic 'while' code. No problems elsewhere. It's so frustrating.
I will cobble a schematic together.
Thank you for responding and helping.
Every bit of learning is great.

Okay.That makes sense.
Thanks.

If the sensor returns a non-zero answer, that is logical true but not 1.

False is 0. True is not false. That is what expressions in ( ) evaluate to.

In void loop()

if ( readsensor() ) // true if read not 0

So here is a sketch with added serial debug-printing.
The logic is exact the same as in your posted code
I Just added debug-printing

enable timestamp in the serial monitor

// MACRO-START * MACRO-START * MACRO-START * MACRO-START * MACRO-START * MACRO-START *
// a detailed explanation how these macros work is given in this tutorial
// https://forum.arduino.cc/t/comfortable-serial-debug-output-short-to-write-fixed-text-name-and-content-of-any-variable-code-example/888298

#define dbg(myFixedText, variableName) \
  Serial.print( F(#myFixedText " "  #variableName"=") ); \
  Serial.println(variableName);

#define dbgi(myFixedText, variableName,timeInterval) \
  { \
    static unsigned long intervalStartTime; \
    if ( millis() - intervalStartTime >= timeInterval ){ \
      intervalStartTime = millis(); \
      Serial.print( F(#myFixedText " "  #variableName"=") ); \
      Serial.println(variableName); \
    } \
  }

#define dbgc(myFixedText, variableName) \
  { \
    static long lastState; \
    if ( lastState != variableName ){ \
      Serial.print( F(#myFixedText " "  #variableName" changed from ") ); \
      Serial.print(lastState); \
      Serial.print( F(" to ") ); \
      Serial.println(variableName); \
      lastState = variableName; \
    } \
  }

#define dbgcf(myFixedText, variableName) \
  { \
    static float lastState; \
    if ( lastState != variableName ){ \
      Serial.print( F(#myFixedText " "  #variableName" changed from ") ); \
      Serial.print(lastState); \
      Serial.print( F(" to ") ); \
      Serial.println(variableName); \
      lastState = variableName; \
    } \
  }
// MACRO-END * MACRO-END * MACRO-END * MACRO-END * MACRO-END * MACRO-END * MACRO-END *


// 009 reverse loop
// 10/09/2023 v010
// SERVO LIBRARY - loads servo control library
#include <Servo.h>

// ASSIGN PINS

int servoPinL = 38; Servo ServoL; // Yellow
int servoPinU = 30; Servo ServoU; // Yellow

int LOOPL_IR = 47; // White
int LOOPU_IR = 39; // White
int HILLTOP_IR = 13; // White
int HILLBOT_IR = 12; // yellow

int LOOPS_PWM = 3; // PWM output to loops is on pin 3 MOTOR B Grey ENABLE B
int LOOPS_CW = 22; // pin 22 controls direction of travel on loops Purple (input 4)
int LOOPS_ACW = 2; // pin 2 controls direction of travel on loops Blue (input 3)

int TWOWAY_PWM = 5; // PWM output to 2-way section is on pin 5 Motor A Green ENABLE A
int TWOWAY_UP = 8; // pin 8 controls polarity on two-way section. Yellow (Input 1)
int TWOWAY_DOWN = 46; // pin 46 controls polarity on two-way section. Orange (Input 2)

int FROGU = 23; // pin 23 switches upper frog to yellow (outer rail)
int FROGL = 31; // pin 31 switches lower frog to white (inner rail)


int SERVO_ISO = 48; // pin 48 relay L1 to isolate servos (yellow)



// ASSIGN NUMERIC VALUES
int TRAINSPEED = 90;
int UPSPEED = 120;
int DOWNSPEED = 55;
int SPEEDUP = (((TRAINSPEED - DOWNSPEED) / 2) + DOWNSPEED);
int dec = 70;
int acc = 70;


void setup() {

  Serial.begin(115200);
  while(!Serial); // wait until serial interface is ready
  Serial.println("Setup-Start");
  // INITIALISE PINS
  ServoL.attach(servoPinL); // Sets up 'servoPinL' as output for LOWER POINT
  ServoU.attach(servoPinU); // Sets up 'servoPinU' as output for UPPER POINT

  pinMode(LOOPL_IR, INPUT);
  pinMode(LOOPU_IR, INPUT);
  pinMode(HILLTOP_IR, INPUT_PULLUP); //NOTE: I called this SENSOR2 in my example
  pinMode(HILLBOT_IR, INPUT_PULLUP); //NOTE: I called this SENSOR1 in my example

  pinMode(LOOPS_PWM, OUTPUT); // Output to loops PWM 'ENABLE B'
  pinMode(LOOPS_CW, OUTPUT);  // Output to loops polarity input 1
  pinMode(LOOPS_ACW, OUTPUT); // Output to loops polarity input 2

  pinMode(TWOWAY_PWM, OUTPUT); // Output to 2-way PWM 'ENABLE A'
  pinMode(TWOWAY_UP, OUTPUT); // Output to 2-way polarity input 3
  pinMode(TWOWAY_DOWN, OUTPUT); // Output to 2-way polarity input 4

  pinMode(FROGL, OUTPUT); // Output to RELAY 1
  pinMode(FROGU, OUTPUT); // Output to RELAY 8

  pinMode(SERVO_ISO, OUTPUT); // output to relay L1 (yellow)

  // DEFAULTS - the list below is part of setup - define defaults before programe code loop begins
  analogWrite(LOOPS_PWM, 0); // loops PWM OFF
  analogWrite(TWOWAY_PWM, 0); // 2-way PWM OFF
  ENDSCW(); // sets loops polarity to CW
  digitalWrite(TWOWAY_UP, LOW); digitalWrite(TWOWAY_DOWN, HIGH); // sets 2-way section to UP
  digitalWrite(FROGL, HIGH);
  digitalWrite(FROGU, LOW); // Sets lower frog to right white, Sets upper frog to left yellow
  digitalWrite(SERVO_ISO, 1); //turns off power to servos
}

//____________________________________ MAIN LOOP ______________________________________

void loop() {
  ENDSCW(); // Both loops set to CW

  GOINGUP(); // Prep points etc to go UP
  delay(500);
  UP(); delay(500); // sets polarity & speed to go UP
  Serial.println("HILLBOT UP");
  HILLBOTup(); delay(500);
  Serial.println("HILLTOP UP");
  HILLTOPup();
  LOOPU(); // waits for upper sensor to be tripped


  GOINGDOWN(); // Prep points etc to go down
  delay(500);
  DOWN(); // sets polarity & speed to go down
  Serial.println("HILLTOP DOWN");
  HILLTOPdown(); delay(500);
  Serial.println("HILLBOT DOWN");
  HILLBOTdown();
  LOOPL(); // waits for lower sensor to be tripped
}


// ____________________ SUBROUTINES _______________________
void STOP() {
  analogWrite(LOOPS_PWM, 0); // loops PWM OFF
  analogWrite(TWOWAY_PWM, 0); // 2-way PWM OFF
}

// Sets LOOPS polarity to CW
void ENDSCW() {
  analogWrite(LOOPS_PWM, TRAINSPEED);
  digitalWrite(LOOPS_CW, LOW); 
  digitalWrite(LOOPS_ACW, HIGH); // sets loops polarity to CW
}

// This sub sets points to go UP
void GOINGUP() {
  TWOWAYOFF(); // 2-way power off
  digitalWrite(FROGL, HIGH); // sets frog
  digitalWrite(FROGU, LOW); // relay ON sets frog LEFT **********
  digitalWrite(SERVO_ISO, 0); //turns on power to servos
  ServoU.write(115); delay(500); // upper point LEFT
  ServoL.write(105); delay(500); // changes  lower point
  digitalWrite(SERVO_ISO, 1); //turns off power to servos
}

void UP() {
  TWOWAYOFF(); // two-way power OFF
  digitalWrite(TWOWAY_UP, LOW); digitalWrite(TWOWAY_DOWN, HIGH); // sets 2-way section to UP
  analogWrite(TWOWAY_PWM, TRAINSPEED); // two-way power ON
}

void HILLBOTup() {
  // Checks HILLBOT sensor (HILLBOT SENSOR is SENSOR1)
  dbg("entering HILLBOTup",digitalRead(HILLBOT_IR));
  while (digitalRead(HILLBOT_IR) == 1) {
    dbgc("HILLBOTup",digitalRead(HILLBOT_IR) );
    delay(50);
  }
  analogWrite(TWOWAY_PWM, UPSPEED); // two-way power ON
  dbg("leaving HILLBOTup",digitalRead(HILLBOT_IR));
}



void HILLTOPup() {
  // Checks HILLTOP sensor (HILLTOP is SENSOR2)
  dbg("entering HILLTOPup",digitalRead(HILLTOP_IR));
  while (digitalRead(HILLTOP_IR) == 1) {
    dbgc("HILLTOPup",digitalRead(HILLTOP_IR));
    delay(50);
  }
  analogWrite(TWOWAY_PWM, TRAINSPEED); // two-way power ON
  dbg("leaving HILLTOPup",digitalRead(HILLTOP_IR));
}



void LOOPU() {
  dbg("entering LOOPU",digitalRead(LOOPU_IR));
  while (digitalRead(LOOPU_IR) == 1) {
    dbg("LOOPU",digitalRead(LOOPU_IR));
    delay(20); // waits until upper loop IR is tripped
  }
  dbg("leaving LOOPU",digitalRead(LOOPU_IR));
}

// This sub sets points to go DOWN
void GOINGDOWN() {
  TWOWAYOFF(); // 2-way power off
  digitalWrite(SERVO_ISO, 0); //turns on power to servos
  ServoU.write(125); delay(500); //sets point RIGHT
  digitalWrite(FROGU, HIGH); // sets frog
  digitalWrite(FROGL, LOW); // sets frog
  ServoL.write(85); delay(500);
  digitalWrite(SERVO_ISO, 1); //turns off power to servos
}

void DOWN() {
  TWOWAYOFF();
  digitalWrite(TWOWAY_UP, HIGH); digitalWrite(TWOWAY_DOWN, LOW); // sets 2-way section to DOWN
  analogWrite(TWOWAY_PWM, TRAINSPEED);
  delay(1000);
}


void HILLTOPdown() {
  // checks HILLTOP sensor
  dbg("entering HILLTOPdown",digitalRead(HILLTOP_IR));
  while (digitalRead(HILLTOP_IR) == 1) {
    dbgc("HILLTOPdown",digitalRead(HILLTOP_IR));
    delay(50);
  }
  analogWrite(TWOWAY_PWM, DOWNSPEED); // slows train on descent
  dbg("leaving HILLTOPdown",digitalRead(HILLTOP_IR));
}

void HILLBOTdown() {
  dbg("entering HILLBOTdown",digitalRead(HILLBOT_IR));
  while (digitalRead(HILLBOT_IR) == 1) {
    dbgc("HILLBOTdown",digitalRead(HILLBOT_IR));
    delay(10);
  }
  analogWrite(TWOWAY_PWM, TRAINSPEED); // increases voltage after descent
  dbg("leaving HILLBOTdown",digitalRead(HILLBOT_IR));
}


void LOOPL() {
  dbg("entering LOOPL",digitalRead(LOOPL_IR) );
  while (digitalRead(LOOPL_IR) == 1) {
    dbgc("LOOPL",digitalRead(LOOPL_IR) );
    delay(50);
  }
  dbg("leaving LOOPL",digitalRead(LOOPL_IR) );
}


// _______________________________________________
void TWOWAYOFF() {
  analogWrite(TWOWAY_PWM, 0); // 2-way PWM OFF
}


void LOOPSACW() {
  analogWrite(LOOPS_PWM, TRAINSPEED);
  digitalWrite(LOOPS_CW, HIGH); digitalWrite(LOOPS_ACW, LOW); // sets loops polarity to ACW
}


void PrintFileNameDateTime() {
  Serial.println( F("Code running comes from file ") );
  Serial.println( F(__FILE__) );
  Serial.print( F("  compiled ") );
  Serial.print( F(__DATE__) );
  Serial.print( F(" ") );
  Serial.println( F(__TIME__) );
}


// easy to use helper-function for non-blocking timing
boolean TimePeriodIsOver (unsigned long &startOfPeriod, unsigned long TimePeriod) {
  unsigned long currentMillis  = millis();
  if ( currentMillis - startOfPeriod >= TimePeriod ) {
    // more time than TimePeriod has elapsed since last time if-condition was true
    startOfPeriod = currentMillis; // a new period starts right here so set new starttime
    return true;
  }
  else return false;            // actual TimePeriod is NOT yet over
}

best regards Stefan

As you are using delays() a lot

Is there a chance that the sensor is triggered at a point in time when your code is waiting for a delay() to finish?
As long as you are in a delay() your code can not detect a change of a sensor-signal

Here is a sketch that does similar.

This sketch does not do much but should give you some ideas.

I appears there are a lot of helpers pitching in so I will hold back unless you have a specific question about the sketch.

//********************************************^************************************************
//  URL
//
//  LarryD
//
//  Version    YY/MM/DD    Comments
//  =======    ========    ====================================================================
//  1.00       YY/MM/DD    Running code
//
//
//

//********************************************^************************************************
#define LEDon                      HIGH   //PIN---[220R]---A[LED]K---GND
#define LEDoff                     LOW

#define PUSHED                     LOW    //+5V---[Internal 50k]---PIN---[switch]---GND
#define RELEASED                   HIGH

#define CLOSED                     LOW    //+5V---[Internal 50k]---PIN---[switch]---GND 
#define OPEN                       HIGH

#define CLEAR                      HIGH   //+5V---[Internal 50k]---PIN---[sensor]---GND 
#define BLOCKED                    LOW

#define ENABLED                    true
#define DISABLED                   false

#define YES                        true
#define NO                         false

#define EXPIRED                    true
#define stillTIMING                false


//                          m i l l i s ( )   B a s e d   T I M E R S
//********************************************^************************************************
//
struct makeTIMER
{
  //#define ENABLED       true
  //#define DISABLED      false
  //
  //#define YES           true
  //#define NO            false
  //
  //#define EXPIRED       true
  //#define stillTIMING   false

  unsigned long Time;           //when the TIMER started
  unsigned long Interval;       //delay time in ms which we are looking for
  bool          TimerFlag;      //is the TIMER enabled ? ENABLED/DISABLED
  bool          Restart;        //restart this TIMER ? YES/NO

  //****************************************
  //function to check if the TIMER is enabled and check if the TIMER has expired
  bool checkTIMER()
  {
    //*********************
    //is this TIMER enabled and has this TIMER expired ?
    if (TimerFlag == ENABLED && millis() - Time >= Interval)
    {
      //*********************
      //should this TIMER restart again?
      if (Restart == YES)
      {
        //restart this TIMER
        Time = millis();
      }

      //this TIMER is enabled and has expired
      return EXPIRED;
    }

    //this TIMER is disabled and/or has not expired
    return stillTIMING;

  } //END of   checkTIMER()

  //****************************************
  //function to enable the TIMER
  void enableTIMER()
  {
    TimerFlag = ENABLED;

    //restart this TIMER
    Time = millis();

  } //END of   enableTIMER()

  //****************************************
  //function to disable this TIMER
  void disableTIMER()
  {
    TimerFlag = DISABLED;

  } //END of    disableTIMER()

  //****************************************
  //function to restart this TIMER
  void restartTIMER()
  {
    Time = millis();

  } //END of    restartTIMER()

}; //END of   struct makeTIMER

//********************************************^************************************************
/*example
  // *******************
  makeTIMER toggleLED =
  {
  0, 500ul, ENABLED/DISABLED, YES/NO  //.Time, .Interval, .TimerFlag, .Restart
  };
*/

//*******************
makeTIMER heartbeatTIMER =
{
  0, 500ul, ENABLED, YES      //.Time, .Interval, .TimerFlag, .Restart
};

//*******************
makeTIMER scanSwitchesTIMER =
{
  0, 50ul, ENABLED, YES      //.Time, .Interval, .TimerFlag, .Restart
};
//*******************


//********************************************^************************************************
const byte sensor1               = 2;
const byte sensor2               = 3;

const byte heartbeatLED          = 13;

bool sensor1Flag                 = DISABLED;
bool sensor2Flag                 = DISABLED;

byte lastSensor1                 = CLEAR;
byte lastSensor2                 = CLEAR;


//                                       s e t u p ( )
//********************************************^************************************************
void setup()
{
  Serial.begin(115200);

  pinMode(sensor1, INPUT_PULLUP);
  pinMode(sensor2, INPUT_PULLUP);

  pinMode(heartbeatLED, OUTPUT);

} //END of   setup()


//                                        l o o p ( )
//********************************************^************************************************
void loop()
{
  //************************************************              T I M E R  heartbeat
  //is this TIMER enabled and is it time toggle the LED ?
  if (heartbeatTIMER.checkTIMER() == EXPIRED)
  {
    //toggle the LED
    digitalWrite(heartbeatLED, !digitalRead(heartbeatLED));
  }

  //************************************************              T I M E R  scanSwitches
  //is this TIMER enabled and is it time to scan our switches ?
  if (scanSwitchesTIMER.checkTIMER() == EXPIRED)
  {
    checkSwitches();
  }

  //************************************************
  //other non blocking code goes here
  //************************************************

} //END of   loop()


//                               c h e c k S w i t c h e s ( )
//********************************************^************************************************
void checkSwitches()
{
  byte state;

  //************************************************              sensor1
  state = digitalRead(sensor1);

  //has there been a change in "sensor1" state ?
  if (lastSensor1 != state)
  {
    //update to this new state
    lastSensor1 = state;

    //*************************************
    //is the sensor blocked ?
    if (state == BLOCKED)
    {
      sensor1Flag = ENABLED;
    }

    else
    {
      sensor1Flag = DISABLED;
    }

  } //END of this sensor

  //************************************************              sensor2
  state = digitalRead(sensor2);

  //has there been a change in "sensor2" state ?
  if (lastSensor2 != state)
  {
    //update to this new state
    lastSensor2 = state;

    //*************************************
    //is the sensor blocked ?
    if (state == BLOCKED)
    {
      sensor2Flag = ENABLED;
    }

    else
    {
      sensor2Flag = DISABLED;
    }

  } //END of this sensor

} //END of   checkSwitches()



//********************************************^************************************************

Edit:

These may need reversing:

#define CLEAR                      HIGH   //+5V---[Internal 50k]---PIN---[sensor]---GND 
#define BLOCKED                    LOW
1 Like

D13 is always a good pin to use as a relay driver output or something like that, the LED is already wired up and working on the Mega2560.

There's one thing no one's mentioned - if the problem is always the same pin, have you inspected the solder joint of that pin? Whether you built the Mega, or a factory did, it's always possible to have a bad solder joint.

Every Arduino board I know of has an onboard user-led and power led. But I don't know them all. Uno has a led on pin 13, so does the Nano.

If you have a jumper, you have a button. With a pin moded INPUT_PULLUP, jumper it to ground and the button is pressed. Cap sense takes a header pin but more code.

I will review this. Thanks for your input.

Thank you.

Thank you. This is useful. I'm going to experiment with this.

Thank you for your input. It's much appreciated.

I have moved the input pins to two ordinary digital pins. 28 & 29.
It seems I only learn new things when things go wrong.
Thanks for the info.

side note on this

it's not completely true, the code that gets executed during the while() can issue a break and exit the loop, for example if you waited for too long.

I don't want to derail the thread - so won't start a discussion on this. Just wanted to say there are ways and "can't do anything else than waiting" does not represent the exact reality.

1 Like

I wondered this too. I have tried different pins and I've even changed the Arduino.
Thanks for your input.

Thank you.

Thanks for this. I wasn't aware of this before engaging with this forum.
I've now moved the input pins used for these two sensors to D28 & D29. Unfortunately, it hasn't solved the issue.