ESP-WROOM-02とArduino UNO 受信したデータから整数を取り出す

今までの流れです。

Arduino UNO + ESP-WROOM-02(ESP8266) Arduino UNO + ESP-WROOM-02(ESP8266)

サーバに設置したPHPから情報を取得しました。Arduinoはサーバから返って来た返答が文字列として入っています。ここから必要な値だけを取り出します。サーバからの文字列は次の様になっています。

[html]
HTTP/1.1 200 OK
Date: Sat, 29 Aug 2015 11:55:30 GMT
Server: Apache/2.2.29
X-Powered-By: PHP/5.2.17
Connection: close
Content-Type: text/html

10
[/html]

この返答の内容ですが、サーバが変わると違う場合があります。上記はサクラのレンタルサーバの場合。Amazon EC2の場合は次の様になります。

[html]
HTTP/1.1 200 OK
Date: Sat, 29 Aug 2015 19:09:25 GMT
Server: Apache/2.2.31 (Amazon)
X-Powered-By: PHP/5.3.29
Content-Length: 2
Connection: close
Content-Type: text/html; charset=UTF-8

10
[/html]

Content-Length:があったりなかったり、サーバの設定によって異なるようです。どちらにしても欲しいデータは最後の行に入っています。この行を取り出し、文字列を整数に直す処理を行う必要があります。Linuxの改行コードはLFなので、LF(スケッチ上では”\n”)を文字列の最後から検索して、そこから文字列の最後までをとりだします。
文字列を最後から検索するにはlastIndexOf()を使います。詳しくはこちらlastIndexOf
データの受信後の処理は次の様になります。

[c]
wifi.send((const uint8_t*)hello, strlen(hello));

String resultCode = "";//サーバからの文字列を入れるための変数

uint32_t len = wifi.recv(buffer, sizeof(buffer), 10000);
if (len > 0) {
for(uint32_t i = 0; i < len; i++) {
resultCode += (char)buffer[i];
}
Serial.println(resultCode);//確認のため出力
//lastIndexOfでresultCodeの最後から改行を探す。
int lastLF = resultCode.lastIndexOf(‘\n’);
//resultCodeの長さを求める。
int resultCodeLength = resultCode.length();

//substringで改行コードの次の文字から最後までを求める。
String resultString = resultCode.substring(lastLF+1, resultCodeLength);
Serial.println(resultString);//確認のため出力
resultString.trim();//念のために前後のスペースを取り除く。無くても可。

int resultValue = resultString.toInt();//Stringをintに変換

Serial.print("resultValue=");//値の出力
Serial.print(resultValue);
Serial.print("\r");
}
[/c]