Integrating the STM32L4 Discovery Kit IoT Node
with Google Cloud Platform Using Wi-Fi
By Greg Toth for Mouser Electronics
The STMicroelectronics STM32L4 Discovery Kit IoT Node provides a feature-packed development board for prototyping Internet of Things (IoT) applications that connect to the cloud. In this project we’ll set up an IoT development environment and configure the Discovery Kit and Google Cloud to run a sensor application that reads hardware sensors and transmits real-time data to the cloud. The Discovery Kit board contains a number of sensors that can measure environmental, motion, sound, and other data. Once data is sent to the cloud it can be stored, processed, and analyzed using a variety of cloud computing resources. Along the way, we show you how to modify and rebuild the application software to make your own changes. This provides a foundation for prototyping other types of IoT applications.
Project Materials and Resources
This bill of materials (BOM) lists components for the project. We also identify additional hardware and software development tools:
Project BOM
- STMicroelectronics
- Type-A to Micro-B Universal Serial Bus (USB) cable
Hardware
- 11 b/g/n Wi-Fi access point with a Dynamic Host Configuration Protocol (DHCP) server and Internet connectivity without a firewall or proxy that blocks outgoing traffic to the Internet
- Personal computer with Windows, Linux, or Mac OS X
Accounts and Software
Project Technology Overview
B-L475E-IOT01A1 STM32L4 Discovery Kit IoT Node
The B-L475E-IOT01A1 (Figure 1) is a development board from STMicroelectronics (STM) that is used to test and evaluate the STM32L4 ultra-low-power Arm Cortex®-M4 microcontroller along with several types of sensors and wireless communications interfaces. It allows developers to prototype IoT applications that directly connect to cloud computing services through the Internet. More detailed information about the board can be found here.
The board contains a number of on-board resources that make it ideal for prototyping IoT designs:
- STM32L4 ultra-low-power Arm Cortex-M4 microcontroller with 1MB of flash and 128KB of static random-access memory (SRAM)
- 8MB serial peripheral interface (SPI) flash memory
- Bluetooth®1 wireless module
- Sub-GHz (868MHz or 915MHz) low-power-programmable radio-frequency (RF) module
- Wi-Fi® wireless module supporting 802.11 b/g/n
- Near-Field Communication (NFC) tag
- Two digital microphones
- Digital temperature and humidity sensor
- 3-axis magnetometer
- 3D accelerometer and 3D gyroscope
- Digital barometer
- Proximity sensor
- Two push-buttons and light-emitting diode (LED) indicators
- Two USB connectors
- Arduinoä Uno V3 and Peripheral Module (PMOD) expansion connectors
- On-board ST-LINK/V2 debugger/programmer
The board is supported by a range of integrated development environments (IDEs) including IAR Keil®, GNU Compiler Collection (GCC)-based IDEs, and Arm® Mbed Enabledä. It also connects to a PC using a USB cable for programming and debugging.
The board is available in two variants, and depending on the sub-GHz frequency for your country, you’ll use either 915MHz or 868MHz. This project uses the Wi-Fi interface, so the sub-GHz frequency is not applicable.
System Workbench for STM32
Firmware programs that run on microcontrollers typically employ an IDE on a personal computer for developments and tests. The IDE provides an editor, compiler, linker, debugger, and a mechanism for transferring binary program images to the microcontroller.
The STM32L4 Discovery Kit IoT Node is programmable using several different IDEs, some of which are freely available and others that have a licensing fee. For this project, we’ll use the free System Workbench for STM32—an Eclipse and GCC-based IDE that runs on Windows, Linux, or Mac OS X PCs. It supports the full range of STM32 microcontrollers and associated boards and is available through the STMicroelectronics SW4STM32 web page.
System Workbench for STM32 also supports the ST-LINK debugger interface built into the STM32L4 Discovery Kit IoT Node. The debug interface allows compiled programs to be downloaded and executed with debug support for breakpoints and memory inspections.
X-CUBE-GCP
The X-CUBE-GCP expansion package is a free software download made available by STMicroelectronics on the X-CUBE-GCP web page. It consists of libraries and example programs for STM32L4 and other microcontrollers on several types of STM development boards. The purpose of this package is to provide the libraries necessary to connect the STM32L4 Discovery Kit IoT Node to Google Cloud IoT through the Internet. The libraries implement specific communication and security protocols used by Google Cloud. Such protocols include Transport Layer Security (TLS), Message Queue Telemetry Transport (MQTT), JavaScript Object Notation [JSON] Web Tokens (JWT), and Transmission Control Protocol/Internet Protocol (TCP/IP) network stacks. X-CUBE-GCP also contains libraries for reading sensors on the Discovery Kit IoT Node, freeing you from an obligation to write low-level driver code yourself.
Google Cloud Platform and Google Cloud IoT Core
Google Cloud Platform (GCP) is a collection of computing services and tools that run in Google datacenters located throughout the world. GCP provides a large set of services that can be used in a building-block fashion to create a variety of applications using a pay-as-you-go billing model. Cloud services include computation, storage, databases, networking, monitoring, containerization, mapping, data analytics, pub/sub, machine learning, and the IoT. We’ll use Google’s own Cloud IoT Core service to integrate our board with Google Cloud.
Wi-Fi Access Point
The STM32L4 Discovery Kit IoT Node contains a built-in Wi-Fi module that connects to the Internet through Wi-Fi. The module supports 802.11 b/g/n standards, so we’ll need an access point that supports 802.11 b/g/n. The access point’s SSID and security credentials will be configured into the board’s Wi-Fi module during the setup process, and the Wi-Fi module will obtain an IP address via DHCP. The board must be able to communicate to the Internet through the access point; therefore, the Internet connection must not have a proxy or firewall that blocks outgoing traffic.
OpenSSL
OpenSSL is a free toolkit and cryptography library that supports the TLS and Secure Sockets Layer (SSL) protocols. We’ll use the OpenSSL command-line tool to create a digital-key pair for board authentication in Google Cloud IoT.
Gcloud
Gcloud is a command-line tool for interacting with Google Cloud from the command line of a PC.
The Setup (Hardware)
While setting up the hardware, be sure to remember the following:
- Electronic components are static-sensitive, so handle them accordingly.
- The time-of-flight and gesture detection sensor (proximity sensor) on the B-L475E-IOT01A contains a laser emitter and corresponding drive circuitry. Be sure to adhere to the laser considerations described in the B-L475E-IOT01A datasheet.
Personal Computer (PC)
Power on your PC and allow it to boot up.
B-L475E-IOT01A STM32L4 Discovery Kit IoT Node
Remove the board from its packaging and place it on a suitable work surface. On the bottom of the board, confirm the jumper settings:
- JP8 open
- JP5, JP6, JP7 closed
- JP4 set to 5V_ST_LINK
Using the Type-A to Micro-B USB cable, connect the Micro-B end to the board’s Micro-B USB connector labeled “ST LINK” and “CN7.” Connect the other end to the PC. When the cable is connected, the board will power on, and you should see LED activity.
Wi-Fi Access Point
Make sure your Wi-Fi access point is running with an active connection to the Internet and with a DHCP server that assigns IP addresses. You’ll need to know the access point SSID, security type, and security credentials for use later when configuring the board’s Wi-Fi module.
The Setup (Software)
System Workbench for STM32
In this step, let’s download and install System Workbench for STM32. Web browse to the ST4STM32 website and look for Get Software towards the bottom, then click Go To Site. This takes you to the OpenSTM32 Community home page.
If you already have an OpenSTM32.org login account you can use that, otherwise you’ll need to register for a free account to download the software. If you need to register, find the registration section on the home page and register a new account. You can register by verifying your email address through an automated registration email message.
Once your registration is complete, go back to the OpenSTM32.org home page. Look for Step 1: Explore, and click the “download area” link for the System Workbench for STM32 installer. This takes you to a download page containing installers for Windows 7, Mac OS X, and Linux. Locate the correct download for your PC and download the software. Run the installer to install System Workbench for STM32 on your system. Be sure to select both the System Workbench for STM32 and ST-LINK-SERVER components. The download page has tips if you have trouble installing the Workbench.
After its installation, launch System Workbench for STM32. You’ll be presented with a Workspace selection dialog box. The Workspace is the directory that will contain your application source code files. A default workspace directory should display on the screen, then click OK to start the IDE using this default workspace. On some PCs (depending on your security settings), you may get a message about System Workbench accepting incoming network connections—please permit these connections so the debugger will work.
Once the Welcome page displays itself (Figure 2), click the Workbench button in the upper-right corner to enter the main workbench page (Figure 3).
Figure 2: Welcome Screen for the System Workbench for STM32 IDE
Figure 2: Main IDE Workbench Screen
X-CUBE-GCP
This step adds the board libraries and example application to the IDE. Web browse to the STM X-CUBE-GCP website, and towards the bottom click on Get Software. Review and accept the license agreement, enter your name and email, and click Download. Once you receive an email with a link to download the software, click the link to download the x-cube-gcp zip file. Unzip the downloaded zip file into a working directory, and inspect the directory’s structure (Figure 4 for X-CUBE-GCP V1.0.0).
Figure 4: X-CUBE-GCP V1.0.0 Directory Structure
Import X-CUBE-GCP into System Workbench for STM32
Next we’ll import the libraries and an example application into the IDE using these steps:
- Click File > Import…
- Select General > Existing Projects into Workspace
- Click Next
- Look to the right of “Select root directory,” then click Browse.
- Navigate to and select the STM32CubeExpansion_Cloud_GCP_V1.0.0/Projects/B-L475E-IOT01A/Applications/Cloud/GoogleIoT/SW4STM32 directory within the unzipped X-CUBE-GCP download (Figure 4), then click Open.
- Ensure the B-L475E-IOT01_GoogleIoT project is check-marked in the Projects section.
- Click Finish to complete the import.
After importing the project, the Project Explorer panel shows the project and its components (Figure 5).
Figure 5: X-CUBE-GCP Project After the Import Into System Workbench for STM32
Verify You Can Build and Run the Project
Next, verify that you can build the imported project.
Start the serial terminal program on the PC and select the communication (COM) port corresponding to the board’s USB connection. The identification (ID) name of the COM port will vary depending on the operating system and serial terminal program. On a Mac workstation, the ID may appear as “STM32 STLink – CDC – SN XXXXXXX.” On a PC, it may say “COMxx.” Open the board’s COM port and adjust the terminal settings to 115200bauds, 8-data bits, 1-stop bit, no parity, and no hardware flow control. Turn on Echo, set the transmit end-of-line to LF, and set the receive end-of-line to AUTO or CRLF. Leave the terminal open so you can see messages from the board during the next step. The X-CUBE-GCP application is highly sensitive and requires the correct end-of-line settings in the terminal. If you have trouble using the terminal re-check the settings carefully.
In the IDE Project Explorer panel, right click B-L475E-IOT01_GoogleIoT, and select Build Project. Watch the build’s progress until it completes successfully, then click the Run button in the toolbar. In the IDE’s Console panel, you should see informational messages about connecting to the target, erasing the device, programming the device, and resetting the target. If these steps complete successfully, you should see messages in the serial terminal (Figure 6). Note that a fresh board may be pre-programmed with a different application program from the factory, and the messages in Figure 6 won’t appear until the board is programmed with the X-CUBE-GCP software.
Figure 6: Serial Console Output During the Initial Application Execution
Congratulations, your board is now up and running! At this point, the board is waiting for you to enter Wi-Fi connection parameters. Although you haven’t set up Google Cloud IoT yet, you can go ahead and configure the Wi-Fi portion to confirm it can connect to the access point. Enter the Wi-Fi SSID, security type, and password (if applicable) in the serial terminal. Afterwards the firmware will connect to the access point and, if successful, print the assigned IP address. It will then prompt you for a Google Cloud IoT connection string, which we’ll create in the next step.
Google Cloud Platform
This step makes your board known to Google Cloud IoT and adds a digital key for board authentication in the cloud. Use your web browser to navigate to the Google Cloud console at https://console.cloud.google.com. You’ll need to establish a Google Cloud login account and create a new cloud project with billing support enabled at the project level. The rest of the steps below occur within the newly created cloud project.
Enable the Pub/Sub API
Navigate to the Pub/Sub service, and enable the Pub/Sub application programming interface (API) (Figure 7).
Figure 7: Enabling the Pub/Sub API
Enable the IoT Core API
Navigate to the IoT Core page, and enable the IoT Core API (Figure 8).
Figure 8: Enabling the IoT Core API
Create the Device Registry
While still in the IoT Core service, click on “Create a device registry” (Figure 9).
Figure 9: Creating a Device Registry
You’ll enter multiple fields using these settings:
Registry ID: my-iot-registry
Region: us-central1
Protocol: MQTT (checked) and HTTP (checked)
Under “Default telemetry topic,” click on “Select a Cloud Pub/Sub topic,” and then select “Create a topic.” Type the word “events” (in lowercase and without quotes) at the end of the topic string, and click Create. The events topic matches the event name programmed in the X-CUBE-GCP application code.
Next, under “Default state topic,” click on “Select a Cloud Pub/Sub topic,” and select “Create a topic.” Type the word “state” (in lowercase and without quotes) at the end of the topic string, and click Create.
Finally, apply the following setting:
Stackdriver Logging: None
Once you apply all the settings, click Create. The settings should look like Figure 10, except you’ll have a different project name:
Figure 10: Cloud IoT Core Registry Settings
Create Public and Private Keys
Run the following commands on the PC where OpenSSL is installed:
openssl genrsa -out rsa_private.pem 2048
openssl rsa -in rsa_private.pem -pubout -out rsa_public.pem
On your PC, this creates two files containing public and private keys for the board:
- rsa_private.pem
- rsa_public.pem
Create the Device and Upload the Public Key
In the Cloud IoT Core navigation menu, select Devices, and then click “Create a device.” You’ll enter multiple fields using these settings:
Device ID: stm-discovery-kit-iot-1
Device communication: Allow
Authentication Input method: Upload
Public key format: RS256
Public key value: Browse to the rsa_public.pem file created in the previous step
Public key expiration date: Unchecked
Device metadata: Leave empty
Stackdriver Logging: Use registry default setting
The settings should look like Figure 11. Once you enter these settings, click Create.
Figure 11: Cloud IoT Core Device Settings part 2
At this point, our device is defined in Google Cloud, and the board is ready to connect to Google Cloud IoT.
Configure Google Cloud IoT Core Parameters in the Board Firmware
The serial terminal should still be prompting you to enter the Google IoT Core connection string for your device. The connection string looks like this:
project-id=lithe-lens-228601;registry-id=my-iot-registry;device-id=stm-discovery-kit-iot-1;cloud-region=us-central1
The only exception is that your connection string will have a different project-id value, which you can find within the telemetry pub/sub topic name, shown in Google Cloud IoT. Once you find your project-id, type the correct string with your project-id into the serial terminal, and press Enter.
Next, the serial terminal will prompt you to enter the TLS credentials:
The first item is the root certificate authority (CA). In the unzipped X-CUBE-GCP directory (Figure 4), find the file Projects/Common/GoogleIoT/comodo_google.pem, then copy and paste its entire contents into the serial terminal. The first line of the file contains “-----BEGIN CERTIFICATE-----.”
The second item is the device key. Copy and paste the contents of the rsa_private.pem file created earlier. The first line of the file contains “-----BEGIN RSA PRIVATE KEY-----.”
After successfully entering the connection string, root CA, and private key, the application will start running and will connect to Google Cloud IoT. You should see messages in the serial terminal about sockets being created, the MQTT connection being opened, and message subscriptions for topic /devices/stm-discovery-kit-iot-1/config.
Publishing Sensor Data Messages to Google Cloud IoT
At this point the board is running the X-CUBE-GCP application and publishing sensor messages to the cloud according to how the blue button is used:
- Single-press: The firmware acquires and publishes one set of temperature, humidity, and pressure readings to Google Cloud IoT.
- Double-press: The firmware enters a continuous loop to acquire and publish a set of temperature, humidity, and pressure readings every five seconds (default interval). Double-pressing the blue button again exits the continuous loop and returns the board to single-press mode.
The X-CUBE-GCP V1.0.0 application codes each set of sensor readings as a string in the following format, with separate fields for temperature, humidity, and pressure:
"data":[{"dataType":"temp","value":"29.10"},{"dataType":"hum","value":"24.26"},{"dataType":"pres","value":"1016.54"}]}
Note that the first character of this string is not a left curly brace, so the string is not a valid JSON object. You can modify the string to make it a valid JSON object, by using the System Workbench for STM32 IDE to edit the B-L475E-IOT01_GoogleIoT/Application/GoogleIoT/googleiot.c file and to change the following line in the GcpIoT_publishTelemetry() function:
From: strcpy((char *)payload,"\"data\":[{");
To: strcpy((char *)payload,"{\"data\":[{");
After making this change, rebuild the project, and click the Run button to download the project to the board. By default the Wi-Fi and Google Cloud IoT connection parameters stay in flash memory when the application is modified. Now, the application will publish sensor messages that look like this:
{"data":[{"dataType":"temp","value":"29.10"},{"dataType":"hum","value":"24.26"},{"dataType":"pres","value":"1016.54"}]}
Monitoring Messages
You can monitor the published sensor messages by creating a subscription using the gcloud command-line tool on your PC and then running a short Python program that uses this subscription to receive and print messages.
Use gcloud to create a monitoring subscription (substitute your own project name in place of lithe-lens-228601), as shown here:
gcloud --project lithe-lens-228601 pubsub \
subscriptions create --topic events monitor-sub
Install the Google Cloud Pub/Sub Python client package on your PC:
pip install google-cloud-pubsub
Create a new file named monitor-sub.py that contains the following Python code (be sure to replace lithe-lens-228601 with your own project name):
import time
from google.cloud import pubsub_v1
project_id = "lithe-lens-228601"
subscription_name = "monitor-sub"
subscriber = pubsub_v1.SubscriberClient()
# The `subscription_path` method creates a fully qualified identifier
# in the form `projects/{project_id}/subscriptions/{subscription_name}`
subscription_path = subscriber.subscription_path(
project_id, subscription_name)
def callback(message):
print('Received message: {}'.format(message.data))
message.ack()
subscriber.subscribe(subscription_path, callback=callback)
# The subscriber is non-blocking. We must keep the main thread from
# exiting to allow it to process messages asynchronously in the background.
print('Listening for messages on {}'.format(subscription_path))
while True:
time.sleep(60)
Run the Python program using this command:
python monitor-sub.py
As new messages are published to Google Cloud, they’ll print on your PC like this:
Received message: {"data":[{"dataType":"temp","value":"27.72"},{"dataType":"hum","value":"24.19"},{"dataType":"pres","value":"1015.65"}]}
Press Control-C to terminate the monitor program. Remember to power off the board when you’re done, so the board doesn’t continue to send messages to Google Cloud and consume cloud resources.
Where to Go Next
This project creates an end-to-end sensor-to-cloud application that you can modify and extend in a number of ways. Here are a few examples:
- Dive deeper into the application’s details by reading the X-CUBE-GCP user manual and studying its source code.
- Change the Wi-Fi access point and/or Google Cloud connection parameters by pressing the blue button immediately after resetting the board.
- Modify the sensor application to include a timestamp in the message data.
- Modify the sensor application to read additional sensors on the board.
- Modify the sensor application to provision Google Cloud IoT connection parameters programmatically rather than manually entering them via the serial terminal.
- Add additional types of sensors using an Arduino shield.
- Connect the pub/sub topic to a Google Cloud BigQuery table to record sensor data for further analysis.
- Develop a data display application that subscribes to the sensor data topic and displays received data values.
- Configure the automatic transmission interval by publishing to the pub/sub config topic.
Don’t forget to let us know how well this project worked for you. Would you expand upon this project? If so, let us know on Facebook, Twitter, LinkedIn, Instagram, or Google+.
Greg is an architect, engineer and consultant with more than 30 years experience in sensors, embedded systems, IoT, telecommunications, enterprise systems, cloud computing, data analytics, and hardware/software/firmware development. He has a BS in Electrical Engineering from the Univ. of Notre Dame and a MS in Computer Engineering from the Univ. of Southern California.