Switch not working

I have a servo and on and off switch connected. digitRead(4) for some reason keeps outputting as HIGH even though the switch is set to OFF. So even when the switch is off, it still does actions inside the if statement. How do I fix this? Note that I have an Arduino Nano.

​
[pre]​#include <Servo.h>

Servo servo; //initialize a servo object for the connected servo 

int onoffswitch;

void setup() {
 pinMode(4, INPUT); 
 servo.attach(9); // attach the signal pin of servo to pin9 of arduino
}

void loop() { 
 onoffswitch = digitalRead(4);

 if (onoffswitch==1){
 servo.write(60);
 delay(1000);
 servo.write(120);
 delay(1000);
 }

}[/pre]

pinMode(4, INPUT_PULLUP);
...
if (onoffswitch==LOW){

It looks like your switch is connected to ground, the lettering in your non-schematic is so tiny that you will have to verify that.

Hi lefo,

welcome to the forum.
You should post code by using code-tags
There is an automatic function for doing this inthe Arduino-IDE
just three steps

  1. press Ctrl-T for autoformatting your code
  2. do a rightclick with the mouse and choose "copy to forum"
  3. paste clipboard into write-window of a posting

for reliable function switches need a pull-up or pull-down-resistor
read here
http://www.gammon.com.au/switches

best regards Stefan

Do not use the 5v pin for powering servos; you may destroy the Arduino.

There are two thing to pay attention to: