无法将mysql数据库中的数据获取到arduino变量中

iovurdzv  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(413)

我四处看看,但没找到什么能帮我的。
我有一个arduino uno和ethernet shield,我试图从mysql获取一个数据到一个变量。我使用wamp作为服务器。
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代码:


# 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);
}
}

输出为:

Program running...

Connected
The value of light is 
Finish

我不明白为什么它不能恢复光的价值。我想提到的是,如果我把php文件放到浏览器中,它将检索值。

yptwkmov

yptwkmov1#

我想你把一些陈述的顺序弄错了。第一组a GET 请求,然后执行 while . 试试这个:

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();
}

你可以考虑使用 port 80 对于传输(您可能需要在路由器的端口80上为arduino设置端口转发)

相关问题