1
這是打開/關閉LED的ESP8266代碼。我正在使用Arduino IDE內置的示例代碼。該LED工作正常,但我想發送HTTP請求到我本地託管的網站(發送電子郵件),但它不起作用。ESP8266代碼無法正常工作
- 跟我的本地WiFi
- 分配一個靜態IP
- 當我打192.168.1.101/gpio/1(Led ON)
- 當我打192.168.1.101/gpio/0(Led關)它的工作,但無法打我的網站。
- 當我打192.168.1.101/gpio/1那麼就應該打我的本地託管的URL(192.168.1.100/home/ardchk)
請幫助我理清這個問題。
#include <ESP8266WiFi.h>
const char* ssid = "SMART";
const char* password = "123456789";
const char* host = "192.168.1.100"; // Your domain
IPAddress ip(192, 168, 1, 101); // where xx is the desired IP Address
IPAddress gateway(192, 168, 1, 1); // set gateway to match your network
IPAddress subnet(255, 255, 255, 0);
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
// prepare GPIO3
pinMode(3, OUTPUT);
digitalWrite(3, 0);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.config(ip,gateway,subnet);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.println(WiFi.localIP());
}
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("new client");
while(!client.available()) {
delay(1);
}
// Read the first line of the request
String req = client.readStringUntil('\r');
Serial.println(req);
// Match the request
int val;
if (req.indexOf("/gpio/0") != -1) {
val = 0;
if (client.connect(host, 80)) {
//starts client connection, checks for connection
Serial.println("connected to website/server");
client.println("GET /home/ardchk HTTP/1.1"); //Send data
client.println("Host: 192.168.1.100");
Serial.println("Email Sended");
client.println("Connection: close");
//close 1.1 persistent connection
client.println(); //end of get request
}
} else if (req.indexOf("/gpio/1") != -1) {
val = 1;
} else {
Serial.println("invalid request");
client.stop();
return;
}
// Set GPIO2 according to the request
digitalWrite(3, val);
client.flush();
// Prepare the response
String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
s += (val)?"high":"low";
s += "</html>\n";
// Send the response to the client
client.print(s);
delay(1);
Serial.println("Client disconnected");
// The client will actually be disconnected
// when the function returns and 'client' object is destroyed
}
請解釋當您嘗試點擊網址時會發生什麼。 「不工作」不清楚 – Billa
您需要學會拼寫(隨機大寫字母不會被視爲正確的拼寫),並正確縮進您的代碼。幸運的是,Arduino IDE爲您做到了這一點:按下ctrl-T ... – dda
代碼塊:if(client.connect(host,80)) {此代碼未運行,因爲未與主機連接}甚至網站託管於同一網絡 –