Showing posts with label WiFi. Show all posts
Showing posts with label WiFi. Show all posts

2022/12/04

App Inventor #11自己來寫 App - 骰子遊戲 (Dice Game)

大家好, 歡迎收看本週的Weekend project with Stonez56。 

本周要進行的是 App Inventor 第10集 -  自己來寫 App - 骰子遊戲

這個影片適合稍進階同學來觀看&學習, 想要越級挑戰的朋也也歡迎拿來這個單元來學習 App Inventor 2! 

這是一個學習任意組件的好範例, Android, iPad 都可以使用!




本次教學你可以學到:

 * 本集會使用到:

 * 感測器 (Sensor)

 * 變數應用 (Variables)

 * 清單的應用 (List)

 * 圖片的應用 (Image)

 * 為APP加上音音效 (Audio)

 * 亂數的應用 (Randomized)

 * 用任意組件 (Any component)

 * 程序的應用 (Procedure)


參考資料: 

App inventor 語法 & 使用方式: http://ai2.appinventor.mit.edu/reference/blocks/ 

音效來源: https://pixabay.com/ 

圖片製作:  https://figma.com 


如果你時間不夠, 也可以從以下的時間軸挑選想看的部份即可! 


影片時間軸: 

00:00 開始

00:24 骰子 App 示範

01:20 App 畫面的配置 / 素材上傳

04:39 App 程式設計

05:18 如何使用變數/變數種子

06:31 設定音效

11:54 如何使用任意元件

15:22 使用任意組件來移除重複的運算

16:26 把骰子元件放入清單中

23:11 使用任意組件 vs 未使用任意組件


App Inventor 相關教學影片:


* App Inventor #11自己來寫 App - 骰子遊戲 (Dice Game)

https://youtu.be/2d6Si6u8FVE


* App Inventor #10 集 自己來寫 APP YouBike 2.0 (下). 

https://youtu.be/Cli-_lUPjgU


* App Inventor #9 集 - 自己來寫 APP YouBike 2.0 (上) 

https://youtu.be/D78-eDRFiXM


*App Inventor #8 AI2 Companion 一直斷線怎麼辦? AI2 小技巧 (How to keep AI2 always connected for Android) https://youtu.be/_HeM9GyVmIE


* App Inventor #7 ESP32 語音辨識控制 IOT 專案, 使用 IoT Essential Library Example (CC available)  https://youtu.be/senjdb-cREY


* App Inventor #6 使用’ 繪圖動畫' 製作使用者介面 (App Inventor 2 UI design with Draw and Animation) https://youtu.be/RfYi8h9y6kE


* App Inventor #5 - “無線搖控 ESP32-CAM APP 下集 (Write ESP32-CAM remote APP 2/2) https://youtu.be/J8b3zWX1FXM


* App Inventor #4 無線搖控 ESP32-CAM APP 上集 (Write ESP32-CAM remote APP 1/2)

https://youtu.be/x545mFSZWgg


* App Inventor #3 “自己來寫APP 快篩何處買?” (How to process .csv files in App Inventor)

https://youtu.be/u5J4FJQ5UQQ


* App Inventor #2 “自己來寫mqtt APP Android & iOS都能用” (Create MQTT Apps with App Inventor 2)

https://youtu.be/kIONEfLO4sI


* MIT App Inventor 2 #1 - 語音辨識 (Voice Recognition)

https://youtu.be/msV4V6af6tA 

2022/11/06

Arduino #38 YouBike 2.0 餘車通知器 (Arduino #38 ESP32 1306 YouBik 2.0 remain notifier)

大家好, 歡迎收看本週的Weekend project with Stonez56。 

本周要進行的是Arduino 第38集 -  UBike 2.0 餘車通知器.



大多數坐捷運上下班的朋友, 一定有這樣的經驗:下班時,匆匆忙忙趕到捷運站,卻發現捷運站的Ubike已經都沒有了, 只好在那邊癡癡的等候.

如果下班之前, 看一下YouBike 2.0, 餘車通知器, 確定站點還有較多的Ubike, 這時候再過去牽車, 是不是很安心呢? 我們來看看怎麼做吧!


如果你時間不夠, 也可以從以下的時間軸挑選想看的部份即可! 

影片時間軸:

00:00 開始

00:43 UBike 2.0 餘車通知器使用方法

03:22 Google Sheet 設定

14:44 Google Sheet 發佈API設定

17:19 Google Script doPost(e) 程式解釋

20:27 Google Script doGet(e) 程式解釋

21:46 ESP32 程式解釋

26:51 ESP32 refreshYouBike2data (更新SHEET資料)

28:52 ESP32 goGetData 由Sheet取得資料

30:03 showUTF8String 顯示餘車資料


App Inventor 相關教學影片:

* App Inventor #11自己來寫 App - 骰子遊戲 (Dice Game)
https://youtu.be/2d6Si6u8FVE

* App Inventor #10 集 自己來寫 APP YouBike 2.0 (下).
https://youtu.be/Cli-_lUPjgU

* App Inventor #9 集 - 自己來寫 APP YouBike 2.0 (上)
https://youtu.be/D78-eDRFiXM

*App Inventor #8 AI2 Companion 一直斷線怎麼辦? AI2 小技巧 (How to keep AI2 always connected for Android) https://youtu.be/_HeM9GyVmIE

* App Inventor #7 ESP32 語音辨識控制 IOT 專案, 使用 IoT Essential Library Example (CC available)  https://youtu.be/senjdb-cREY

* App Inventor #6 使用’ 繪圖動畫' 製作使用者介面 (App Inventor 2 UI design with Draw and Animation) https://youtu.be/RfYi8h9y6kE

* App Inventor #5 - “無線搖控 ESP32-CAM APP 下集 (Write ESP32-CAM remote APP 2/2) https://youtu.be/J8b3zWX1FXM

* App Inventor #4 無線搖控 ESP32-CAM APP 上集 (Write ESP32-CAM remote APP 1/2)

https://youtu.be/x545mFSZWgg

* App Inventor #3 “自己來寫APP 快篩何處買?” (How to process .csv files in App Inventor)

https://youtu.be/u5J4FJQ5UQQ

* App Inventor #2 “自己來寫mqtt APP Android & iOS都能用” (Create MQTT Apps with App Inventor 2)   https://youtu.be/kIONEfLO4sI

* MIT App Inventor 2 #1 - 語音辨識 (Voice Recognition)
https://youtu.be/msV4V6af6tA 

2022/10/01

App Inventor #8 AI2 Companion 一直斷線怎麼辦? AI2 小技巧

大家好, 歡迎收看本週的Weekend project with Stonez56。

本周要進行的是 App Inventor 第8集 -   AI2 Companion 一直斷線怎麼辦?


在使用 App Inventor 時, 我比較喜歡是在手機上安裝 AI2 Companion 來測試 App 以確保App

的畫面設計與預期的相符合, 但是你是不是常常發生ai2 companion常常發生斷線的問題? 


斷線後, 你必須在App inventor裡, 重新產生QR Code, 掃描, 等待ai2 companion再次連線,

真的是很麻煩呢! 本集我們就來在Android手機上做一些設定讓ai2 companion永遠連線, 這樣子以後就很方便喔!


也可以從以下的時間軸挑選想看的部份即可! 


影片時間軸: 

00:00 開始

00:54 為什麼 AI2 會斷線?

01:31 Android 手機設定打開發人員選項

02:12 在版本號碼上點7次

03:04 打開螢幕不休眠選項


2022/09/04

App Inventor #7 ESP32 語音控制-IOT 專案必備程式庫範例 (Voice Control ESP32 with IoT Essential Code Base/Voice command )

 

前言:


大家好, 歡迎收看本週的Weekend project with Stonez56。
本周要進行的是 App Inventor 第7集 -  語音控制ESP32 - IOT 專案必備程式庫範例


本週要來示範如何設計App inventor 2 語音控制 APP, 只要加上我之前介紹的IoT專用必備程式庫, (請參考下方的#27連結), 為了讓初學者更好上手, 本次採用沒有放入MQTT的程式庫, 讓範例更簡單一點. 我們先來看一下實際的操作影片. https://www.youtube.com/watch?v=senjdb-cREY&t=40s


整個範例做完,你就可以以語音來控制遠端的 ESP32 了.  本次範例, 除了可以控制ESP32上的LED開 & 關, 也可以控制伺服馬達的開 & 關, 這集也加上了多語功能的控制, 中文和英文都可以喔. 範例中也設定了法文, 西班牙文, 和日文,有興趣的朋友可以自行加上這些語言的控制程式碼. 


#27 AsyncWifimanager ElegantOTA ESP32 (WiFi 密碼管理+ WiFi 韌體更新)
https://stonez56.blogspot.com/2021/07/asyncwifimanager-elegantota-esp32-wifi.html 


請先到上方的連結, copy 所有的程式嗎, 再複製到 Arduino 編輯程式中存檔.

也要記得把  esp32_servo.h 檔案給儲存下來.

好, 那我們就開始吧今天的練習吧~





Source code:


37_vioceControl_ESP32_ECBv1.ino

#include "esp32_servo.h" //------->
#define myLED 2          //------->

#include <AsyncElegantOTA.h>
const char *FOTA_USERNAME = "un"; 
const char *FOTA_PASSWORD = "pw"; 
/****************************************************************************************************************************
  Async_AutoConnect_ESP32_minimal.ino
  For ESP8266 / ESP32 boards
  Built by Khoi Hoang https://github.com/khoih-prog/ESPAsync_WiFiManager
  Licensed under MIT license
 *****************************************************************************************************************************/
#if !(defined(ESP32))
#error This code is intended to run on the ESP32 platform! Please check your Tools->Board setting.
#endif
#include <ESPAsync_WiFiManager.h> //https://github.com/khoih-prog/ESPAsync_WiFiManager
AsyncWebServer webServer(80);

#define DEVICE_NAME "VoiceCommandESP32"  //------->
DNSServer dnsServer;

void setup()
{
    pinMode(myLED, OUTPUT);  //------->
    servo_setup();           //------->
    // put your setup code here, to run once:
    Serial.begin(115200);
    while (!Serial)
        ;
    delay(200);
    Serial.println("\nStarting Async_AutoConnect_ESP32_minimal on " + String(ARDUINO_BOARD));
    Serial.println(ESP_ASYNC_WIFIMANAGER_VERSION);

    ESPAsync_WiFiManager ESPAsync_wifiManager(&webServer, &dnsServer, DEVICE_NAME);  //------->

    //ESPAsync_wifiManager.resetSettings();   //reset saved settings
    //ESPAsync_wifiManager.setAPStaticIPConfig(IPAddress(192, 168, 132, 1), IPAddress(192, 168, 132, 1), IPAddress(255, 255, 255, 0));
    ESPAsync_wifiManager.autoConnect();
    if (WiFi.status() == WL_CONNECTED)
    {
        Serial.print(DEVICE_NAME);  //------->
        Serial.print(F(" Connected. Local IP: "));
        Serial.println(WiFi.localIP());
    }
    else
    {
        Serial.println(ESPAsync_wifiManager.getStatus(WiFi.status()));
    }

    webServer.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
        { request->send(200, "text/plain", "Hi! I am ESP32S. access to URL /update to update firmware"); });  //------->

    webServer.onNotFound([](AsyncWebServerRequest *request)   
        { request->send(404, "text/plain", "Page not found!"); });  //------->
    
    // move the motors  //-------> NEW ADDITION Codes
    webServer.on("/go", HTTP_GET, [](AsyncWebServerRequest *request)
        {
            String motor = "";
            String rotation = "";
            // Get input value from URL/go?motor=msg1&rotation=msg2
            if(request->hasParam("motor") && request->hasParam("rotation")){
                if(request->hasParam("motor")){
                    AsyncWebParameter* p = request->getParam("motor");
                    Serial.print(p->name().c_str());
                    Serial.println(p->value().c_str());
                    motor = p->value();
                }
                if(request->hasParam("rotation")){
                    AsyncWebParameter* p = request->getParam("rotation");
                    Serial.print(p->name().c_str());
                    Serial.println(p->value().c_str());
                    rotation = p->value();
                }

                if(rotation == "0"){
                    digitalWrite(myLED, LOW);
                }else if(rotation == "1"){
                    digitalWrite(myLED, HIGH);
                }else{
                    servo_spin(rotation.toInt());
                }
                request->send(200, "text/plain", "Command executed!");
            }else{
                request->send(200, "text/plain", "Error command!");
                Serial.println("Error commands!");
            }
        });
    
    //AsyncElegantOTA.begin(&webServer); // Start ElegantOTA WITHOUT username & password
    AsyncElegantOTA.begin(&webServer, FOTA_USERNAME, FOTA_PASSWORD); // Start ElegantOTA with username & password 

    webServer.begin();
    Serial.println("HTTP server started");
}

void loop() {

}


esp32_servo.h

// ESP32Servo by John K. Bennett,autoConnectKevin Harrington Version 0.11.0
// https://github.com/jkb-git/ESP32Servo/blob/master/src/ESP32_Servo.h
#include <analogWrite.h>
#include <ESP32PWM.h>
#include <ESP32Servo.h>
#include <ESP32Tone.h>

/** Define SERVO pins **/

#define SERVO_PIN2 13   //
Servo SERVO_LR; //left right

const int MAX_ANGLE = 170; //keep servo at minimum range
const int MIN_ANGLE = 10;
int SERVO_LR_POS = 90;

void servo_setup()
{
    SERVO_LR.setPeriodHertz(50); // standard 50 hz servo
    // http://yehnan.blogspot.com/2013/09/arduinotower-pro-sg90.html
    SERVO_LR.attach(SERVO_PIN2, 500, 2400);

    //init position 90 degree for LR & UD
    SERVO_LR.write(SERVO_LR_POS);
}

void servo_spin(int angle){
    // motor protection
    if(angle > MAX_ANGLE) angle = MAX_ANGLE;
    if(angle < MIN_ANGLE) angle = MIN_ANGLE;
    
    SERVO_LR.write(angle);
}



2022/08/14

Android #36 IoT 基本程式庫 Wifimanager FOTA MQTT (IOT Essential Code base with wifimanager, ElegantOTA, & MQTT)

Hi, Welcome to weekend project with Stonez56

This week's Arduino episode #37, "Essential IoT Code Base- Wifimanager FOTA + MQTT"

Here is the source code: https://stonez56.blogspot.com/2022/08/android-36-iot-wifimanager-fota-mqtt.html 


Today, I will show how to combine three commonly used IoT libraries;

WiFimanager, AsyncElegantOTA, and MQTT To become a common IoT code base. So, for our future projects, ESP8266 or ESP32, would have these basic functions.

Let's first look at these three libraries:

  • Wifimanager = Wi-Fi password management, no need to re-burn the code to change the Wi-Fi SSID & password
  • FOTA = Use Wi-Fi to update ESP32 code, you can burn code without connecting to USB
  • MQTT = Streamlined and lightweight communication protocol (Message Queueing Telemetry Transport)


This episode will only introduce how to integrate MQTT into Wifimanager + AsyncElegantFOTA.

To learn how to start Wifimanager + AsyncElegantOTA, Please watch Android #27 Wifimanager + OTA for ESP32/ESP8266 (ESPAsyncWifimanager / ESPAsyncElegantOTA)) https://youtu.be/UlRLTvl4DRc 


==References==

Arduino Library URL:


==Sample code URL==

ESPAsync_WiFiManager minimal: https://github.com/khoih-prog/ESPAsync_WiFiManager/blob/master/examples/Async_AutoConnect_ESP32_minimal/Async_AutoConnect_ESP32_minimal.ino 


ESP32 Async OTA : https://github.com/ayushsharma82/AsyncElegantOTA/blob/master/examples/ESP32_Async_Demo/ESP32_Async_Demo.ino 


If you don't have enough time, you can also select the part you want to watch from the timeline below!

Video Timeline: 00:00 Start 01:39 Demonstration of project results 01:57 mqttgo.io MQTT server, free, fast, & stable 05:52 Install three libraries 07:14 Added two ESP32 PINs as MQTT example 07:41 Encrypt the firmware update (ElegantOTA) page 11:44 Explain how the MQTT callback function works 13:07 Control ESP32 I/O pins with MQTT 15:16 Future program can be written from here

=====中文版本======

大家好, 歡迎收看本週的Weekend project with Stonez56。 

本周要進行的是 Arduino 第36集,"IoT 基本程式庫 - Wifimanager FOTA + MQTT”

今天來跟大家介紹如何把 一般的 IoT 專案常用到的三個程式庫,  WiFiManager 以及WiFi 韌體更新FOTA (Firmware Over the Air), 再加上 MQTT 三個整合在一起, 變成一個常用的 Code base.  往後你的 ESP32 IoT 專案呢, 就可以俱備這些基本功能了! 


  • Wifimanager = WiFi 密碼管理, 不用重新燒 Code 改 Wifi SSID & 密碼
  • FOTA = 用Wi-Fi更新ESP32程式碼, 不用接USB就可以燒Code
  • MQTT = 精簡輕量化的通訊協定(Message Queueing Telemetry Transport)


本集僅會介紹如何把 MQTT 整合到 Wifimanager + AsyncElegantFOTA

若想了解如何整合 Wifimanager + AsyncElegantOTA, 

請觀看 Arduino #26 AsyncWifimanager ElegantOTA ESP32 (WiFi 密碼管理+ WiFi 韌體更新) https://youtu.be/zepkinJ46Zg  




==參考資料==

Arduino Library URL: 


==Sample code URL==


如果時間不夠的朋友, 也可以從以下的時間軸挑選想看的部份即可! 

影片時間軸:

影片時間軸: 00:00 Start 01:39 專案成果示範 01:57 mqttgo.io 快速免費的 MQTT 伺服器 05:52 安裝三支程式庫 07:14 加入兩個 ESP32 PIN做為MQTT範例 07:41 為韌體更新(ElegantOTA)頁面加密 11:44 說明MQTT callback 函數運作方式 13:07 MQTT由此控制ESP32 PIN 15:16 把你的程式可以寫在這裡


IoT基本程式庫原始程式:


/** 
 * Arduino code base for IoT Projects
 * By: Stonez56 aka Kevin Chen 2022-08-16
 * 
 * This source code combined three most common Arduino libraries for IoT Projects, 
 * ESPAsync_Wifimanager, AsyncElegantOTA, & Pubsubclient MQTT Client.
 * 
 * 1. ESPAsync_WiFiManager: https://github.com/khoih-prog/ESPAsync_WiFiManager 
 * 2. AsyncElegantOTA: https://github.com/ayushsharma82/AsyncElegantOTA 
 * 3. Pubsubclient MQTT Client: https://github.com/knolleary/pubsubclient 
 * 
 * YouTube video: https://youtu.be/giFHp9RSMvQ
 * Source code is available my blog: https://stonez56.blogspot.com/2022/08/android-36-iot-wifimanager-fota-mqtt.html 
 **/

/*
 * Define Relay pins as examples to send/receive MQTT messages
 * **/
#define RELAY_PIN_1 12
#define RELAY_PIN_2 14

/** 
 * Perform OTAs for ESP8266 / ESP32 Elegantly with password protection! 
 * https://github.com/ayushsharma82/AsyncElegantOTA
 * **/
#include <AsyncElegantOTA.h>
const char *FOTA_USERNAME = "un";
const char *FOTA_PASSWORD = "pw";

/** 
 * Add MQTT client here` PubSubClient V2.8 by Nick O'Leary
 * https://github.com/knolleary/pubsubclient 
*/
#include <WiFiClient.h>
#include <PubSubClient.h>
#define MSG_BUFFER_SIZE (1024)
char msg[MSG_BUFFER_SIZE];

/** Taiwan No. 1 Free MQTT Server!! **/
const char *mqtt_server = "mqttgo.io";
const int mqtt_port = 1883;

/****************************************************************************************************************************
  Async_AutoConnect_ESP32_minimal.ino
  For ESP8266 / ESP32 boards
  Built by Khoi Hoang https://github.com/khoih-prog/ESPAsync_WiFiManager
  Licensed under MIT license
 *****************************************************************************************************************************/
#if !(defined(ESP32))
#error This code is intended to run on the ESP32 platform! Please check your Tools->Board setting.
#endif
#include <ESPAsync_WiFiManager.h> 
AsyncWebServer webServer(80);

//Start DNS server
DNSServer dnsServer;

//MQTT - Start WiFi client and connect to MQTT server
WiFiClient espClient;
PubSubClient mqtt_client(espClient);

//Define device name
String DEVICE_NAME = "Dual_Relay_Switch";
String home_page_message = "";

void setup()
{
    Serial.begin(115200);
    pinMode(RELAY_PIN_1, OUTPUT);
    pinMode(RELAY_PIN_2, OUTPUT);

    while (!Serial)
        ;
    delay(200);
    Serial.print("\nAsyncWifimanager started on " + String(ARDUINO_BOARD) + "\n");

    //Initialize ESPAsyncWifimanager instance and assign Wi-Fi Client name "AsyncAutoConnect"!
    //This name and IP address can be checked from the router
    ESPAsync_WiFiManager ESPAsync_wifiManager(&webServer, &dnsServer, "Dual_Relay_Switch");

    //####### RESET SAVED WIFI SETTINGS #############
    //ESPAsync_wifiManager.resetSettings();   

    //ESPAsync_wifiManager.setAPStaticIPConfig(IPAddress(192, 168, 132, 1), IPAddress(192, 168, 132, 1), IPAddress(255, 255, 255, 0));
    //ESPAsync_wifiManager.autoConnect("Stonez_ESP32S", "AP-NAME", "AP-PASSWORD");
    
    ESPAsync_wifiManager.autoConnect("Dual_Switch_ESP32S");
    if (WiFi.status() == WL_CONNECTED)
    {
        Serial.print(DEVICE_NAME);
        Serial.print(" is on Local IP: ");
        Serial.println(WiFi.localIP());
    }
    else
    {
        Serial.println(ESPAsync_wifiManager.getStatus(WiFi.status()));
    }

    //Setup home page access content when visite
    home_page_message = "<!DOCTYPE html><html><head><title>" + DEVICE_NAME 
        + "</title></head><body><p><h2> Hi! This is " + DEVICE_NAME + "</h2>"
        + "To update firmware, <a href='/update'>Click here!!</a><br/><span>Username & Password required!</span></p><body></html>";

    webServer.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
                 { request->send(200, "text/html", home_page_message); });

    //AsyncElegantOTA.begin(&webServer); // Start ElegantOTA WITHOUT username & password
    AsyncElegantOTA.begin(&webServer, FOTA_USERNAME, FOTA_PASSWORD); // Start ElegantOTA with username & password
    webServer.begin();
    Serial.println("AsyncElegantOTA server started @URL/update");

    //MQTT starts here!
    mqtt_client.setServer(mqtt_server, mqtt_port);
    mqtt_client.setCallback(callback);
}

/**
//When MQTT lost connection, this function will be called to reconnect MQTT//
 * Modified to accept multiple MQTT topics 
 * https://www.baldengineer.com/multiple-mqtt-topics-pubsubclient.html
 */
void callback(char *topic, byte *payload, unsigned int length)
{
    //Print message received
    Serial.print("Message arrived [");
    Serial.print(topic);
    Serial.print("] ");
    for (int i = 0; i < length; i++)
    {
        Serial.print((char)payload[i]);
    }
    Serial.println();

    //Process multiple topics here//
    payload[length] = '\0';
    String message = (char*)payload;
    
    if (strcmp(topic, "studio/humd_switch") == 0)
    {
      if(message == "true"){
        digitalWrite(RELAY_PIN_1, HIGH);
        Serial.println("humd_switch true");
      }
      if(message == "false"){
        digitalWrite(RELAY_PIN_1, LOW);
        Serial.println("humd_switch false");
      }
    }
    if (strcmp(topic, "studio/humd_switch2") == 0)
    {
      if(message == "true"){
        digitalWrite(RELAY_PIN_2, HIGH);
        Serial.println("humd_switch2 true");
      }
      if(message == "false"){
        digitalWrite(RELAY_PIN_2, LOW);
        Serial.println("humd_switch2 false");
      }
    }
}

//============= MQTT ===================
//When MQTT lost connection, this function will be called to reconnect MQTT//
void reconnect(){
    //Loop while MQTT connected
    while (!mqtt_client.connected())
    {
        Serial.print("Attempting MQTT connection... ");
        // Create a random client ID
        String clientId = "Stonez_ESP32Client-";
        clientId += String(random(0xffff), HEX);
        // Attempt to connect
        if (mqtt_client.connect(clientId.c_str()))
        {
            Serial.print("connected to ");
            Serial.print(mqtt_server);
            // Once connected, publish an announcement...
            mqtt_client.publish("outTopic", "Hello world");
            // ... and resubscribe
            mqtt_client.subscribe("studio/humd_switch");
            mqtt_client.subscribe("studio/humd_switch2");
        }
        else
        {
            Serial.print("failed, rc=");
            Serial.print(mqtt_client.state());
            Serial.println(" try again in 5 seconds");
            // Wait 5 seconds before retrying
            delay(5000);
        }
    }
}
void loop() {
    //============= MQTT ===================
    //if can't connect to MQTT server, then re-connect
    if (!mqtt_client.connected())
        { reconnect(); }
    //constantly check MQTT to see for messages sending/receiving
    mqtt_client.loop();

    /**
     * Write your own code here....
     * 
     */
}

Async_AutoConnect_ESP32_minimal.ino

/****************************************************************************************************************************
  Async_AutoConnect_ESP32_minimal.ino
  For ESP8266 / ESP32 boards
  Built by Khoi Hoang https://github.com/khoih-prog/ESPAsync_WiFiManager
  Licensed under MIT license
 *****************************************************************************************************************************/
#if !(defined(ESP32) )
  #error This code is intended to run on the ESP32 platform! Please check your Tools->Board setting.
#endif
#include <ESPAsync_WiFiManager.h>              //https://github.com/khoih-prog/ESPAsync_WiFiManager
AsyncWebServer webServer(80);
DNSServer dnsServer;

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(115200); while (!Serial); delay(200);
  Serial.print("\nStarting Async_AutoConnect_ESP32_minimal on " + String(ARDUINO_BOARD)); Serial.println(ESP_ASYNC_WIFIMANAGER_VERSION);
  ESPAsync_WiFiManager ESPAsync_wifiManager(&webServer, &dnsServer, "AutoConnectAP");
  //ESPAsync_wifiManager.resetSettings();   //reset saved settings
  ESPAsync_wifiManager.setAPStaticIPConfig(IPAddress(192,168,132,1), IPAddress(192,168,132,1), IPAddress(255,255,255,0));
  ESPAsync_wifiManager.autoConnect("AutoConnectAP");
  if (WiFi.status() == WL_CONNECTED) { Serial.print(F("Connected. Local IP: ")); Serial.println(WiFi.localIP()); }
  else { Serial.println(ESPAsync_wifiManager.getStatus(WiFi.status())); }
}

void loop() {  }

Async_AutoConnect_ESP8266_minimal.ino

/****************************************************************************************************************************
  Async_AutoConnect_ESP8266_minimal.ino
  For ESP8266 / ESP32 boards
  Built by Khoi Hoang https://github.com/khoih-prog/ESPAsync_WiFiManager
  Licensed under MIT license
 *****************************************************************************************************************************/
#if !( defined(ESP8266) )
  #error This code is intended to run on ESP8266 platform! Please check your Tools->Board setting.
#endif
#include <ESPAsync_WiFiManager.h>              //https://github.com/khoih-prog/ESPAsync_WiFiManager
AsyncWebServer webServer(80);
DNSServer dnsServer;

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(115200); while (!Serial); delay(200);
  Serial.print("\nStarting Async_AutoConnect_ESP8266_minimal on " + String(ARDUINO_BOARD)); Serial.println(ESP_ASYNC_WIFIMANAGER_VERSION);
  ESPAsync_WiFiManager ESPAsync_wifiManager(&webServer, &dnsServer, "AutoConnectAP");
  //ESPAsync_wifiManager.resetSettings();   //reset saved settings
  //ESPAsync_wifiManager.setAPStaticIPConfig(IPAddress(192,168,186,1), IPAddress(192,168,186,1), IPAddress(255,255,255,0));
  ESPAsync_wifiManager.autoConnect("AutoConnectAP");
  if (WiFi.status() == WL_CONNECTED) { Serial.print(F("Connected. Local IP: ")); Serial.println(WiFi.localIP()); }
  else { Serial.println(ESPAsync_wifiManager.getStatus(WiFi.status())); }
}

void loop() {  }


2022/04/23

Android #34 用一塊ESP32來學IOT - Android手機也能通 (Learn IOT with an ESP32 / remote control w/ MQTTDash)

Android #34 用一塊ESP32來學IOT - Android手機也能通 Learn IOT with an ESP32 / remote control w/ MQTTDash

** ENGLISH closed captions is now available for this video ** Learn IOT with an ESP32 / remote control w/ MQTTDash APP

Video timeline:

00:58 Download MQTTDash App 01:29 Create an MQTT connection 03:20 Dashboard Design 04:17 Review subscriptions on MQTTLens 05:15 Enter subscription topics in MQTTDash 10:30 See the Demo on the phone 12:39 Modify ESP32 code accordingly 大家好, 歡迎收看本週的Weekend project with Stonez56。 本周是Android 第34集,"用一塊ESP32來學IOT - Android 手機也能通”。這個是一個專門為初學者來開發的一個系列。 繼上集之後, 有網友反應無法在手機上用 MQTTlens. 所以我們今天要把只能在電腦上使用的 MQTTLens 改成 MQTTDash 這支Android APP. 這樣子, 只要帶著手機, 我們就可真正隨時隨地的遠端控制IOT設備了~ 那我們就一起來學習吧。 Android MQTTDash App: https://play.google.com/store/apps/details?id=net.routix.mqttdash&hl=zh_TW&gl=US&showAllReviews=true 尚未看過這系列的朋友, 建議從這裡依序學習: * 用一塊ESP32來學 IOT https://youtu.be/rjPU4YZG338 * 溫溼度篇 https://youtu.be/x3k_dZXua1I * Android App 也能通 https://youtu.be/0IjQOxD2j48 如果時間不夠的朋友, 也可以從以下的時間軸挑選想看的部份即可! 影片時間軸: 00:00 開始 00:58 下載 MQTTDash APP 01:29 建立 EMQX MQTT 連線 03:20 儀表板設計 04:17 查看之前 MQTTLens 上的訂閱/發佈主題 05:15 在 MQTTDash 中加入訂閱/發佈主題 10:30 看實際手機+ESP32 展示 12:39 如何修改 ESP32 相應代碼

Source code:

/*
 Basic ESP8266 MQTT example
 This sketch demonstrates the capabilities of the pubsub library in combination
 with the ESP8266 board/library.
 It connects to an MQTT server then:
  - publishes "hello world" to the topic "outTopic" every two seconds
  - subscribes to the topic "inTopic", printing out any messages
    it receives. NB - it assumes the received payloads are strings not binary
  - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
    else switch it off
 It will reconnect to the server if the connection is lost using a blocking
 reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
 achieve the same result without blocking the main loop.
 To install the ESP8266 board, (using Arduino 1.6.4+):
  - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
       http://arduino.esp8266.com/stable/package_esp8266com_index.json
  - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
  - Select your ESP8266 in "Tools -> Board"
*/

#include <WiFi.h>
#include <PubSubClient.h>
#include <EasyButton.h>
#define LED 2        //built-in LED on ESP32

#include "DHT.h"
#define DHTPIN 23     // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT11
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor.
// Set up the temp / humidity update cycle
const int updateCycle = 5000;

// Update these with values suitable for your network.
const char *ssid = "Wi-Fi SSID";
const char *password = "Wi-Fi Password";

// Define your client ID on EMQX
String mqtt_ClientID = "stonez56_IOT_Station_";

// Define your topics to subscribe / publish
const char* sub_topic = "stonez56/esp32s";
const char* pub_led_topic = "stonez56/esp32s_led_state";
const char* pub_init_topic = "stonez56/esp32s_is_back";
const char* pub_temp_topic = "stonez56/esp32s_temp";
const char* pub_humd_topic = "stonez56/esp32s_humd";

// EMQX broker parameters
const char *mqtt_server = "broker.emqx.io";
const char *mqtt_userName = "emqx";
const char *mqtt_password = "public";

WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
char msg1[MSG_BUFFER_SIZE];

int value = 0;

void setup_wifi()
{
    delay(10);
    // We start by connecting to a WiFi network
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);

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

    randomSeed(micros());

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

void callback(char *topic, byte *payload, unsigned int length)
{
    Serial.print("Message arrived [");
    Serial.print(topic);
    Serial.print("] ");
    for (int i = 0; i < length; i++)
    {
        Serial.print((char)payload[i]);
    }
    Serial.println();

    payload[length] = '\0';
    String message = (char *)payload;
    
    if (strcmp(topic, sub_topic) == 0)
    {
        if (message == "off")
        {
            digitalWrite(LED, LOW); //Turn off
            client.publish(pub_led_topic, "off");
        }
        if (message == "on")
        {
            digitalWrite(LED, HIGH); //Turn on
            client.publish(pub_led_topic, "on");
        }
    }

    /* Switch on the LED if an 1 was received as first character
    // if ((char)payload[0] == '1')
    // {
    //     digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
    //                                     // but actually the LED is on; this is because
    //                                     // it is active low on the ESP-01)
    // }
    // else
    // {
    //     digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
    // } */
}

void reconnect()
{
    // Loop until we're reconnected
    while (!client.connected())
    {

        Serial.println("Attempting EMQX MQTT connection...");
        // Create a random client ID
        mqtt_ClientID += String(random(0xffff), HEX);
        // Attempt to connect
        if (client.connect((mqtt_ClientID, mqtt_userName, mqtt_password)))
        {
            Serial.print(" connected with Client ID: ");
            Serial.println(mqtt_ClientID);
            // Once connected, publish an announcement...
            client.publish(pub_init_topic, "Hi, I'm online!");
            // ... and resubscribe
            client.subscribe(sub_topic);
        }
        else
        {
            Serial.print("failed, rc=");
            Serial.print(client.state());
            Serial.println(" try again in 5 seconds");
            // Wait 5 seconds before retrying
            delay(5000);
        }
    }
}

void setup()
{
    //Start DH11 sensor
    dht.begin();

    pinMode(LED, OUTPUT); // Initialize the _LED pin as an output
    digitalWrite(LED, LOW); //default ESP32 LOW is turn off

    Serial.begin(115200);
    setup_wifi();
    client.setServer(mqtt_server, 1883);
    client.setCallback(callback);
}

void loop()
{

    if (!client.connected())
    {
        reconnect();
    }
    client.loop();

    unsigned long now = millis();
    if (now - lastMsg > updateCycle)
    {
        lastMsg = now;
        float humidity = dht.readHumidity();
        float temperature = dht.readTemperature();
        // Check if any reads failed and exit early (to try again).
        if (isnan(humidity) || isnan(temperature))
        {
            Serial.println(F("Failed to read from DHT sensor!"));
            return;
        }else{ // publish the message
            snprintf(msg, MSG_BUFFER_SIZE, "%.1lf°", temperature);
            snprintf(msg1, MSG_BUFFER_SIZE,"%.0lf%%", humidity);
            Serial.print("Publish message: ");
            Serial.println(msg);
            client.publish(pub_temp_topic, msg);
            client.publish(pub_humd_topic, msg1);
            
        }

    }
}

;

2022/03/27

Arduino #32 用一塊ESP32來學 IOT (#32 Learn IOT with MQTT + ESP32)

大家好, 今天和大家來分享, Arduino #32 用一塊ESP32來學 IOT (#32 Learn IOT with MQTT + ESP32) 這個影片很適合初學者來觀看學習. 影片內容主要是告訴大家, 只要手上有一塊 ESP32 和一台電腦, 就可以開始學習 IOT 了 ! 看過這個影片, 你會了解學習 IOT 一點都不難喔! 甚至可以延伸作法, 利用 MQTTlens 透過雲端EMQX來做遠端的控制!



參考資料:

如果時間不夠的朋友, 也可以從以下的時間軸挑選想看的部份即可!

影片時間軸:

  • 00:00 開始
  • 00:29 什麼是 MQTT,它是如何運作的?
  • 01:30 你的第一個IOT專案!
  • 01:55 MQTT 程式:pubsubclient
  • 02:40 Arduino IDE: 設定Additional Boards Manager URL
  • 03:09 Arduino IDE 其它設定
  • 03:48 從我的部落格中下載程式並貼在Arduino IDE
  • 04:07 在程式中更改必要的設定
  • 07:27 從 Chrome 瀏覽器啟動 MQTTlens
  • 07:54 在 MQTTlens 新增 EMQX 連線
  • 09:54 訂閱 ESP32上的兩個主題
  • 11:19 從 MQTTlens 發布主題
  • 12:45 本次主要內容摘要

程式碼:


/*
 Basic ESP8266 MQTT example
 This sketch demonstrates the capabilities of the pubsub library in combination
 with the ESP8266 board/library.
 It connects to an MQTT server then:
  - publishes "hello world" to the topic "outTopic" every two seconds
  - subscribes to the topic "inTopic", printing out any messages
    it receives. NB - it assumes the received payloads are strings not binary
  - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
    else switch it off
 It will reconnect to the server if the connection is lost using a blocking
 reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
 achieve the same result without blocking the main loop.
 To install the ESP8266 board, (using Arduino 1.6.4+):
  - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
       http://arduino.esp8266.com/stable/package_esp8266com_index.json
  - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
  - Select your ESP8266 in "Tools -> Board"
*/

#include <WiFi.h>
#include <PubSubClient.h>
#include <EasyButton.h>
#define LED 2        //built-in LED on ESP32

// Update these with values suitable for your network.
const char *ssid = "WiFi-SSID";
const char *password = "WiFi-PASSWORD";

// Define your client ID on EMQX
String mqtt_ClientID = "stonez56_IOT_Station_";

// Define your topics to subscribe / publish
const char* sub_topic = "stonez56/esp32s";
const char* pub_led_topic = "stonez56/esp32s_led_state";
const char* pub_init_topic = "stonez56/esp32s_is_back";

// EMQX broker parameters
const char *mqtt_server = "broker.emqx.io";
const char *mqtt_userName = "emqx";
const char *mqtt_password = "public";

WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

void setup_wifi()
{
    delay(10);
    // We start by connecting to a WiFi network
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);

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

    randomSeed(micros());

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

void callback(char *topic, byte *payload, unsigned int length)
{
    Serial.print("Message arrived [");
    Serial.print(topic);
    Serial.print("] ");
    for (int i = 0; i < length; i++)
    {
        Serial.print((char)payload[i]);
    }
    Serial.println();

    payload[length] = '\0';
    String message = (char *)payload;
    
    if (strcmp(topic, sub_topic) == 0)
    {
        if (message == "off")
        {
            digitalWrite(LED, LOW); //Turn off
            client.publish(pub_led_topic, "off");
        }
        if (message == "on")
        {
            digitalWrite(LED, HIGH); //Turn on
            client.publish(pub_led_topic, "on");
        }
    }

    /* Switch on the LED if an 1 was received as first character
    // if ((char)payload[0] == '1')
    // {
    //     digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
    //                                     // but actually the LED is on; this is because
    //                                     // it is active low on the ESP-01)
    // }
    // else
    // {
    //     digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
    // } */
}

void reconnect()
{
    // Loop until we're reconnected
    while (!client.connected())
    {

        Serial.println("Attempting EMQX MQTT connection...");
        // Create a random client ID
        mqtt_ClientID += String(random(0xffff), HEX);
        // Attempt to connect
        if (client.connect((mqtt_ClientID, mqtt_userName, mqtt_password)))
        {
            Serial.print(" connected with Client ID: ");
            Serial.println(mqtt_ClientID);
            // Once connected, publish an announcement...
            client.publish(pub_init_topic, "Hi, I'm online!");
            // ... and resubscribe
            client.subscribe(sub_topic);
        }
        else
        {
            Serial.print("failed, rc=");
            Serial.print(client.state());
            Serial.println(" try again in 5 seconds");
            // Wait 5 seconds before retrying
            delay(5000);
        }
    }
}

void setup()
{
    pinMode(LED, OUTPUT); // Initialize the _LED pin as an output
    digitalWrite(LED, LOW); //default ESP32 LOW is turn off

    Serial.begin(115200);
    setup_wifi();
    client.setServer(mqtt_server, 1883);
    client.setCallback(callback);
}

void loop()
{

    if (!client.connected())
    {
        reconnect();
    }
    client.loop();

    /* unsigned long now = millis();
    // if (now - lastMsg > 2000)
    // {
    //     lastMsg = now;
    //     ++value;
    //     snprintf(msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
    //     Serial.print("Publish message: ");
    //     Serial.println(msg);
    //     client.publish("stonez56/esp32s_button_pushed", msg);
    // } */
}

2021/02/17

Arduino - No more SSID and password with Wifimanager



NOTICE: If you encountered problems in compiling the code, see this updated video.

ESP8226:  https://youtu.be/NLRuqjhArg8

ESP32-CAM: https://youtu.be/TTdMKW6HhXM​

Have you met this problem before? You were making an fantastic Arduino IoT project. However, in the code, Wi-Fi SSID and Password were hard-coded and the only way to change these is to edit the code and re-upload the code to Arduino. At home, this is okay, since you were experimenting things here and there anyway.

Let’s say you bring this project to a friend place or a venue to demo. And you didn’t know the Wi-Fi SSID nor the password beforehand. Then, you need to bring your computer to change SSID and password and re-upload to Arduino.  

Is there a way to get rid this problem? Yes. The answer is use Arduino Wifimanager library. 


Start

Open Arduino IDE. From Tools and select Manager Library
in space here type Wi-Fi Manager to search

Arduino  IDE will filter keywords with Wi-Fi manager. Scroll down until you find a Wi-Fi manager by author Zabu. The current version 0.14 just click and install.  Ok, install completed. Click close.




Upload "Auto Connect" sketch to NodeMCU

Next, let's get a Wi-Fi Manager code. example from Files-> Example, scroll down and find Wi-Fi manager. Let's open "Auto Connect" in a new window.


In the "Auto Connect" code., let's not make any change and upload this code directly to NODEMCU to understand how it worked.

Now, let me compile the code and upload this code to my NODEMCU Compiled sketch.


This will take a while depending on your computer configuration. You can see the progress bar is showing here it's uploading the flashing LED indicates the program is uploading. Let's wait until upload complete. Okay.


Set it up on your smartphone


Upload completed. Let's look at the Arduino  Serial port right now. It says: using last saved values, should be faster. Since this is a new NODEMCU and I haven't set anything to it in the program code. There's neither Wi-Fi SSID nor password setting. The "AutoConnectAP"  is AP name that you could define yourself.

Let's see the serial monitor NODEMCU now acts as Wi-Fi AP named AutoConnectAP and waiting for Wi-Fi client connection. As I said this NODEMCU is now in Wi-Fi AP mode with IP address 192.168.4.1 What I need to do now is to input this IP address in a browser either smartphone or a computer. Let me enter this IP address into my smartphone browser.


Type IP here 192.168.4.1
Remember to connect the phone to  NODEMCU Wi-Fi AutoConnectAP first.

Swipe down and click Wi-Fi symbol and then click AutoConnectAP from available Wi-Fi list.  It's connected to AutoConnectAP. 



The Wi-Fi manager AP page will show up on your smartphone now. 



On this page let's,  click configure Wi-Fi. Wi-Fi Manager will scan adjacent available Wi-Fi AP and show them here.  Let me click my home Wi-Fi AP named stonez24 and and type in Wi-Fi password. Password entered and click Save. 


it shows Credential saved.  Let's look here NODEMCU you will now connect tostonez24 AP automatically.



Ready to go!


Okay, connection result shows connected. Great!! We have connected NODEMCU to Stonez24 AP. In the future when you visit a new place or venue, there's no need to Hard-Code SSID or password in Arduino code let Wifimanager do the hard work for you!



That's all for today's tutorial. I hope you find this useful! 

The YouTube video is here:




2017/11/12

Getting Started with EPS8266-12E Wi-Fi | ESP8266-12E 筆記本



I wanted to test out ESP8266 for a long time. However, I never got it to work until today. There are many tutorials and articles detailed how to make ESP8266 work, but even I followed many of those tutorials step by step mine ESP8266 just didn't work.  It was very frustrating not able to figure out what went wrong.  Anyway, I got it worked today, so it's better for me to write the steps down, not just for blog visitor like you, but also for myself as a good reference later on.

Previous three failed attempts... 😒


Different Version of ESP8266

There are many ESP8266 variations, the one I used for this tutorial is ESP8266-12E. Please refer to this page[2] to get more information for ESP8266 variations.

ESP8266 Pin Assignment

Most of the people probably will solder ESP8266 with metal covers facing up, so I placed a reversed pin assignment on the right side for easier pin reference.

Material Needed:
  • ESP8266-12E * 1
  • Perfboard * 1 
  • Breadboard * 1 
  • Wires - as many as needed
  • Resistors 1K * 4 
  • CP2102 USB-Serial Converter * 1
Tools Needed:
  • Power supply (3.3V)
  • Soldering iron 
  • Solder Tin
  • Plier-wire cutter
  • Plier

Step One: 

ESP8266 has 2mm pin pitch instead of 2.54mm standard pitch. So we have to place it on a prefboard to make connections easier. 

Place ESP8266 on a prefboard and draw its relative size that's larger to accommodate pins along both sides for easier connections with DuPoint wires. Cut down the piece of prefboard with a plier. 

[Important: I later found out from the ESP8266 datasheet recommended to place Wi-Fi antenna outside of prefboard to get better signal reception & transmission.] 😄

Step Two:

Solder wires on each ESP8266 pin to the prefboard as shown below. I found out that after stripped skin of the wires, soldering job just got a little bit easier.

Note: My previous attempt was to solder wires without strip the wire skin and it was more difficult to solder; harder to bend the wires. Be careful, do not short these wires! :) 

Step Three:

Solder 8 pin headers on each side of ESP8266 as shown below.

Step Four: 

Time to connect all wires together. Check out the schematic diagram below for all the connections needed.

Schematic Diagram




ESP8266 Connection:

  1. VCC -> 3.3V power source
  2. EN-CHPD -> 1K resistor -> 3.3V
  3. Reset -> 1K resistor -> 3.3V
  4. TX -> USB/UART RX
  5. RX -> USB/UART TX
  6. GPIO0 -> do not connect anything for this AT command tutorial
  7. GPIO15 -> 1K resistor -> GND
  8. GND -> GND
CP2012 USB/UART Connection
  1. RX -> ESP8266 TX
  2. TX -> ESP8266 RX
  3. GND -> GND (command ground with ESP8266)
NOTE:
  • Supply 3.3V to EPS8266! 5V will burn ESP8266!
  • GPIO-0 is connected to GND: upload Arduino programming code. 
  • GPIO-0 is not connected: Enter AT Command.


Step Five:

Here, I used a red breadboard for wire connections with resistors and the power supply. As long as you follow the schematic diagram above and wiring tips for the connection, it shouldn't be too difficult. (I only use two transistors to share with common pins to VCC and GND.  Not sure if this is a good practice?)


I have purchased an inexpensive power supply as the 3.3V power source. It displayed the how much the current is using, in this case "068mA",  allowing me to see what power was consumed at the particular point of time, which it's very convenient!  I checked ESP8266 datasheet "68mA ~ 71mA" means it's working probably.


Step Six:

Test AT Command. I think this is a quick method to check whether the ESP8266 is working or not. 
  • Connect CP2012 to a Mac USB port
  • Power on power supply with 3.3V 

Arduino IDE Operations:

  • First, let's load ESP8266 Library into Arduino IDE
  • Copy this string "http://arduino.esp8266.com/stable/package_esp8266com_index.json" into Arduino IDE preference -> Settings -> Additional Board Manager URLs. See below in yellow highlighted strings.



  • Select correct Arduino board type. Select "ESPino (ESP-12 module)" If you don't see this option, please restart Arduino IDE to ensure the library is properly loaded.


  • Select Port from port list. My serial port is /dev/cu.SLAB_USBtoUART


    • Click [Tools] - [Serial Monitor] from Arduino IDE to open the serial monitor.
    • Select baud rate from the baud rate list below. Select [115200 baud].  Your ESP8266 might have default baud rate of 9600 or 38400. If 15200 doesn't work, please try all other baud rate values.

    Start AT Command

    • AT:  You should be able to see the terminal replied "AT   OK" back. Congratulation, your ESP8266 is working!

    • AT+GMR: Display ESP8266 firmware version. My ESP8266 is V1.2.0.0 Date: Dec 2, 2016.  
    • AT+CWJAP="Wi-Fi_SSID","Password": Connect to the particular Wi-Fi Access point with the password designated.  As you can see, the WiFi got connected immediately. 
          

    • AT+CWMODE?[1]: Setup ESP8266 working mode. Let's setup ESP8266 to mode 3 both STA and AP. This allows ESP8266 connecting to your Wi-Fi router/Access point as a client also works as a router/Access point allowing other Wi-Fi client connect to it.
      • AT+CWMODE=1: STA (Become a Wi-Fi client to connect to AP)
      • AT+CWMODE=2: AP (Become an Assess point, so other clients can connect to this AP)
      • AT+CWMODE=3: BOTH = STA + AP (As an access point and a Wi-Fi client)

    • AT+CIFSR: Get IP Address. Since we setup CWMODE=3 (STA+AP mode), the first IP you see is AP IP (ESP8266 IP 192.168.4.1), the second IP is the WAN IP(your Wi-Fi IP 192.168.0.105 where ESP8266 is connected to)


    • AT+CWLAP: Scan Wi-Fi AP in the nearby area and show them all in a list.
      Text in first double quotes are WI-Fi SSID.


      • AT+RST: Reset command to reset ESP8266



      It's great! Your ESP8266 is ready to connect to the Internet.

      Load First Arduino Code:

      ESP8266 can be used as an Arduino board itself without buying another Arduino board to work with ESP8266. Let's flash Arduino code into ESP8266 to test it out. 
      1. Connect GPIO0 -> 1K resistor -> GND (Without GPIOpull low, you can't flash code to ESP8266!
      2. Copy the code below into your Arduino IDE and upload the code and the ESP8266-12E
      *********************************************************************************
      IMPORTANT:  After you upload Arduino codes, the AT command will no longer work. If you still prefer use AT command with ESP8266, you have to reflash AT command firmware to enable it. 

      It took me few days to figure out this!
      ***
      ******************************************************************************

      First Arduino code for ESP8266-12E, Connect to Wifi

      This Arduino code below will connect ESP8266 to your WiFi AP/router and display the IP address it obtain.  For this code to work, please replace Wifi_SSID with your Wifi-SSID and Wifi_Password with your own Wifi-Password. Do not forget to open Arduino IDE serial port to see the connection message!

      #include <ESP8266WiFi.h>
      
      void setup()
      {
        Serial.begin(115200);
        Serial.println();
      
        WiFi.begin("Wifi_SSID", "Wifi_Password");
      
        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() {}
      
      

      Second Arduino code for ESP8266-12E, Blink

      #include <ESP8266WiFi.h>
      void setup()
      {
        Serial.begin(115200);
        Serial.println();
        pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
      
        WiFi.begin("Wifi-SSID", "Wifi-Password");
      
        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() {
        digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                          // but actually the LED is on; this is because 
                                          // it is acive low on the ESP-01)
        delay(1000);                      // Wait for a second
        digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
        delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
        }
      

      That's all for this step by stpe notes. Hope you are getting something from here! :)

      REFERENCE

      1. ESP8266 Wi-Fi Library Great info to get more about ESP8266 Wi-Fi Library as well as what's AP, STA, and BOTH modes.
      2. Various ESP8266 boards Great info to understand the different types of ESP8266.
      ==============================================================

        EPS8266-12E Wi-Fi 筆記

      真的很高興,這個部落格在這幾天已經超過30萬的瀏覽次數!謝謝大家拜訪Stonez56的部落格來獲取有對你價值的資訊。😁

      長久以來,我一直想測試ESP8266,但是一直沒有成功。雖然,網上有很多教學和文章詳細介紹如何使用ESP8266,但即使我跟著很多這些教學一步一步地做,大部份都失敗了。 很多時候無法弄清楚哪裡出了問題,真是令人非常沮喪。 今天我手上的ESP8266已經正常的能回覆 AT Command,所以我趕快把這些步驟寫下來,不只可以提各位讀者參考,以後也可以作為自己的一份筆記。

      看看我之前失敗的例子...都堆在角落裡!


      不同版本的 ESP8266

      市面上有很多不同的版本,請參考這裡[2] 來了解其它ESP8266版本的差異。


      ESP8266 腳位說明

      ESP8266腳位說明如下。 由於大多數人可能會把ESP8266的金屬蓋朝上焊接,所以我在右側放置了一個反向的腳位,以便於大家參考。

      所需材料:

      •      ESP8266-12E * 1
      •      洞洞板* 1
      •      麵包板* 1
      •      電線 - 十多條
      •      電阻器1K * 4
      •      CP2102 USB 轉換器 * 1

      所需工具:

      •      電源(3.3V)
      •      烙鐵
      •      焊錫
      •      鋼絲鉗
      •      鑷子

      步驟一:

      ESP8266 腳位是 2mm 的間距,而不是2.54mm的標準間距。 所以我們必須把它銲在洞洞板上以方便連接

      先將ESP8266放置在
      洞洞板上,並畫下其相對尺寸較大的尺寸,沿著兩側留下兩三個洞的距離,等會要銲上接腳,便於用杜邦線測試連接。 先用鉗子剪下畫好大小的洞洞板。

      [重要說明:我從ESP8266官方文件中發現,
      Wi-Fi天線不能放在金屬的上方,以便獲得更好的接收信號和處理能力!所以最後我把天線底下的洞洞板都用斜口鉗剪掉!]😄

      步驟二:

      如下所示,把每個ESP8266的腳位上用電線連接到洞洞板上。我發現電線剝皮後,比較容易焊一些。我看許多網友也都這樣做!

      注意:我以前的嘗試是焊接電線時沒有剝掉電線的外皮,焊接起來也比較困難; 也較不容易彎曲電線。 但是請小心,不要把這些電線短路! ☺

      步驟三:

      在ESP8266的兩側焊接上 8 個針腳,如下所示。

      步驟四:

      參考下面的示意圖,把所有電線接好準備測試。

      Schematic Diagram


      ESP8266連接方法:

      •      VCC - &gt; 3.3V 電源
      •      EN-CHPD - &gt; 1K 電阻 - &gt;3.3V
      •      重置 - &gt; 1K 電阻 - &gt;3.3V
      •      TX - &gt; USB / UART RX
      •      RX - &gt; USB / UART TX
      •      GPIO0 - &gt; 請先不要連接任何腳位,才能做 AT Command 測試
      •      GPIO15 - &gt; 1K 電阻 - &gt;GND
      •      GND - &gt;GND

      CP2012 USB / UART連接方法:

      •      RX - &gt; ESP8266 TX
      •      TX - &gt; ESP8266 RX
      •      GND - &gt; GND(ESP8266共同接地)

      注意:

      •      EPS8266只能使用 3.3V 電源! 使用5V會燒掉ESP8266!
      •      GPIO-0連接到GND:可上傳Arduino程式
      •      GPIO-0未連接:可輸入AT Command


      步驟五:

      如下圖,我用一個紅色小麵包板用來連接電阻和電源連接。 只要你按照上面的示意圖和接線提示連接即可。 (我只使用兩個 1K 電阻與VCC和GND共用腳位,不知道這是否是一個好的方法?)

      我買了一台電源供應器來提供3.3V穩定電源。它也可以顯示目前的電流量,如:“068mA”,讓我知道在特定的時間點,電流量是多少,非常方便! 我查了一下ESP8266的資料“68mA〜71mA”,表示它 Wi-Fi 是開啟中工作中。


      步驟六:

      測試AT命令。這是一個檢查ESP8266是否正常運作的快速方法。
      •      將 CP2012 連接到 Mac USB
      •      開啟3.3V電源

      Arduino IDE使用說明:

      •      先讓我們將ESP8266程式資料載入到Arduino IDE 中
      •      將此字串 “http://arduino.esp8266.com/stable/package_esp8266com_index.json” 複製到Arduino IDE Preference - &gt; Settings - &gt; Additional Board Manager URLs:  下方我用黃色標出的字符:



      • 一定要選擇正確的Arduino類型。 在選單中選擇“ESPino(ESP-12 Module)”如果您沒有看到此選項,請重新啟動一次Arduino IDE以確保ESP8266資料有帶進來。


      • 選擇 Port,我的 serial port 設定是 /dev/cu.SLAB_USBtoUART


        • 按一下 [Tools] -> [Serial Monitor] 打開序列埠的監看視窗。
        • 選擇連接速率 baud rate。 我用的是 [115200 baud].  您的ESP8266的內建速率可能是9600或38400.如果15200沒法使用,請嘗試所有其他的速率值。

        開使使用 AT Command:

        • 在最上方的命令列上打 AT,您應該能夠看到監看視窗回答“AT OK”。 恭喜,您的ESP8266已在正常工作中!

        • AT+GMR: 顯示 ESP8266 軔體版本. 我的 ESP8266 是 V1.2.0.0 Date: Dec 2, 2016.  
        • AT+CWJAP="Wi-Fi_SSID","Password": 使用指定的SSID 和 密碼 連接到特定的Wi-Fi分享器或路由器。 監看視窗會顯示,WiFi已連接成功!
              

        • AT+CWMODE?[1]: 設定ESP8266工作模式。讓我們將ESP8266設置為模式3 STA和AP。 這可以讓ESP8266作為客戶端連接到您的Wi-Fi路由器,ESP8266自己也可以作為路由器/,允許其他Wi-Fi客戶端連接到它。
          • AT+CWMODE=1: STA (Become a Wi-Fi client to connect to AP)
          • AT+CWMODE=2: AP (Become an Assess point, so other clients can connect to this AP)
          • AT+CWMODE=3: BOTH = STA + AP (As an access point and a Wi-Fi client)

        • AT+CIFSR: 顯示IP位址。 由於我們設置了CWMODE = 3(STA + AP模式),所以您看到的第一個IP是ESP8266自己的 IP(ESP8266 IP 192.168.4.1),第二個IP是連到Internet的路由器 IP(ESP8266 Wi-Fi IP 192.168.0.105)


        • AT+CWLAP: 掃描附近區域的Wi-Fi 路由器,並將其全部顯示在列表中。
          下方左側第一個雙引號中的文字是各路由器的 SSID。為了安全,我把 mac adress 畫掉了~


          • AT+RST: 重置 ESP8266,讓它重新開機!


          太好了! 您的ESP8266已準備好連接到Internet。

          載入第一個Arduino 程式到 ESP8266:

          其實ESP8266可以當作一般Arduino板來使用,它上面也有很多 I/O 腳位,不要再連另一塊 Arduino 來節省成本。 現在我們把Arduino的程式碼載入到ESP8266中進行測試。
          • 記得連接GPIO0 -&gt; 1K電阻器 - &gt; GND(GPIO0 要 pull low,不然,程式碼無法載入到ESP8266!
          • 將以下程式碼複製到您的Arduino IDE並載入到ESP8266-12E裡
          *********************************************************************************
          重要提示:在您上傳Arduino程碼後,AT命令將不能再使用。 如果您仍然想要使用ESP8266的AT命令,則必須上載AT command 的軔體才能再使用。
          ***
          ******************************************************************************

          第一個 ESP8266-12E 程式,連接到 WiFi AP :

          下面這個Arduino程式碼將啟動ESP8266連接到您的WiFi AP /路由器,並顯示它取得的IP地址。 要使用此程式碼,記得把您的Wifi密碼將Wifi_SSID替換為您的Wifi-SSID和Wifi_Password。

          #include <ESP8266WiFi.h>
          
          void setup()
          {
            Serial.begin(115200);
            Serial.println();
          
            WiFi.begin("Wifi_SSID", "Wifi_Password");
          
            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() 
          {}
          

          第二個 ESP8266-12E 程式,  閃爍 ESP8266 內建 LED

          #include <esp8266wifi.h>
          
          void setup()
          {
            Serial.begin(115200);
            Serial.println();
            pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
          
            WiFi.begin("Wifi-SSID", "Wifi-Password");
          
            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() {
            digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                              // but actually the LED is on; this is because 
                                              // it is acive low on the ESP-01)
            delay(1000);                      // Wait for a second
            digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
            delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
            }
          

          OK,希望你從這裡能得到你要的一些資訊!:)

          參考文件:

          1. ESP8266 Wi-Fi Library Great info to get more about ESP8266 Wi-Fi Library as well as what's AP, STA, and BOTH modes.
          2. Various ESP8266 boards Great info to understand the different types of ESP8266.