WiFi.config()
描述
WiFi.config() 用来设定 IP 位址、 DNS、闸道(gateway)、子网路遮罩(subnet)。
不像是 WiFi.begin() 会自动设定这些资讯,WiFi.config() 让使用者可以手动的设定。
在呼叫 WiFi.begin() 之前呼叫 WiFi.config(),使得 begin() 使用 config() 的设定值去设定网路。
如果是先呼叫 WiFi.begin() 再呼叫 WiFi.config(),在 begin() 执行时预设使用 DHCP 连线,一旦呼叫 config() 后,会使用输入的参数重新设定网路。
语法
WiFi.config(ip);
WiFi.config(ip, dns);
WiFi.config(ip, dns, gateway);
WiFi.config(ip, dns, gateway, subnet);
参数
ip:IP 位址,型态为 4 个位元组的阵列
dns:DNS 伺服端的 IP 位址
gateway:闸道的 IP 位址,型态为 4 个位元组的阵列。可以不填这个参数,预设的位址前三个数值会与 IP 位址相同,而最后一个数值会设为 1
subnet:子网路遮罩,型态为 4 个位元组的阵列。可以不填这个参数,预设使用 255.255.255.0
回传
无回传值
范例
示范如何把 IP 位址设定为 192.168.0.177:
#include <WiFi.h>
// 欲设定的 IP 位址
IPAddress ip(192, 168, 0, 177);
char ssid[] = "yourNetwork"; // 无线网路的 SSID
char pass[] = "secretPassword"; // WPA 的密码
int status = WL_IDLE_STATUS;
void setup()
{
// 初始化序列埠并等待其开启
Serial.begin(9600);
while (!Serial) {
;
}
// 检查 WiFi Shield
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while(true);
}
WiFi.config(ip);
// 尝试连线到无线网路
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// 连线到使用 WPA/WPA2 加密的无线网路
status = WiFi.begin(ssid, pass);
// 等待 10 秒
delay(10000);
}
// 透过序列埠印出 IP 位址
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
}
void loop () {}
The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.
