我环顾四周,但我没有找到帮助我的东西。
我有一个带有以太网屏蔽的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文件,它将检索该值。
答案 0 :(得分:0)
我认为你在这里混淆了一些陈述的顺序。首先设置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设置端口转发)
答案 1 :(得分:0)
我已经尝试了上面更正的代码,但是什么也没得到。我使用了Arduino mega和enc28j60。在我的代码中client.available未执行,意味着客户端不可用,那么我该如何解决这个问题?下面是我的代码部分。
void readValue()
{
Serial.println();
delay(1000); //Keeps the connection from freezing
if (client.connect(server ,80)) {
Serial.println("Connected");
Serial.println("The value of light is ");
client.print("GET /new/new1.php HTTP/1.1");
client.println("Host: 192.168.43.98");
while (client.available())
{
Serial.print("client available");
Serial.print(client.read());
}
client.println("Connection: close");
client.println();
Serial.println();
Serial.println("Finish");
if (!client.connected())
{
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
}
else
{
Serial.println("Connection unsuccesful");
}
//stop client
client.stop();;
}