Loop script through several Variables

Hi Guys,

I’ve been at this arduino scripting less than a week so take it easy on me please :slight_smile:

I want to make my JSON script loop over several Strings name{1-3}, I can’t see how you would loop through them, guessing some sort of array? Can someone show me some examples of how to make a script loop through a series of Variables?

I’m testing on a Wemos D1 mini.

// Libraries
#include <ESP8266WiFi.h> //Provides WiFI
#include <ArduinoJson.h> //Handles the returned JSON data

  // WiFi settings
  const char* ssid     = "VM123456789";
  const char* password = "xxx";

  //hostname
  const char* host = "jsonplaceholder.typicode.com"; //Test JSON data

  //Declare the url - may not be required.
  String url = "";
  
  //My Custom Strings - Loop through these might be more or less.
  String name1 = "1";
  String name2 = "2";
  String name3 = "3";
  
void setup() {
  Serial.begin(115200);   // Serial Setup

  Serial.print("Test Host: ");
  Serial.println(host);
  Serial.print("Test String: ");
  Serial.println(name1); //check String name via serial
   
  WiFi.begin(ssid, password); // Do wifi stuff
  
  while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   }
  
  Serial.println(WiFi.localIP()); //Show WiFi connection
  delay(100);
}

void jsonfunc(){
    WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
     Serial.println("connection failed");
    return;
  }

  // We now create a URI for the request
  String url = String("/todos/") + 
  String(name1);

  Serial.print("URL: ");
  Serial.print(host);
  Serial.println(url);
  
    // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" + 
               "Connection: close\r\n\r\n");
  Serial.println("Got Data...");
  delay(1000);
  
  // Read all the lines of the reply from server.
  String answer;
  while(client.available()){
    String line = client.readStringUntil('\r');
    answer += line;
  }            
  
  client.stop();
  Serial.println();
  Serial.println("closing connection");
  
   // Process answer
  //Serial.println("Answer: ");
  //Serial.println(answer);

  // Convert to JSON
  String jsonAnswer;
  int jsonIndex;

  for (int i = 0; i < answer.length(); i++) {
   if (answer[i] == '{') {
     jsonIndex = i;
     break;
    }
  }

  // Get JSON data
  jsonAnswer = answer.substring(jsonIndex);
  Serial.println();
  Serial.print("JSON answer: ");
  Serial.println(jsonAnswer);
  jsonAnswer.trim();

  //Get current currency price index data
  int rateIndex = jsonAnswer.indexOf("title");
  String result = jsonAnswer.substring(rateIndex + 10, rateIndex + 27);

  //Print Results to the serial
   Serial.print("");
   Serial.print("");
   Serial.print("Returns = ");
   Serial.println(result);
}

void loop() {
   jsonfunc(); //Call the jsonfunc Function :)
   delay(10000);//Wait before looping
}

Thanks for any help in advance.

P

//My Custom Strings - Loop through these might be more or less.
  String name1 = "1";
  String name2 = "2";
  String name3 = "3";

You can't do it like that. Variables don't have names after compilation. So there's no way for the processor to make sense of this.

You need to learn to use arrays. With an array those numbers can actually mean something.

Thanks, Delta_G,

You gave me the push I needed, I’ve always had a fear of Arrays, and even with my bash scripting knowledge, I’ve avoided it like the plague. I know they are great and I can totally see why they are used, I’ve just found it easier to present a list and get a for loop to process it, rather than set an array up.

Well here is my Testing Array script in case it helps someone else out struggling with making a String array as opposed to an int array I see everywhere.

#define ARRAYSIZE 3
  String itemName[ARRAYSIZE] = { "rock", "paper", "scissors" };

  
void setup() {
  Serial.begin(115200);   // Serial Setup
  Serial.println("Storing numbers in an array");

void loop(){
  for (int i =0; i< ARRAYSIZE; i++) {
  Serial.println(itemName[i]);
    delay(1000);
  }
}

Well here is my Testing Array script

Which does not compile. Missing } at the end of setup()

It is usually better to let the compiler work out how many entries there are in the array

String itemName[] = { "rock", "paper", "scissors" };
const byte ARRAYSIZE = sizeof(itemName) / sizeof(itemName[0]);

void setup()
{
  Serial.begin(115200);   // Serial Setup
  Serial.print(ARRAYSIZE);
  Serial.println(F(" entries"));
  Serial.println(F("Storing numbers in an array"));
}
void loop()
{
  for (int i = 0; i < ARRAYSIZE; i++)
  {
    Serial.println(itemName[i]);
    delay(1000);
  }
}

That way entries can be added to the array with no need to manually change the array size variable

Many (most) members here would caution against the use of Strings because of the limited memory available on most Arduinos and suggest the use of cstrings instead.

Thanks, UKHeliBob

Not sure how I dropped the "}" thanks for checking.

I will look into the c string further as I would like the program to be optimised as best I can get. I did want to make the array length dynamic but had not got to that side of things as of yet, it was on my todo :slight_smile:

The-evils-of-arduino-strings Looks to be quite a good source of info to absorb.

Thanks
P

I did want to make the array length dynamic

The array length is only dynamic in the sense that the compiler works out its length at compile time. Its size cannot be changed in the program itself.