I tried to use the mills() to instead of delay(),
I pushed the buttonState to High and the time is reach the condition,but how it can't work...
unsigned long currentMillis = millis();
if ((buttonState == HIGH) && (currentMillis - previousMillis >= OnTime)){
previousMillis = currentMillis;
if ((buttonState == LOW) && (currentMillis - previousMillis >= OffTime)){
previousMillis = currentMillis;
#include <Four7Seg74hc595.h>
/*
* PRESS BUTTON COUNTER INCREMENT
*/
esl::Four7Seg74hc595 display( 10,9,8 );
// Pin connected to Pin 14 of 74HC595 (Data=DIO,arduino pin8)
// Pin connected to Pin 12 of 74HC595 (Latch=RCLK,arduino pin9)
// Pin connected to Pin 11 of 74HC595 (Clock=SCLK,arduino pin10)
char sbuf[5];
uint16_t Counter;
uint32_t ts1,ts2 ,ts3 ,ts4 ,ts5;
const int buttonPin = 2; // (pushbutton)
const int relayPin = 13; // (Relay)
int buttonPushCounter = 0; //counter for the number of button presses
int buttonState = 0; //current state of the button
int lastButtonState = 0; //previous state of the button
unsigned long previousMillis = 0;
long OnTime = 10000 ;
long OffTime = 3000;
void setup() {
Serial.begin(9600); // Serial port, 9600 bps
pinMode(buttonPin, INPUT); // buttonPin setup to INPUT
pinMode(relayPin, OUTPUT); // relayPin setup to OUTPUT
for (uint8_t i=0; i < 100; i++) {
display.setDigits( "----", 4 );
display.update();
delay(10);
}
delay(1000);
buttonPushCounter = 0;
sprintf( sbuf, "%04u", buttonPushCounter );
display.setDigits( sbuf, 4 );
display.update();
ts1 = ts2 = ts3 = ts4 = millis();
}
uint32_t ts;
void loop() {
ts = millis();
if ( ts - ts2 >= 5 ) {
display.setDigits( sbuf, 4 );
display.update();
ts2 += 5; // display-update interval = 5msec
}
buttonState = digitalRead(buttonPin);
if (buttonState != lastButtonState) { // Check the buttonstate (pressed)
// if pressed then buttonState become to HIGH
unsigned long currentMillis = millis();
if ((buttonState == HIGH) && (currentMillis - previousMillis >= OnTime)){
// if the current state is HIGH then the button
// went from off to on:
previousMillis = currentMillis;
buttonPushCounter++;
Serial.print("number of button pushesON: ");
Serial.println(buttonPushCounter,DEC);
sprintf( sbuf, "%04u", buttonPushCounter );
digitalWrite(relayPin, HIGH);
}
if ((buttonState == LOW) && (currentMillis - previousMillis >= OffTime)){
// if the current state is HIGH then the button
// went from off to on:
previousMillis = currentMillis;
buttonPushCounter++;
Serial.print("number of button pushesON: ");
Serial.println(buttonPushCounter,DEC);
sprintf( sbuf, "%04u", buttonPushCounter );
digitalWrite(relayPin, HIGH);
}
}
lastButtonState = buttonState; // save the current state as the last state, for next time through the loop
}