jurs:
OK, here is the code (not fully tested, I just used serial debugging in the serial monitor):
const byte keyPin=2; // pin number for key switch
#define keyPinMode INPUT_PULLUP // INPUT or INPUT_PULLUP
#define BOUNCETIME 20 // bounce time of keyswitch in milliceconds
const byte relayPins[]={6,7,8,9,10,11,12,13};
#define NUMRELAYS sizeof(relayPins)
#define RELAY_ACTIVE LOW // pin state for active/switched relay
#define INTERVAL 1000 // time interval between switching relays
byte readKeySwitch()
{ // read and debounce key switch pin
static byte onState=false;
static unsigned long lastRuntime;
if (millis()-lastRuntime<BOUNCETIME) return onState;
lastRuntime=millis();
onState=digitalRead(keyPin);
if (keyPinMode==INPUT_PULLUP) onState=!onState;
return onState;
}
void switchRelays(byte howMany)
{ // switch "howMany" relays to on
for (int i=0;i<NUMRELAYS;i++)
{
if (i<howMany)
{
digitalWrite(relayPins[i],RELAY_ACTIVE);
Serial.print('1');
}
else
{
digitalWrite(relayPins[i],!RELAY_ACTIVE);
Serial.print('0');
}
}
Serial.println();
}
void setup() {
Serial.begin(9600);
Serial.println("Good night and good luck!");
pinMode(keyPin, keyPinMode);
for (int i=0;i<NUMRELAYS;i++)
{
digitalWrite(relayPins[i], !RELAY_ACTIVE);
pinMode(relayPins[i], OUTPUT);
}
}
byte lastSwitchState;
unsigned long switchTime;
byte relayCount;
void loop() {
byte switchState=readKeySwitch();
if (switchState!=lastSwitchState)
{
switchTime=millis();
lastSwitchState=switchState;
}
if (switchState && relayCount<NUMRELAYS)
{ // key switch is on, but not all relays are on
if (millis()- switchTime >= INTERVAL)
{
switchTime+=INTERVAL;
relayCount++;
}
}
else if (!switchState && relayCount>0)
{ // key switch is off, but there is at least one relay on
if (millis()- switchTime >= INTERVAL)
{
switchTime+=INTERVAL;
relayCount--;
}
}
switchRelays(relayCount);
}
As I don't know whether you are using pull-up or pull-down resistors with your key swith and whether your relays are switching on "active HIGH" or "active LOW", I have prepared the sketch for all combinations.
Just set accordingly in the source code:
#define keyPinMode INPUT // if key switch is connected to a pull-down resistor
or
#define keyPinMode INPUT_PULLUP // if key switch shall use the "internal pull-up" resistor in the controller
And depending on the type of relays:
#define RELAY_ACTIVE LOW // relay switches on LOW signal
or
#define RELAY_ACTIVE HIGH // relay switches on HIGH signal
If everything works as expected, you can remove all the "Serial" debug code from the sketch.
Have fun!
Thanks for the program,
I will test it but i have one question,
I must start the relais after a individual setting delay because not all the relais have the same delay.
I think this is now one delay for all relays,
Is that possible to make it with the individual delays for startup and for switching down?