M5Stack支持wifi因此可以方便的连接到WiFi网络,本节介绍如何使用M5Stack扫描附近的WiFi网络,显示到屏幕上。 以下内容主要涉及到WiFi库的使用以及简单的屏幕菜单绘制。
- #include
- #include "WiFi.h"
- #include
- int n; //网络数量
- int ssidLength = 10; //网络名称显示10个字符
- int thisPage = 0; //首页标记
- const int pageSize = 8; //每页显示网络数
- bool on = false; //标记
- bool leftLocked = false; //标记
- bool rightLocked = false; //标记
- void setup()
- {
- M5.begin();
- WiFi.mode(WIFI_STA); //建立Station模式
- WiFi.disconnect(); //断开所有连接
- M5.Lcd.setBrightness(100); //屏幕亮度100
- M5.Lcd.setTextSize(3); //设置字体
- M5.Lcd.setCursor(45, 110);
- M5.Lcd.printf("Wi-Fi scanner");
- DrawMenu(); //绘制菜单
- }
- void LCD_Clear() { //清屏
- M5.Lcd.fillScreen(BLACK);
- M5.Lcd.setCursor(0, 0);
- M5.Lcd.setTextColor(WHITE);
- M5.Lcd.setTextSize(2);
- }
- void DrawMenu(){
- M5.Lcd.setTextSize(3);
- M5.Lcd.setTextColor(BLUE);
-
- if (on == true) //判断开始扫描显示网络
- {
- M5.Lcd.setCursor(110, 215);
- M5.Lcd.printf("RESCAN");
- if (thisPage != 0) //如果当前页不是首页 显示<
- {
- M5.Lcd.setCursor(60, 215);
- M5.Lcd.printf("<");
- leftLocked = false;
- }
- else //否则本页不显示“<”
- {
- leftLocked = true;
- }
- if (thisPage < ((n - 1) / pageSize)) //如果扫描到的网络数量超过页面大小(8)显示“>”
- {
- M5.Lcd.setCursor(250, 215);
- M5.Lcd.printf(">");
- rightLocked = false;
- }
- else
- {
- rightLocked = true; //否则不显示“>”
- }
- }
- else //没有开启扫描显示“SCAN”
- {
- M5.Lcd.setCursor(128, 215);
- M5.Lcd.printf("SCAN");
- }
- }
- void Show(int nav = 0) // nav为-1左翻页
- if (nav == -1)
- {
- if ((on == true) && (leftLocked == false))
- {
- thisPage--;
- if (thisPage < 0) thisPage = 0;
- Show();
- }
- }
- else if (nav == 1) // nav为1右翻页
- {
- if ((on == true) && (rightLocked == false))
- {
- if ((thisPage) <= (n / pageSize)) thisPage++;
- Show();
- }
- }
- else
- {
- LCD_Clear();
- M5.Lcd.setCursor(100, 2);
- M5.Lcd.print("TOTAL: ");
- M5.Lcd.print(n); //显示网络总数
- M5.Lcd.setCursor(0, 30);
- for (int i = (thisPage * pageSize); i < ((thisPage * pageSize) + pageSize); i++) //通过当前页面索引求出显示的序号
- {
- if (i >= n) break;
- M5.Lcd.print(i + 1);
- String ssid = (WiFi.SSID(i).length() > ssidLength) ? (WiFi.SSID(i).substring(0, ssidLength) + "...") : WiFi.SSID(i);
- M5.Lcd.print(") " + ssid + " (" + WiFi.RSSI(i) + ");n");
- }
- DrawMenu();
- }
- }
- void Search() { //扫描网络
- on = true;
- LCD_Clear();
- M5.Lcd.setTextSize(3);
- M5.Lcd.setCursor(50, 90);
- M5.Lcd.printf("Please, wait.");
- M5.Lcd.setCursor(50, 120);
- M5.Lcd.printf("Searching...");
- n = WiFi.scanNetworks();
- Show();
- }
- void loop()
- {
- if (M5.BtnA.wasPressed()) Show(-1); //A键左翻页
- if (M5.BtnB.wasPressed()) Search(); //B键搜索
- if (M5.BtnC.wasPressed()) Show(1); //C键右翻页
- M5.update();
- }
复制代码
|