Weird repetition in the middle of the code

I hope I selecected the correct category

I am currently making my own "useless machine" (the box with a switch and some arm assembly inside that doesn't want the switch flipped, etc.. etc..)

I have wrote a simple while loop that moves the servo motor slowly to the desired position instead of usual instaneous movement behavior
This while loop executes as expected but the code afterwards doesn't
for some reason the next two lines are executed twice

Code attached below
arm is my servo name
SPDT is the pin the switch is connected to
LED was initially used for debugging but I haven't removed its code yet
SPDTState is the reading of the switch
(I have the switch connected to VCC and Ground at the throws and the pole acting as a lane director, sorta like a MUX Switch, I hope that's easy to grasp)

#include <Servo.h>

Servo arm;
int armPos = 0;

const int SPDT = 6;
const int LED = LED_BUILTIN;
int SPDTState;

unsigned long timePrevious = 0;
const long timePeriod = 2000;

void setup() {
  // put your setup code here, to run once:
  arm.attach(9);
  pinMode(SPDT, INPUT);
  pinMode(LED, OUTPUT);
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
  //unsigned long timeInitial = millis();
  delay(10);
  int SPDTState = digitalRead(SPDT);
  if (SPDTState == HIGH) {
    while(armPos <= 100) {
      arm.write(armPos);
      armPos++;
      delay(10);
    }
    Serial.println(armPos);
    delay(100);
    Serial.println("Delay Ended");
    arm.write(160);
  }
  else {
    //delay(10);
    armPos = 15;
    arm.write(armPos);
  }
}

The problem is that code lines

    Serial.println(armPos);
    delay(100);
    Serial.println("Delay Ended");

get repeated twice, which I really couldn't figure out why it happens


This is the output I get on the serial monitor per ONE switch activation

Any input is greatly appreaciated and thanks in advance

You never read the SPDTState again, so the while just loops.

Not really. That is why schematics were invented. You see, I'm 50% sure I know what you mean, but if you're also 50% sure of what you say, we're only 25% sure in the end. :slight_smile:

You need to check for state change, and debounce the switch:

byte lastSPDTState = 255; //Impossible value to start with

void loop
{
  byte SPDTState = digitalRead(SPDT);
  if (SPDTState != lastSPDTState)
  {
    lastSPDTState = SPDTState; //State changed, save for next iteration
    delay(50); //Poor mans debounce
    //Do the stuff with SPDTState
  }
  //Handle other stuff
}

Here is my implementation of a useless box if you would like to use any of the code:

Silly Box

Also, the construction and wiring are well documented. I do not provide support however.

how is the SPDT wired?

the conventional approach is to connect the button between the pin and ground, configure the pin as INPUT_PULLUP to use the internal pullup resistor which pulls the pin HIGH and for the button to pull the pin LOW.