how is the state==HIGH is consider high

i have problem with my project? can anyone help me?
the motor should run when pin 7 should be connect to 5v, but the problem is the motor run before i connect pin 7 to 5v… the other side just connect to the air… but motor start running

servo_dc.ino (1.23 KB)

#include <Servo.h>

Servo myservo; // create servo object to control a servo

int pos = 0; // variable to store the servo position
int IN3 = 5;
int IN4 = 4;

void setup() {
pinMode (7, INPUT);
myservo.attach(12); // attaches the servo on pin 12 to the servo object
pinMode (IN4, OUTPUT); // output 4 connect to pin 4
pinMode (IN3, OUTPUT); // output 3 connect to pin 5
}

void loop() {
int state = digitalRead(7);
if (state == HIGH)
{
digitalWrite (IN4, HIGH); // Motor turn clockwise
digitalWrite (IN3, LOW);

for (pos = 0; pos <= 45; pos += 1) // goes from 0 degrees to 90 degrees
{
myservo.write(pos); // tell servo to go to position in variable ‘pos’
delay(20); // waits 15ms for the servo to reach the position
}

for (pos = 45; pos >= 0; pos -= 1) // goes from 90 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable ‘pos’
delay(20); // waits 15ms for the servo to reach the position
}
}

else if (state == LOW)
{

digitalWrite (IN4, LOW);
digitalWrite (IN3, LOW);

}
}

Show us how your switch is wired.

Hi

Indent your code (press ctrl-T in the IDE) Give meaningful names to your pins. IN3 or IN4 for OUTPUT pin is somewhat ridiculous Do you have a servo or a motor? How is pin7 wired? Do you have a pull down?

other side just connect to the air

--> so if that is a wire hanging off Pin 7, you built an antenna :) you'll read weird state based on what your antenna sees

(If you don't want to add extra wiring and resistor and want to keep your wire up in the air, use the built in pull-up

const byte buttonPin = 7;
...
pinMode(buttonPin, INPUT_PULLUP);
....

and test against low (connect to GND not 5v to trigger)

aarg: Show us how your switch is wired.

how can i show? sorry im new here. my sort video cannot be uploaded here

fooyu523: . the other side just connect to the air.. but motor start running

It is called a floating pin if you leave it unconnected. You will get random reading from it. You should connect it to ground via a 10k ohm (value not important, but should be minimum a few kilo ohm) resistor. It is called a pull-down resistor as it makes sure you get a low reading before you push your button. A small current will leak through the resistor to ground when your button feed 5 volt to the pin, but it not a problem.

fooyu523: how can i show? sorry im new here. my sort video cannot be uploaded here

Please don't do videos; waste of (at least my) bandwidth. Draw a diagram on paper, scan it or take a photo, make sure it's a reasonable size (100k or so) and post it here.

And please edit your reply #1 and add code tags Add ``` [code] ``` before your code Add ``` [/code] ``` after your code