Controlling a relay with a limit switch

Hi,
I am having trouble with some code that I have written. The code is inspired by a limit switch tutorial and then modified for my project.
I am making an automatic dog ball launcher for my dog and am using a limit switch to control a relay and a servo (The relay powers a weedwhacker motor that runs on wall power).
For some reason, the relay stays on when the switch is not active and the servo spins randomly. I do not think that this is a problem to do with the hardware as I have built the circuit three times and it hasn't worked for two of them.
If anyone can help me it is greatly appreciated.
Cheers.

Here is the code for you all to see:
`#include <Arduino.h>

#include <Servo.h>

// C++ code

//

//Switch to relay ints

int Lswitch = 6;

int relay = 5;

int flag = 0;

//Servo ints

int servocontrol=3;

int servoPos=90;

Servo myServo;

void setup()

{

pinMode(Lswitch, INPUT);

pinMode(relay, OUTPUT);

pinMode(servocontrol,OUTPUT);

Serial.begin(9600);

myServo.attach(servocontrol);

}

void loop()

{

if( (digitalRead(Lswitch) == LOW) && (flag == 0) )

{

flag = 1;

delay(20);

}

if( (digitalRead(Lswitch) == HIGH) && (flag == 1) ) 

{

flag = 0;

delay(20);

}

if ( flag == 1 )

{ Serial.println("GAy");

digitalWrite(relay, HIGH); 

  delay(5000);

  myServo.write(servoPos);

delay(2000);

myServo.write(0);

digitalWrite(relay, LOW);

}

if ( flag == 1 ) 

{

digitalWrite(relay, LOW);

}

digitalWrite(Lswitch, HIGH);

}`


This is my wiring just different pin numbers

Hello and good morning
Please post your sketch well formated and in code tags to see how we can help.

Sorry, I am new to the Arduino forum. How do I use code tags? This is how I wrote it in my code along with the tutorial so I don't know how I could format it to a greater ability.

Hello
Inside the message editor take a view above and you will find
grafik
This are the mentioned code tags.

Is the new edit good? Are the code tags correct?

Hello
I can´t see it.

Hi, @subjext69
How have you got your button wired?

To add code please click this link;

If your button is between 5V and the digital input, you will need a 10K resistor between the input pin and gnd.

If your button is between gnd and the digital input, you will need a 10K resistor between the input pin and 5V.

A circuit diagram of your project would be good.
Don't forget to include powersupply, pin names and component labels.

Thanks.. Tom.... :smiley: :+1: :coffee: :australia:

Wiring diagram.....

Oh I don't have a 10k resistor wired into the limit switch. I will try this. Thank you

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