帮我写一段stm32连接esp8266的代码案例
时间: 2023-03-10 19:27:39 浏览: 115
stm32+esp8266+阿里云+温湿度+光照-烟雾-远程显示+控制-之STM32代码
5星 · 资源好评率100%
下面是 stm32 连接 ESP8266 的代码案例:
#include <ESP8266WiFi.h>
const char* ssid = "NetworkName";
const char* password = "Password";
WiFiServer server(80);
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");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
}
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);
client.flush();
// Match the request
if (req.indexOf("/LED=1") != -1) {
digitalWrite(LED_BUILTIN, LOW); // LED ON
}
if (req.indexOf("/LED=0") != -1) {
digitalWrite(LED_BUILTIN, HIGH); // LED OFF
}
// Return the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // do not forget this one
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.print("Led pin is now: ");
if(digitalRead(LED_BUILTIN)) {
client.print("Off");
} else {
client.print("On");
}
client.println("<br><br>");
client.println("<a href=\"/LED=1\"\"><button>Turn On </button></a>");
client.println("<a href=\"/LED=0\"\"><button>Turn Off </button></a><br />");
client.println("</html>");
delay(1);
Serial.println("Client disonnected");
Serial.println("");
}
阅读全文