Search code examples
phpmysqlhttpgetarduino

Can't get data from mysql database into arduino variable


I was looking around, but I didn't found something to help me.

I have an Arduino Uno with ethernet shield and I'm trying to take a data from mysql to a variable. I use WAMP as the server.

Php :

<?php   

$db_name = "aquarium";
$user = "root";
$password = "root";
$host = "localhost";

$con = mysqli_connect($host,$user,$password,$db_name);

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT value FROM light WHERE id='1'");

while($row = mysqli_fetch_array($result)) {
  echo $row['value'];
  echo "<br>"; 
}

?>

Arduino code:

#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0x2A, 0x8D  };
byte ip[] = { 192, 168, 0, 46  };
byte gw[] = {192, 168, 0, 1};
byte subnet[] = { 255, 255, 255, 0 };

IPAddress server(192,168,0,101);
EthernetClient client;


void setup()
{

Ethernet.begin(mac, ip, gw, gw, subnet); 
Serial.begin(9600);                  

}

void loop()
{
 Serial.println("Program running...");
 delay(5000);
 readValue();                                
}

void readValue()
{
Serial.println();
delay(1000);                          //Keeps the connection from freezing

if (client.connect(server ,8080)) {
Serial.println("Connected");

//client.print("GET 192.168.0.101:8080/aquarium_light_read.php ");
client.print("GET /aquarium_light_read.php ");

Serial.println("The value of light is ");

  while (client.available())
  {   
    Serial.print(client.read());    
  }

Serial.println("Finish");

client.println(" HTTP/1.1");
client.println("Host: 192,168,0,101");
client.println("Connection: close");
client.println();
Serial.println();
}

else
{
Serial.println("Connection unsuccesful");
}
 //stop client
 client.stop();
 while(client.status() != 0)
{
  delay(5);
}
}

And the output is:

Program running...

Connected
The value of light is 
Finish

and I don't understand why it doesn't retrieve the value of light. I want to mention that if I put in browser the PHP file it will retrieve the value.


Solution

  • I think you mixed up the order of a few statements here. First set a GET request, then do the while. Try this:

    Serial.println("The value of light is ");
    
    client.print("GET /aquarium_light_read.php HTTP/1.1");
    client.println("Host: 192.168.0.101");
    client.println("Connection: close");
    client.println();
    Serial.println();
    
    while (client.available())
    {   
       Serial.print(client.read());    
    }
    
    Serial.println("Finish");
    
    if (!client.connected())
    {
       Serial.println();
       Serial.println("disconnecting.");
       client.stop();
    }
    

    And you might consider using port 80 for the transfer (you might need to set up port forwarding for the arduino on port 80 in your router)