Simple String to Byte conversion

All,

I'm working on a new project and as a beginner, I need to catch a string (a figure) from a HTTP request and convert it to Byte type. I receive data from a server a need to intergrate these into my Arduino program. After some shours surfing on the web, I'm back on this forum to search some help...

A byte can only store a single character, so unless the String is only a single character, you'll need an array of bytes. If you are using the String object, then there should be a charAt() member function that can return the individual characters. If you're using a string (null-terminated char array), then you can already reference the characters individually just as you would with any array. Alternatively, you can just cast it to a byte*, depending on how you are using the byte array.

Understood, Problem : I need to use this 1234 in the Ethernet.begin(mac, IP). More into details : a server will send the IP to use in the Arduino.

Then, I got something like GET/?IP1=192&IP2=168 and so on. Then, I need to catch thses values to integrate that in the Ethernet.begin variables...

I use this arduino in a hudge project and this can help me to solve some automatism issues...

RGeeze: Understood, Problem : I need to use this 1234 in the Ethernet.begin(mac, IP). More into details : a server will send the IP to use in the Arduino.

Then, I got something like GET/?IP1=192&IP2=168 and so on. Then, I need to catch thses values to integrate that in the Ethernet.begin variables...

I use this arduino in a hudge project and this can help me to solve some automatism issues...

Post the code that you have now, so that we can see how far you have gotten.

Few explanations: the code above is a part only of the overall program (dealing with RFID and LCD).

The variable readString is the http request. For this part of the program, readString = setup?SBM=1&DT1=192&DT2=168&DT3=0&DT4=20&DT5=255&DT6=255&DT7=255&DT8=0&DT9=192&DT10=168&DT11=0&DT12=2

I’ve used few lines of another project I found on the web (thanks to Jori : http://www.jo3ri.be/arduino/arduino-projects/network-settings-web-page-form-using-eeprom-to-save-submit) but need to drastically change jori’s code.

The entire program is quite hudge but if it can help, I can post all of it.

//***************Begin Setup Page**********************
//*********************************************************
void PageSetup()
{
char readStringchar[150];
char buffer[150];
char *pos,*key,*data;
char *keyarray[25];
char *dataarray[25];

readString.toCharArray(readStringchar, 150);

  int i=0;
  key = pos = readStringchar;
  while(*pos)
  {
    switch(*pos)
    {
      case '=':
        *pos = 0;
        pos++;
        data = pos;
        break;
      case '&':
        *pos = 0;
        Serial.print("Key: ");
        Serial.print(key);
        keyarray[i] = key;
        Serial.print(" Value: ");
        Serial.println(data);
        dataarray[i] = data;
        pos++;
        i++;
        key = pos;
        break;
    }
    pos++;
  }

  Serial.print("Key: ");
  Serial.print(key);
  Serial.print(" Value: ");
  Serial.println(data);
  //keyarray[i] = key;
  //dataarray[i] = data;
    
                  for (int i = 0 ; i < 4; i++){
                  Serial.print ("ip");
                  Serial.println (ip[i]);                }
                for (int i = 0 ; i < 4; i++){
                  Serial.print ("subnet");
                  Serial.println (subnet[i]);                }
                for (int i = 0 ; i < 4; i++){
                  Serial.print ("gw");
                  Serial.println (gateway[i]);                }
  
          if (readString.indexOf("SBM")>0){
                Serial.println ("ok SBM");
                for (int i = 1 ; i < 5; i++){
                  ip[i] = int(dataarray[i]);
                  Serial.print ("ip");
                  Serial.println (ip[i]);                }
                for (int i = 1 ; i < 5; i++){
                  subnet[i] = byte(*dataarray[i+4]);
                  Serial.print ("subnet");
                  Serial.println (subnet[i]);                }
                for (int i = 1 ; i < 5; i++){
                  gateway[i] = byte(*dataarray[i+8]);
                  Serial.print ("gw");
                  Serial.println (gateway[i]);                }
            // save to EEPROM
/*            for (int i = 1 ; i < 5; i++){
              EEPROM.write(i, ip[i]);
            }
            for (int i = 1 ; i < 5; i++){
              EEPROM.write(i + 4, subnet[i]);
            }
            for (int i = 1 ; i < 5; i++){
              EEPROM.write(i + 8, gateway[i]);
            }

            // set ID to the known bit
            EEPROM.write(0, 0x92); 
*/
          }//End if SBM
          
          
  //ShieldSetup();
  server.begin(); //starting the server
  EthernetClient client = server.available();
  char c;
  if (client) {
    Serial.println ("If CLient");
  boolean currentLineIsBlank = true;
    Serial.println ("While client connected");
  if (client.available()) {
          Serial.println ("If CLient Available");
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
          for (int i = 0; i < 4; i++)
            {
            strcpy_P(buffer, (char*)pgm_read_word(&(string_table0[i])));
            client.print( buffer );
            }

          strcpy_P(buffer, (char*)pgm_read_word(&(string_table1[0])));
          client.print( buffer );
          
          strcpy_P(buffer, (char*)pgm_read_word(&(string_table2[0])));
          client.print( buffer );
          client.print(ip[0],DEC);
          strcpy_P(buffer, (char*)pgm_read_word(&(string_table2[1])));
          client.print( buffer );
          client.print(ip[1],DEC);
          strcpy_P(buffer, (char*)pgm_read_word(&(string_table2[2])));
          client.print( buffer );
          client.print(ip[2],DEC);
          strcpy_P(buffer, (char*)pgm_read_word(&(string_table2[3])));
          client.print( buffer );
          client.print(ip[3],DEC);
          
          strcpy_P(buffer, (char*)pgm_read_word(&(string_table3[0])));
          client.print( buffer );
          client.print(subnet[0],DEC);
          strcpy_P(buffer, (char*)pgm_read_word(&(string_table3[1])));
          client.print( buffer );
          client.print(subnet[1],DEC);
          strcpy_P(buffer, (char*)pgm_read_word(&(string_table3[2])));
          client.print( buffer );
          client.print(subnet[2],DEC);
          strcpy_P(buffer, (char*)pgm_read_word(&(string_table3[3])));
          client.print( buffer );
          client.print(subnet[3],DEC);

          strcpy_P(buffer, (char*)pgm_read_word(&(string_table4[0])));
          client.print( buffer );
          client.print(gateway[0],DEC);
          strcpy_P(buffer, (char*)pgm_read_word(&(string_table4[1])));
          client.print( buffer );
          client.print(gateway[1],DEC);
          strcpy_P(buffer, (char*)pgm_read_word(&(string_table4[2])));
          client.print( buffer );
          client.print(gateway[2],DEC);
          strcpy_P(buffer, (char*)pgm_read_word(&(string_table4[3])));
          client.print( buffer );
          client.print(gateway[3],DEC);


          strcpy_P(buffer, (char*)pgm_read_word(&(string_table4[4])));
          client.print( buffer );
          strcpy_P(buffer, (char*)pgm_read_word(&(string_table4[5])));
          client.print( buffer );


    }//end If Client.available
    delay(5);

    Serial.println("Client Stop");
    client.stop();
//  }// End While Client
          readString="";

  }//End If Client

      }//End Void
//***************End Setup Page**********************
//*********************************************************

Here is a quick example of how to break down a string.

void setup() {
  //For this example, we will seed the string with a random one
  char readStringchar[] = "GET/?HI1=123&IP1=192&IP2=168&IP3=2&IP4=12";
  Serial.begin(115200);
  
  int address[4] = {0}; //Address will be stored as 4 ints.
  
  char* token;
  char seperators[] = "?=&";
  char identifier[] = "IP";
  token = strtok (readStringchar,seperators); //Find first token. Tokens seperated by '?','=', or '&'
  //see here for more about strtok: http://www.cplusplus.com/reference/clibrary/cstring/strtok/
  
  //Count through all tokens in string
  byte i = 0;
  boolean success = false;
  while (token != NULL && !success) {
    char check[4] = {0};
    sprintf(check,"%s%d",identifier,i+1); //Find the (i+1)th IP token.
    if(!strcmp(token,check)){
      token = strtok (NULL,seperators); //The token after is the (i)th part of the IP.
      address[i] = atoi(token);
      i++; //Move to the next
      if(i == 4){
        success = true;
        break; //All ip segments are found
      }
    }
    token = strtok (NULL,seperators); //Get next token
  }
  if(!success){
    //Failed to get IP. Warn user? Or load default?
    //e.g.
    address[0] = 192;
    address[1] = 168;
    address[2] = 0;
    address[3] = 1;
  }
  
  //Log the address:
  for (int i = 0; i < 4; i++){
    Serial.println(address[i]);
  }
}

void loop() {
  // put your main code here, to run repeatedly: 
  
}

I suppose I should describe the example.

Basically, a large string of tokens is taken in (readStringChar[]), then the tokens are one by one broken down and analysed. T

he seperators[] array is used to declare how tokens are seperated, so in this case they are broken apart at any instance of &,=, or ?.

Then to find a specific part, each token is checked to see if it matches the identifier[] array. In this example, any token named IP is kept. As there are 4 IP tokens, the while loop adds a number between 1 and 4 to the end. If it finds the toke "IP1", then it finds the next token and converts that to an integer and stores as the first address. Then it starts looking for "IP2" and so on (They have to be in order for this example to work, though others can be between them, i.e. "IP1,IP2,FISH2,CAT3,DOG1,IP3,HI1,IP4").

Once it finds all 4 IP tokens, it stops looking. If the end of the string is reached before that happens, the loop exits, and the if statement at the end shows that it failed to locate the whole IP.

You could modify this to check through an array of known identifiers, such as "IP","DT", etc. and then compare each found token with each of the identifiers. I can post a modified code to do that if you would like.

There are probably other ways to do this, but I quite like strtok() it is a rather useful function.

Thanks for the code... and for the explanation. I will keep it in mind for futur development, but.... time is flying faster in France than in the US. I will test this tomorrow morning and intergrate that in my code. Before working on this, may I change the int type of address[] in byte ? Still the same issue : I need to integrate this variable in the Ethernet.begin function... but may be I ask this question as it is late for me now.

Once again, I thank you for these lines

You should just be able to change it to a byte:

byte address[4] = {0}; //Address will be stored as 4 bytes.

And then use the atoi() function like:

address[i] = (byte)atoi(token);

If the number is longer than 255 it will just wrap around, e.g. 256 = 1. But that wont be an issue with an IP.

(Oh, and I'm in the UK, so same timezone as France :D)

Alright,

I've intergrated your code in mine and used the 'magic atoi'. That works properly now... But just for fun, I kept my previous code and simply unsed this 'atoi'... it works too. Finally, I've used yours.

Thanks for the help