Thank you, i understood what you want tell me, but i am not good programmer. And a think, this is my maximum from me heh...
I try press the button before 3 sec timout and this is good, the Code go in to OFF mode. But after 3 sec is not good, the code is still restarting. And A7, thank you very much for the simulation but fix in simulation code (relay2 to a OUTPUT).
This is my last CODE update. It's almost good as you can see. But when I first time press the button, nothing happens - because first is "turn off". And when i press the button second time, the program run OK. And last bug, when I press he button twice and hold the button pressed, he program jump from OFF mode to ON mode in 3 seconds - and this is not OK.
const int button = 0; //button on my shield TL2
const int relay1 = 8; //relay1 this relay on for 3 sec when LED_R + LED_G is light (in shield is YELLOW LED)
const int relay2 = 7; //relay2 this relay is on when the LED_G is light (in shield is BLUE LED)
const int led_R = 5; //this LED light when is START mode or OFF mode
const int led_G = 6; //this LED ligh when is START mode or ON mode
//record the current button state
enum { Off = LOW, On = HIGH }; // relay on when HIGH
int buttonState;
#define RelayPeriod 3000 // how long to relay1 is ON
unsigned long msecRelay;
int relayState = Off;
void setup () {
pinMode (button, INPUT_PULLUP);
pinMode (relay1, OUTPUT);
pinMode (relay2, OUTPUT);
pinMode (led_R, OUTPUT);
pinMode (led_G, OUTPUT);
digitalWrite (relay1, Off);
digitalWrite (relay2, Off);
digitalWrite (led_R, On);
digitalWrite (led_G, Off);
buttonState = digitalRead (button);
Serial.begin(9600);
}
bool buton = false;
void loop () {
unsigned long msec = millis ();
// check for button press
delay (50);
byte but = digitalRead (button);
if (buttonState != but) {
buttonState = but;
delay (25); // debounce
if (LOW == but) {
if(buton){
buton = false;
if (On == digitalRead (relay1)) {
digitalWrite (relay1, Off);
digitalWrite (relay2, Off);
relayState = 0;
digitalWrite (led_G, Off);
digitalWrite (led_R, On);
}
else {
digitalWrite (relay1, On);
digitalWrite (relay2, Off);
digitalWrite (led_R, On);
digitalWrite (led_G, On);
relayState = 1;
msecRelay = msec;
}
} else{
buton = true;
Serial.println("turn off");
digitalWrite (relay1, Off);
digitalWrite (relay2, Off);
digitalWrite (led_G, Off);
digitalWrite (led_R, On);
}
} }
if (relayState && (msec - msecRelay) >= RelayPeriod) {
// turn off
digitalWrite (relay1, Off);
digitalWrite (relay2, On);
digitalWrite (led_G, On);
digitalWrite (led_R, Off);
relayState = 0;
}
}