# Wio Terminal Wifi Tutorial ## Wio Terminal RTL8720DN WiFi Getting Started ### Overview This wiki introduce how to update the latest firmware for the Wireless Core Realtek RTL8720 on Wio Terminal, as well as installing all the dependent libraries for Wio Terminal to enable wireless connectivity. !!!Note **We are moving the Wi-Fi Software to the new eRPC Structure which is more stable and can work with the Bluetooth at the same time**! Please follow through to update to eRPC Wi-Fi firmware and related libraries! ### Update the Wireless Core Firmware First, we need to update the firmware for the Realtek RTL8720 Wireless core on Wio Terminal. **This is essential and must update to the latest firmware before proceeding to examples.** <div class="tips" style="display: table; table-layout: fixed; background-color: #F5A9A9; height: auto; width: 100%;"> <div class="left-icon" style="display: table-cell; vertical-align: middle; background-color: #DF0101; padding-top: 10px; box-sizing: border-box; height: auto; width: 38px; text-align: center;"><img style="width: 26px; vertical-align: middle;" src="https://s3-us-west-2.amazonaws.com/static.seeed.cc/seeed/icon/Danger.svg" alt="attention icon" /></div> <div class="right-desc" style="display: table-cell; vertical-align: middle; padding-left: 15px; box-sizing: border-box; width: calc(95% - 38px);"> <p style="color: #000000; font-weight: bold; margin-top: 10px;">Attention</p> <p style="color: #000000; font-size: 14px;">Please update the Wi-Fi Core before usage!</p> </div> </div> #### Step 1 - Arduino Configuration To be able to update the firmware on the RTL8720, we need to enable the Serial connection from SAMD51 to RTL8720. This is done by a simple Arduino Program. ##### `uf2` Method For convenience, we the provide `uf2` methods of uploading Wio Terminal's firmware. Simply download the `uf2` files from below. - Download the [**rtl8720_update_v2.uf2**](http://files.seeedstudio.com/wiki/Wio-Terminal/res/rtl8720_update_v2.uf2) `uf2` files. Entering the bootloader mode by **sliding the power switch twice quickly**. For more reference, please also see [here](https://wiki.seeedstudio.com/Wio-Terminal-Getting-Started/#faq). An external drive named `Arduino` should appear in your PC. Drag the the downloaded `rtl8720_update_v2.uf2` files into the `Arduino` drive and it will reset the Wio Terminal and loaded loaded the sketch! <div align=center><img src="https://files.seeedstudio.com/wiki/Circuitpython-XIAO/df2.png"/></div> You should see that **Burn RTL8720 fw** on the Wio Terminal's screen. This means that it is currently in the burning firmware mode! > You can also find the source code of the rtl8720_update_v2.uf2 [**here**](https://github.com/Seeed-Studio/Seeed_Arduino_Sketchbook/blob/master/examples/WioTerminal_USB2Serial_Burn8720/WioTerminal_USB2Serial_Burn8720.ino). #### Step 2 - Download the Latest Firmware **Note:** This is the latest **eRPC Structure Firmware** for RTL8720 - Download the latest [**RTL8720 Firmware**](https://github.com/Seeed-Studio/seeed-ambd-firmware/releases) Here. ### CLI Methods Now, you can flash the RTL8720 firmware to Wio Terminal using the **CLI methods**. Download the **CLI tools** as follows using **Terminal**: ```sh $ cd ~ $ git clone https://github.com/LynnL4/ambd_flash_tool ``` #### CLI Example Usage - For **macOS** and **LinuxOS**, please use the **`ambd_flash_tool.py`** script. - For **Windows OS**, please use the **`ambd_flash_tool.exe`** script. > Usage under **Window OS**: <div align=center><img src="https://files.seeedstudio.com/wiki/Wio-Terminal/img/win-new-tool.png"/></div> Let's take macOS as an example, which is the `ambd_flash_tool.py` script. - Open terminal and navigate to the file location. Run `python3 ambd_flash_tool.py` in the location and you should see the help usage: **NOTE**: Make you have **Python 3 installed on your PC (macOS and LinuxOS)**, and the script will auto-download all the dependent libraries. > In some cases, you may only have Python 3 on your PC, then replace `python3 ambd_flash_tool.py` with `python ambd_flash_tool.py`. <div align=center><img src="https://files.seeedstudio.com/wiki/Wio-Terminal/img/v2-1.png"/></div> - To erase the initial firmware inside the RTL8720, run: > It supports Auto-Detect Port function! ```sh $ python3 ambd_flash_tool.py erase ``` **NOTE:** The initial erase process may take a while. Please be patient and **do not** close windows. It should look something like this: <div align=center><img src="https://files.seeedstudio.com/wiki/Wio-Terminal/img/v2-2.png"/></div> - To flash the new downloaded firmware into the RTL8720, run: ```sh $ python3 ambd_flash_tool.py flash -d [RTL8720-firmware-path] ``` Replace `[RTL8720-firmware-path]` with the path you downloaded the RTL8720 from above. This location should contain `km0_boot_all.bin`, `km0_km4_image2.bin` and `km4_boot_all.bin` these 3 files. <div align=center><img src="https://files.seeedstudio.com/wiki/Wio-Terminal/img/v2-3.png"/></div> If everything goes well, you should see all a successful message. Now you have flashed the new RTL8720 firmware into the RTL8720 core! ### Libraries Installations (eRPC) There are few Arduino Libraries that are needed for the Wireless connectivity. Follow through to install all the libraries needed: #### 1. Install the Seeed_Arduino_rpcWiFi 1. Visit the [**Seeed_Arduino_rpcWiFi**](https://github.com/Seeed-Studio/Seeed_Arduino_rpcWiFi) repositories and download the entire repo to your local drive. 2. Now, the Seeed_Arduino_rpcWiFi library can be installed to the Arduino IDE. Open the Arduino IDE, and click `sketch` -> `Include Library` -> `Add .ZIP Library`, and choose the `Seeed_Arduino_rpcWiFi` file that you've have just downloaded. ![InstallLibrary](https://files.seeedstudio.com/wiki/Wio-Terminal/img/Xnip2019-11-21_15-50-13.jpg) #### 2. Install the Seeed_Arduino_rpcUnified 1. Visit the [**Seeed_Arduino_rpcUnified**](https://github.com/Seeed-Studio/Seeed_Arduino_rpcUnified) repositories and download the entire repo to your local drive. 2. Now, the Seeed-Arduino-FreeRTOS library can be installed to the Arduino IDE. Open the Arduino IDE, and click `sketch` -> `Include Library` -> `Add .ZIP Library`, and choose the `Seeed_Arduino_rpcUnified` file that you've have just downloaded. #### 3. Install the Seeed_Arduino_FreeRTOS 1. Visit the [**Seeed_Arduino_FreeRTOS**](https://github.com/Seeed-Studio/Seeed_Arduino_FreeRTOS) repositories and download the entire repo to your local drive. 2. Now, the Seeed-Arduino-FreeRTOS library can be installed to the Arduino IDE. Open the Arduino IDE, and click `sketch` -> `Include Library` -> `Add .ZIP Library`, and choose the `Seeed_Arduino_FreeRTOS` file that you've have just downloaded. ## Wio Terminal RTL8720DN WiFi User Manual ### Wi-Fi Connectivity This wiki introduces how to configure Wi-Fi connectivity on Wio Terminal using the Realtek RTL8720 core. !!!Note Make sure that you have followed through the Network overview, **updated the latest firmware on RTL8720 and downloaded the dependant Arduino libraries.** <div class="tips" style="display: table; table-layout: fixed; background-color: #f5cfa9; height: auto; width: 100%;"> <div class="left-icon" style="display: table-cell; vertical-align: middle; background-color: #eda964; padding-top: 10px; box-sizing: border-box; height: auto; width: 38px; text-align: center;"><img style="width: 26px; vertical-align: middle;" src="https://s3-us-west-2.amazonaws.com/static.seeed.cc/seeed/icon/Danger.svg" alt="attention icon" /></div> <div class="right-desc" style="display: table-cell; vertical-align: middle; padding-left: 15px; box-sizing: border-box; width: calc(95% - 38px);"> <p style="color: #000000; font-weight: bold; margin-top: 10px;">Attention</p> <p style="color: #000000; font-size: 14px;">The following examples have updated to work with <b>eRPC Structure Framework Firmware</b>, please update to eRPC structure. Simply replace the <code><b>AtWifi.h</b></code> with <code><b>rpcWiFi.h</b></code>.</p> </div> </div> ### Configuring as Station (STA) Mode - Include the `rpcWifi.h` library in Arduino. - Configure as STA mode: ```cpp WiFi.mode(WIFI_STA); ``` #### Scanning Wi-Fi Network Example Code This example will configure itself as Wi-Fi STA mode, scan and print out all the available networks to the Serial. ```cpp #include "rpcWiFi.h" void setup() { Serial.begin(115200); while(!Serial); // Wait for Serial to be ready delay(1000); // Set WiFi to station mode and disconnect from an AP if it was previously connected WiFi.mode(WIFI_STA); WiFi.disconnect(); delay(100); Serial.println("Setup done"); } void loop() { Serial.println("scan start"); // WiFi.scanNetworks will return the number of networks found int n = WiFi.scanNetworks(); Serial.println("scan done"); if (n == 0) { Serial.println("no networks found"); } else { Serial.print(n); Serial.println(" networks found"); for (int i = 0; i < n; ++i) { // Print SSID and RSSI for each network found Serial.print(i + 1); Serial.print(": "); Serial.print(WiFi.SSID(i)); Serial.print(" ("); Serial.print(WiFi.RSSI(i)); Serial.print(")"); Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? " " : "*"); delay(10); } } Serial.println(""); // Wait a bit before scanning again delay(5000); } ``` #### Connecting to Specified Network Example Code This example connects to a specified Wi-Fi Network. Change the `ssid` and `password` to your Wi-Fi network. ```cpp #include "rpcWiFi.h" const char* ssid = "yourNetworkName"; const char* password = "yourNetworkPassword"; void setup() { Serial.begin(115200); while(!Serial); // Wait for Serial to be ready // Set WiFi to station mode and disconnect from an AP if it was previously connected WiFi.mode(WIFI_STA); WiFi.disconnect(); Serial.println("Connecting to WiFi.."); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.println("Connecting to WiFi.."); WiFi.begin(ssid, password); } Serial.println("Connected to the WiFi network"); Serial.print("IP Address: "); Serial.println (WiFi.localIP()); // prints out the device's IP address } void loop() { } ``` #### WiFi Multi Example Code - Include the `rpcWiFi.h`and `WiFiMulti.h` libraries in Arduino. This example invoke the `WiFiMulti` class, you can use ```cpp wifiMulti.addAP("ssid", "password"); ``` to add several AP Wi-Fi to the list and `wifiMulti.run()` will try to connect to the best signaled Wi-Fi. **Note:** Change the `SSID` and `Password` according to your Wi-Fi. ```cpp #include "rpcWiFi.h" #include <WiFiMulti.h> WiFiMulti wifiMulti; void setup() { Serial.begin(115200); while(!Serial); // Wait for Serial to be ready delay(1000); wifiMulti.addAP("ssid_from_AP_1", "your_password_for_AP_1"); wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2"); wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3"); Serial.println("Connecting Wifi..."); if (wifiMulti.run() == WL_CONNECTED) { Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } } void loop() { if (wifiMulti.run() != WL_CONNECTED) { Serial.println("WiFi not connected!"); delay(1000); } } ``` #### Wi-Fi Client Example Code This example demonstrates Wio Terminal configures as STA mode, connects to a specific AP Wi-Fi and sends a HTTP GET request and receive a HTTP response from the web server on the same network. - Change the `ssid` and `password` to your Wi-Fi. - Change the `host` to the Web server IP address. To simply test the example, you can start a simple web server using Python on your PC: 1. Copy and save the following in your local drive, and name it `index.html`. ```html <html> <body> Hello World! </body> </html> ``` 2. In Powershell/Terminal, change directory to the path you just saved `index.html` and run the following code to start a simple Web server using Python: For Pyhton 3: ```py python3 -m http.server 80 ``` For Python 2: ```py python -m SimpleHTTPServer 80 ``` 3. Change the `host` to the IP address of this PC in the Arduino code. Also, change the `ssid` and `password` in Arduino code to the same Wi-Fi that is connected with this PC. 4. Upload the code to Wio Terminal, check Serial monitor to observe results. ```cpp #include <rpcWiFi.h> const char* ssid = "yourNetworkName"; const char* password = "yourNetworkPassword"; void setup() { Serial.begin(115200); while(!Serial); // Wait for Serial to be ready delay(1000); // Set WiFi to station mode and disconnect from an AP if it was previously connected WiFi.mode(WIFI_STA); WiFi.disconnect(); delay(2000); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.println("Connecting to WiFi.."); } Serial.println("Connected to the WiFi network"); Serial.print("IP Address: "); Serial.println (WiFi.localIP()); // prints out the device's IP address } void loop() { const uint16_t port = 80; // Default port const char* host = "192.168.0.10"; // Target Server IP Address Serial.print("Connecting to "); Serial.println(host); // Use WiFiClient class to create TCP connections WiFiClient client; if (!client.connect(host, port)) { Serial.println("Connection failed."); Serial.println("Waiting 5 seconds before retrying..."); delay(5000); return; } // This will send a request to the server //uncomment this line to send an arbitrary string to the server //client.print("Send this data to the server"); //uncomment this line to send a basic document request to the server client.print("GET /index.html HTTP/1.1\n\n"); // sending HTTP GET request int maxloops = 0; //wait for the server's reply to become available while (!client.available() && maxloops < 1000) { maxloops++; delay(1); //delay 1 msec } if (client.available() > 0) { //read back one line from the server String line = client.readString(); // Read from the server response // Proceed various line-endings line.replace("\r\n", "\n"); line.replace('\r', '\n'); line.replace("\n", "\r\n"); Serial.println(line); } else { Serial.println("client.available() timed out "); } Serial.println("Closing connection."); client.stop(); Serial.println("Waiting 5 seconds before restarting..."); delay(5000); } ``` #### Wi-Fi Https Connection Example Code This example demonstrates establishing Https connection using Wio Terminal. With this, you can connect to almost all website and obtain data for needs. - Change the `ssid` and `password` to your Wi-Fi. ```cpp #include <rpcWiFi.h> #include <WiFiClientSecure.h> const char* ssid = "yourNetworkName"; // your network SSID const char* password = "yourNetworkPassword"; // your network password const char* server = "www.example.com"; // Server URL const char* test_root_ca = \ "-----BEGIN CERTIFICATE-----\n" "MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n" "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" "d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n" "QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n" "MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n" "b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n" "9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n" "CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n" "nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n" "43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n" "T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n" "gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n" "BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n" "TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n" "DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n" "hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n" "06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n" "PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n" "YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n" "CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n" "-----END CERTIFICATE-----\n"; // You can use x.509 client certificates if you want //const char* test_client_key = ""; //to verify the client //const char* test_client_cert = ""; //to verify the client WiFiClientSecure client; void setup() { //Initialize serial and wait for port to open: Serial.begin(115200); while(!Serial); // Wait for Serial to be ready delay(1000); Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); WiFi.begin(ssid, password); // attempt to connect to Wifi network: while (WiFi.status() != WL_CONNECTED) { Serial.print("."); // wait 1 second for re-trying delay(1000); } Serial.print("Connected to "); Serial.println(ssid); client.setCACert(test_root_ca); //client.setCertificate(test_client_key); // for client verification //client.setPrivateKey(test_client_cert); // for client verification Serial.println("\nStarting connection to server..."); if (!client.connect(server, 443)) { Serial.println("Connection failed!"); } else { Serial.println("Connected to server!"); // Make a HTTP request: client.println("GET https://www.example.com HTTP/1.0"); client.println("Host: www.example.com"); client.println("Connection: close"); client.println(); while (client.connected()) { String line = client.readStringUntil('\n'); if (line == "\r") { Serial.println("headers received"); break; } } // if there are incoming bytes available // from the server, read them and print them: while (client.available()) { char c = client.read(); if (c == '\n') { Serial.write('\r'); } Serial.write(c); } client.stop(); } } void loop() { // do nothing } ``` ##### Obtaining Website's root CA To obtain the root CA for a website, you can run the following command in Terminal (Linux Bash Shell): ```sh openssl s_client -showcerts -verify 5 -connect www.example.com:443 < /dev/null ``` Replace **`www.example.com`** with desired website's root url. **For Windows**, you can use the **Windows Subsystem for Linux (WSL)** to run the same Linux command. **Note:** Make sure you have the dependencies installed: ```sh sudo apt update sudo apt install openssl ``` #### Connecting to MQTT Server Example Code This example demonstrates establishing MQTT connection using Wio Terminal with a MQTT Server. With this, you can use the Wio Terminal to subscribe and publish messages to the MQTT server. Here used a free MQTT Server: https://test.mosquitto.org/. - Download and Install the [**Arduino MQTT Library**](https://github.com/knolleary/pubsubclient) here. ```cpp #include "rpcWiFi.h" #include <PubSubClient.h> // Update these with values suitable for your network. const char *ssid = "yourNetworkName"; // your network SSID const char *password = "yourNetworkPassword"; // your network password const char *ID = "Wio-Terminal-Client"; // Name of our device, must be unique const char *TOPIC = "WioTerminal"; // Topic to subcribe to const char *subTopic = "inTopic"; // Topic to subcribe to const char *server = "test.mosquitto.org"; // Server URL WiFiClient wifiClient; PubSubClient client(wifiClient); 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(); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect if (client.connect(ID)) { Serial.println("connected"); // Once connected, publish an announcement... client.publish(TOPIC, "{\"message\": \"Wio Terminal is connected!\"}"); Serial.println("Published connection message successfully!"); // ... and resubscribe client.subscribe(subTopic); Serial.print("Subcribed to: "); Serial.println(subTopic); } 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() { Serial.begin(115200); while (!Serial) ; // Wait for Serial to be ready Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); WiFi.begin(ssid, password); // attempt to connect to Wifi network: while (WiFi.status() != WL_CONNECTED) { Serial.print("."); WiFi.begin(ssid, password); // wait 1 second for re-trying delay(1000); } Serial.print("Connected to "); Serial.println(ssid); delay(500); client.setServer(server, 1883); client.setCallback(callback); } void loop() { if (!client.connected()) { reconnect(); } client.loop(); } ``` #### Connecting to MQTTs Server Example Code <div align=center><video width="560" height="315" controls> <source src="https://files.seeedstudio.com/wiki/Wio-Terminal/img/mqtts.mp4" type="video/mp4"> </video></div> This example demonstrates establishing MQTTs connection using Wio Terminal. Here used a free MQTTs Server: https://test.mosquitto.org/ and sending accelerator data to a topic. - Download and Install the [**Arduino MQTT Library**](https://github.com/knolleary/pubsubclient) here. - Install the Accelerator Library for Wio Terminal following [**this wiki**](https://wiki.seeedstudio.com/Wio-Terminal-IMU-Overview/). - The Wio Terminal will publish accelerator to the `WioTerminal/IMU` topic and subscribe messages from the `inTopic` topic. ```cpp #include "rpcWiFi.h" #include <PubSubClient.h> #include <WiFiClientSecure.h> #include"LIS3DHTR.h" const char *ssid = "yourNetworkName"; // your network SSID const char *password = "yourNetworkPassword"; // your network password const char *ID = "Wio-Terminal-Client"; // Name of our device, must be unique const char *TOPIC = "WioTerminal/IMU"; // Topic to subcribe to const char *subTopic = "inTopic"; // Topic to subcribe to const char *server = "test.mosquitto.org"; // Server URL const char *test_root_ca = "-----BEGIN CERTIFICATE-----\n" "MIIEAzCCAuugAwIBAgIUBY1hlCGvdj4NhBXkZ/uLUZNILAwwDQYJKoZIhvcNAQEL\n" "BQAwgZAxCzAJBgNVBAYTAkdCMRcwFQYDVQQIDA5Vbml0ZWQgS2luZ2RvbTEOMAwG\n" "A1UEBwwFRGVyYnkxEjAQBgNVBAoMCU1vc3F1aXR0bzELMAkGA1UECwwCQ0ExFjAU\n" "BgNVBAMMDW1vc3F1aXR0by5vcmcxHzAdBgkqhkiG9w0BCQEWEHJvZ2VyQGF0Y2hv\n" "by5vcmcwHhcNMjAwNjA5MTEwNjM5WhcNMzAwNjA3MTEwNjM5WjCBkDELMAkGA1UE\n" "BhMCR0IxFzAVBgNVBAgMDlVuaXRlZCBLaW5nZG9tMQ4wDAYDVQQHDAVEZXJieTES\n" "MBAGA1UECgwJTW9zcXVpdHRvMQswCQYDVQQLDAJDQTEWMBQGA1UEAwwNbW9zcXVp\n" "dHRvLm9yZzEfMB0GCSqGSIb3DQEJARYQcm9nZXJAYXRjaG9vLm9yZzCCASIwDQYJ\n" "KoZIhvcNAQEBBQADggEPADCCAQoCggEBAME0HKmIzfTOwkKLT3THHe+ObdizamPg\n" "UZmD64Tf3zJdNeYGYn4CEXbyP6fy3tWc8S2boW6dzrH8SdFf9uo320GJA9B7U1FW\n" "Te3xda/Lm3JFfaHjkWw7jBwcauQZjpGINHapHRlpiCZsquAthOgxW9SgDgYlGzEA\n" "s06pkEFiMw+qDfLo/sxFKB6vQlFekMeCymjLCbNwPJyqyhFmPWwio/PDMruBTzPH\n" "3cioBnrJWKXc3OjXdLGFJOfj7pP0j/dr2LH72eSvv3PQQFl90CZPFhrCUcRHSSxo\n" "E6yjGOdnz7f6PveLIB574kQORwt8ePn0yidrTC1ictikED3nHYhMUOUCAwEAAaNT\n" "MFEwHQYDVR0OBBYEFPVV6xBUFPiGKDyo5V3+Hbh4N9YSMB8GA1UdIwQYMBaAFPVV\n" "6xBUFPiGKDyo5V3+Hbh4N9YSMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL\n" "BQADggEBAGa9kS21N70ThM6/Hj9D7mbVxKLBjVWe2TPsGfbl3rEDfZ+OKRZ2j6AC\n" "6r7jb4TZO3dzF2p6dgbrlU71Y/4K0TdzIjRj3cQ3KSm41JvUQ0hZ/c04iGDg/xWf\n" "+pp58nfPAYwuerruPNWmlStWAXf0UTqRtg4hQDWBuUFDJTuWuuBvEXudz74eh/wK\n" "sMwfu1HFvjy5Z0iMDU8PUDepjVolOCue9ashlS4EB5IECdSR2TItnAIiIwimx839\n" "LdUdRudafMu5T5Xma182OC0/u/xRlEm+tvKGGmfFcN0piqVl8OrSPBgIlb+1IKJE\n" "m/XriWr/Cq4h/JfB7NTsezVslgkBaoU=\n" "-----END CERTIFICATE-----\n"; long lastMsg = 0; LIS3DHTR<TwoWire> lis; WiFiClientSecure wifiClient; PubSubClient client(wifiClient); 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(); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect if (client.connect(ID)) { Serial.println("connected"); // Once connected, publish an announcement... client.publish(TOPIC, "{\"message\": \"Wio Terminal is connected!\"}"); Serial.println("Published connection message successfully!"); // ... and resubscribe client.subscribe(subTopic); Serial.print("Subcribed to: "); Serial.println(subTopic); } 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() { //Initialize serial and wait for port to open: Serial.begin(115200); while (!Serial) ; // Wait for Serial to be ready delay(1000); lis.begin(Wire1); if (!lis) { Serial.println("ERROR"); while(1); } lis.setOutputDataRate(LIS3DHTR_DATARATE_25HZ); //Data output rate lis.setFullScaleRange(LIS3DHTR_RANGE_2G); //Scale range set to 2g Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); WiFi.begin(ssid, password); // attempt to connect to Wifi network: while (WiFi.status() != WL_CONNECTED) { Serial.print("."); WiFi.begin(ssid, password); // wait 1 second for re-trying delay(1000); } Serial.print("Connected to "); Serial.println(ssid); wifiClient.setCACert(test_root_ca); client.setServer(server, 8883); client.setCallback(callback); } void loop() { if (!client.connected()) { reconnect(); } float x_values, y_values, z_values; // Sending Data long now = millis(); if (now - lastMsg > 5000) { lastMsg = now; x_values = lis.getAccelerationX(); y_values = lis.getAccelerationY(); z_values = lis.getAccelerationZ(); String data="{\"x-axis\": "+String(x_values)+","+"\"y-axis\": "+String(y_values)+","+"\"z-axis\": "+String(z_values)+"}"; if (!client.publish(TOPIC, data.c_str())) { Serial.println("Message failed to send."); } Serial.printf("Message Send [%s] ", TOPIC); Serial.println(data); } client.loop(); } ``` #### UDP Client Example Code <div align=center><img src="https://files.seeedstudio.com/wiki/Wio-Terminal/img/udp-example.png"/></div> This example connects to a Wi-Fi and sends UDP packets to a UDP Server that's running on your PC. **Note:** Make sure that your PC and Wio Terminal are in the same network! ##### Python UDP Server Code - Save the following code as `udp_server.py`. - Run the python script : **`python udp_server.py`**. ```py # This python script listens on UDP port 3333 # for messages from the Wio Terminal board and prints them import socket import sys try : s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except socket.error, msg : print 'Failed to create socket. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() try: s.bind(('', 3333)) except socket.error , msg: print 'Bind failed. Error: ' + str(msg[0]) + ': ' + msg[1] sys.exit() print 'Server listening' while 1: d = s.recvfrom(1024) data = d[0] if not data: break print data.strip() s.close() ``` ##### Arduino Code - Change the `networkName` and `networkPswd` to your Wi-Fi settings. - Change the `udpAddress` to your PC's IP address and make sure your PC that's running the UDP Server is at the same network as Wio Terminal. - Upload the code to Wio Terminal. ```cpp #include <rpcWiFi.h> #include <WiFiUdp.h> // WiFi network name and password: const char * networkName = "your-ssid"; const char * networkPswd = "your-password"; //IP address to send UDP data to: // either use the ip address of the server or // a network broadcast address const char * udpAddress = "192.168.0.255"; const int udpPort = 3333; //Are we currently connected? boolean connected = false; //The udp library class WiFiUDP udp; void setup(){ // Initilize hardware serial: Serial.begin(115200); //Connect to the WiFi network connectToWiFi(networkName, networkPswd); } void loop(){ //only send data when connected if(connected){ //Send a packet udp.beginPacket(udpAddress,udpPort); udp.printf("Seconds since boot: %lu", millis()/1000); udp.endPacket(); } //Wait for 1 second delay(1000); } void connectToWiFi(const char * ssid, const char * pwd){ Serial.println("Connecting to WiFi network: " + String(ssid)); // delete old config WiFi.disconnect(true); //register event handler WiFi.onEvent(WiFiEvent); //Initiate connection WiFi.begin(ssid, pwd); Serial.println("Waiting for WIFI connection..."); } //wifi event handler void WiFiEvent(WiFiEvent_t event){ switch(event) { case SYSTEM_EVENT_STA_GOT_IP: //When connected set Serial.print("WiFi connected! IP address: "); Serial.println(WiFi.localIP()); //initializes the UDP state //This initializes the transfer buffer udp.begin(WiFi.localIP(),udpPort); connected = true; break; case SYSTEM_EVENT_STA_DISCONNECTED: Serial.println("WiFi lost connection"); connected = false; break; default: break; } } ``` ### Configuring Wi-Fi as Access Point (AP) Mode / Web Server - Include `rpcWiFi.h`, `WiFiClient.h` and `WifiAP.h` libraries in Arduino. - Configure AP Wi-Fi `ssid` and `password`. - Initialize Wi-Fi Server on port 80: ```cpp WiFiServer server(80); ``` - Initialize AP with the `ssid` and `password`: ```cpp WiFi.softAP(ssid, password); ``` - Start the Web Server: ```cpp server.begin(); ``` #### Configure as AP Mode (Simple Web Server) Example Code This example configures Wio Terminal as a simple web server and allows you to connect to its AP network and control the hardware based on the response on the HTTP. ```cpp /* WiFiAccessPoint.ino creates a WiFi access point and provides a web server on it. Steps: 1. Connect to the access point "yourAp" 2. Point your web browser to http://<This-AP-IP>/H to turn the LED on or http://<This-AP-IP>/L to turn it off (<This-AP-IP> should be replaced with the IP got in terminal/SerialPort, see Note 1) OR Run raw TCP "GET /H" and "GET /L" on PuTTY terminal with IP address (see Note 1) and 80 as port Created for arduino-esp32 on 04 July, 2018 by Elochukwu Ifediora (fedy0) */ #include <rpcWiFi.h> #include <WiFiClient.h> #include <WiFiAP.h> #define LED_BUILTIN 2 // Set the GPIO pin where you connected your test LED // or comment this line out if your dev board has a built-in LED // Set these to your desired credentials. const char* ssid = "yourAP"; const char* password = "yourPassword"; WiFiServer server(80); void setup() { pinMode(LED_BUILTIN, OUTPUT); Serial.begin(115200); while(!Serial); // Wait for Serial to be ready delay(1000); Serial.println(); Serial.println("Configuring access point..."); // You can remove the password parameter if you want the AP to be open. WiFi.softAP(ssid, password); IPAddress myIP = WiFi.softAPIP(); /* * Note 1 * Record this IP, will used by Client (such as Web Browser) */ Serial.print("AP IP address: "); Serial.println(myIP); server.begin(); Serial.println("Server started"); } void loop() { WiFiClient client = server.available(); // listen for incoming clients if (client) { // if you get a client, Serial.println("New Client."); // print a message out the serial port String currentLine = ""; // make a String to hold incoming data from the client while (client.connected()) { // loop while the client's connected if (client.available()) { // if there's bytes to read from the client, char c = client.read(); // read a byte, then Serial.write(c); // print it out the serial monitor if (c == '\n') { // if the byte is a newline character // if the current line is blank, you got two newline characters in a row. // that's the end of the client HTTP request, so send a response: if (currentLine.length() == 0) { // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) // and a content-type so the client knows what's coming, then a blank line: client.println("HTTP/1.1 200 OK"); client.println("Content-type:text/html"); client.println(); // the content of the HTTP response follows the header: client.print("Click <a href=\"/H\">here</a> to turn ON the LED.<br>"); client.print("Click <a href=\"/L\">here</a> to turn OFF the LED.<br>"); // The HTTP response ends with another blank line: client.println(); // break out of the while loop: break; } else { // if you got a newline, then clear currentLine: currentLine = ""; } } else if (c != '\r') { // if you got anything else but a carriage return character, currentLine += c; // add it to the end of the currentLine } // Check to see if the client request was "GET /H" or "GET /L": if (currentLine.endsWith("GET /H")) { digitalWrite(LED_BUILTIN, HIGH); // GET /H turns the LED on } if (currentLine.endsWith("GET /L")) { digitalWrite(LED_BUILTIN, LOW); // GET /L turns the LED off } } } // close the connection: client.stop(); Serial.println("Client Disconnected."); } } ``` ## Connecting Wio Terminal to Blynk <div align=center><img src="https://files.seeedstudio.com/wiki/Wio-Terminal-Blynk/banner.gif"/></div> This wiki introduces how to use the Wio Terminal with the [**Blynk**](https://blynk.io/) software to interact with Wi-Fi or Bluetooth. This allows you to use Wio Terminal as the core of an IoT device and able to control hardware from phones very easily! - **What is Blynk** [**Blynk**](https://blynk.io/) is a new platform that allows you to quickly build interfaces for controlling and monitoring your hardware projects from your iOS and Android device. After downloading the Blynk app, you can create a project dashboard and arrange buttons, sliders, graphs, and other widgets onto the screen ### Hardware Required - [**Wio Terminal**](https://www.seeedstudio.com/Wio-Terminal-p-4509.html) - Mobile Phone - Download Blynk App from App Store ### Installing the blynk-library 1. Visit the [blynk-library](https://github.com/ansonhe97/blynk-library) repositories and download the entire repo to your local drive. 2. Now, the library can be installed to the Arduino IDE. Open the Arduino IDE, and click `sketch` -> `Include Library` -> `Add .ZIP Library`, and choose the `blynk-library` file that you've have just downloaded. ![InstallLibrary](https://files.seeedstudio.com/wiki/Wio-Terminal/img/Xnip2019-11-21_15-50-13.jpg) #### Wi-Fi Dependencies For now, the Wi-Fi and Bluetooth are **two separate firmware** for Wio Terminal and **therefore they CANNOT be used at the same time**. >Note: The new firmware of Wi-Fi and Bluetooth working together is under development and will be released very soon. - Please follow the **[Wi-Fi Overview Wiki](https://wiki.seeedstudio.com/Wio-Terminal-Network-Overview/)** to upload the Wi-Fi firmware to Wio Terminal. - Please also **download and install all the dependent Wi-Fi Libraries**. #### Bluetooth Dependencies - Please follow the [**Bluetooth Overview Wiki**](https://wiki.seeedstudio.com/Wio-Terminal-Bluetooth-Overview/) to upload the Bluetooth firmware to Wio Terminal. - Please also **download and install all the dependent Bluetooth Libraries**. ### Blynk Mobile App Set-up Once you have downloaded the Blynk App. - Open the App. - Click on the **New Project**: <div align=center><img width = 300 src="https://files.seeedstudio.com/wiki/Wio-Terminal-Blynk/1.jpg"/></div> - Fill in your **Project Name**, choose **Arduino UNO** as device, and select **WiFi** or **Bluetooth** as your Connection Type. Then click on Create Project: <div align=center><img width = 300 src="https://files.seeedstudio.com/wiki/Wio-Terminal-Blynk/1.1.png"/></div> - Now, you will **have a token sent to the email you registered with Blynk**. This is needed in the Arduino Sketches later. <div align=center><img width = 300 src="https://files.seeedstudio.com/wiki/Wio-Terminal-Blynk/3.png"/></div> ### Wi-Fi Examples These examples are using Wi-Fi to communicate between Wio Terminal and the Blynk App: #### Simple Wi-Fi Connection This example simply connects to a specific Wi-Fi then connects to the Blynk Server: - Replace the **token** that sent to your emails to `auth`. - Replace your network's `SSID` and `Password`. - Upload the sketch to Wio Terminal. ```cpp #define BLYNK_PRINT Serial #include <rpcWiFi.h> #include <WiFiClient.h> #include <BlynkSimpleWioTerminal.h> // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "YourToken"; // Your WiFi credentials. // Set password to "" for open networks. char ssid[] = "SSID"; char pass[] = "Password"; void setup() { // Debug console Serial.begin(9600); Blynk.begin(auth, ssid, pass); } void loop() { Blynk.run(); } ``` Once uploaded, open the Blynk app from your phone and click the top right `play` button to go live. You should be able to see that it is connected! <div align=center><img src="https://files.seeedstudio.com/wiki/Wio-Terminal-Blynk/wifi.png"/></div> <div align=center><img width = 300 src="https://files.seeedstudio.com/wiki/Wio-Terminal-Blynk/4.png"/></div> ### Sending Temperature to Blynk This example is an demonstrations of sending data from Wio Terminal to the Blynk server of which can then be viewed on the mobile app. - Replace WiFi credentials and token. - Temperature data are sent to **Virtual Pin 0** (`V0`). - Upload to Wio Terminal. !!!Note In this example, temperature values are randomly generated. ```cpp #define BLYNK_PRINT Serial #include <rpcWiFi.h> #include <WiFiClient.h> #include <BlynkSimpleWioTerminal.h> // Your WiFi credentials. const char* ssid = "SSID"; const char* pass = "Password"; // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "YourToken"; BlynkTimer timer; void sendTemperature() { // Generate random temperature value 10.0 to 30.0 (for example) float t = float(random(100, 300)) / 10; // Format: 1 decimal place, add ℃ String str = String(t, 1) + "℃"; // Send it to the server Blynk.virtualWrite(V0, str); } void setup() { // Debug console Serial.begin(9600); Blynk.begin(auth, ssid, pass); timer.setInterval(1000L, sendTemperature); } void loop() { Blynk.run(); timer.run(); } ``` Now open the Blynk App from your mobile phones again. - Swipe left to get the Widget Box out and select **Value Display**: <div align=center><img width = 300 src="https://files.seeedstudio.com/wiki/Wio-Terminal-Blynk/step-1.png"/></div> - Click on the button and configure the button to assign to **Virtual Pin 0**: <div align=center><img width = 300 src="https://files.seeedstudio.com/wiki/Wio-Terminal-Blynk/step-3.png"/></div> - Save the configurations and click top right play button to go live! And you can see the temperature values on your phone. <div align=center><img width = 300 src="https://files.seeedstudio.com/wiki/Wio-Terminal-Blynk/step-4.png"/></div> Here is the link for [**<font color=red>Wio Terminal Getting Started</font>**](https://hackmd.io/@amebaiot/SyeByHzYD). Here is the link for [**<font color=red>Wio Terminal Bluetooth Tutorial</font>**](https://hackmd.io/@amebaiot/H1uRHufYv).