Controlling a motor using a switch.

I seem to be having some trouble, and I'm not sure exactly where this is occurring.

Here's my code, all I want to do is have a motor start off, and when I hit the switch turn it on. But, it's not functioning like it should.

int d1 = 15;
int m1 = 8;
int m2 = 11;
int r1 = 0;
int r1o = 0;
void setup()
{
  pinMode(d1, INPUT);
  pinMode(m1, OUTPUT);
  pinMode(m2, OUTPUT);
}
void loop()
{
digitalWrite(m2, LOW);
  r1 = digitalRead (d1);

  if (r1 == LOW && r1 != r1o)
  {
    digitalWrite(m1, HIGH);
    delay(50);
    digitalWrite(m1, LOW);

  }
  r1o = r1;
}

I can't seem to get the switch to work. When I have the switch set to low, it works, but in reverse order (motor starts on, then it goes off when I hit the switch). When I switch the if to (r1 == HIGH && ... ) it works just like the LOW.

I do not have a resistor on the switch (it was doing somewhat the same thing before when it was on, and I was thinking that it was dropping the voltage too much to get the 3.3 reference).

The motor is a teeny tiny one, and it runs fine with the current in the arduino.

I would like to have the motors connected to the ground, and only use one pin to control them, but it's just not working.

Any pointers? Thanks!

How about this:

[UNTESTED CODE]

byte d1 = 15;
byte m1 = 8;
byte m2 = 11;

int r1 = 0;
int r1o = 0;

void setup()
{
pinMode(d1, INPUT);
digitalWrite(d1,HIGH);
pinMode(m1, OUTPUT);
pinMode(m2, OUTPUT);
}
void loop()
{
digitalWrite(m2, LOW);

r1 = digitalRead(d1);

if (r1 == LOW && r1 != r1o)
{
digitalWrite(m1, HIGH);
delay(500);
}
r1o = r1;
}

Hmmm, okay this works. Now i'm a little confused, the only thing you did was change the ints -> bytes (takes up less space?), and initialize the d1 as high?

It works perfectly now, thanks a lot.

Actually

I do not have a resistor on the switch

led me to do this:

 pinMode(d1, INPUT);
 digitalWrite(d1,HIGH);

Which enables the internal pullpup resistors. Pull-up resistor - Wikipedia

:slight_smile:

I'm glad it works!