ESP8266WiFi Library - ESP8266 Arduino Core Documentation

Quick Start¶

Hopefully, you are already familiar how to load the Blink.ino sketch to an ESP8266 module and get the LED blinking. If not, please use this tutorial by Adafruit or another great tutorial developed by Sparkfun.

To hook up the ESP module to Wi-Fi (like hooking up a mobile phone to a hot spot), you need only a couple of lines of code:

#include<ESP8266WiFi.h> voidsetup() { Serial.begin(115200); Serial.println(); WiFi.begin("network-name","pass-to-network"); Serial.print("Connecting"); while(WiFi.status()!=WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.print("Connected, IP address: "); Serial.println(WiFi.localIP()); } voidloop(){}

In the line WiFi.begin("network-name", "pass-to-network") replace network-name and pass-to-network with the name and password of the Wi-Fi network you would like to connect to. Then, upload this sketch to ESP module and open the serial monitor. You should see something like:

Connection log on Arduino IDE's Serial Monitor

How does it work? In the first line of the sketch, #include <ESP8266WiFi.h> we are including the ESP8266WiFi library. This library provides ESP8266 specific Wi-Fi routines that we are calling to connect to the network.

The actual connection to Wi-Fi is initialized by calling:

WiFi.begin("network-name","pass-to-network");

The connection process can take couple of seconds and we are checking for whether this has completed in the following loop:

while(WiFi.status()!=WL_CONNECTED) { delay(500); Serial.print("."); }

The while() loop will keep looping as long as WiFi.status() is other than WL_CONNECTED. The loop will exit only if the status changes to WL_CONNECTED.

The last line will then print out the IP address assigned to the ESP module by DHCP:

Serial.println(WiFi.localIP());

If you don’t see the last line but just more and more dots ........., then likely name or password to the Wi-Fi network is entered incorrectly in the sketch. Verify the name and password by connecting from scratch to this Wi-Fi network with a PC or a mobile phone.

Note: if connection is established, and then lost for some reason, ESP will automatically reconnect to the last used access point once it is again back on-line. This will be done automatically by Wi-Fi library, without any user intervention.

That’s all you need to connect ESP8266 to Wi-Fi. In the following chapters we will explain what cool things can be done by the ESP once it’s connected.

Từ khóa » Thư Viện Esp8266wifi