JSON from arduino to PHP server

From Wiki2
Revision as of 15:24, 12 January 2013 by Tim (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
JSON from arduino to PHP server
php in /var/www/feeds/getnoise.php, arduino sketch /tim/Documents/electronics/Arduino/phptest/phptest.ino

Encoding pin values in JSON: <syntaxhighlight>

   // last pieces of the HTTP PUT request:
   client.println("Content-Type: application/json");
   client.println("Connection: close");
   client.println();
     
   client.print("{"); 
   // here's the actual content of the PUT request:
   for (int analogChannel = 2; analogChannel < 6; analogChannel++) {
     int sensorReading = analogRead(analogChannel);    
     String schan = "\"sensor" + analogChannel + "\":";
     client.print(schan);
     client.print(sensorReading);
     if (analogChannel != 5) {
         client.print(",");
     }
    }
    client.println("}");

</syntaxhighlight> Reading arduino JSON from PHP server: <syntaxhighlight> <?php $thefile=file_get_contents("php://input"); echo ($thefile); $thearray = json_decode($thefile); print_r($thearray); ?> </syntaxhighlight> Output produced: <syntaxhighlight> {"sensor2":376,"sensor3":349,"sensor4":251,"sensor5":285} stdClass Object (

   [sensor2] => 376
   [sensor3] => 349
   [sensor4] => 251
   [sensor5] => 285

) </syntaxhighlight> <sytaxhighlight> </syntaxhighlight>