i really having difficult for using delay, i know theres a lot libary, but the procedure is too complex for me, all i need is just blink using millis when the trigger occurs.
example usecase
when button is pressed
turn on led for 1 sec
then off
heres the code.
void loop()
{
if (digitalRead(ShifterPin)==HIGH)
{
if(digitalRead(ShifterPin)==HIGH && ShiftState==0)
digitalWrite(RelayPin,HIGH);
digitalWrite(ShiftLight,HIGH);
delay(QC_Duration); << i want this using millis instead of delay
digitalWrite(RelayPin,LOW);
digitalWrite(ShiftLight,HIGH);
ShiftState=1;
}
else
{
ShiftState=0;
}
}
Here is an example of one way to do what you want. The stated change method and switch wiring is covered in the state change for active low inputs tutorial. The timer is covered in the previously linked tutorials on millis() timing.
// LED lights for 1 second upon a button press
// Button swich wired to ground and pin (INPUT_PULLUP)
// by c gouling aka groundFungus
const byte buttonPin = 4;
const byte ledPin = 7;
const unsigned long ledOnTime = 1000; // 1 second on time
void setup()
{
Serial.begin(115200);
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop()
{
static unsigned long timer = 0;
static bool runTimer = false;
// state change detection to sense switch closure
static bool lastButtonState = HIGH;
bool buttonState = digitalRead(buttonPin);
if(buttonState != lastButtonState)
{
// button is active low and locked out during on time
if(buttonState == LOW && runTimer == false)
{
runTimer = true;
timer = millis();
digitalWrite(ledPin, HIGH);
}
lastButtonState = buttonState;
}
// LED on timer
if(runTimer == true)
{
if(millis() - timer >= ledOnTime)
{
runTimer = false;
digitalWrite(ledPin, LOW);
}
}
}
For shure.
But you will create code duplicates.
Part of the code for the LED and another part of the code for the relay. This will continue with other devices.
OOP with C++ prevents this behaviour by using objects and methods that do the processing.
For your project, you will have an object that contains the data for the button, the output and the timing data for debouncing and turning on the output.
Two services take care of debouncing the button and switching on the outputs.