Help for a simple for loop

Hi guys. I want to make my code a bit more robust and light because I have a little bit of trouble with the amount of data the ethernet shield can handle. If I am near 16kb of code, it crashes, although the arduino has 32kb. Anyway... To the point :slight_smile:

I want to substitute the following piece of code and make a "for loop" for the pins 2-9 but I don't know how to make it read the ("on1"), ("off1), with 1 being an int i.

if(readString.indexOf("on1") >0)//checks for on
{
digitalWrite(2, HIGH); // set pin 2 high
// Serial.println("Led On");
//client.println("Light 1 Is On");
//client.println("
");
}
else{
if(readString.indexOf("off1") >0)//checks for off
{
digitalWrite(2, LOW); // set pin 2 low
// Serial.println("Led Off");
//client.println("Light 1 Is Off");
//client.println("
");
}
}

if(readString.indexOf("on2") >0)//checks for on
{
digitalWrite(3, HIGH); // set pin 3 high
// Serial.println("Led On");
}
else{
if(readString.indexOf("off2") >0)//checks for off
{
digitalWrite(3, LOW); // set pin 3 low
// Serial.println("Led Off");
}
}

I want it to be something like but obviously doesn't work because its wrong syntax.

for (int i=1; i<9;i++)
if(readString.indexOf("on"i) >0)//checks for on
          {
            digitalWrite(i+1, HIGH);    // set pin i+1 high

          }
          else{
            if(readString.indexOf("off"i) >0)//checks for off
            {
              digitalWrite(i+1, LOW);    // set pin i+1 low

            }
          }
}

If I am near 16kb of code, it crashes, although the arduino has 32kb.

It has 32K of program space, but only 2K of SRAM, which you are pissing away using the String class.

sprintf() can be used to make "on1", "on2", "on3", etc.

How to use this forum

Code tags please, not quote tags.

Thanks for your answer :slight_smile: The on1, on2, on3 etc are address bar queries for switches so that's what I m trying to read. I m not sure how to use sprintf() to achieve that (noob alert :D). Can you make a proper synstax on this if(readString.indexOf("on"i) >0) with i being the int? Thanks again

For that you would use sscanf. Drop the String class and use C strings (null-terminated character arrays). Then you can use something like

int num;

if (sscanf(incomingString, "on%d", &num) == 1) {
  switchOnLED(num);
}

I did it by using the String(n) function to read the integer as a string. Thanks everyone for your help

SOLVED

Do a search on Port Manipulation. With an UNO you have 6 pins open on 2 ports and 4 on the other by default. You could pack your data bits into 2 ports and get your 8 bits out in just 2 writes. With a MEGA I am guessing you'd have a full port open to use, 1 write would do.

SOLVED

sp. "postponed".
Please, try not to use String.

AWOL:

SOLVED

sp. "postponed".
Please, try not to use String.

LOL, postponed till the next Help! thread.