php - 无法将数据从mysql数据库获取到arduino变量

标签 php mysql http get arduino

我环顾四周,但没有找到可以帮助我的东西。

我有一个带以太网屏蔽的 Arduino Uno,我正在尝试将数据从 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 文件,它将检索值。

最佳答案

我认为您在这里混淆了一些语句的顺序。首先设置一个 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();
}

您可能会考虑使用端口 80 进行传输(您可能需要在路由器的端口 80 上为 arduino 设置端口转发)

关于php - 无法将数据从mysql数据库获取到arduino变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48053160/

相关文章:

http - fb Lint : Error Scraping Page: Bad Response Code

web-services - 处理用户特定数据时的 Rest api 路由名称

php paypal express结账问题

php - 查询数据并显示在html表格中

mysql - 根据国家和地区代码选择地区名称

mysql - 指定不同的主机以使用grails进行读写

php - 使用 UPDATE/SET 的 SQL 语法错误

php - 在 wordpress 中修改主题时,当我想删除主题内容时,最好删除 CSS 或 PHP 或两者都删除

php - PHP PDO 语句可以接受表名或列名作为参数吗?

Python 请求库 HTTPBasicAuth 三个参数