我正在开发一个项目,我正在尝试使用HTTP和POST方法从我的Arduino Mega2560发送数据到我在localhost上托管的网站。我住在学生宿舍,因此,我无法访问路由器。但是,我买了一台路由器并通过WAN连接到墙上。此外,Arduino通过以太网屏蔽连接到路由器的以太网插头之一,我的笔记本电脑连接到另一个以太网插头。我试图从网站上检索数据,但我似乎无法加载它们。
Arduino代码
#include <dht.h>
#include <SPI.h>
#include <Ethernet.h>
dht DHT1;
int temperatureSensorPin1 = 25;
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
EthernetClient client;
EthernetServer server(80);
long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 250000;
String data;
long lastUpdate = 0;
void setup() {
Serial.begin(9600);
if(Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
}
data = "";
pinMode(temperatureSensorPin1, INPUT);
}
void loop() {
int temp1 = DHT1.read11(temperatureSensorPin1);
switch (temp1)
{
case DHTLIB_OK:
Serial.print("OK,\t");
break;
case DHTLIB_ERROR_CHECKSUM:
Serial.print("Checksum error,\t");
break;
case DHTLIB_ERROR_TIMEOUT:
Serial.print("Time out error,\t");
break;
case DHTLIB_ERROR_CONNECT:
Serial.print("Connect error,\t");
break;
case DHTLIB_ERROR_ACK_L:
Serial.print("Ack Low error,\t");
break;
case DHTLIB_ERROR_ACK_H:
Serial.print("Ack High error,\t");
break;
default:
Serial.print("Unknown error,\t");
break;
}
currentMillis = millis();
if(currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
}
String data="temp1="+String(DHT1.temperature, 0)+"&temp2="+String(DHT2.temperature, 0)+"&temp3="+String(DHT3.temperature, 0)+"&temp4="+String(DHT4.temperature, 0)+"&temp5="+String(DHT5.temperature, 0)
+"&hum1="+String(DHT1.humidity, 0)+"&hum2="+String(DHT2.humidity, 0)+"&hum3="+String(DHT3.humidity, 0)+"&hum4="+String(DHT4.humidity, 0)+"&hum5="+String(DHT5.humidity, 0)+"&gas="+gasValue;
Serial.println(Ethernet.localIP());
if(client.connect("192.168.0.1", 80)) {
client.println("POST /home/visualisation.php HTTP/1.1");
client.println("Host: 192.168.0.1");
//client.println("User-Agent: Arduino/1.0");
//client.println("Connection: close");
client.println("Content-Type: application/x-www-form-urlencoded;");
client.print("Content-Length: ");
client.println(data.length());
client.println();
client.print(data);
//Serial.println(data);
Serial.println("We have connection");
}
if(client.connected()) {
Serial.println("We have abc");
client.stop();
}
delay(4000);
}
PHP代码
<?php
$temp1 = "";
if(isset($_POST['temp1'])) {
$temp1 = $_POST['temp1'];
}
echo $temp1;
?>
我的连接是否合适?我该怎么做才能工作?
P.S。:我想澄清一下,我对网络没有广泛的了解。
答案 0 :(得分:1)
我有Arduino发送数据的ip是路由器,因此,我应该使用192.168.0.100 ip,这是我的计算机之一。
我还需要将值保存到数据库以注意更改,因为 echo $ temp1; 似乎不起作用,可能我应该将它包含在HTML label 标签。无论如何,我只是将数据库中的值加载到PHP变量中,我就能完成任务。