Need help coding a button switch relay

I need help with coding a button switch relay that whenever you press the temporary button switch it turns on for 25 seconds then turns off. I am an extremely novice coder, so please explain it very simply.

const int buttonPin = 8;
const int relayPin = 7;
int buttonState = 1;
void setup() {
  pinMode(7, OUTPUT);// connected to S terminal of Relay
 pinMode(buttonPin, INPUT);

}
void loop() {
buttonState = digitalRead(buttonPin);
{
if (buttonState == LOW)
  digitalWrite(relayPin,LOW);
  delay(3000); 
if (buttonState == HIGH)  
  digitalWrite(relayPin,HIGH);
 delay(25000);
}}

This is what we have so far, also cannot upload attachments so this is just the text. The button's wires are connected to ground and pin 8 and the relay's wires are connected to pin 7 and ground.

1 Like

Welcome to the forum

How is the button input wired ?
Have you got a pullup or pulldown resistor in place keeping the input at a known state at all times ?

As to your requirements, will the sketch ever be required to do anything other than what you have described so far ? I ask because it may affect the solution offered

First, congratulations for posting your code properly!

  1. The way you have it coded it implies you have the button wired to ground with an external pull up resistor. If that is not the case there is a problem with your button. I would suggest wiring the button to ground and using the internal pull up resistor.
  2. You are basing your conditionals on whether the button IS pressed and not when the button BECOMES pressed. You want to know when the button becomes pressed to start a timer. See the following tutorial: StateChangeDetection
  3. In the code below I assume you think both the digitalWrite() and delay() calls only execute if the conditional is true. That is not the case below. Only the digitalWrite() executes as part of the conditional. The delay() calls are executing for every loop().
if (buttonState == LOW)
  digitalWrite(relayPin,LOW);
  delay(3000); 
if (buttonState == HIGH)  
  digitalWrite(relayPin,HIGH);
 delay(25000);

I think what you intended was this:

if (buttonState == LOW)
{
  digitalWrite(relayPin,LOW);
  delay(3000); 
}
if (buttonState == HIGH)  
{
  digitalWrite(relayPin,HIGH);
  delay(25000);
}
  1. I don't recommend delay() to time the relay. It will cause the button to not be read during the relay activation because the program is stuck not doing anything during the delay. I recommend using millis() to time the relay. Look at these tutorials:
    Example-code for timing based on millis()
    BlinkWithoutDelay

You and I know that those are all good points, but possibly too much for @codergamerhawkalphasqudron at the moment and we don't actually know what the requirement is yet, hence my questions to him/her

Of the switch schemes (S2 or S3) shown below which one more closely resembles what you've constructed?

consider

const int buttonPin = 8;
const int relayPin  = 7;

void loop () {
    if (LOW == digitalRead (buttonPin)) { // button pressed
        digitalWrite (relayPin,HIGH);     // relay on
        delay (25000);                    // wait 25 sec
        digitalWrite (relayPin,LOW);      // relay off
    }
}

void setup () {
    pinMode (relayPin,  OUTPUT);        // can output drive relay ??
    pinMode (buttonPin, INPUT_PULLUP);  // button between pin and ground
}
    if (LOW == digitalRead (buttonPin))

This order of test values always makes me shudder. I know the reasons for using it, but I like my code to read as much like English as possible, which this isn't, but Yoda would be proud of it, I am sure

you've brought this up many times

but just recently i wrote "=" instead of "==" which resulted in an error which saved me time. i believe the benefit flagging an error outweighs the grammatical consideration.

did you ever use an HP calculator with reverse polish notation

HP, no, but I used a Sinclair Scientific calculator that used RPN and I didn't like that either

If I were you I would start again. Accept this attempt as a learning experience.

Open up a new sketch and name it something descriptive, like 'button'. In this new sketch you will only code the button, nothing else. Once finished you will have a working button with appropriate code which you can reuse in any project.

Look carefully at the diagram presented in the posts above. The typical way to wire a button it with one side to the buttonPin and the other side to ground. When you press your button it will ground the pin. There is, however, a problem. The pin, when the button is not pushed is floating. this means the pin is not connected to any known voltage and therefore it will wander wherever it pleases, occasionally triggering even when the button is not pushed. The solution is to attach a resistor to pull it up to the VCC. You can do this in code by setting the pin to INPUT_PULLUP which will activate the internal pullup resistor.

Now you have the right hardware, in your code do the standard stuff: declare the pins with a good name like buttonPin, set pinmode buttonPin to INPUT_PULLUP. Now you need to detect the 'edge'. This is the moment when the button 'becomes' pressed, examples here State Change Detection (Edge Detection) for pushbuttons | Arduino. You do this by declaring the buttonState globally and then looking for a change in the state in loop. This is an important concept because mostly, with buttons, you want to detect a single push and not waste processor time detecting all the time the button is pushed.

If you get this concept then you can start to think about debouncing. The code above uses a dirty delay which is blocking code and should be avoided. Here is an example that avoids this problem: Debounce | Arduino

Once you have all that sorted then you want to think about putting it all into a function. You could call this function buttonPoll or something nice like that. When called in loop it can check the button/s each time through and see if there is a press. If there is it can change the RelayState. This function is useful because it will be somewhat 'encapsulated' so can be used in other code without messing stuff up.

Use the serial monitor to debug. It can print variables and you can even have it print button pressed and button released.

it seems complex but it is actually a series of quite simple concepts (once you get your mind round them). You next open a sketch and call it relays!....

Concepts:
loop should be fast and with non-blocking code
pins can't be left floating if you need to know what state they are in
Millis timing (blink without delay example in ide)
state change and edge detection
functions and encapsulated code
serial debugging
Always coding in discrete, small, well named sketches with an iterative approach. Save often, give new names to each iteration, always have a last working code and a current working-on code.

Try this for the button code as @pmagowan recommends:

Also, post a wiring diagram.

@anon44338819

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