# Why global variables are slowing down my loop??

basshunter:

No it's not!

13.2.2 Toggling the Pin
Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn. Note that the SBI
instruction can be used to toggle one single bit in a port.

This is actually weird enough that I may try to reproduce it if I feel like it tonight. But probably not, I'm pretty swamped atm.

DrAzzy:
No it's not!

This is actually weird enough that I may try to reproduce it if I feel like it tonight. But probably not, I'm pretty swamped atm.

So your attempt is to use an unused register as a variable?

Change it to this:

``````#define PC7 (PINC & 128) //PC7
#define PC6 (PINC & 64) //PC6
#define PC5 (PINC & 32)//PC5
#define PC4 (PINC & 16) //PC4
#define PC3 (PINC & 8) //PC3
#define PC2 (PINC & 4) //PC2
#define PC1 (PINC & 2) //PC1
#define PC0 (PINC & 1) //PC0

void setup() {
Serial.begin(9600);
DDRC = 0;
}

//DECLARE THEM HERE AND GET 6000+ MICROSECONDS
byte ex_counter[20] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
byte ex_counter0;

void loop() {
//DECLARE THEM HERE AND GET 300 MICROSECONDS
byte counter[20] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
byte counter0;

long t1 = micros();
for (byte i = 0; i <= 250; i++) {
counter[0] += !PC7;
counter[1] += !PC6;
counter[2] += !PC5;
counter[3] += !PC4;
counter[4] += !PC3;
counter[5] += !PC2;
counter[6] += !PC1;
counter[7] += !PC0;
counter[8] += !PC7;
counter[9] += !PC6;
counter[10] +=!PC5;
counter[11] += !PC4;
counter[12] += !PC3;
counter[13] += !PC2;
counter[14] += !PC1;
counter[15] += !PC0;
counter[16] += !PC7;
counter[17] += !PC6;
counter[18] += !PC5;
counter[19] += !PC4;
}
counter0 =  counter[0];

ex_counter0 = counter0;
memcpy(ex_counter, counter, sizeof(counter));
long t2 = micros();
Serial.println(t2 - t1);

}
``````

and report back.

What everyone else said. You are performing 250 * 20 * (fetch from a volatile variable + bitmask it with a constant + check for zero + increment a value in an array).

If it's taking 300 microseconds as you say, then each one of these series of four operations is being done in 60 picoseconds, which is impossible.

5000 clock cycles at 16mz is 312.5 microseconds. If you are doing 5000 things in 300 microseconds, then each of those things is a no-op taking one tick.