Trying to make an output only HIGH if an input is HIGH

Hi,
I have a arduino micro and I am making a project that requires a motor to only run when an Input is HIGH. The problem is the motor will just go on as soon as I connect it to the arduino even if the input is LOW and it just stays on until I disconnect it. Here is my code and maybe someone can help me out here.

int motorPin = 5;
int switchIn = 8;
int val = 0;
void setup() 
{ 
  pinMode(motorPin, OUTPUT);
  pinMode(switchIn, INPUT);
 
}

void loop() 
{
 val = digitalRead(switchIn);
 
 switch(val) 
 {
   case HIGH:
     digitalWrite(motorPin, HIGH);
     break;
   case LOW:
     digitalWrite(motorPin, LOW);
     break;
    default:
      digitalWrite(motorPin, LOW);
 }
}

How is your switch wired up?
Is one side connect to pin 8 and the other to GND or through a resistor to +5V.
If it connected to GND then you need to turn on internal pullup on pin 8 and reverse the switch logic (LOW = Pressed, HIGH = Released)

How is your switch wired up?
Is one side connect to pin 8 and the other to GND or through a resistor to +5V.
If it connected to GND then you need to turn on internal pullup on pin 8 and reverse the switch logic (LOW = Pressed, HIGH = Released)

I don`t know how to reply to comments so I did this...

I have the switch wired from my batteries to pin 8.

I have the switch wired from my batteries to pin 8.

A switch has two legs. Where does each one connect to? Is the battery ground connected to the Arduino ground? What else is connected to pin 8? Draw a picture!

PaulS:

I have the switch wired from my batteries to pin 8.

A switch has two legs. Where does each one connect to? Is the battery ground connected to the Arduino ground? What else is connected to pin 8? Draw a picture!

Well i dont think im going to draw a picture but one side of the switch connects to the batteries and the other side connects to pin 8. And yes the arduino grounds to the batteries.

Well there's the problem, you have a floating pin 8.

Add a resistor (in the range 1k to 10k or so) from pin 8 to ground.

You missed a trick - if you had wired the switch between pin 8 and ground,
and initialized it thus:

  pinMode (8, INPUT_PULLUP) ;

You wouldn't have needed the resistor (but you would need to reverse the
sense of the logic).

Thank you so much this worked perfectly. I only wish I had posted this sooner!

Your code is unnecessarily long and there is no need for a default case, there are only 2 possibilities.

digitalWrite(motorPin, digitalRead(switchIn));

will do the same thing, mind you so will a length of wire :slight_smile:


Rob