Jump to content
Electronics-Lab.com Community


  • Posts

  • Joined

  • Last visited

  • Days Won


Posts posted by MENG XI

  1. Machine Learning and TensorFlow Lite for Microcontrollers(TFL4M)
    While TensorFlow Lite (TFL) for Microcontrollers is designed to run machine learning models on microcontrollers and other devices with only a few kilobytes of memory. The core runtime just fits in 16 KB on an Arm Cortex M3 and can run many basic models. It doesn't require operating system support, nor any standard C or C++ libraries, not even dynamic memory allocation.

    Ameba and TFL4M
    Ameba is an easy-to-program hardware platform for developing all kinds of IoT applications. AmebaD is equipped with various peripheral interfaces, including WiFi, GPIO INT, I2C, UART, SPI, PWM, ADC. Through these interfaces, AmebaD can connect with electronic components such as LED, switches, manometer, hygrometer, PM2.5 dust sensors, …etc. 

    What's best? Ameba can be programmed using Arduino IDE, MicroPython and standard C SDK which are all open-source!


    TFL for Microcontrollers--Hello World

    Hello World is by far the easiest ML model that can be demo, you only need a LED,or not at all. Here is how we run TFL4M with Hello World,


    • Ameba D [RTL8722 CSM/DM] x 1
    • LED x 1


    Download the Ameba customized version of TensorFlow Lite for Microcontrollers library at https://github.com/ambiot/ambd_arduino/tree/master/Arduino_zip_libraries.
    Follow the instructions at https://www.arduino.cc/en/guide/libraries to install it.
    Ensure that the patch files found at https://github.com/ambiot/ambd_arduino/tree/master/Ameba_misc/ are also installed.

    Open the example, “Files” -> “Examples” -> “TensorFlowLite_Ameba” -> “hello_world”.


    Upload the code and press the reset button on Ameba once the upload is finished.
    Connect the LED to digital pin 10 and ground, ensuring that the polarity is correct. You should see the LED fade in and out rapidly.
    In the Arduino serial plotter, you can see the output value of the Tensorflow model plotted as a graph, it should resemble a sine wave.



    Need more resources to get started with Ameba?

    Check out the

    1. Ameba Official website at https://bit.ly/AmebaOfficialWebsite

    2. Ameba Forum at https://bit.ly/AmebaForum

    3. Ameba Facebook at https://bit.ly/AmebaFB



  2. Have you wondered how many WiFi are there in your surroundings? What are they? Any free network I might connect to? Using MicroPython on Realtek Ameba RTL8722DM, you can do it in just 1 line of Python code, here is how,



    • Ameba x 1


    WiFi Scan function can help us quickly discover what WiFi networks are available in our surrounding. This example does not require any additional hardware, thus simply copy, and paste the following code into REPL to see its effect.

    #The long version
    from wireless import WLAN
    wifi = WLAN(mode = WLAN.STA)
    # The short version
  3. For an IoT development board, the tricky part is connecting to other wireless devices, for example wifi router or bluetooth sensor, now with MicroPython, you can connect to any wifi device with only few line of code typed in real time, no compilation is needed! Check out how ameba RTL8722DM does that as follows,




    • Ameba x 1


    Ameba can connect to WiFi access point with open security or WPA2 security type, which is the most common security type used in household wireless routers. Here we are going to connect to a WiFi access point using code below, copy and paste the following code line by line into REPL to see their effects.

    from wireless import WLAN
    wifi = WLAN(mode = WLAN.STA)
    wifi.connect(ssid = "YourWiFiName", pswd = "YourWiFiPassword")
  4. Take a look of UART communication with Ameba RTL8722 which runs MicroPython


    • Ameba x 1, TTL USB to Serial module x 1


    UART is a very versatile communication protocol and almost an essential part of a microcontroller. A TTL USB to Serial module is an IC that helps to translate UART signal to USB signal so that we can see uart log printed on our PC. This module is often found on many development boards, including ameba. However, the module on Ameba is reserved for LOG UART and Firmware uploading, that is why we need a separate module to communicate between ameba and PC.

    There are currently 2 sets of UART available to MicroPython users and they are,

    Unit TX RX
    Here we are using unit 0 to demonstrate how uart works on ameba.
    Connect TTL module to PA_21 and PA_22 as shown below,
    Then, copy and paste the following code line by line into REPL to see its effect.
    from machine import UART
    uart = UART(tx="PA_21", rx= "PA_22")
    uart.read(5) # read up to 5 bytes
  5. Time is very useful when come to medium size project that requires periodical triggering of certain task over time, here we are going to show you how ot program Ameba RTL8722 dual-band wifi and BLE microcontrollers,



    • Ameba x 1


    There are 3 sets of general timers available to user, each at 32KHz, they are timer 1/2/3.
    Here we use timer 1 as example to demonstrate how a periodical timer works.

    Copy and paste the first 3 lines of code into REPL to see its effect.

    from machine import Timer
    t = Timer(1) # Use Timer 1/2/3 only
    t.start(2000000, t.PERIODICAL) # Set GTimer fired periodically at duration of 2 seconds, printing text on the terminal
    # To stop the periodical timer, type

    A text of “–timer triggered. to stop: type t.stop()–” will be printed on the terminal every 2 seconds.To stop the timer, simply type t.stop().

  6. SPI is a highly important peripheral for microcontroller as it allows for high speed communication over short range, here is how we use python to send msg to another microcontroller over SPI



    • Ameba x 1, Arduino UNO x 1



    在通讯连接建立之前,需要先将以下代码烧录到Arduino UNO。

    rtc = RTC()
    // SPI Master Write //
    void setup (void) {
    Serial.begin(115200); //set baud rate to 115200 for usart
    digitalWrite(SS, HIGH); // disable Slave Select
    SPI.begin ();
    void loop (void) {
    char c;
    digitalWrite(SS, LOW); // enable Slave Select
    // send test string
    for (const char * p = "Hello, world!\r" ; c = *p; p++) {
    digitalWrite(SS, HIGH); // disable Slave Select

    Arduino UNO将以如下图所示的连接方式和Ameba连接,我们使用第“0”组SPI作为从机, 并将Arduino UNO当作SPI的主机。



    from machine import SPI
    s1= SPI(0 , mode = SPI.SLAVE)
    for i in range(14):

    RTC helps to reveal the real time to the machine thus it's critical to some applications. Using MicroPython on Ameba RTL8722, we can get RTC time in just 2 lines, here is how,





    • Ameba x 1


    RTC module help microcontroller to keep track of time and is essential to our time module. Here we an example to demonstrate how to get local time and update the time.

    Copy and paste the following code line by line into REPL to see its effect.

    rtc = RTC()
    rtc.datetime() # get date and time
    rtc.datetime((2020, 12, 31, 4, 23, 58, 59, 0)) # set a specific date and time (year, month, day, weekday(0 for Monday), hour, minute, second, total seconds)
    rtc.datetime() # check the updated date and time

    PWM is one of the crucial peripheral of an MCU, with MicroPython, you can control RTL8722DM to output PWM signal to fade and brighten an LED with ease, here is how,




    • Ameba x 1, LED x 1, Resistor(220ohm) x 1


    PWM use pulse width modulation to control output duty cycle and is widely used to control LED brightness and motor. Here we are using an LED to demonstrate how PWM works.

    Let us connect pin PA_26 to the anode leg of an LED which in series with a current limiting resistor and GND to cathode of the LED as shown below,


    Then, copy and paste the following code line by line into REPL and hit Enter. If everything is in order, you should be able to see the LED slowly become brighter as you paste another line of code.

    from machine import Pin, PWM
    import time
    p = PWM(pin = "PA_26")
    # 0 duty cycle thus output 0
    # 10% duty cycle
    # 50% duty cycle
    # 100% duty cycle
  9. Sometimes we need to exchange some data with another microconrtoller in close range, then we can use I2C for this job, even better, with MicroPython, we can do it in less than 5 lines of code, here is how it's done on ameba  RTL8722 from Realtek,



    • Ameba x 1, Arduino UNO x 1


    I2C is a very common module on microcontrollers, it only takes 2 wire and able to achieve data rate at up to 3.4Mbps. It works in master-slave model and a master can simultaneously connect to up to 128 slaves, making it a very versatile communication protocol between microcontroller and sensor.
    Here we are going to use Ameba as an I2C master and Arduino UNO as a slave to achieve I2C send and recv.
    Before connection, make sure to upload the “Examples -> Wire -> Slave_receiver” example code to Arduino UNO.
    Connection is shown as follows, here we are using PA_26 as SDA pin and PA_25 as SCL.
    Note: There is currently 1 set of I2C available to MicroPython user, they are
    Unit SDA SCL


    Then copy and paste the following code line by line into REPL to see their effects.

    from machine import Pin, I2C
    i2c = I2C(scl = "PA_25", sda = "PA_26", freq=100000) # configure I2C with pins and freq. of 100KHz
    i2c.writeto(8, 123) # send 1 byte to slave with address 8
    i2c.readfrom(8, 6) # receive 6 bytes from slave


  10. Controlling LED has never been easier with MicroPython on Ameba RTL8722 WiFi and BLE microcontroller, today I am gonna show you just how to blink an LED in 3 different ways!




    • Ameba x 1, LED x 1, Resistor(220ohm) x 1


    Blink is one of the best examples to get started with MicroPython.

    Let us connect pin PB_22 to the anode leg of an LED which in series with a current limiting resistor and GND to cathode of the LED as shown below,


    Then, copy the following code and press Ctrl + e in REPL to enter the paste mode (for more information about REPL and paste mode, check “Getting started” page). If you are using Tera Term, simply right click on any blank space of the terminal and paste the code into REPL, then press Ctrl + d to execute the code. If everything is order, you should be able to see the LED blink for 3 times in 3 seconds.

    from machine import Pin
    a = Pin("PB_22", Pin.OUT)
  11. Introduction

    Arduino IDE is a convenient tool to write your code and upload to microcontrollers. However, it doesn’t come with debugger function, which means the only way to debug our program is through using debug message through standard output, in this case, Serial Monitor.

    Debug message is handy and it helps to print out the information the registers holds at a specific time, but once you have done debugging and your program is ready to go, we often have to delete/comment out those debug message code manually, in a big project, this could be problematic as there are just too manny of them.

    Today, I am going to show you an easy method to turn on / off debug message with only a few lines of code.


    The method here is to use a macro function

    Take a look of the following C code,

    //#define __DEBUG__
    #ifdef __DEBUG__
    #define DEBUG(...) printf(__VA_ARGS__)
    #define DEBUG(...)

    Since all Ameba microcontroller supports printf(), we can re-define printf() to a preprocessor function, in this case, I name it DEBUG(). Whenever you want to print out the debug message, instead of Serial.print() or printf(), you should try using DEBUG() instead, it works just like the previous two, but can be easily enabled or disabled by uncomment //#define __DEBUG__ or just leave the comment syntax there.

    Let’s look at an example

    Example code 1

    This is a simple code that only print out “Debug msg 1” and “Debug msg 2” alternatively with a 1 second delay in between.



    Note that the first line of the code is uncommented, and we are seeing the debug messages actually got printed out using the DEBUG() function.

    Example code 2



    Note that this is the same code except I keep the first line commented out, and as a result, no debug messages got print out at all.

    It works! :sunglasses:


    All you need to do is to copy the few lines of code from above into the top of your arduino sketch and you may name your custom debug function anything you like and it will work like a charm.

    Turn on / off is just to keep / remove the // at the first line, very convenient.

    Hope you like this content, stay healthy and happy coding~ :sunglasses:

  12. With a BLE5.0 & Dual-band WiFi microcontroller, you will never have to worry about re-compiling the code just to change the WiFi ssid and password.

    Ameba RTL8722 is a BLE5.0 and dual-band WiFi (2.4G & 5G) Iinternet-of-Things (IoT) developing platform that suit the need for many IoT application scenarios.

    Taking advantge of its BLE + WiFi combination, we can easily change Ameba's WiFi setting and save us great deal of time.

    Take a look at the short video below to learn more


  13. RTL8722 from Realtek supports MicroPython and reading ADC values using Python script in 3 lines, here is an example



    ADC read potentiometer:
    • Materials: Ameba x 1, potentiomete x 1
    • Steps:

    Here we connect ameba to a potentiometer to measure its analogue value, the connection is as follows.1

    Copy and paste the following code into REPL.

    from machine import ADC
    a = ADC(0)
    Values will be obtained and printed on serial terminal once the last line code is executed.
  14. 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)


    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!


    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,



    • AmebaD [RTL8722 CSM/DM] x 2



    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.


    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.

  16. Transmit IR NEC Raw Data and Decode



    • Ameba x2 (one for IR transmitting, the other one for IR receiving)
    • Grove – Infrared Emitter x1 (Figure 1)
    • Grove – Infrared Receiver x1 (Figure 2)


    In this example, we use two Ameba RTL8722 modules that connecting with an infrared (IR) Emitter and an IR Receiver separately to transmit and receive IR NEC Raw data.


    Figure 1: Grove – Infrared Receiver


    Figure 2: Grove – Infrared Emitter

    On the transmission side, the transmitter will send IR NEC raw data. The raw data can be seen as consecutive durations of “marks” and “spaces” (Figure 3) in microseconds (us).
    • Mark: a specific period of sending pulses
    • Space: a specific period of sending nothing


    Figure 3: A typical IR transmission and reception setup implementation

    For more details, please refer to SB-Projects’ topic of IR Remote Control Theory to learn the theory of IR remote controls operation and a collection of IR protocol descriptions. In this example, we are going to use NEC (Now Renesas, also known as Japanese Format) as the transmission protocol.

    NEC Features
    • 8-bit address and 8-bit command length.
    • Extended mode available, doubling the address size.
    • Address and command are transmitted twice for reliability.
    • Pulse distance modulation.
    • The carrier frequency of 38kHz.
    • Bit time of 1.125ms or 2.25ms.

    NEC protocol uses Pulse Distance Encoding of the bits for data communication (Figure 4). A logical “1” is represented by total duration of 2250us, with 560us of “marks” and (2250-560) us of “spaces”. While logical ”0” is represented by total duration of 1120us, with 560us “marks” and (1120-560) us of “spaces”.


    Figure 4: Modulation of NEC

    Since a total number of 32-bit data together with the header and the end-bit will be transferred (Figure 5). If we separate the data in the time-frame (in us), there will be ( 2 + 32 ) x 2 + 1 = 69 “marks” / “spaces” to be transmitted (Figure 6), which forms the raw NEC data we would like to transmit in our Arduino “*.ino” file. This part of the code can be modified by users. Details of how to obtain raw data code for your remote devices, you may refer to Ken Shirriff’s blog, where it provides multiple libraries provided online.


    Figure 5: Sample of a Full NEC Data (in logic1 or 0)


    Figure 6: Sample of a Full NEC RAW Data (in us)

    Figure 7 and 8 shows the pin configuration of IR Emitter and Receiver with Ameba RTL8722 board.


    Figure 7: Pin configuration of IR Emitter and Ameba RTL8722


    Figure 8: Pin configuration of the IR Receiver and Ameba RTL8722

    After the connection is being set up correctly, we will move to the coding part for this example. First, make sure the correct Ameba development board is selected in Arduino IDE: “Tools” -> “Board” -> “RTL8722CSM/RTL8722DM”.

    Open the “IRSendRAW” example in “File” -> “Examples” -> “AmebaIRDevice” -> “IRSendRAW” (Figure 9) and upload to 1st board connected with IR Emitter:


    Figure 9: Example Location of IRSendRaw and IRRecvNEC

    After successfully upload the sample code for IRSendRaw, you might need to upload the IRRecvNEC example for the 2nd board connected with IR Receiver from “File” -> “Examples” -> “AmebaIRDevice” -> “IRRecvNEC”.

    After opening the serial monitor on the IR Receiver side and press the reset buttons on two boards, the data “48” will be received every 3 seconds (due to the delays () function, not compulsory to wait). After decoding the signal from the receiving Pin D8 and transmitting Pin D9 with Logic Analyser and Pulse View (Figure 10), the result is also shown as “48” after decoding the receiving data with IR NEC Protocol.


    Figure 10: Pulse View results from sending and receiving pin

    Code Reference

          [1] Seeed Official website for Grove – Infrared Receiver

    [2] Seed Official website for Grove – Infrared Emitter

    [3] Ken SHirriff’s blog on A Multi-Protocol Infrared Remote Library for the Arduino

    [4] SB-Projects: IR Remote Control Project

  17. 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,
    Code used:
    #!/usr/bin/env python3
    #PC Client code
    import socket
    HOST = ''  # 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)
    led = Pin("PB_4",Pin.OUT)
    s = socket.SOCK()
    port = 80
    data = ' '
    conn, addr = s.accept()
    while True:
    	data = conn.recv(1024)
    	if data == b'Hello, world':
    		print('turn on LED 1')
    		for i in range(6):
    	if not data:


  18. Python has become the most popular language in the past few years, and now we can even program Microcontrollers with Python language through a project named MicroPython.


    MicroPython is, by its definition, a efficient and lean python compiler and runtime that is designed for Microcontroller. It supports Python 3 syntax and can be run interactively using its command prompt--REPL. 


    Now, MicroPython has even been ported to Ameba RTL8722 dual-band WiFi and BLE 5.0 microntroller, here is a demo of how it works,


    Demo Video

  19. 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



    • Ameba D [RTL8722 CSM/DM] x 1
    • RGB LED
    • Android / iOS smartphone



    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.


    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:

    – Apple App Store:

    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.

  20. 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,





    Ameba x 1

    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:2
    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.
  21. 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



    • Ameba x 1


    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:


    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.


    Key in with Google Cloud SDK Shell:

    $ gcloud beta pubsub subscriptions pull --auto-ack \

    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) 
        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:


    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);   

    Publish the payload with client.publish method. Remember to disconnect, free mqtt_id and pub_topic buffer。

  22. WiFi microcontroller usually consume a lot more power than ones without WiFi connection. Even in sleep mode, 2 AA batteries would only last a week, but RTL8722 from Realtek has 2 cores, a cortex M4 core handling user application and a cortex M0 core that help to conserve power by entering the deep sleep mode to extend battery life to few months, here is an example of it,


    Power Management – Enter Deepsleep After Uploading DHT Data To LASS


    • Ameba x 1
    • DHT11/DHT22/DHT21 x 1
    In this example, we will get the humidity and temperature data from DHT, connect to AP, retrieve NTP time, upload the data to LASS MQTT server, then enter deepsleep mode every 10 minutes.


    Open "File" -> "Examples" -> "AmebaPowerSave" -> "DeepSleepWithDHTLass"
    Modify detailed settings in the sample code:
    - Model of DHT sensor: DHT11/DHT22/DHT21
    - Connection to WiFi AP: ssid, password
    - GPS position: latitude & longitude

    Compile and upload to Ameba. The actual power cosumption depends on many factors such as network condition, the time it takes for the server to respond. In our case, the program completes in 13 seconds, the power consumption of the Ameba Module is 1.3mA.
    This number is larger than the one we get in the "DeepSleepWithDHT" example. This is because the power consumption of Ameba in operation is usually larger than 29mA, and when Ameba is using wifi connection the power consumption is larger than 68 mA, which are considerably larger than the 0.018 mA power consumption in deepsleep mode. Therefore, we should keep Ameba in the deepsleep mode as far as possible to save energy.

    To compare the result with the case without entering power-saving mode, we modify the sample code as below. We keep the network connection and get the data from DHC sensor every 10 minutes, then upload the MQTT server.

    void setup()
    void loop()
      if (gatherHumidityAndTemperature() == DATA_CNT_FOR_UPLOAD) {
        while(!sendMQTT()) {
        pDhtData->dataCount = 0;
      // store data back to flash memory
      delay(measureInterval * 1000);

    As a result, the average power consumption is 67 mA.
    Use 2 AA batteries to compare the results: (We use the Keysight 34465A multimeter in the experiment)

    According to the result, the energy of 2 AA batteries can only last for about 1 day without power-saving, and it can last about 2.8 months with power-saving.

    NOTE: In reality, due to the energy loss in the voltage conversion and operation, the actual usage time may be different.

  • Create New...