For Loop Question

Hi,

Could I just have a bit of help understanding the loop, please?

void loop()
{
  byte aSwitch;
  byte last_switch[5];

for (byte i = 0; i < 5; i++) {

    aSwitch = digitalRead(2 + i);

    if (aSwitch != last_switch[i]) {

      last_switch[i] = aSwitch;

      if (aSwitch == HIGH) {  // When button pressed the voltage goes high

The program works perfectly but I do not fully understand how it counts up the number of switches.

Does it take notice of this line the very first time through when i = 0

aSwitch = digitalRead(2 + i);

Also, is it comparing it to last_switch which I assume also starts at 0 the first time through?
Here:- if (aSwitch != last_switch*)*
Thanks for any replies,
Martin

for (byte i = 0; i < 5; i++)
i goes from 0 thru 4 inclusive. (reading pins 2,3,4,5 and 6)

You can simply plug values 0-4 for i and do the math in your head.

if (aSwitch != last_switch[ i] )
Compares the current state of the input pin to the last read state of the input pin.
It updates the last sate read to the current state when there is a change detected.

First time thru, last_switch[ i] is the initialized value you give it.
You might want to initialize the array to the value of the input pins when setup() runs.

Hi Larry,

Thanks very much for the reply.

That makes more sense now that you have explained it.8-))

I must be getting old as I didn't realise that aswitch was getting a High or Low from the pin!

Don't know how I missed that......

I'm OK without initializing the array as it works fine as it is but you have a valid point!

Martin

When the array is a global variable, the compiler gets the array initialized to zero ‘or’ whatever you tell it.

Place this in setup() to initialize things at power up:

for (byte i = 0; i < 5; i++) 
{
   last_switch[i] = digitalRead(2 + i);
}