ESP8266向php发送数据代码
时间: 2023-06-24 07:03:10 浏览: 89
以下是ESP8266向php发送数据的示例代码:
```c++
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* host = "your_PHP_host";
void setup() {
Serial.begin(115200);
delay(10);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
}
void loop() {
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("Connection failed");
return;
}
// We now create a URI for the request
String url = "/your_php_script.php";
url += "?data=";
url += "your_data_here";
Serial.print("Requesting URL: ");
Serial.println(url);
// This will send the request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n" +
"\r\n");
delay(500);
// Read all the lines of the reply from server and print them to Serial
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
delay(10000); // Wait for 10 seconds before sending the next request
}
```
在这个示例中,你需要将以下变量替换为你的实际值:
- ssid: 你的WiFi网络名称
- password: 你的WiFi网络密码
- host: 你的PHP主机的地址
- url: 你的PHP脚本的路径和文件名
- data: 你要发送到PHP脚本的数据
此代码将通过GET请求发送数据到PHP脚本,并在串口监视器中打印服务器的响应。你可以根据需要更改请求类型和数据格式。
阅读全文