Relay not working properly

Where is the problem?
when the switch is turned off, whether the lights are timed to be on or off, the relay jumps from on to off rapidly.

#include <DS3231.h>

int Relay = 4;
int switchPin = 8;
int ledPin = 13;
String today ;

bool timedOn = false;

DS3231  rtc(SDA, SCL);
Time t;

void setup() {
  Serial.begin(9600);
  rtc.begin();
  pinMode(Relay, OUTPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(Relay, LOW);
  digitalWrite(ledPin, LOW);
  delay (2000);
}

void loop() {

  today = rtc.getDOWStr();

  bool switchOn = digitalRead(switchPin) == HIGH; //when using pulldown configuration

if (today == "Wednesday") {
    if ( 13 < t.hour && t.hour < 20) {
      timedOn = true;
    } else {
      timedOn = false;
    }
} else if (today == "Friday") {        
    if ( 16 < t.hour && t.hour < 20) {
      timedOn = true;
    } else {
      timedOn = false;
    }
} else {
    timedOn = false;
}

if(switchOn || timedOn){
    digitalWrite (Relay, HIGH);
} else {
    digitalWrite (Relay, LOW);
}

if(switchOn){
    digitalWrite (ledPin, HIGH);
} else {
    digitalWrite (ledPin, LOW);
}
}
  bool switchOn = digitalRead(switchPin) == HIGH; //when using pulldown configuration

Can you please explain exactly what this line of code does and how the input is wired ?

The switch is used to turn on and off the LED light strip when it is not timed to be on.

Can Anybody help?

Need to figure this out tonight.

that line of code with the switchOn should actually work as you said, if you'd have put the condition in braces i wouldn't have wondered.

so switchOn is false, therefore if timedOn is true, the relay first gets turned on and then gets turned off over and over again, that is not what you want obviously,

if(switchOn){
    digitalWrite (ledPin, HIGH);
} else {
    digitalWrite (ledPin, LOW);
}

change this to :

if(switchOn){
    digitalWrite (ledPin, HIGH);
}

switchOn should not turn the relay off if it false.

Hi,
Where have you stated pinMode for the switchPin ?

Tom... :slight_smile:

TomGeorge:
Hi,
Where have you stated pinMode for the switchPin ?

Tom... :slight_smile:

It will default to INPUT but I would use pinMode() anyway to make the intention clear. Furthermore I would use INPUT_PULLUP in the pinMode() to avoid the need for external resistors.

Incidentally, I find

  bool switchOn = digitalRead(switchPin) == HIGH;

unnecessarily obscure

yes and a little overactive since this is the same

 bool switchOn = digitalRead(switchPin);

Maybe
‘switchOn’
should be
‘switchState’