2021年3月31日 星期三

ESP8266WiFi.h Library

ESP8266WiFi library

ESP8266 is all about Wi-Fi. If you are eager to connect your new ESP8266 module to a Wi-Fi network to start sending and receiving data, this is a good place to start. If you are looking for more in depth details of how to program specific Wi-Fi networking functionality, you are also in the right place.

Introduction

The Wi-Fi library for ESP8266 has been developed based on ESP8266 SDK, using the naming conventions and overall functionality philosophy of the Arduino WiFi library. Over time, the wealth of Wi-Fi features ported from ESP8266 SDK to esp8266 / Arduino outgrew Arduino WiFi library and it became apparent that we would need to provide separate documentation on what is new and extra.

This documentation will walk you through several classes, methods and properties of the ESP8266WiFi library. If you are new to C++ and Arduino, don’t worry. We will start from general concepts and then move to detailed description of members of each particular class including usage examples.

The scope of functionality offered by the ESP8266WiFi library is quite extensive and therefore this description has been broken up into separate documents marked with :arrow_right:.

Quick Start

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>

void setup()
{
    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());
}

void loop() {}

In the code 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:

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.

Who is Who

Devices that connect to Wi-Fi networks are called stations (STA). Connection to Wi-Fi is provided by an access point (AP), that acts as a hub for one or more stations. The access point on the other end is connected to a wired network. An access point is usually integrated with a router to provide access from a Wi-Fi network to the internet. Each access point is recognized by a SSID (Service Set IDentifier), that essentially is the name of network you select when connecting a device (station) to the Wi-Fi.

ESP8266 modules can operate as a station, so we can connect it to the Wi-Fi network. It can also operate as a soft access point (soft-AP), to establish its own Wi-Fi network. When the ESP8266 module is operating as a soft access point, we can connect other stations to the ESP module. ESP8266 is also able to operate as both a station and a soft access point mode. This provides the possibility of building e.g. mesh networks.

The ESP8266WiFi library provides a wide collection of C++ methods (functions) and properties to configure and operate an ESP8266 module in station and / or soft access point mode. They are described in the following chapters.

Class Description

The ESP8266WiFi library is broken up into several classes. In most of cases, when writing the code, the user is not concerned with this classification. We are using it to break up description of this library into more manageable pieces.

Chapters below describe all function calls (methods and properties in C++ terms) listed in particular classes of ESP8266WiFi. The description is illustrated with application examples and code snippets to show how to use functions in practice. This information is broken up into the following documents.

Station

Station (STA) mode is used to get the ESP module connected to a Wi-Fi network established by an access point.

Station class has several features to facilitate the management of a Wi-Fi connection. In case the connection is lost, the ESP8266 will automatically reconnect to the last used access point, once it is available again. The same happens on module reboot. This is possible since ESP saves the credentials to the last used access point in flash (non-volatile) memory. Using the saved data ESP will also reconnect if sketch has been changed but code does not alter the Wi-Fi mode or credentials.

Station Class documentation, examples.

Soft Access Point

An access point (AP) is a device that provides access to a Wi-Fi network to other devices (stations) and connects them to a wired network. The ESP8266 can provide similar functionality, except it does not have interface to a wired network. Such mode of operation is called soft access point (soft-AP). The maximum number of stations that can simultaneously be connected to the soft-AP can be set from 0 to 8, but defaults to 4.

The soft-AP mode is often used and an intermediate step before connecting ESP to a Wi-Fi in a station mode. This is when SSID and password to such network is not known upfront. ESP first boots in soft-AP mode, so we can connect to it using a laptop or a mobile phone. Then we are able to provide credentials to the target network. Then, the ESP is switched to the station mode and can connect to the target Wi-Fi.

Another handy application of soft-AP mode is to set up mesh networks. The ESP can operate in both soft-AP and Station mode so it can act as a node of a mesh network.

Soft Access Point Class documentation, examples.

Scan

To connect a mobile phone to a hot spot, you typically open Wi-Fi settings app, list available networks and pick the hot spot you need. Then enter a password (or not) and you are in. You can do the same with the ESP. Functionality of scanning for, and listing of available networks in range is implemented by the Scan Class.

Scan Class documentation, examples.

Client

The Client class creates clients that can access services provided by servers in order to send, receive and process data.

Check out the separate section with list of functions.

WiFi Multi

ESP8266WiFiMulti.h can be used to connect to a WiFi network with strongest WiFi signal (RSSI). This requires registering one or more access points with SSID and password. It automatically switches to another WiFi network when the WiFi connection is lost.

BearSSL Client Secure and Server Secure

BearSSL::WiFiClientSecure and BearSSL::WiFiServerSecure are extensions of the standard Client and Server classes where connection and data exchange with servers and clients using secure protocol. It supports TLS 1.2 using a wide variety of modern ciphers, hashes, and key types.

Secure clients and servers require significant amounts of additional memory and processing to enable their cryptographic algorithms. In general, only a single secure client or server connection at a time can be processed given the little RAM present on the ESP8266, but there are methods of reducing this RAM requirement detailed in the relevant sections.

BearSSL::WiFiClientSecure contains more information on using and configuring TLS connections.
BearSSL::WiFiServerSecure discusses the TLS server mode available. Please read and understand the BearSSL::WiFiClientSecure first as the server uses most of the same concepts.
Examples.

Server

The Server Class creates servers that provide functionality to other programs or devices, called clients.

Clients connect to sever to send and receive data and access provided functionality.

Check out separate section with examples / list of functions.

UDP

The UDP Class enables the User Datagram Protocol (UDP) messages to be sent and received. The UDP uses a simple “fire and forget” transmission model with no guarantee of delivery, ordering, or duplicate protection. UDP provides checksums for data integrity, and port numbers for addressing different functions at the source and destination of the datagram.

Check out separate section with examples / list of functions.

Generic

There are several functions offered by ESP8266’s SDK and not present in Arduino WiFi library. If such function does not fit into one of classes discussed above, it will likely be in Generic Class. Among them is handler to manage Wi-Fi events like connection, disconnection or obtaining an IP, Wi-Fi mode changes, functions to manage module sleep mode, hostname to an IP address resolution, etc.

Check out separate section with examples / list of functions.

Diagnostics

There are several techniques available to diagnose and troubleshoot issues with getting connected to Wi-Fi and keeping connection alive.

Check Return Codes

Almost each function described in chapters above returns some diagnostic information. Such diagnostic may be provided as a simple boolean type true or false to indicate operation result. You may check this result as described in examples, for instance:

Serial.printf("Wi-Fi mode set to WIFI_STA %s\n", WiFi.mode(WIFI_STA) ? "" : "Failed!");

Some functions provide more than just a binary status information. A good example is WiFi.status().

Serial.printf("Connection status: %d\n", WiFi.status());

This function returns following codes to describe what is going on with Wi-Fi connection:

  1. WL_IDLE_STATUS when Wi-Fi is in process of changing between statuses
  2. WL_NO_SSID_AVAIL in case configured SSID cannot be reached
  3. WL_CONNECTED after successful connection is established
  4. WL_CONNECT_FAILED if connection failed
  5. WL_CONNECT_WRONG_PASSWORD if password is incorrect
  6. WL_DISCONNECTED if module is not configured in station mode
It is a good practice to display and check information returned by functions. Application development and troubleshooting will be easier with that.

Check Return Codes

There is a specific function available to print out key Wi-Fi diagnostic information:

    WiFi.printDiag(Serial);
A sample output of this function looks as follows:
    Mode: STA+AP
    PHY mode: N
    Channel: 11
    AP id: 0
    Status: 5
    Auto connect: 1
    SSID (10): sensor-net
    Passphrase (12): 123!$#0&*esP
    BSSID set: 0
Use this function to provide snapshot of Wi-Fi status in these parts of application code, that you suspect may be failing.

Enable Wi-Fi Diagnostic

By default the diagnostic output from Wi-Fi libraries is disabled when you call Serial.begin. To enable debug output again, call Serial.setDebugOutput(true). To redirect debug output to Serial1 instead, call Serial1.setDebugOutput(true). For additional details regarding diagnostics using serial ports please refer to the documentation.
Below is an example of output for sample sketch discussed in Quick Start above with Serial.setDebugOutput(true):

    Connectingscandone
    state: 0 -> 2 (b0)
    state: 2 -> 3 (0)
    state: 3 -> 5 (10)
    add 0
    aid 1
    cnt
    
    connected with sensor-net, channel 6
    dhcp client start...
    chg_B1:-40
    ...ip:192.168.1.10,mask:255.255.255.0,gw:192.168.1.9
    .
    Connected, IP address: 192.168.1.10
The same sketch without Serial.setDebugOutput(true) will print out only the following:
    Connecting....
    Connected, IP address: 192.168.1.10

Enable Debugging in IDE

Arduino IDE provides convenient method to enable debugging for specific libraries.

What’s Inside?

If you like to analyze in detail what is inside of the ESP8266WiFi library, go directly to the ESP8266WiFi folder of esp8266 / Arduino repository on the GitHub.

To make the analysis easier, rather than looking into individual header or source files, use one of free tools to automatically generate documentation. The class index in chapter Class Description above has been prepared in no time using great Doxygen, that is the de facto standard tool for generating documentation from annotated C++ sources.

The tool crawls through all header and source files collecting information from formatted comment blocks. If developer of particular class annotated the code, you will see it like in examples below.


If code is not annotated, you will still see the function prototype including types of arguments, and can use provided links to jump straight to the source code to check it out on your own. Doxygen provides really excellent navigation between members of library.

Several classes of ESP8266WiFi are not annotated. When preparing this document, Doxygen has been tremendous help to quickly navigate through almost 30 files that make this library.

2021年3月14日 星期日

Arduino Begineer

Arduino 是什麼?

Arduino 是整合微控制晶片及燒錄功能在一塊開發板上,就可以它的作用就好比人類的大腦,可以設計判斷不同條件,來去決定身體要做甚麼?眼睛看到前方有障礙物 > 大腦判斷 > 控制雙腳移動避開。

所以只有這一塊 Arduino 是沒辦法做太多事,因為它只雍有大腦的功能,眼睛、雙腳必須得搭配感測器或周邊設備,才能達到邏輯判斷或是自動控制的目的。

Arduino 由來

Massimo Banzi 是一家高科技設計學院的老師,他的學生常常抱怨找不到好用又便宜的微控制器。於是2005年,Massimo Banzi 與 David Cuartielles (西班牙籍晶片工程師,當時在學院做訪問學者) 討論這個問題。過幾天後,程式碼及電路板就設計完成,並命名為 Arduino。

Arduino 硬體簡介

  • 透過 USB 方口連接線,連接電腦與 Arduino,提供電源以及電腦燒錄程式的端口。
  • 想要讓 Arduino 重置,按一下重新開機就可以了。
  • 每個接腳都有它的定義,電路板上有簡單標示出來,我們主要是透過接腳來連接感測器或週邊設備。

使用 Arduino 開發的優點

  • 開源硬體及軟體,任何人都可以依照官網的電路圖自己製作或修改電路板,軟體也是可以修改,創造了更多可能性。
  • 價格便宜,義大利原廠約 600~800,由於任何人都可以生產電路板,因此有些副廠的電路板很便宜約 150~200,這讓我們可以更容易取得。
  • 支援很多感測器元件或模組,且價格也都不會很貴。
  • 網路上有許多函式庫,我們只需要知道如何應用我們的感測器,很多技術性的問題,已經被許多大神解決了,因此我們不需要懂太複雜的程式,專注在專案上就可以了。

Arduino 的創作


8x8x8 LED CUBE WITH ARDUINO UNO


DIY Arduino Robot Arm with Smartphone Control


HOW TO BUILD A SMART ARDUINO CAT FEEDER

Youtube - LazyTamato Lab : Arduino SpeedUp


Arduino 自學影片 #1 - Arduino 到底是什麼?What is Arduino?


Arduino 自學影片 #2 - 基本指令真的好簡單!Arduino commands are so easy!


Arduino 自學影片 #3 - 完成你的第一個專案!Complete your first project!


Arduino 自學影片 #4 - 判斷式 if else 讓你操縱自如!Comfortably make judgments with if else!


Arduino 自學影片 #5 - 麵包板是什麼?好吃嗎?What is breadboard Does it taste good?


Arduino 自學影片 #6 - LED 與電阻的必學之術!LED & resistors 101!


Arduino 自學影片 #7 - 程式宣告?取個綽號吧!Function declaration Let’s create a nickname!


Arduino 自學影片 #8 - 否定?彈跳?按鈕特輯 Part.1!NOT Bouncing Button Special Part. 1!


Arduino 自學影片 #9 - 邏輯?旗標?按鈕特輯 Part.2!Logic Flag Button Special Part.2!


Arduino 自學影片 #10 - 互動?遊戲?按鈕特輯 Part.3!Interaction Game Button Special Part.3!


Arduino 自學影片 #11 - Serial monitor 讀心術!Serial monitor - Mind reader!


Arduino 自學影片 #12 - 分類帽 switch case 降臨!Sorting Hat aka switch case!


Arduino 自學影片 #13 - 迴圈 for 讓你功力大提升!The almighty for loop!


Arduino 自學影片 #14 - 迴圈 while 稱霸 Arduino!

請參閱:LazyTomatoLab 官網,以獲取個多內容。