Servo not working using 6pin push ON OFF Switch

Hi Everyone I need help!!!
I was making an Iron Man helmet project. I have connected to 9g servos one 6pin push on off switch an Arduino uno and 2 3.7v Lithium batteries. But the servo motors are moving by itself and the button is only working when the Arduino is connected to computer. Here is the pinout of my project

Battery Ground = Servo1 gnd Servo2 gnd Arduino gnd and button center pin to gnd
Battery Positive = Servo1 and Servo2 positive and Arduino Positive
Arduino pin3 = Servo1
Arduino pin4 = button 1st pin
Arduino pin5 = servo2

Here is the code


//open = 120d
//close = 0

#include <Servo.h>

Servo servo;
Servo servo1;
const int button = 4;
int buttonState = 0; 

void setup(){
  Serial.begin(9600);
  servo.attach(3);
  servo1.attach(5);
  pinMode(button, INPUT);
}

void loop(){
  buttonState = digitalRead(button);
  if (buttonState == HIGH) {
    servo.write(120); 
    servo1.write(120);
    Serial.println("ON");
    delay(1000);
  }
  else{
    servo.write(0);
    servo1.write(0);
    Serial.println("off");
    delay(1000);
  }
}

pls help me out why my project is not working and why servo is moving by itself and my switch not giving signal

Thank You
I will be so happy if you will help me

Welcome to the forum

  buttonState = digitalRead(button);
  if (buttonState == HIGH)

What, if anything, is keeping the button pin LOW when the button is not pressed ?

Post a wiring diagram.

That doesn't fit together. If your switch is connected to ground, you must use the internal pullup:
pinMode(button, INPUT_PULLUP);
and ask for low state:
if (buttonState == LOW) {

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.