Jump to content
Electronics-Lab.com Community

Search the Community

Showing results for tags 'iot'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Electronics Forums
    • Projects Q/A
    • Datasheet/Parts requests
    • Electronic Projects Design/Ideas
    • Power Electronics
    • Service Manuals
    • Theory articles
    • Electronics chit chat
    • Microelectronics
    • Electronic Resources
  • Related to Electronics
    • Spice Simulation - PCB design
    • Inventive/New Ideas
    • Mechanical constructions/Hardware
    • Sell/Buy electronics - Job offer/requests
    • Components trade
    • High Voltage Stuff
    • Electronic Gadgets
  • General
    • Announcements
    • Feedback/Comments
    • General
  • Salvage Area

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


Website URL


Yahoo


Skype


Location


Interests

  1. What is MQTT? MQTT stands for Message-Queue-Telemetry-Transport, is a publish/subscribe protocol for machine-to-machine communication. This simple protocol, is easy to implement for any client. Termed as the Pub and Sub, both are used for same purpose but with different methods. Get PCBs for Your Projects Manufactured You must check out PCBWAY for ordering PCBs online for cheap! You get 10 good-quality PCBs manufactured and shipped to your doorstep for cheap. You will also get a discount on shipping on your first order. Upload your Gerber files onto PCBWAY to get them manufactured with good quality and quick turnaround time. PCBWay now could provide a complete product solution, from design to enclosure production. Check out their online Gerber viewer function. With reward points, you can get free stuff from their gift shop. Getting Started Here, there are 2 sections - Publish and Subscribe. And then there is a middleman - Broker. Let us see in depth IoT Devices play the role to collect sensor data and send to the cloud (broker). While PC/Server/Mobile devices play the role to monitor and receive the sensor data to be viewed - Here, IoT Device is a Publisher, and PC Devices are Subscriber. According to the above analogy, the image that is published is the data, that was transferred from user1 to user2 📤. And that is the exact scenario in an MQTT Pub/Sub model. We have a more secure layer 🔒 to make sure the data is shared through a specific path, we call that 'topic', When user1 publishes data on topic, the subscriber automatically receives if already connected to the broker. Hence, the LOW latency. MQTT Broker Whenever there is a pub-sub model used as a message communication protocol, we require a broker that can transfer the information in the required device. This can be done by sending the message under correct topic. Let us understand this - A Broker is a runtime server (continuously running service), which can have 2 types of clients - Publisher (seller) & Subscriber (buyer) For instance, when a seller sells a product through a broker to a buyer, then it is using the Broker's service to reach & find a secured buyer. Similarly, when publisher publishes a piece of information, the data reaches to the subscriber through the Broker. The broker is responsible for having specific storage space where it can expect data from the publisher to store temporarily and then send to the subscriber. In the pub-sub MQTT, clients talk to each other through an MQTT broker. There are many MQTT Brokers in the market. It is even possible to create our own broker, or use an open-source broker 'paho'. For the current project, we shall first understand the mechanism and then watch a trial movement of data on Mosquitto MQTT Broker. Mosquitto Platform Now that we understand how MQTT works, let us use a cloud MQTT service and send data across the internet. In this article, we'll be using Mosquitto MQTT - test.mosquitto.org Under the Server section, we can see different ports provide feature-separated servers. These servers act like channels for sharing data over the cloud. Let us understand it first - MQTT Broker Port (default: 1883): This is the standard port used for MQTT communication. MQTT clients use I to connect to the Mosquitto broker and publish/subscribe to topics. It operates over TCP. MQTT Broker SSL/TLS Port (default: 8883): This is the secure version of the MQTT broker port. It uses SSL/TLS encryption to provide secure communication between MQTT clients and the Mosquitto broker. Clients connect to this port to establish a secure connection. WebSocket Port (default: 9001): Mosquitto also supports MQTT over WebSockets, allowing MQTT clients to connect to the broker using the WebSocket protocol. The WebSocket port is used for WebSocket-based MQTT communication. WebSocket SSL/TLS Port (default: 9443): This is the secure WebSocket port used for encrypted WebSocket-based MQTT communication. It provides a secure connection using SSL/TLS encryption. We shall be using 1883 port to send data and monitor. As we know, MQTT has 3 services - Publisher, Broker, and Subscriber. In this case, mosquito MQTT Cloud is already playing the role of a broker. Now, we'd be using ESP32 Dev Board, which has a wifi chip and is able to connect to the Internet, playing the role of a Publisher for sharing its temperature and humidity data from the sensor. On the other hand, we shall use the PC to view this data as a Subscriber. This will enable us to fully understand the working principle of the MQTT protocol used in IoT Communication between devices. Publisher (ESP32) To set up the ESP32 for MQTT, we need to install a library - PubSubClient. This library has functions that use variables as mentioned below to send data to the broker. mqtt_server: This variable represents the address or IP of the MQTT broker. We shall be using "test.mosquitto.org" mqtt_port: This variable represents the port number of the MQTT broker. In our case 1883. mqtt_topic: This variable represents the topic to which the publisher will send messages. For Example "schoolofiot/device1". Where 'schoolofiot' is the general-most topic level. And 'device1' is a sub-level. The provided code is an Arduino sketch that uses the ESP32 WiFi module and the PubSubClient library to connect to an MQTT broker and publish temperature and humidity data. Let's break down the code step by step: 1. Include necessary libraries: #include <WiFi.h> #include <PubSubClient.h> This code includes the required libraries for the ESP32 WiFi module and the MQTT client functionality. 2. Define WiFi & MQTT Server variables: const char* ssid = "XXXXXXXXXX"; const char* password = "XXXXXXXXXX"; const char* mqtt_server = "test.mosquitto.org"; These variables store the SSID (network name) and password for the WiFi network you want to connect to. The mqtt_server variable holds the IP address or hostname of the MQTT broker. 3. Declare global variables and objects: WiFiClient espClient; PubSubClient client(espClient); long lastMsg = 0; char msg[50]; int value = 0; float temperature = 0; float humidity = 0; Here, a WiFi client object (espClient) and an MQTT client object (client) are declared. The lastMsg variable stores the timestamp of the last message, and the msg is a character array for message storage. The value, temperature, and humidity variables are used to hold the respective sensor values. 4. Setup function: void setup() { Serial.begin(115200); setup_wifi(); client.setServer(mqtt_server, 1883); client.setCallback(callback); } The setup() function is called once at the start of the program. It initializes the serial communication, sets up the WiFi connection, configures the MQTT server and port, and sets the callback function to handle incoming messages. 5. WiFi setup function: void setup_wifi() { //... } The setup_wifi() function handles the connection to the WiFi network using the provided SSID and password. It waits until the connection is established and prints the local IP address to the serial monitor. 6. MQTT callback function: void callback(char* topic, byte* message, unsigned int length) { //... } This function is called when a message is received from the MQTT broker. It prints the received message along with the corresponding topic. 7. MQTT reconnection function: void reconnect() { //... } The reconnect() function is responsible for reconnecting to the MQTT broker if the connection is lost. It attempts to connect to the broker using a randomly generated client ID. If the connection is successful, it prints a success message. Otherwise, it waits for 5 seconds before retrying. 8. Main loop: void loop() { if (!client.connected()) { reconnect(); } client.loop(); long now = millis(); if (now - lastMsg > 2000) { lastMsg = now; sendData(); } } The loop() function is the main program loop that runs continuously after the setup() function. It checks if the MQTT client is connected and, if not, attempts to reconnect. It also calls the client.loop() function to maintain the MQTT client's internal state. Every 2 seconds, it calls the sendData() function to publish temperature and humidity data. 9. Publish sensor data function: void sendData() { //... } The sendData() function is responsible for publishing temperature and humidity data to specific MQTT topics. It generates random values for temperature and humidity, converts them to strings, and publishes them along with the corresponding topic. - Publish a gap message: client.publish("schoolofiot/gap", "--------------"); This line publishes a message consisting of a series of dashes (--------------) to the MQTT topic "schoolofiot/gap". It is used to indicate a separation or gap between different sets of data. - Read and publish temperature data: temperature = random(30, 40); char tempString[8]; dtostrf(temperature, 1, 2, tempString); Serial.print("Temperature: "); Serial.println(tempString); String tempdata = "Temperature: " + String(tempString); client.publish("schoolofiot/temperature", tempdata.c_str()); These lines generate a random temperature value between 30 and 40 degrees, store it in the temperature variable, and usedtostrf() function to convert decimal point data to String. The temperature value is then printed to the serial monitor and concatenated with the string "Temperature: ". The resulting string is stored in the tempdata variable. Finally, the tempdata string is published to the MQTT topic schoolofiot/temperature using the client.publish() function. - Read and publish humidity data: humidity = random(60, 70); char humString[8]; dtostrf(humidity, 1, 2, humString); Serial.print("Humidity: "); Serial.println(humString); String humdata = "Humidity: " + String(humString); client.publish("schoolofiot/humidity", humdata.c_str()); These lines generate a random humidity value between 60 and 70 percent, store it in the humidity variable. Overall, the sendData() function generates random temperature and humidity values, converts them to strings, and publishes them to specific MQTT topics for further processing or monitoring. Final Code can be found in the Code section But to confirm this, we also need to read the data from other the side - Subscriber. Subscriber (Windows PC) To set up the Subscriber on PC, we need to install Mosquitto MQTT Applcation. This application can create a broker, publisher & subscriber - all sections To install Mosquitto MQTT on your PC from the official website and make changes to the configuration file for listener 1883 and allow anonymous connections, you can follow these steps: 1. Download andInstall Mosquitto: Go to the official Mosquitto website (https://mosquitto.org/). Navigate to the "Downloads" section. Choose the appropriate installer for your operating system (Windows x64 in this case) and download it Install the application in desired location. 2. Edit Configuration File: Open the installation directory where Mosquitto is installed. Locate the mosquitto.conf file (usually found in the main directory). Open mosquitto.conf in a text editor of your choice.Add the below 2 lines - listener 1883 allow_anonymous true It should look somewhat like this - We can uncomment ad make changes in the file as well, but adding only 2 lines on the top is more simple and noticeable. 3. Run Mosquitto Subscriber We can run the Mosquitto broker and then subscribe to the topic we desire. But running directly the subscriber is best in our case. Open the folder/directory where the mosquitto.exe along with mosquitto_sub.exe is present. Run the PowerShell/CMD terminal from within the directory. For windows, open the directory > Press shift + right-mouse-button(right-click), and we'd see options for running a terminal like powershell. On the terminal, enter below command - > .\mosquitto_sub -h test.mosquitto.org -t "schoolofiot/#" In the above command, if you noticed, I did not subscribe to a specific topic. As per the topics we published (from ESP32), like "schoolofiot/gap", "schoolofiot/temperature" or "schoolofiot/humidity". The reason is, gap, temperature & humidity comes under the general topic of schoolofiot level. So, to access/view any data published as a sub-level of schoolofiot, we can use '#'. Apart from this, in case we need to subscribe to a specific topic (like temperature), we can use command like this - > .\mosquitto_sub -h test.mosquitto.org -t "schoolofiot/temperature" Therefore, no matter what name is put under the general topic, we can subscribe to it and view all of them together. Hurray! 🎉 We have learned another IoT Platform - Mosquitto MQTT (By Eclipse) Code #include <WiFi.h> #include <PubSubClient.h> // Replace the next variables with your SSID/Password combination const char* ssid = "XXXXXXXXXX"; const char* password = "XXXXXXXXXX"; // Add your MQTT Broker IP address, example: const char* mqtt_server = "test.mosquitto.org"; WiFiClient espClient; PubSubClient client(espClient); long lastMsg = 0; char msg[50]; int value = 0; float temperature = 0; float humidity = 0; void setup() { Serial.begin(115200); // default settings setup_wifi(); client.setServer(mqtt_server, 1883); client.setCallback(callback); } void setup_wifi() { delay(10); // We start by connecting to a WiFi network Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void callback(char* topic, byte* message, unsigned int length) { Serial.print("Message arrived on topic: "); Serial.print(topic); Serial.print(". Message: "); String messageTemp; for (int i = 0; i < length; i++) { Serial.print((char)message[i]); messageTemp += (char)message[i]; } Serial.println(); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect String clientId = "client-" + random(100, 999); if (client.connect(clientId.c_str())) { Serial.println("connected"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } void loop() { if (!client.connected()) { reconnect(); } client.loop(); long now = millis(); if (now - lastMsg > 2000) { lastMsg = now; Serial.println(client.connected()); sendData(); } } void sendData(){ Serial.println(); client.publish("schoolofiot/gap", "--------------"); //Read Temperature temperature = random(30,40); char tempString[8]; dtostrf(temperature, 1, 2, tempString); Serial.print("Temperature: "); Serial.println(tempString); String tempdata = "Temperature: " + String(tempString); client.publish("schoolofiot/temperature", tempdata.c_str()); //Read Humidity humidity = random(60,70); char humString[8]; dtostrf(humidity, 1, 2, humString); Serial.print("Humidity: "); Serial.println(humString); String humdata = "Humidity: " + String(humString); client.publish("schoolofiot/humidity", humdata.c_str()); }
  2. Do you want to always keep track with the time of place of your interest without having to google it? Then this project is what you are looking for! This LCD Real-Time Network Clock make use of Network Time Protocol (NTP) together with a WiFi-enabled IOT microcontroller--Realtek Ameba 1 (RTL8195AM/ RTL8710AF) to create the product that you need. All you need to do is to let the microcontroller know which area's time that you would like to see and key in your WiFi SSID and password and that's it ! No matter how many time the power is off, or you have moved, as soon as it's powered back on and connected to the network, it will tell you the rigth time instantaneously! And of course, if you are arduino-savvy, you can program this product to read out the time or even control the lightings in your room accroding to the time bocause the soc used in the microcontroller is so powerful that it's able to connect more than dozens of devices and run multiple tasks simultaneously. For DIY upgrading this project, you may refer to www.amebaiot.com for more information.
  3. One of the most useful IoT applications is home security. Imagine a thief cutting your security camera wire while trying to break into your house. This won’t happen if your security system goes wireless and smart. This project demonstrates the capability of Realtek Ameba dev. board to conduct board-to-board communication via MQTT (FREE MQTT broker hosted at cloud.amebaiot.com). With this home security system, you will definitely be alarmed when your window/door is opened by the self-invited as the buzzer will make loud irritating noise while red LED flashes continuously. Of course, this project has left rooms to add your own logic to it. For example, sending MQTT messages to your phone to alert you, or to an IP camera to capture the image of the thief. Hardware Preparation - Ameba1 RTL8195AM x2 - Buzzer x1 - LED (red) x1 - Reed switch x1 - Magnet x1 - Jumpers x6 As 2 boards are needed to implement this project, there are 2 connection illustration as follows, https://github.com/Realtek-AmebaApp/Ameba_Examples/blob/master/RTL8195AM/006_HOME_SECURITY/WindowSecuritySystem_Switch_bb.png https://github.com/Realtek-AmebaApp/Ameba_Examples/blob/master/RTL8195AM/006_HOME_SECURITY/WindowSecuritySystem_Buzzer_bb.png Software Preparation 1. Check and make sure you have installed the ameba 1 board to Arduino IDE via adding this link into “additional boards manager URLs” under “Preference”, and install it in “board manager” under “Tools”, https://github.com/ambiot/amb1_arduino/raw/master/Arduino_package/package_realtek.com_ameba1_index.json 2. Copy the [buzzer source code](https://github.com/Realtek-AmebaApp/Ameba_Examples/blob/master/RTL8195AM/006_HOME_SECURITY/windowSecuritySystem_buzzer_Github.ino) and [switch source code](https://github.com/Realtek-AmebaApp/Ameba_Examples/blob/master/RTL8195AM/006_HOME_SECURITY/windowSecuritySystem_switch_Github.ino) you find in this repository to your Ameba1 RTL8195 boards respectively using arduino IDE 3. In order to connect to WiFi and MQTT server, you need to key in your WiFi SSID, WiFi passowrd, MQTT username and MQTT password, - username: same as your amebaiot.com username - password: same as your amebaiot.com password Done that's it! You have created a simple yet powerful home security system! To watch how how it is done, click link below,
  4. One of the challenges of using IoT enabled MCU is the power consumption. However, on Ameba, you can keep the WiFi on while in sleep mode thus enabling power saving and connectivity. Here is a demo of how to achieve WiFi in sleep mode. Preparation Ameba x 1 DHT11/DHT22/DHT21 x 1 Example In deepsleep mode, the WiFi feature of Ameba is disabled. If you want to save power and keep the WiFi connection at the same time, please use the sleep API. Open "File" -> "Examples" -> "AmebaPowerSave" -> "SleepWithDHTUdpServ" Remember to set the ssid & password in the sample code. In this example, Ameba act as an UDP server, it establishes a wifi connection then enter sleep mode. When Ameba receives UDP packets with content "H", it replies the humidity value, and when it receives UDP packets with content "T", it replies the temperature value. When the sleep mode is enabled, Ameba goes to sleep or wakes up automatically. We use the "Sokit" tool to set the IP & port of Ameba, and request for temperature and humidity values in turn. Note that Ameba would check the status of pin D18, if it is connected to the GND, Ameba would not enter sleep mode. We compare the example with/without power-saving: (We use the Keysight 34465A multimeter in the experiment) NOTE: In reality, due to the energy loss in the voltage conversion and operation, the actual usage time may be different.
  5. Materials AmebaD [RTL8722 CSM/DM] x 2 Example Introduction BLE connections use a server client model. The server contains the data of interest, while the client connects to the server to read the data. Commonly, a Bluetooth peripheral device acts as a server, while a Bluetooth central device acts as a client. Servers can contain many services, with each service containing a some set of data. Clients can send requests to read or write some data and can also subscribe to notifications so that the server can send data updates to a client. In this example, a basic battery client is set up on the Ameba Bluetooth stack. The client connects to another Ameba board running the corresponding BLE battery service to read the battery level data. Procedure On the first Ameba board, upload the BLEBatteryService example code and let it run. For the second Ameba board, open the example “Files” -> “Examples” -> “AmebaBLE” -> “BLEBatteryClient”. Upload the code and press the reset button on Ameba once the upload is finished. Open the serial monitor and observe the log messages as the Ameba board with the battery client scans, connects, and reads data from the Ameba board with the battery service. Highlighted in yellow, the Ameba board with the battery client first scans for advertising BLE devices with the advertised device name “AMEBA_BLE_DEV” and the advertised service UUID of 0x180F representing the battery service. After finding the target device, the Ameba board with the battery client forms a BLE connection and searches for a battery service on the connected device, highlighted in blue. With the client connected to the service, the battery client begins to read data using both regular data reads and notifications, highlighted in green. Code Reference BLEClient is used to create a client object to discover services and characteristics on the connected device. setNotifyCallback() is used to register a function that will be called when a battery level notification is received. BLE.configClient() is used to configure the Bluetooth stack for client operation. addClient(connID) creates a new BLEClient object that corresponds to the connected device. For more resources: If you need additional technical documents or the source code for this project. Please visit the official websites and join the Facebook group and forum. Ameba Official Website: https://www.amebaiot.com/en/ Ameba Facebook Group: https://www.facebook.com/groups/amebaioten Ameba Forum: https://forum.amebaiot.com/
  6. 1. Ecosystem LoRaWAN is supported by the LoRa Alliance, an open non-profit association composed of more than 500 members. Its members work closely together and share experiences, promote and promote the success of the LoRaWAN protocol, and become the leading and open global standard for secure, carrier-grade Internet of Things LPWAN connections. NB-IoT is supported by two telecommunications standards associations, 3GPP and GSMA, both of which have the same goal of promoting the interests of mobile networks and equipment. 2. Spectrum LoRaWAN is optimized for ultra-low power consumption and remote applications. Therefore, network operators and equipment manufacturers can access the networks running on the license-free ISM Sub-1GHz spectrum for free. NB-IoT uses a cellular spectrum network, which is optimized for spectrum efficiency. The licensing fee for frequency band usage is very high, and it is limited to a few operators. 3. Deployment status According to the LoRa Alliance, 83 public network operators in 49 countries are currently using LoRaWAN, and more private companies are also using LoRaWAN networks. GSMA is an organization representing the interests of NB-IoT, LTE and other mobile networks. According to it, 40 countries will launch NB-IoT networks in the future. 4. Deployment options LoRaWAN network provides highly flexible deployment. It can be installed in a public, private, or mixed network, indoor or outdoor. LoRaWAN signals can penetrate into urban infrastructure, and each gateway can cover 30 miles (approximately 48.3 kilometers) in an open rural environment. NB-IoT uses LTE cellular infrastructure, which is an outdoor public network and requires the deployment of 4G/LTE cellular towers. If the sensor exceeds the coverage area of the base station, the base station is not easy to move. 5. Protocol The LoRaWAN protocol sends data asynchronously, and the data is sent only when needed. This can extend the battery life of the sensor device up to 10 years, and the battery replacement cost is low. NB-IoT needs to maintain a synchronous connection to the cellular network, regardless of whether it needs to send data. For sensor devices, it consumes a long battery life, resulting in high battery replacement costs, which may be too costly in many applications. 6. Emission current LoRaWAN provides 18 mA emission current at 10 dBm, and 84 mA emission current at 20 dBm. Modulation differences can enable LoRaWAN to support very low-cost batteries, including button batteries.  The NB-IoT sensor consumes ~220 mA at 23 dBm and 100 mA at 13 dBm, which means that it needs more power to operate and requires more frequent battery replacement or a larger capacity battery. 7. Receive current LoRaWAN provides lower sensor BOM cost and battery life for remote sensors. The receiving current is about 5 mA, and the overall power consumption is reduced by 3-5 times.  The NB-IoT receiving current is about ~40 mA. The communication between the cellular network and the device consumes more than 110 mA on average, and a communication lasts for tens of seconds. The protocol overhead has a significant impact on the battery life of devices that need to work for 3, 5, or 10 years or more. 8. Data rate LoRaWAN data rate is about 293 bps-50 kbps. The LoRaWAN protocol dynamically adjusts the data rate according to the distance between the sensor and the gateway, thereby optimizing the air time of the signal and reducing conflicts. The peak data rate of NB-IoT is about 250 kbps, which is more suitable for use cases with higher power budget and higher data rate (above 50 kbps). 9. Link budget LoRaWAN's MCL signal varies according to regional regulatory restrictions. The link budget is between 155 dB and 170 dB.  NB-IoT needs to repeat remote sensors at a low bit rate in order to be able to support remote sensors. The link budget is up to 164 dB. 10. Mobility LoRaWAN can support mobile sensors to track the movement of assets from one place to another. Even without GPS, high enough accuracy can be obtained for many applications.
  7. Microcontrollers are known for its low power usage and limited resources thus often deemed unable to understand Python script as Python need interpretor to translate script into machine langauge and intepretor are usaully quite resource-consuming. However, MicroPython has arisen as a lean and efficiant Python 3 interpretor that can be run on ARM Cortex-M series microcontrollers. Ameba RTL8722 is an ARM Cortex-M33 microcontroller that has dual-band WiFi and BLE 5.0, other than that it is fully capable of running MicroPython and controls WiFi using Python script. In addition, its requirement for developing platform is also quite minimal-- only needs a serial port terminal like Tera term. Here is an example of RTL8722 controlling WiFi using just a few lines of Python code on Tera Term, from wireless import WLAN wifi = WLAN(mode = WLAN.STA) wifi.scan() Right after the last line, you will be able to see the result printed on the Tera term almost immediately, Hope this post give you some ideas of how easy it is to control microcontroller using MicroPython, stay tuned and happy coding!
  8. BLE – Battery Client Nowadays a lot of DIY project use rechargable battery to make the product mobile and portable, but monitor the battery level can be quite troublesome, with RTL8722DM BLE and WiFi microcontroller from Realtek, we can retrieve battery information through BLE easily, here is how, Materials AmebaD [RTL8722 CSM/DM] x 2 Example Introduction BLE connections use a server client model. The server contains the data of interest, while the client connects to the server to read the data. Commonly, a Bluetooth peripheral device acts as a server, while a Bluetooth central device acts as a client. Servers can contain many services, with each service containing a some set of data. Clients can send requests to read or write some data and can also subscribe to notifications so that the server can send data updates to a client. In this example, a basic battery client is set up on the Ameba Bluetooth stack. The client connects to another Ameba board running the corresponding BLE battery service to read the battery level data. Procedure On the first Ameba board, upload the BLEBatteryService example code and let it run. For the second Ameba board, open the example “Files” -> “Examples” -> “AmebaBLE” -> “BLEBatteryClient”. Upload the code and press the reset button on Ameba once the upload is finished. Open the serial monitor and observe the log messages as the Ameba board with the battery client scans, connects, and reads data from the Ameba board with the battery service. Highlighted in yellow, the Ameba board with the battery client first scans for advertising BLE devices with the advertised device name “AMEBA_BLE_DEV” and the advertised service UUID of 0x180F representing the battery service. After finding the target device, the Ameba board with the battery client forms a BLE connection and searches for a battery service on the connected device, highlighted in blue. With the client connected to the service, the battery client begins to read data using both regular data reads and notifications, highlighted in green. Code Reference BLEClient is used to create a client object to discover services and characteristics on the connected device. setNotifyCallback() is used to register a function that will be called when a battery level notification is received. BLE.configClient() is used to configure the Bluetooth stack for client operation. addClient(connID) creates a new BLEClient object that corresponds to the connected device.
  9. This is MicroPython project developed using Ameba RTL8722. MicroPython is offically supported on Ameba RTL8722, so through this demo video, we will see how easy and fast it is to develop a simple server socket on Ameba, which would then control other peripheral to perform other tasks. Here we are using a client socket code running on PC to send a 'Hello, world' string via the WiFi network, Ameba receives it and if it is indeed 'Hello, world' then it will blink the LED. Check out the demo video down below, https://youtu.be/pEMkwvw-r18 Code used: #!/usr/bin/env python3 #PC Client code import socket HOST = '192.168.1.152' # The server's hostname or IP address PORT = 80 # The port used by the server with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) s.send(bytes('Hello, world','utf8')) #Ameba Code from machine import Pin from wireless import WLAN import time import socket wifi = WLAN(WLAN.STA) wifi.connect("MPSSID","upyameba") led = Pin("PB_4",Pin.OUT) s = socket.SOCK() port = 80 data = ' ' s.bind(port) s.listen() conn, addr = s.accept() while True: data = conn.recv(1024) print(data) if data == b'Hello, world': print('turn on LED 1') for i in range(6): led.toggle() time.sleep_ms(200) if not data: break
  10. Bluetooth Low Energy is energy conversing wireless procotol that help IoT microcontroller to save a great deal of power as compared to using WiFi. Here we use Realtek's RTL8722 dual-band WiFi and BLE 5.0 IoT microcontroller to demo how to output PWM signal to a RGB led over BLE UART Materials Ameba D [RTL8722 CSM/DM] x 1 RGB LED Android / iOS smartphone Example Introduction In this example, a smartphone app is used to transmit commands over BLE UART to control the PWM outputs and change the color of a RGB LED. Refer to the other example guides for detailed explanations of the BLE UART service. Procedure Connect the RGB LED to the RTL8722 board following the diagram, the common LED pin may need to connect to 3.3V or GND depending on the type of LED (common anode / common cathode). Ensure that the required app is installed on your smartphone, it is available at: – Google Play Store: https://play.google.com/store/apps/details?id=com.adafruit.bluefruit.le.connect – Apple App Store: https://apps.apple.com/us/app/bluefruit-connect/id830125974 Open the example, “Files” -> “Examples” -> “AmebaBLE” -> “PWM_over_BLEUart”. Upload the code and press the reset button on Ameba once the upload is finished. Open the app on your smartphone, scan and connect to the board shown as “AMEBA_BLE_DEV” and choose the controller -> color picker function in the app. Using the color selection wheel, saturation, and brightness sliders, choose a desired color and click select to send the RGB values to the board. You should see the RGB LED change to the matching color. Code Reference The RGB values are sent as three consecutive bytes prefixed by “!C” characters. The “!” exclamation mark is used to indicate that the following data is a command, and the “C” character is used to indicate that the data is RGB values. The received UART message is checked in the callback function for “!C” first, otherwise it is treated as a regular message and printed to the serial terminal.
  11. MQTT is one of the most popular IoT network protocol thanks to its light-weight and Publish-subscribe model. However, some doubts the security of MQTT as it is usually unprotected to reduce overhead, this can be easily fixed with the use of TLS (Transport Layer Security), here we are using Realtek's RTL8722 dual-band WiFi and BLE5.0 microcontroller as example and see how it achieve security with MQTT, Preparation Ameba x 1 Example In this example, we connect Ameba to a MQTT broker using TLS authentication. Then send messages as a publisher and receive messages from as a subscriber. Open the MQTT example “File” -> “Examples” -> “AmebaMQTTClient” -> “MQTT_TLS” Please modify the WiFi-related parameters to connect to your WiFi network. Modify the MQTT parameters to fit your application: The “mqttServer” refers to the MQTT-Broker, we use the free MQTT sandbox “test.mosquitto.org” for testing. “clientId” is an identifier for MQTT-Broker to identify the connected device. “publishTopic” is the topic of the published message, we use “outTopic” in the example. The devices subscribe to “outTopic” will receive the message. “publishPayload” is the content to be published. “subscribeTopic” is to tell MQTT-broker which topic we want to subscribe to. Next, compile the code and upload it to Ameba. Press the reset button, then open the serial monitor After Ameba is connected to MQTT server, it sends the message “hello world” to “outTopic”. To see the message, use another MQTT client. Refer to the MQTT_Basic example guide on how to setup a PC-based MQTT client. If you wish to use TLS client authentication in addition to server authentication, you will need to generate an OpenSSL private key and obtain a signed certificate from the server. For testing purposes, signed certificates can be obtained from test.mosquitto.org by following the guide at https://test.mosquitto.org/ssl/. Replace the character strings “certificateBuff” and “privateKeyBuff” with your signed certificate and OpenSSL private key, ensuring that they are formatted the same way as the shown in the example code. Also uncomment the highlighted code to enable client authentication, and to change the MQTT port number.
  12. There are a lot of online IoT platform out there, google is one of the first few platforms that provide free and easy-to-use IoT services to maker and developer, here is an example using Realtek' RTL8195 development board for Google IoT service, Google Cloud IOT Preparation Ameba x 1 Example This example illustrates how to use Cloud IoT Core on AMEBA. It doesn't need extra Library and use WiFiSSLClient and PubSubClient to connect. Before compiling to Ameba, we need to register and set up Google Cloud IoT Platform. Please refer to Standard SDK examples: https://www.amebaiot.com/google-cloud-iot/ Open the example “File” -> “Examples” -> “AmebaMQTTClient” -> “google_cloud”, we can get project_id, registry_id, device_id and private.pem.key if Google Cloud IoT Platform has been set up. In the example, fill in amebago-193913 for project_id, amebago-registry for registry_id and amebago-rs256-device for device_id as follows. Remember to fill in private.pem.key for privateKeyBuff. Compile and download to Ameba after updating these parameters. Then open the terminal, start to connect to Google Cloud and it shows ” This is Ameba's x message!!” when the connection is successful as follows. The "x" is the increment value for each loop. Verify: Key in with Google Cloud SDK Shell: $ gcloud beta pubsub subscriptions pull --auto-ack \ projects/amebago-193913/subscriptions/amebago-subscription The following are the messages sent by Ameba. Code Reference In setup(), we set up Certificate, which means setting RootCA and Private Key wifiClient.setRootCA((unsigned char*)rootCABuff); wifiClient.setClientCertificate(NULL, (unsigned char*)privateKeyBuff); In loop(), each loop checks the Internet status and re-connect to it when the environment has a problem. if (WiFi.status() != WL_CONNECTED) { while (WiFi.begin(ssid, pass) != WL_CONNECTED) { delay(1000); } Serial.println("Connected to wifi"); } It requires mqtt_id , clientPass and pub_topic to publish: produce mqtt_id: mqtt_id = (char *)malloc(strlen("projects/") + strlen(project_id) + strlen("/locations/us-central1/registries/") + strlen(registry_id) + strlen("/devices/") + strlen(device_id) + 1); sprintf(mqtt_id, "projects/%s/locations/us-central1/registries/%s/devices/%s", project_id, registry_id, device_id); produce clientPass(via JWT Format): clientPass = jwt_generator((unsigned char*)privateKeyBuff, project_id, 3600*1); produce pub_topic: pub_topic = (char *)malloc(strlen("/devices/") + strlen(device_id) + strlen("/events") + 1); sprintf(pub_topic, "/devices/%s/events", device_id); MQTT Server setting: client.setServer(GOOGLE_MQTT_SERVER, GOOGLE_MQTT_PORT); client.setPublishQos(MQTTQOS1); client.waitForAck(true); Start to connect to google cloud if (client.connect(mqtt_id, clientUser, clientPass) ) { .......... for(int i = 0; i < count; i++){ .......... sprintf(payload, "This is Ameba's %d message!!", i); ret = client.publish(pub_topic, payload); ..........  } .......... client.disconnect(); } free(mqtt_id); free(pub_topic); Publish the payload with client.publish method. Remember to disconnect, free mqtt_id and pub_topic buffer。
  13. As clean energe continue to attract huge attention due to the foreseeable demise of fossil fuel, harvesting clean energy , particularly solar energy, for embedded system make sense in many IOT applications for its low power consumption and sometime awkward placement, this example will guide you through how to harvest solar energy for an IOT project, Solar Panel – Upload Temperature And Humidity Data To LASS System Preparation Ameba x 1 DHT11 x 1 Solar Panel (1W) x 1 Lipo rider pro x 1 Li-Po battery (1100 mAh) x 1 DS3231 RTC x 1 AMS1117-3.3V x 1 (Optional) Solar Panel The solar panel we use is: http://www.seeedstudio.com/depot/1W-Solar-Panel-80X100-p-633.html The difference of the models with different power is the time it takes to charge the lithium battery. In general, solar panels with 1W power is sufficient for the weather in Taiwan. Lithium Battery In the night, we use lithium battery to provide power. Take the occasional cloudy days into account, we choose the lithium battery of size 1100mAh. Note that batteries with capacity smaller than 500mAh are not recommended. Lithium Charge-Discharge Module In the daytime, besides providing power to Ameba, we expect the solar panel to supply power to charge the lithium battery. On the other hand, if the solar panel cannot provide enough power, we rely on the lithium battery to supply power. Therefore, we need a Charge-Discharge Module for the lithium battery. Here we use Lipo Rider pro, it uses JST 2.0 joint. There are a number of alternatives: Lipo Rider: http://www.seeedstudio.com/depot/Lipo-Rider-v13-p-2403.html PowerBoost 500C: https://www.adafruit.com/product/1944 PowerBoost 1000C: https://www.adafruit.com/product/2465 DS3231 RTC We use DS1307RTC library supports DS1307/ DS1337/DS3231, here we use DS3231. AMS1117-3.3V The default output of Lipo Rider Pro is 5V, hence can be connected to Ameba directly. If you wish to provide only 3.3V to Ameba module to save power, you can use AMS1117 to step-down the voltage to 3.3V. Example In this example, we use solar panel to supply power for Ameba. When the power output of the solar panel exceeds the power demanded by Ameba, surplus power charges the lithium battery, which can supply power at night. Open the sample code in "File" -> "Examples" -> "AmebaMQTTClient" -> "lass_for_dht_plus_ps_nfc" Note that when you choose to supply power only to Ameba module, the 3.3V on Ameba board would be unavailable. For the modules that require 3.3V power, you need to step-down the voltage to 3.3V to supply power. If you do not want to use AMS1117, you can supply power to 5V directly (note this enables DAP and leads to additional power consumption). Another noteworthy point is that the antenna in the figure is cut down from Ameba, and is connected to Ameba through wires. To run the example, a few settings should be done: Please provide the ssid/password for WiFi connection. The clientId of LASS is set to FT_LIVE_12345678 by default, please replace it with a different value. Compile and upload the sample to Ameba and press reset button. Wait for a while, then you should see the data in the website: http://g0vairmap.3203.info/map.html The sample code uses the location of Realtek by default. For the NFC function, you can use your android phone to scan the NFC antenna to download the NFC APP from google play. (Or you can download from: https://play.google.com/store/apps/details?id=com.realtek.sensortag) After the APP is installed successfully, use your phone to scan the Tag to read the latest temperature and humidity. Press the button at the bottom to get the temperature and humidity information of the day. Energy consumption analysis The power efficiency of the solar panel The measure of brightness here is Illuminance(LUX), light with different wave length have different illuminance. We use Halogen bulbs to simulate sun light. In Taiwan, in the time between 10am to 2pm, the measured illuminance is about 100 LUX on average. At 4pm, the measured illuminance is about 10 LUX on average. Using 100W Halogen bulb, we measure 10k LUX illuminance in distance 20cm, and 100k LUX in distance 5cm. However, the shorter the distance between light source and solar panel, the higher the temperature of the solar panel. As the temperature of solar panel increases, the power efficiency decreases. We keep the distance 20cm in our experiment here. When the illuminance is 100k LUX, the solar panel outputs 210mA current, with voltage 4.8V. 4.8V x 0.21 A = 1.008 W. When the illuminance is 10k LUX, the solar panel outputs only 40~60mA current Power consumption of NFC In this example, the NFC function is kept available when Ameba enters deepsleep. The power consumption of NFC is about 7mA, which is considerably high compared with deepsleep. Power consumption of RTC Normally, RTC uses battery to hold the time precision. However, when RTC is connected to Ameba, Ameba enables its I2C interface by default, which leads to additional 2mA power consumption. Total power consumption If you step-down power source to 3.3V and connect to Ameba module, the measured current in deepsleep is 12mA, and long-term average is 13mA. If you supply 5V power to Ameba, the measured current in deepsleep is 17mA, long-term average is 18mA. Besides NFC and RTC, voltage step-down module and LED light also consumes power. Not considering the power consumed by the battery charge-discharge module, assume that the solar panel provides 40mA current and the 1100mAh lithium battery has used up half of its capacity. Then we need 550mA / (210mA - 13mA) = 2.8 hours to fully charge the lithium battery. If the solar panel cannot provide sufficient current output to supply power for Ameba and the lithium battery, and the Ameba board relies on the lithium battery as power source. Then the battery can provide power for 550 mAh / 13mA = 42 hours. Code Reference The program is composed by previous examples. The execution flow is as follows: At the beginning, we setup watchdog and activate a GTimer to feed/kick watchdog every second, and if the total execution flow is not completed in 30 seconds, go into deepsleep. Note that we put the WiFi connection part in the rear of the flow. Since turning on WiFi consumes relatively more power, to design low-power project, it is recommended that put WiFi-unrelated parts at the beginning of the execution flow.
  14. IR (Infrared) is often used in our remote controller to control TV, fans and light etc for its easy-to-use and affordibility. However, we can also use it for some other purposes like sending and receiving sensor data in a close range, and Realtek's Ameba RTL8722 equiped with dual band WiFi and BLE 5.0 also comes with special designed registers just for IR transmissions, here is demo, IR – Infra-Red Receiver And Emitter Preparation Ameba x 1 Grove - Infrared Receiver x 1 Grove - Infrared Emitter x 1 Principle Infra-red refers to the invisible light with wavelength 770nm~1mm. It is commonly used in our life, for example the remote control in our home. In general, the infra-red emitter and receiver specify the frequency used in transmission. There are some widely used frequency regulations such as NEC, Philips RC5, RC6, RCMM, Toshiba, Sharp, JVC, Sony SIRC,...etc. Among them, NEC uses 38KHz frequency and is commonly used in appliances. The demodulator in the IR receiver outputs 0V when it receives signals with specified frequency, otherwise it outputs 3.3V(or 5V). For the IR emitter, it needs to emit signal with specified frequency (generally PWM signal), since IR receiver would only respond to the specified frequency, The figure below shows a complete Infra-red signal emitted from the IR emitter: First it sends the start signal, which contains a start high and a start low. Start high is PWM signal with frequency 38KHz. Start low is digital signal output, usually we output 0V signal for start low. Then it sends the data a byte at a time. A byte is sent in the order from LSB (Least Significant Bit) to MSB (Most Significant Bit). A bit 1 is represented by a 560us-long PWM signal, and stop for 1.69 ms. A bit 0 is represented by a 560us-long PWM signal, and stop for 560 us. When the data transmission is finished, send a bit 1 as the stop bit. At the receiver side, through demodulation, the received PWM signals are converted to general digital input: And those signals other than PWM signals, are put at 3.3V (or 5V). Example: IR receiver For implementation, Ameba uses a GPIO Interrupt pin and hardware Timer 4. Open the example in "File" -> "Examples" -> "AmebaIRSendRecv" -> "recv" In this example, we use Grove Infrared Receiver, other infra-red receiver works similarly. In general, we will use 3 pins: VCC(connects to 3.3V), GND, RX. In the example, we connect RX to D3 (which has GPIO Interrupt function). Wiring diagram: RTL8710 Wiring diagram: Compile the code and upload to Ameba, then press reset. If you have NEC remote control in hand, you can test that whether the Ameba IR receiver works. Or you can follow next example to use another Ameba board to make an IR emitter yourself. Note that the received messages of the IR receiver will be shown on the serial monitor. Example: IR emitter A typical IR emitter has 2 pins. However, the Grove Infrared Emitter has 3 pins: VCC, GND and TX. In practice, we can only use GND and TX. To transmit 38KHz signal in real time, Ameba uses TX of UART to emit the signal. Hence, when we are using Ameba to emit IR signal, D0 pin (UART RX) would be unavailable. Following is the wiring diagram: However, since the TX of UART is usually on 3.3V, this leads to unnecessary power consumption. Therefore, we rearrange the wires to connect Ameba UART TX to the GND pin of Grove Infrared Emitter, and connect the signal wire of emitter to 3.3V: RTL8710 Wiring Diagram: In this case, when the emitter is not emitting signal, GND and TX are both at 3.3V, voltage difference is 0. Open the example "File" -> "Examples" -> "AmebaIRSendRecv" -> "send". Compile and upload to Ameba, and press reset. In this example, the IR emitter emits signal every 2 seconds. You can test it with the previous IR receiver example. Code Reference We refer to Grove infra-red Send Recv library to design our API. The original source code can be found here. Although the API of Ameba looks similar to that of Arduino, the implementation details is different. IR receiver First, we have to specify the pin used to receive data. Since it needs GPIO interrupt, we have to select a pin with GPIO interrupt function. We use D3 pin in the example. IR.Init(pinRecv) In the loop, we keep checking if there is incoming signal. IR.IsDta() When we receive signal, put the data into user buffer. IR.Recv(dta) The format of the buffer: Byte 0: Data length of whole packet. Byte 1: Length of start high, unit is 50us. Byte 2: Length of start low, unit is 50us. Byte 3: The stop length after the PWM signal when the data bit is 1, unit is 50us. Byte 4: The stop length after the PWM signal when the data bit is 0, unit is 50us. Byte 5...: Data. IR emitter Use Send() API to transmit data. The first argument is the data to be transmitted, and the second argument is the frequency(unit is 1K), in the example we use 38KHz. IR.Send(dtaSend, 38) The transmission format of the data: Byte 0: Data length of whole packet. Byte 1: Length of start high, unit is 50us. Byte 2: Length of start low, unit is 50us. Byte 3: The stop length after the PWM signal when the data bit is 1, unit is 50us. Byte 4: The stop length after the PWM signal when the data bit is 0, unit is 50us. Byte 5: Length of data to transmit. Byte 6...: Data to transmit.
  15. MCU is often considered not powerful enough to communicate with smartphone, yet many projects actually works a lot better if MCU can communicate with smartphone in some way. RTL8722 WiFi+BLE microcontroller from Realtek can do just that with the help of Firebase Messaging Service, and here is how it is done, Use Firebase To Push Messaging Services Preparation Ameba x 1 Android Studio Smart phone with Google Play Service x 1 Example In the era of the popularity of smart phones, people often receive reminders from specific apps. In this example, we will teach how to use Google Firebase to send messages from the Ameba Client to mobile phones. First, we use Firebase Cloud Messaging (FCM) as a cross-platform messaging solution that lets you deliver messages for free and reliably. With FCM, you can notify your client application (App) to sync emails or other data. You can send a message to drive user engagement. For instant messaging content, a message can transfer up to 4KB of payload to the client application. The FCM implementation includes two main parts for sending and receiving: 1. A trusted environment, such as Cloud Functions for Firebase or an application server for building, locating, and sending messages. 2. Receive iOS, Android or Web (JavaScript) client applications for messages. You can use Admin SDK or HTTP&XMPP API to send messages.To test or send marketing or engagement messages with powerful built-in targeting and analytics, you can also useNotifications composer We know that Ameba can send messages to specific apps as long as it implements the http client function. First of all, we must first set up an environment for developing Android apps. Please download Android Studio first on Android official website. https://developer.android.com/studio/install Then we can use the Android example provided by Firebase to download Firebase Quickstart Samples. https://github.com/firebase/quickstart-android Open Android Studio and click on Import Project, select the messaging project in Firebase Quickstart Samples. Since we won't use other functions, we can only choose the messaging project. Android Studio will need to install the SDK and Google repository for the first time to start the messaging project. You can refer to the following page for update. https://developer.android.com/studio/intro/update Wait until the required components for compiling the app are installed, you can open the messaging project, and Android Studio comes with the Firebase registration function. As shown above, open the toolbar and click Tools->Select Firebase. Open Firebase Assisant in the right pane, then see Cloud Messaging, select Set up Firebase Cloud Messaging to start the registration process. Click Connect to Firebase Then bring out the page, and click on Firebase on the left and log in to the Gmail account. Once you log in, you will be taken to the Firebase homepage. Let's keep the homepage first, we need to go to the Firebase Console and go back to Android Studio. We can see that when the webpage is successfully logged in, Android Studio also brings up the login information dialog box, click connect to Firebase You can see Dependencies set up correctly in the right pane and see a google-service.json file in the left pane, indicating that the app has been registered successfully. At this point, you can connect your phone to your computer (press Shift+F10) or press the Runs App in the toolbar. Please note here that Firebase requires a mobile phone to provide Google play service (GPS) service. An example of not being able to use Firebase without installing Google Play. As shown above, the messaging app is installed and executed successfully on the phone. Click LOG TOKEN at this time. There will be a Token ID, which is the Access Token required to send the message, representing the ID of the FCM service APP installed on a particular phone. This ID is unique and will be reassigned when the app is removed and re-installed. It means that the message can be sent to a specific phone. The FCM service can also push messages to a NEWS (Topic). This section can be found in Firebase topic-messaging: https://firebase.google.com/docs/cloud-messaging/android/topic-messaging Therefore, we need to save this Access Token, return to Android Studio as shown below, select Debug at the log level of the Logcat. When you press the LOG TOKEN button on the App, Logcat will print out the Access Token ID. We will save the code after the InstanceID Token: in the Log message. Then we have to go back to the page that was brought when we first logged into Firebase. Click in the upper right corner to go to the console At this point, You can see that Android Studio has just built the messaging project for us in the operation. Click to enter the messaging project with settings page, as shown above. Select Set up Go to the Settings page and select the Cloud Messaging page. We will see the Legacy server key. This Server key also needs to be used in the program. Let's save it and start editing the code. Open the example "File" -> "Examples" -> "AmebaWiFi" -> "Firebase.ino" As shown above, ACCESS_TOKEN and SERVER_KEY are defined in the reverse white part, that is, the ACCESS token ID that we just saved from the APP and the Server Key saved in the Firebase console page. We fill in the two sets of IDs, compile and upload them to Ameba. Press the Reset button and open the terminal. Connect to FCM Server after connecting to AP After showing Connect to Server successful, it means that the FCM connection is successful and the message will be sent. During the process, HTTP/1.1 200 OK will be received to indicate that the message is successfully pushed. At this time, the mobile phone screen is opened and the App receives the message from Ameba. Code Reference Firebase.ino This example uses the HTTP protocol to push messages. Users can learn the payload format from the Firebase development website. https://firebase.google.com/docs/cloud-messaging/send-message The main payload format in the program is as follows. The user can freely change the Title and Body of the message. Body represents the content of the message. char const* payload = "{" \ "\"to\": \"" ACCESS_TOKEN "\"," \ "\"notification\": {" \ "\"body\": \"Hello World!\"," \ "\"title\" : \"From Realtek Ameba\" " \ "} }" ; setup() if (client.connect(server, 80)) { Serial.println("connected to server"); // Make a HTTP request: sprintf(message,"%s%s%s%s%s%d%s%s%s","POST /fcm/send HTTP/1.1\nContent-Type: application/json\nAuthorization: key=",SERVER_KEY,"\nHost: ",HOST_NAME,"\nContent-Length: ",strlen(payload),"\n\n",payload,"\n"); printf("\nRequest:\n%s \n",message); client.println(message); client.println(); } The sprintf part puts the payload into the HTTP POST content and sends the message out after connecting to the FCM Server. loop() while (client.available()) { char c = client.read(); Serial.write(c); } Waiting for the response from Server and printing out the response
  16. Use Ameba As UDP Server When surfing on internet, most of us are using TCP as its reliable and secure, however, UDP could also shine in some other area where speed is more important than integrity, and here is how Realtek's Ameba RTL8722 WiFi+BLE microcontroller works with UDP, Preparation Ameba x 1 Example In this example, we connect Ameba to WiFi and use Ameba to be an UDP server. When Ameba receives a message from UDP client, it replies "acknowledged" message to client. Open the WiFi Web Server example. “File” -> “Examples” -> “AmebaWiFi” -> “WiFiUdpSendReceiveString” Modify related information, including ssid, pass, keyindex Compile the code and upload it to Ameba. After pressing the Reset button, Ameba connects to WiFi and starts the UDP server with port 2390. After the UDP server starts service, Ameba prints the "Starting connection to server" message and waits for client connection. As to the UDP client, we use "sockit" program in the computer to connect to UDP server. Choose client mode and fill in the IP of UDP server (which is the IP of Ameba) and port 2390, then click "UDP Connect". After the connection is established, fill in "Hello World" in the Buf 0 field in sockit and click "Send". Then you can see the Ameba UDP server replies "acknowledged". Code Reference Ameba uses the WiFiUdp class which is compatible with Arduino WiFi Shield, so the Refer to the Arduino tutorial for detailed information about this example. https://www.arduino.cc/en/Tutorial/WiFiSendReceiveUDPString First, use begin() to open an UDP port on Ameba. https://www.arduino.cc/en/Reference/WiFiUDPBegin Use parsePacket() to wait for data from client. https://www.arduino.cc/en/Reference/WiFiUDPParsePacket When a connection is established, use remoteIP() and remotePort() to get the IP and port of the client. https://www.arduino.cc/en/Reference/WiFiUDPRemoteIP https://www.arduino.cc/en/Reference/WiFiUDPRemoteIP Then use read() to read the data sent by client. https://www.arduino.cc/en/Reference/WiFiUDPRead To send reply, use beginPacket(), write(), end(). https://www.arduino.cc/en/Reference/WiFiUDPBeginPacket https://www.arduino.cc/en/Reference/WiFiUDPWrite https://www.arduino.cc/en/Reference/WiFiUDPEndPacket
  17. E-ink display comes in very handy in cutting power consumption when not refreshing the screen, it becomes more power conserving when combined with ARM Cortex M33 microcontroller-- RTL8722 from Realtek. This microcontroller sports dual-band WiFI and BLE 5.0 withh max clock at 200MHz, which make it possible to parse long string of a URL and generate a QR code locally. In this demo, we will show how to generate QR code and display it on a E-ink display. https://youtu.be/KYI5WBmC6ac
  18. The focus of this project is to demonstrates how easy it is for Ameba Wi-Fi Dev. board to communicate with our smart phone via MQTT protocol. Phone to microcontroller communication used to be very difficult as they use totally different hardware interface and phone get its data mainly through the network. Now with a Wi-Fi enabled microcontroller like Ameba RTL8195AM, communication with our phone becomes a bliss. Of course, in this video, only a mini window is used for demonstration purpose, but controlling a real window should not be a problem if you simply replace the servo motor with a bigger DC step motor and change the source code accordingly. With this smart curtain system, you may, 1. Remotely control your curtain to open or close instantaneously 2. Check your curtain status according to the MQTT message received 3. Link with the previous weather station project and automate your room from there GitHub page https://github.com/Realtek-AmebaApp/Ameba_Examples/tree/master/RTL8195AM/005_SMART_CURTAIN Official pages https://www.amebaiot.com.cn/en/ https://www.amebaiot.com/en/ Facebook pages https://www.facebook.com/groups/AmebaIoT/ BiliBili channel https://space.bilibili.com/45777743
  19. Realtek's ameba dev. board is capable of USB OTG and SDIO thus making it possible to take photo with a UVC camera and store it in a SD card via SDIO. Here, combining these 2 function, one can easily create a Time Lapse Photography with merely an arduino size MCU. Here is a tutorial about it, Preparation Ameba x 1 SD card or MicroSD card x 1 SD sniffer x 1 (optional) Logitech C170 web cam x 1 Micro USB OTG adapter x 1 Example In this example, we use UVC to take photos and save to SD card at regular time, which is similar to time lapse photography. Open the sample code in "File" -> "Examples" -> "AmebaSdFatFs" -> "time_lapse_photography" In the sample code, we start the UVC at first, then initialize SD FAT FS. In loop(), use UVC to capture photo every three seconds, and the captured photos are numbered in 0001.jpeg, 0002.jpeg, 0003.jpeg, ... There are some tools to turn these photos to a video. We use ffmpeg here: https://ffmpeg.org/ In Windows OS environment, type the command in the directory of all UVC photos: ffmpeg -framerate 30 -i %04d.jpeg -vf fps=30 -pix_fmt yuv420p output.mp4 The explanation of the arguments in the command: -framrate: By specifying this argument, you tell ffmpeg to use the time handled by framerate to be the timeline. Here we use 30, which means in 30 photos are displayed per second. -i: use this argument to specify input file name. We use "%04d.jpeg" to tell ffmpeg to read the files from 0000.jpeg, 0001.jpeg, 0002.jpeg, ... fps: the framerate of output video, we use 30 frames per second here. The last argument is the output file name. Demo video: Code reference The sample code is comprised of two parts: use UVC to capture photo, and write file to SD card. The UVC part please refer to previous "UVC – Use UVC To Send Image" example. And SD part please refer tp the "SDIO – Edit Files In SD Card" example
  20. LoRa is a low-power wide-area network protocol developed by Semtech. It has a typical range of 10KM at low power consumption which is ideal in some IoT applicaitons. Using LoRa on Realtek's Ameba Dev. board is very easy, here is a tutorial about it, Materials Ameba x 1 Dragino LoRa Shield x 2 Example Dragino Lora Shield is a long range transceiver and based on Open source library. It allows the user to send data and reach extremely long ranges at low data-rates.It provides ultra-long range spread spectrum communication and high interference immunity whilst minimising current consumption. Due to different frequency regulations on each country, please notice the frquency LoRa Shield used when you purchase it. Download the LoRa Library: https://github.com/ambiot/amb1_arduino/raw/master/Arduino_libraries/AmebaLoRa.zip Refer to the documentation on Arduino website to install library and add the .zip file to Ameba: https://www.arduino.cc/en/Guide/Libraries#toc4 Dragino LoRa Shield SPI example wiring explanation: Dragino LoRa Shield can be embedded on Ameba board directly, but the Ameba CS pin is different to the standard SPI protocol. Therefore, Dragino LoRa Shield CS pin cannot connect to Ameba CS pin directly. Modify and pull the CS pin which is pin 10 toward inside and connect to pin 0 with dupont line on Dragino LoRa Shield. The example is shown below: Dragino LoRa Shield SPI Data is produced from ICSP SPI BUS, then connect to AMEBA SPI pin as follows: Below is the RTL8710 Wiring Diagram: Example Illustration This example uses send and receive code to do the functional verification for two Dragino LoRa Shield. One is for sender and another one is fr receiver. Open “File” -> “Examples” -> “AmebaLoRa” -> “LoRaSender” and LoRaReceiverCallback. Compile them separately and upload to Ameba, push the Reset button. Then you can see the results on the terminal:
  21. A BLE beacon broadcasts its identity to nearby Bluetooth devices, to enable the other devices to determine their location relative to the beacon, and to perform actions based on information broadcast by the beacon. Example applications of beacons include indoor positioning system, location-based advertising and more. From the definition of its purpose as a broadcast device, a BLE beacon thus cannot be connected to, and can only send information in its Bluetooth advertisement packets. There are several BLE beacon protocols. The Ameba BLEBeacon library supports the iBeacon and AltBeacon protocols.
  22. BLE connections use a server client model. The server contains the data of interest, while the client connects to the server to read the data. Commonly, a Bluetooth peripheral device acts as a server, while a Bluetooth central device acts as a client. Servers can contain many services, with each service containing a some set of data. Clients can send requests to read or write some data and can also subscribe to notifications so that the server can send data updates to a client. In this example, a basic battery service is set up on the Ameba Bluetooth stack. A mobile phone is used to connect the the Ameba peripheral device and read the battery data. GitHub page https://github.com/Realtek-AmebaApp/ Official pages https://www.amebaiot.com/en/ Facebook pages https://www.facebook.com/groups/AmebaIoT/
  23. Ameba RTL8195AM has onboard NFC tag and run on ARM Cortex-M3 core with WiFi, just nice to make use of all these 3 powerful tool to make an useful applicaiton. Many models of Android smart phone support NFC feature, and numerous of NFC applications are developed for inspection and modification of NFC Tag. In this example, we establish NFC connection between Ameba and a smartphone, and open a webpage on the smartphone via a NFC event. Preparation Ameba x 1 Smartphone with NFC feature x 1 Note: Make sure the onboard NFC antenna is safely connected to the module. Then open the example, "File" -> "Examples" -> "AmebaNFC" -> "UriWebPage" and upload, you will see this message when you tap your NFC-enabled phone on Ameba For more details, refer to the offical website at https://www.amebaiot.com/en/ameba-arduino-nfc-open-web/ Also feel free to join the Facebook group to discuss with other makers! https://www.facebook.com/groups/AmebaIoT
  24. With COVID-19 still wreaking havoc globally, causing thousands of deaths, millions hospitalized, any useful medical device is on high demand, especially household medical device like IR non-contact thermometer. Handheld thermometer usually is on high price point and is hard to come by these days, but the components needed to make thermometer are not that expensive, that give us the perfect reason to DIY one during this lockdown period. This ThermoGun project use Ameba Dev. board RTL8710AF from Realtek, which connects to an OLED display to show temperature data obtained from the MLX90615 IR sensor. Pushing the push button not only perform data acquisition and visualization, but also publish the data via MQTT to all subscribers. Note: The MQTT service used in this project is a FREE MQTT broker hosted at cloud.amebaiot.com, which need to register at www.amebaiot.com . Details of registration is at the link below, https://www.amebaiot.com/en/cloud-getting-started/ For details of step-by-step guide and connections, please refer to Github page here, https://github.com/Realtek-AmebaApp/Ameba_Examples/tree/master/RTL8195AM/007_THERMOGUN Demo Video: https://youtu.be/Yl3arBRmyYI
  25. This project use Ameba Dev. board RTL8710AF, which connects to an OLED display to show temperature data obtained from the MLX90615 IR sensor. Pushing the push button not only perform data acquisition and visualization, but also publish the data via MQTT to all subscribers. The casing is using 3D printing all 3D design files will be open source on github page. GitHub page https://github.com/Realtek-AmebaApp/ Official pages https://www.amebaiot.com/en/ Facebook pages https://www.facebook.com/groups/AmebaIoT/
×
  • Create New...