Turning relay on and off every 5 seconds

Trying to have my relay turn on and off every 5 seconds.

#define relayPin 6
unsigned long previousMillis = 0UL;
unsigned long interval = 10000UL;

String readString;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(relayPin, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  unsigned long currentMillis = millis();
  
  Serial.println(currentMillis - previousMillis);

  while (Serial.available() ) {
    delay(10);
    if (Serial.available() > 0) {
      char c = Serial.read();
      if (c == ',') {
        break;
      }
      readString += c;
    }
     if (readString.length() > 0) {
    Serial.println(readString); //prints string to serial port out

    if (readString.indexOf("w") >= 0) {
      if (currentMillis - previousMillis < interval / 2) {
        Serial.println("RELAY ON");
      digitalWrite(relayPin,HIGH);
      previousMillis = currentMillis;
      }
      

    }
    if (readString.indexOf("s") >= 0) {                      
      Serial.println("RELAY OFF");
      digitalWrite(relayPin,LOW);
    }
  }
  readString = "";
  }
}

Hello,

What’s your question ?
Why are you reading the serial port?


do yourself a favour and help us help you fl! please read How to get the best out of this forum and post accordingly

Reading the serial port to send commands from the serial monitor because I don't use buttons.

The shown code has nothing to do with your assignment.

If you have 1 char commands there is no need to build a string, just check if the char you get matches one of the commands

what are the commands? How are they related to the task at hand?

The test for whether the current timing period has ended depends on Serial data being available. How long will such data be available and what happens if nothing is available ?

Originally it was starting the relay on and off with "w" and "s" commands.

:slight_smile:
Why are you asking something completely different?

Something like this

bool relayIsBlinking = false;

… // other variables and setup()

void loop() {
  switch(Serial.read()) {
    case 's': relayIsBlinking = true; break; // possibly initialize timing variables etc 
    case 'w': relayIsBlinking = false; break;// possibly turn it off depending if you want to keep the last state or not
    default: break; // ignore anything else
  }

  if (relayIsBlinking) {
    // handle the blinking 
    …
  }
}

To handle the blinking study blink without delay, one of the available example in the IDE.

For extra information and examples using millis look at

3 Likes

This code does

turn on/off the relay every 5 seconds
5 seconds on
5 seconds off
repeat

The explanation of this code is similar to your description:
almost non-existant.

unsigned long MyRelayTimer = 0; // Timer-variables MUST be of type unsigned long
const byte    relayPin = 6;
const byte    OnBoard_LED = 13;


void setup() {
  Serial.begin(115200);
  Serial.println("Setup-Start");
  PrintFileNameDateTime();
}


void loop() {
  BlinkHeartBeatLED(OnBoard_LED,250);

  if ( TimePeriodIsOver(MyRelayTimer,5000) ) {
    digitalWrite(relayPin, !digitalRead(relayPin) );
  }  
}


void PrintFileNameDateTime() {
  Serial.println( F("Code running comes from file ") );
  Serial.println( F(__FILE__) );
  Serial.print( F("  compiled ") );
  Serial.print( F(__DATE__) );
  Serial.print( F(" ") );
  Serial.println( F(__TIME__) );  
}


// easy to use helper-function for non-blocking timing
boolean TimePeriodIsOver (unsigned long &startOfPeriod, unsigned long TimePeriod) {
  unsigned long currentMillis  = millis();
  if ( currentMillis - startOfPeriod >= TimePeriod ) {
    // more time than TimePeriod has elapsed since last time if-condition was true
    startOfPeriod = currentMillis; // a new period starts right here so set new starttime
    return true;
  }
  else return false;            // actual TimePeriod is NOT yet over
}


void BlinkHeartBeatLED(int IO_Pin, int BlinkPeriod) {
  static unsigned long MyBlinkTimer;
  pinMode(IO_Pin, OUTPUT);
  
  if ( TimePeriodIsOver(MyBlinkTimer,BlinkPeriod) ) {
    digitalWrite(IO_Pin,!digitalRead(IO_Pin) ); 
  }
}

if this is not what you want to have. There is no way around describing with more precision and more details what you really want to have

best regards Stefan

1 Like

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