Servo moving without input

Hello. I'm new to all this, and I'm trying to get a servo (pin 6) to loop movement after it receives input from pin 2. However, the servo starts the loop as soon as setup finishes.

// C++ code
//
#include <Servo.h>

int poop = 0;

Servo servo_6;

int counter;

void setup() {
  servo_6.attach(6, 500, 2500);
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(2, INPUT);

  servo_6.write(0);
  // countdown to active- sleeby mode
  delay(1000);  // Wait for 3000 millisecond(s)
  // wakey mode now primed-wait for power to commence
  digitalWrite(LED_BUILTIN, HIGH);
  delay(500);  // Wait for 500 millisecond(s)
  digitalWrite(LED_BUILTIN, LOW);
}

void loop() {

  if (digitalRead(2) == HIGH) {
    ;
    servo_6.write(90);
    delay(1000);  // Wait for 1000 millisecond(s)
    ;
    servo_6.write(0);
    delay(1000);  // Wait for 1000 millisecond(s)
  }
}

How is pin 2 wired to the switch ?
is there a pull up somewhere?

1 Like

Unexpected servo behavior is usually due to an inadequate power supply, like trying to use the 5V Arduino output for servo power. A separate power supply is the solution, but don't forget to connect the grounds.

1 Like

This may keep some money in you pocket and save the trash haller some work.
Gil's Crispy Critter Rules for Processor Hardware:
Rule #1: An Arduino is NOT a Power Supply!
Rule #2: Never connect anything inductive (motors, speakers) directly to an Arduino!
Rule #3: Avoid connecting or disconnecting wires while the power is on.
Rule #4: Do not apply power to any pin unless you are certain of what you're doing.
Rule #5: Do not exceed the maximum voltage ratings.
Rule #6: Many Arduinos cannot power transmitters directly.
Rule #7: Before powering your project, take a break and double-check the wiring.

LaryD’s Corollaries:

Coro #1: When starting out, add a 220Ω resistor in series with both input and output pins to protect against shorts.
Coro #2: Invest in a Digital Multi-Meter (DMM) to measure voltages, currents, and resistance.

Note: Violating these rules can turn your Arduinos into crispy critters. For optimal performance, keep your wires under 25 cm (10 inches).

Additional Tips:

The L293 motor driver, though common, is inefficient as it can lose around 3V as heat when driving both legs of a motor. Consider using a motor driver with MOSFET outputs to reduce heat loss and conserve battery power.

For more on powering Arduino boards, explore this guide: Powering Alternatives for Arduino Boards.
1 Like

I change my design just a little. The 4N35 is triggered by an alarm clock i hijacked (12v, 2a) Before I do something incredibly stupid...