Sensing is a major part of the smart objects and equipment, for example, condition monitoring for predictive maintenance, which enables context awareness, production performance improvement, and results in a drastic decrease in the downtime due to preventive maintenance.
The FP-AI-MONITOR2 function pack is a multi-sensor AI data monitoring framework on the wireless industrial node, function pack for STM32Cube. It helps to jump-start the implementation and development of sensor-monitoring-based applications designed with the X-CUBE-AI Expansion Package for STM32Cube or with the NanoEdge™ AI Studio. It covers the entire design of the Machine Learning cycle from the data set acquisition to the integration on a physical node.
The FP-AI-MONITOR2 runs learning and inference sessions in real-time on the SensorTile Wireless Industrial Node development kit (STEVAL-STWINBX1), taking data from onboard sensors as input. The FP-AI-MONITOR2 implements a wired interactive CLI to configure the node and manages the learn and detect phases. For simple in the field operation, a standalone battery-operated mode allows basic controls through the user button, without using the console.
The STEVAL-STWINBX1 has an STM32U585AIIxQ , an ultra-low power Arm® Cortex®-M33 with FPU and TrustZone at 160 MHz, 2 Mbytes of Flash memory and 786 Kbytes of SRAM. In addition, the STEVAL-STWINBX1 embeds industrial-grade sensors, including 6-axis IMU, 3-axis accelerometer and vibrometer, and analog microphones to record any inertial, vibrational and acoustic data with high accuracy at high sampling frequencies.
The rest of the article discusses the following topics:
- The general information about the FP-AI-MONITOR2,
- Setting up the hardware and software components,
- Button-operated modes,
- Command-line interface (CLI),
- Human activity recognition, a classification application using accelerometer data, using a pre-trained model powered by X-CUBE-AI,
- Anomaly detection using NanoEdge™ AI,
- Anomaly classification using NanoEdge™ AI classification libraries based on vibration and inertial data,
- Dual-mode to run the anomaly detection using the NanoEdge™ AI library and state classification of a USB fan based on the ultrasonic data from an analog microphone, using a pre-trained model powered by X-CUBE-AI,
- Performing the data logging using onboard vibration sensors and a prebuilt binary of FP-SNS-DATALOG2, and
- Some links to useful online resources, to help a user better understand and customize the project for specific needs.
1. General information
1.1. Feature overview
- Complete firmware to program an STM32U5 sensor node for an AI-based sensor monitoring application on the STEVAL-STWINBX1 SensorTile wireless industrial node
- Runs classical Machine Learning (ML) and Artificial Neural Network (ANN) models generated by the X-CUBE-AI, an STM32Cube Expansion Package
- Runs NanoEdge™ AI libraries generated by NanoEdge™ AI Studio for AI-based anomaly detection applications. Easy integration by replacing the pre-integrated stub
- Application example of human activity classification based on motion sensors
- Application example of combined anomaly detection based on vibration and anomaly classification based on ultrasound
- Application binary of high-speed datalogger for STEVAL-STWINBX1 data record from any combination of sensors and microphones configured up to the maximum sampling rate on a microSD™ card
- Sensor manager firmware module to configure any of the onboard sensors easily, and suitable for production applications
- eLooM (embedded Light object-oriented fraMework) enabling efficient development of soft real-time, multitasking, event driven embedded applications on STM32U5 Series microcontrollers
- Digital processing unit (DPU) firmware module providing a set of processing blocks, which can be chained together, to apply mathematical transformations to the sensor data
- Configurable autonomous mode controlled by user button,
- Interactive command-line interface (CLI):
- Node and sensor configuration
- Configure the application running either an X-CUBE-AI (ML or ANN) model, or a NanoEdge™ AI Studio anomaly detection model with the learn-and-detect capability
- Configure the application concurrently running an X-CUBE-AI ANN model and a NanoEdge™ AI Studio model with the learn-and-detect capability
- Configure the application running a NanoEdge™ AI Studio model for classification using vibration data
- Easy portability across STM32 microcontrollers using the STM32Cube ecosystem
- Free and user-friendly license terms
1.2. Software architecture
The top-level architecture of the FP-AI-MONITOR2 function pack is shown in the following figure.
The STM32Cube function packs leverage the modularity and interoperability of STM32 Nucleo and expansion boards running STM32Cube MCU Packages and Expansion Packages to create functional examples representing some of the most common use cases in certain applications. The function packs are designed to fully exploit the underlying STM32 ODE hardware and software components to best satisfy the final user application requirements.
Function packs may include additional libraries and frameworks, not present in the original STM32Cube Expansion Packages, which enable new functions and create more targeted and usable systems for developers.
STM32Cube ecosystem includes:
- A set of user-friendly software development tools to cover project development from the design to the implementation, among which are:
- STM32CubeMX, a graphical software configuration tool that allows the automatic generation of C initialization code using graphical wizards
- STM32CubeIDE, an all-in-one development tool with peripheral configuration, code generation, code compilation, and debug features
- STM32CubeProgrammer (STM32CubeProg), a programming tool available in graphical and command-line versions
- STM32CubeMonitor (STM32CubeMonitor, STM32CubeMonPwr, STM32CubeMonRF, STM32CubeMonUCPD) powerful monitoring tools to fine-tune the behavior and performance of STM32 applications in real-time.
- STM32Cube MCU & MPU Packages, comprehensive embedded-software platforms specific to each microcontroller and microprocessor series (such as STM32CubeL4 for the STM32L4+ Series), which include:
- STM32Cube hardware abstraction layer (HAL), ensuring maximized portability across the STM32 portfolio
- STM32Cube low-layer APIs, ensuring the best performance and footprints with a high degree of user control over the HW
- A consistent set of middleware components such as FreeRTOS™, USB Device, USB PD, FAT file system, Touch library, Trusted Firmware (TF-M), mbedTLS, Parson, and mbed-crypto
- All embedded software utilities with full sets of peripheral and application examples
- STM32Cube Expansion Packages, which contain embedded software components that complement the functionalities of the STM32Cube MCU & MPU Packages with:
- Middleware extensions and application layers
- Examples running on some specific STMicroelectronics development boards
To access and use the sensor expansion board, the application software uses:
- STM32Cube hardware abstraction layer (HAL): provides a simple, generic, and multi-instance set of generic and extension APIs (application programming interfaces) to interact with the upper layer applications, libraries, and stacks. It is directly based on a generic architecture and allows the layers that are built on it, such as the middleware layer, to implement their functions without requiring the specific hardware configuration for a given microcontroller unit (MCU). This structure improves library code reusability and guarantees easy portability across other devices.
- Board support package (BSP) layer: supports the peripherals on the STM32 Nucleo boards.
1.3. Folder structure
The figure above shows the contents of the function pack folder. The content of each of these subfolders is as follows:
- Documentation: contains a compiled
.chm
file generated from the source code, which details the software components and APIs. - Drivers: contains the HAL drivers, the board-specific drivers for each supported board or hardware platform (including the onboard components), and the CMSIS vendor-independent hardware abstraction layer for the Cortex®-M processors.
- Middlewares: contains libraries and protocols for ST parts as well as for the third parties. The ST components include the eLoom libraries, X-Cube-AI runtime libraries, NanoEdge™ AI library substitutes, Audio Processing library, FFT library, and USB Device library.
- Projects: contains a sample application software, which can be used to program the sensor board for classification and anomaly detection applications using the data from the motion sensors.
- Utilities: contains python scripts and sample datasets. These python scripts can be used to create
- Human Activity Recognition (HAR) models using
- Convolutional Nural Networks (CNN),
- Support Vector based Classifier (SVC), or
- data preparation scripts for HAR with NanoEdge™ AI Studio.
- Ultra Sound Classification (USC) models using Convolutional Neural Networks (CNN)
- data preparation scripts for anomaly detection library generation from NanoEdge™ AI Studio.
- data preparation scripts for anomaly classification library generation from NanoEdge™ AI Studio.
- Human Activity Recognition (HAR) models using
1.4. Terms and definitions
Acronym | Definition |
---|---|
API | Application Programming Interface |
BSP | Board Support Package |
CLI | Command-Line Interface |
FP | Function Pack |
HAL | Hardware Abstraction Layer |
MCU | Microcontroller Unit |
ML | Machine Learning |
AI | Artificial Intelligence |
NEAI | NanoEdge™ AI |
SVC | Support Vector Classifier |
SVM | Support Vector Machine |
ANN | Artificial Neural Network |
CNN | Convolutional Neural Network |
ODE | Open Development Environment |
USC | Ultrasound Classification |
MFCC | Mel-Frequency Cepstral Coefficient |
1.5. References
References | Description | Source | |
---|---|---|---|
[1] | X-CUBE-AI | X-CUBE-AI | |
[2] | NanoEdge™ AI Studio | st.com/nanoedge | |
[3] | STEVAL-STWINBX1 | STWINBX1 |
1.6. Licenses
FP-AI-MONITOR2 is delivered under the Mix Ultimate Liberty+OSS+3rd-party V1 software license agreement (SLA0048).
The software components provided in this package come with different license schemes as shown in the table below.
Software component | Copyright | License |
---|---|---|
Arm® Cortex®-M CMSIS | Arm Limited | Apache License 2.0 |
Azure RTOS ThreadX | Microsoft Corporation | Microsoft Software License Terms |
Azure RTOS USBX | Microsoft Corporation | Microsoft Software License Terms |
STM32U5xx_HAL_Driver | STMicroelectronics | BSD-3-Clause |
STM32U5xx CMSIS | Arm Limited - STMicroelectronics | Apache License 2.0 |
eLooM application framework | STMicroelectronics | Proprietary |
Python TM scripts | STMicroelectronics | BSD-3-Clause |
Dataset | STMicroelectronics | Proprietary |
Sensor Manager | STMicroelectronics | Proprietary |
Audio preprocessing library | STMicroelectronics | Proprietary |
X-CUBE-AI runtime library | STMicroelectronics | Proprietary |
X-CUBE-AI models | STMicroelectronics | Proprietary |
NanoEdge™ AI library stub | STMicroelectronics | Proprietary |
Signal processing library | STMicroelectronics | Proprietary |
Digital processing unit (DPU) | STMicroelectronics | Proprietary |
2. Hardware and firmware setup
2.1. HW prerequisites and setup
To use the FP-AI-MONITOR2 function pack on STEVAL-STWINBX1, the following hardware items are required:
- STEVAL-STWINBX1 development kit board,
- a microSD™ card and card reader to log and read the sensor data,
- Windows® powered laptop/PC,
- Two Micro USB cables, one to connect the sensor board to the PC, and another one for the STLINK-V3MINI, and
- an STLINK-V3MINI.
2.1.1. Presentation of the Target STM32 board
The STWIN.box (STEVAL-STWINBX1) is a development kit and reference design that simplifies prototyping and testing of advanced industrial sensing applications in IoT contexts such as condition monitoring and predictive maintenance.
It is powered with Ultra-low-power Arm® Cortex®-M33 MCU with FPU and TrustZone at 160 MHz, 2048 kBytes Flash memory (STM32U585AI)
It is an evolution of the original STWIN kit (STEVAL-STWINKT1B) and features a higher mechanical accuracy in the measurement of vibrations, an improved robustness, an updated BoM to reflect the latest and best-in-class MCU and industrial sensors, and an easy-to-use interface for external add-ons.
The STWIN.box kit consists of an STWIN.box core system, a 480mAh LiPo battery, an adapter for the ST-LINK debugger, a plastic case, an adapter board for DIL 24 sensors and a flexible cable.
Other features:
- MicroSD card slot for standalone data logging applications
- On-board Bluetooth® low energy v5.0 wireless technology (BlueNRG-M2), Wi-Fi (EMW3080) and NFC (ST25DV04K)
- Option to implement authentication and brand protection secure solution with STSAFE-A110
- Wide range of industrial IoT sensors:
- Ultra-wide bandwidth (up to 6 kHz), low-noise, 3-axis digital vibration sensor (IIS3DWB)
- 3D accelerometer + 3D gyro iNEMO inertial measurement unit (ISM330DHCX) with Machine Learning Core
- High-performance ultra-low-power 3-axis accelerometer for industrial applications (IIS2DLPC)
- Ultra-low power 3-axis magnetometer (IIS2MDC)
- High-accuracy, high-resolution, low-power, 2-axis digital inclinometer with Embedded Machine Learning Core (IIS2ICLX)
- Dual full-scale, 1.26 bar and 4 bar, absolute digital output barometer in full-mold package (ILPS22QS)
- Low-voltage, ultra low-power, 0.5°C accuracy I²C/SMBus 3.0 temperature sensor (STTS22H)
- Industrial grade digital MEMS microphone (IMP34DT05)
- Analog MEMS microphone with frequency response up to 80 kHz (IMP23ABSU)
- Expandable via a 34-pin FPC connector
2.2. Software requirements
2.2.1. FP-AI-MONITOR2
- Download the latest version of the FP-AI-MONITOR2, package from ST website, extract and copy the .zip file contents into a folder on the PC. The package contains binaries, source code and utilities for the sensor board STEVAL-STWINBX1.
2.2.2. IDE
- Install one of the following IDEs:
- STMicroelectronics STM32CubeIDE version 1.11.0 or later (tested on 1.10.0),
- IAR Embedded Workbench for Arm (EWARM) toolchain version 9.20.1 or later (tested on 9.20.1), or
- μKeil® Microcontroller Development Kit (MDK-ARM) toolchain version 5.32 or later (tested on 5.32).
2.2.3. STM32CubeProgrammer
- STM32CubeProgrammer is an all-in-one multi-OS software tool for programming STM32 products. It provides an easy-to-use and efficient environment for reading, writing, and verifying device memory through both the debug interface (JTAG and SWD) and the bootloader interface (UART, USB DFU, I2C, SPI, and CAN). STM32CubeProgrammer offers a wide range of features to program STM32 internal memories (such as Flash, RAM, and OTP) as well as external memory. FP-AI-MONITOR2 requires STM32CubeProgrammer 2.12.0.
- This software is available from STM32CubeProg.
2.2.4. Tera Term
- Tera Term is an open-source and freely available software terminal emulator, which is used to host the CLI of the FP-AI-MONITOR2 through a serial connection.
- Users can download and install the latest version available from Tera Term website.
2.2.5. STM32CubeMX
STM32CubeMX is a graphical tool that allows a very easy configuration of STM32 microcontrollers and microprocessors, as well as the generation of the corresponding initialization C code for the Arm® Cortex®-M core or a partial Linux® Device Tree for Arm® Cortex®-A core), through a step-by-step process. Its salient features include:
- Intuitive STM32 microcontroller and microprocessor selection.
- Generation of initialization C code project, compliant with IAR™, Keil® and STM32CubeIDE (GCC compilers) for Arm®Cortex®-M core
- Development of enhanced STM32Cube Expansion Packages thanks to STM32PackCreator, and
- Integration of STM32Cube Expansion packages into the project.
FP-AI-MONITOR2 requires STM32CubeMX V 6.7.0 or later (tested on 6.7.0). To download the STM32CubeMX and obtain details of all the features please visit st.com.
2.2.6. X-Cube-AI
X-CUBE-AI is an STM32Cube Expansion Package part of the STM32Cube.AI ecosystem and extending STM32CubeMX capabilities with automatic conversion of pre-trained Artificial Intelligence models and integration of generated optimized library into the user project. The easiest way to use it is to download it inside the STM32CubeMX tool (version 7.3.0 or newer) as described in the user manual Getting started with X-CUBE-AI Expansion Package for Artificial Intelligence (AI) (UM2526). The X-CUBE-AI Expansion Package offers also several means to validate the AI models (both Neural Network and Scikit-Learn models) both on desktop PC and STM32, as well as to measure performance on STM32 devices (Computational and memory footprints) without ad-hoc handmade user C code.
2.2.7. Python 3.7.3
Python is an interpreted high-level general-purpose programming language. Python's design philosophy emphasizes code readability with its notable use of significant indentation. Its language constructs, as well as its object-oriented approach, aim to help programmers write clear, logical code for small and large-scale projects. To build and export AI models the reader requires to set up a Python environment with a list of packages. The list of the required packages along with their versions is available as a text file in /FP-AI-MONITOR2_V1.0.0/Utilities/requirements.txt
directory. The following command is used in the command terminal of the anaconda prompt or Ubuntu to install all the packages specified in the configuration file requirements.txt
:
pip install -r requirements.txt
2.2.8. NanoEdge™ AI Studio
NanoEdge™ AI Studio is a new Machine Learning (ML) technology to bring true innovation easily to the end-users. In just a few steps, developers can create optimal ML libraries for Anomaly Detection, 1-class classification, n-class classification, and extrapolation, based on a minimal amount of data. The main features of NanoEdge™ AI Studio are:
- Desktop tool for design and generation of an STM32-optimized library for anomaly detection and feature classification of temporal and multi-variable signals
- Anomaly detection libraries are designed using very small datasets. They can learn normality directly on the STM32 microcontroller and detect defects in real-time
- Classification libraries are designed with a very small, labeled dataset. They classify signals in real-time
- Supports any type of sensor: vibration, magnetometer, current, voltage, multi-axis accelerometer, temperature, acoustic and more
- Explore millions of possible algorithms to find the optimal library in terms of accuracy, confidence, inference time, and memory footprint
- Generate very small footprint libraries running down to the smallest Arm® Cortex®-M0 microcontrollers
- Embedded emulator to test library performance live with an attached STM32 board or from test data files
- Easy portability across the various STM32 microcontroller series
This function pack supports the Anomaly Detection and n-class Classification libraries generated by NanoEdge™ AI Studio for STEVAL-STWINBX1. It facilitates users to log the data, prepare and condition it to generate the libraries from the NanoEdge™ AI Studio and then embed these libraries in the FP-AI-MONITOR2. NanoEdge™ AI Studio is available from www.st.com/stm32nanoedgeai under several options such as a single user or team license, or trial version, and personalized support based sprints. FP-AI-MONITOR2 is tested using NanoEdge™ AI Studio V3.2.0.
.
2.3. Program firmware into the STM32 microcontroller
This section explains how to select a binary file for the firmware and program it into the STM32 microcontroller. A precompiled binary file is delivered as part of the FP-AI-MONITOR2 function pack. It is located in the FP-AI-MONITOR2_V1.0.0\Projects\STWIN.box\Applications\FP-AI-MONITOR2\Binary\
folder. When the STM32 board and PC are connected through the USB cable on the STLINK-V3E connector, the STEVAL-STWINBX1 appears as a drive on the PC. The selected binary file for the firmware can be installed on the STM32 board by simply performing a drag and drop operation as shown in the figure below. This creates a dialog to copy the file and once it is disappeared (without any error) this indicates that the firmware is programmed in the STM32 microcontroller.
falsh
2.4. Using the serial console
A serial console is used to interact with the host board (Virtual COM port over USB). With the Windows® operating system, the use of the Tera Term software is recommended. Following are the steps to configure the Tera Term console for CLI over a serial connection.
2.4.1. Set the serial terminal configuration
Start Tera Term, select the proper connection, featuring the [USB Serial Device]. For the screenshot below this is COM5 but it could vary for different users.
Set the Terminal parameters:
The interactive serial console can be used with the default values.
2.4.2. Start FP-AI-MONITOR2 firmware
Restart the board by pressing the RESET button. The following welcome screen is displayed on the terminal.
From this point, start entering the commands directly or type help to get the list of available commands along with their usage guidelines.
3. Button-operated modes
This section provides details of the button-operated mode for FP-AI-MONITOR2. The purpose of the extended mode is to enable the users to operate the FP-AI-MONITOR2 on STWIN even in the absence of the CLI console.
In button-operated mode, the sensor node can be controlled through the user button instead of the interactive CLI console. The default values for node parameters and settings for the operations during auto-mode are provided in the FW. Based on these configurations, different modes such as dual_mode, and neai_learn can be started and stopped through the user button on the node.
3.1. Interaction with user
The button-operated mode can work with or without the CLI and is fully compatible and consistent with the current definition of the serial console and its command-line interface (CLI).
The supporting hardware for this version of the function-pack (STEVAL-STWINBX1) is fitted with three buttons:
- User Button, the only button usable by the SW,
- Reset Button, connected to STM32 MCU reset pin,
- Power Button connected to power management,
and three LEDs:
- LED_1 (green), controlled by Software,
- LED_2 (orange), controlled by Software,
- LED_C (red), controlled by Hardware, indicates charging status when powered through a USB cable.
So, the basic user interaction for button-operated operations is to be done through two buttons (user and reset) and two LEDs (green and orange). The following provides details on how these resources are allocated to show the users what execution phases are active or to report the status of the sensor node.
3.1.1. LED Allocation
In the function pack six execution phases exist:
- idle: the system waits for user input.
- ai detect: all data coming from the sensors are passed to the X-CUBE-AI library to perform HAR.
- neai learn: all data coming from the sensors are passed to the NanoEdge™ AI library to train the model.
- neai detect: all data coming from the sensors are passed to the NanoEdge™ AI library to detect anomalies.
- neai class: all data coming from the sensors are passed to the NanoEdge™ AI library to perform classification.
- dual mode: all data coming from the sensors are passed to the NanoEdge™ AI library to detect anomalies and to X-CUBE-AI library to classify them.
At any given time, the user needs to be aware of the current active execution phase. We also need to report on the outcome of the detection when the detect execution phase is active, telling the user if an anomaly has been detected, or what activity is being performed by the user with the HAR application when the "ai" context is running.
The onboard LEDs indicate the status of the current execution phase by showing which context is running and also by showing the output of the context (anomaly or one of the four activities in the HAR case).
The green LED is used to show the user which execution context is being run.
Pattern | Task |
---|---|
OFF | - |
ON | IDLE |
BLINK_SHORT | X-CUBE-AI Running |
BLINK_NORMAL | NanoEdge™ AI learn |
BLINK_LONG | NanoEdge™ AI detection or classification or dual-mode |
The Orange LED is used to indicate the output of the running context as shown in the table below:
Pattern | Reporting |
---|---|
OFF | Stationary (HAR) when in X-CUBE-AI mode, Normal Behavior when in NEAI mode |
ON | Biking (HAR) |
BLINK_SHORT | Jogging (HAR) |
BLINK_LONG | Walking (HAR) or anomaly detected (NanoEdge™ AI detection or dual-mode) |
Looking at these LED patterns the user is aware of the state of the sensor node even when CLI is not connected.
3.1.2. Button Allocation
In the extended autonomous mode, the user can trigger any of the four execution phases. The available modes are:
- idle: the system is waiting for a command.
- dual: runs the X-CUBE-AI library and print the results of the live inference on the CLI (if CLI is available) and the NanoEdge™ AI library to detect anomalies.
- neai_learn: all data coming from the sensor is passed to the NanoEdge™ AI library to train the model.
To trigger these phases, the FP-AI-MONITOR2 is equipped with the support of the user button. In the STEVAL-STWINBX1 sensor node, there are two software usable buttons:
- The user button: This button is fully programmable and is under the control of the application developer.
- The reset button: This button is used to reset the sensor node and is connected to the hardware reset pin, thus is used to control the software reset. It resets the knowledge of the NanoEdge™ AI libraries, the context variables, and sensor configurations to the default values.
To control the executions phases, we need to define and detect at least three different button press modes of the user button.
The following are the types of the press available for the user button and their assignments to perform different operations:
Button Press | Description | Action |
---|---|---|
SHORT_PRESS | The button is pressed for less than (200 ms) and released | Starts the anomaly detection learning phase |
LONG_PRESS | The button is pressed for more than (200 ms) and released | Starts the dual mode that combines anomaly detection and anomaly classification . |
ANY_PRESS | The button is pressed and released (overlaps with the three other modes) | Stops the current running execution phase. |
4. Command-line interface
The command-line interface (CLI) is a simple method for the user to control the application by sending command-line inputs to be processed on the device.
4.1. Command execution model
The commands are grouped into three main sets:
- (CS1) Generic commands
- This command set allows the user to get the generic information from the device like the firmware version, UID, compilation date and time, and so on, and to start and stop an execution phase.
- (CS2) AI commands
- This command set contains commands which are AI-specific. These commands enable users to work with the X-CUBE-AI and NanoEdge™ AI libraries.
- (CS3) Sensor configuration commands
- This command set allows the user to configure the supported sensors and to get the current configurations of these sensors.
4.2. Execution phases and execution context
The five system execution phases are:
- X-CUBE-AI: Data coming from the sensors is passed through the X-CUBE-AI models to run the inference on the HAR classification.
- NanoEdge™ AI learning: Data coming from the sensors is passed to the NanoEdge™ AI library to train the model.
- NanoEdge™ AI detection: Data coming from the sensors is passed to the NanoEdge™ AI library to detect anomalies.
- NanoEdge™ AI Classification: Data coming from the sensor is passed to the NanoEdge™ AI n-class Classification library to perform n-class classification.
- Dual-mode: The data coming from the accelerometer sensor is passed to the NanoEdge™ AI library to detect the anomalies and if an anomaly is detected the data from the analog microphone is passed to an ANN model to perform the classification of the running class of the setup.
Each execution phase can be started and stopped with a user command $ start <execution phase>
issued through the CLI, where valid values for the execution phase
are:
- har,
- neai_learn,
- neai_detect,
- neai_class, and
- dual.
An execution context, which is a set of parameters controlling execution, is associated with each execution phase. One single parameter can belong to more than one execution context.
The CLI provides commands to set and get execution context parameters. The execution context cannot be changed while an execution phase is active. If the user attempts to set a parameter belonging to any active execution context, the requested parameter is not modified.
4.3. Command summary
Command name | Command string | Note |
---|---|---|
CS1 - Generic commands | ||
help | help | Lists all registered commands with brief usage guidelines. Including the list of the applicable parameters. |
info | info | Shows firmware details and version. |
uid | uid | Shows STM32 UID. |
reset | reset | Resets the MCU system. |
CS2 - AI specific commands | ||
start | start <phase> | Starts an execution phase according to its execution context. Available execution phases are:
|
neai_init | neai_init | (Re)Initializes the NanoEdge™ AI model and forgets any learning made on the device. Used in the beginning or to reinitialize the NanoEdge™ AI anomaly detection to start from scratch at any time. |
neai_set | neai_set <parameter> <value> | Sets a NanoEdge™ AI specific parameter. Valid parameters and values are
|
neai_get | neai_get <parameter> | Displays the value of the NanoEdge™ AI parameter. Valid parameters are
|
har_set | har_set <parameter> <value> | Sets a X-CUBE-AI HAR specific parameter. Valid parameters are
|
har_get | har_get <parameter> | Displays the value of the X-CUBE-AI HAR parameters. Valid parameters are
|
dual_set | dual_set <parameter> <value> | Sets a dual AI specific parameter. Valid parameters and values are
sensor: sensor for classification, values can be integer [0, 4]. |
dual_get | dual_get <parameter> | Gets a dual AI specific parameter. Valid parameters could be
|
CS3 - Sensor configuration commands | ||
sensor_info | sensor_info | Get a list of all supported sensors and their ID. |
sensor_set | sensor_set <id> <parameter> <value> | Sets the value of a parameter for a sensor with sensor id provided in id. The settable parameters are
|
sensor_get | sensor_get <id> <parameter> | Gets the value of a parameter for a sensor with sensor id provided in id. Valid parameters are:
|
4.4. Configuring the sensors
Through the CLI interface, a user can configure the supported sensors for sensing and condition monitoring applications. The list of all the supported sensors can be displayed on the CLI console by entering the command sensor_info
. This command prints the list of the supported sensors along with their ids as shown in the image below. The user can configure these sensors using these ids. The configurable options for these sensors include:
- enable: to activate or deactivate the sensor,
- ODR: to set the output data rate of the sensor from the list of available options, and
- FS: to set the full-scale range from the list of available options.
The current value of any of the parameters for a given sensor can be printed using the command,
$ sensor_get <sensor_id> <param>
or all the information about the sensor can be printed using the command:
$ sensor_get <sensor_id> all
Similarly, the values for any of the available configurable parameters can be set through the command:
$ sensor_set <sensor_id> <param> <val>
The snippet below shows the complete example of getting and setting these values along with old and changed values.
$ sensor_info imp34dt05 ID=0 , type=MIC iis2iclx ID=1 , type=ACC stts22h ID=2 , type=TEMP ilps22qs ID=3 , type=PRESS iis2dlpc ID=4 , type=ACC imp23absu ID=5 , type=MIC iis2mdc ID=6 , type=MAG ism330dhcx ID=7 , type=ACC ism330dhcx ID=8 , type=GYRO ism330dhcx ID=9 , type=MLC iis3dwb ID=10, type=ACC ------- 11 sensors supported $ sensor_get 10 all enable = false nominal ODR = 26667.00 Hz, latest measured ODR = 0.00 Hz Availabe ODRs: 26667.00 Hz fullScale = 16.00 g Available fullScales: 2.00 g 4.00 g 8.00 g 16.00 g $ sensor_set 10 enable 1 sensor 10: enable $ sensor_set 10 FS 4 sensor FS: 4.00 $ sensor_get 10 all enable = true nominal ODR = 26667.00 Hz, latest measured ODR = 0.00 Hz Availabe ODRs: 26667.00 Hz fullScale = 4.00 g Available fullScales: 2.00 g 4.00 g 8.00 g 16.00 g
5. Available Applications
5.1. Inertial data classification with STM32Cube.AI
The CLI application comes with a prebuilt Human Activity Recognition model. This functionality is started by typing the command:
$ start har
Note that the provided HAR model is built with a dataset created using the IHM330DHCX_ACC sensor with ODR = 26, and FS = 4. To achieve the best performance, the user must set these parameters to the sensor configuration using the sensor_set command as provided in the Command Summary table.
Running the $ start har
command starts doing the inference on the accelerometer data and predicts the performed activity along with the confidence. The supported activities are:
- Stationary,
- Walking,
- Jogging, and
- Biking.
The following figure is a screenshot of the normal working session of the har command in the CLI application.
5.2. Anomaly detection with NanoEdge™ AI studio
FP-AI-MONITOR2 includes a pre-integrated stub which is easily replaced by an AI condition monitoring library generated and provided by NanoEdge™ AI Studio. This stub simulates the NanoEdge™ AI-related functionalities, such as running learning and detection phases on the edge.
The learning phase is started by issuing a command $ start neai_learn
from the CLI console or by long-pressing the [USR] button. The learning process is reported either by slowly blinking the green LED light on STEVAL-STWINBX1 or in the CLI as shown below:
$ NanoEdge AI: learn CTRL:! This is a stubbed version, please install the NanoEdge AI library! {"signal": 1, "status": "need more signals"}, {"signal": 2, "status": "need more signals"}, : : {"signal": 10, "status": success} {"signal": 11, "status": success} : : End of execution phase
The CLI shows that the learning is being performed and at every signal learned. The NanoEdge AI library requires to learn for at least ten samples, so for all the samples until ninth sample a status message saying 'need more signals' is printed along with the signal id. Once, ten signals are learned the status of 'success' is printed. The learning can be stopped by pressing the ESC key on the keyboard or simply by pressing the [USR] button.
Similarly, the user starts the condition monitoring process by issuing the command $ start neai_detect
. This starts the inference phase. The anomaly detect phase checks the similarity of the presented signal with the learned normal signals. If the similarity is less than the set threshold default: 90%
, a message is printed in the CLI showing the occurrence of an anomaly along with the similarity of the anomaly signal.
The process is stopped by pressing the ESC key on the keyboard or pressing the [USR] button.
This behavior is shown in the snippet below:
$ start neai_detect NanoEdgeAI: starting detect phase... $ NanoEdge AI: detect CTRL: ! This is a stubbed version, please install NanoEdge AI library ! {"signal": 1, "similarity": 0, "status": anomaly}, {"signal": 2, "similarity": 1, "status": anomaly}, {"signal": 3, "similarity": 2, "status": anomaly}, : : {"signal": 90, "similarity": 89, "status": anomaly}, {"signal": 91, "similarity": 90, "status": anomaly}, {"signal": 102, "similarity": 0, "status": anomaly}, {"signal": 103, "similarity": 1, "status": anomaly}, {"signal": 104, "similarity": 2, "status": anomaly}, End of execution phase
Other than CLI, the status is also presented using the LED lights on the STEVAL-STWINBX1. Fast blinking green LED light shows the detection is in progress. Whenever an anomaly is detected, the orange LED light is blinked twice to report an anomaly. If not enough signals (at least 10) are learned, a message saying "need more signals"
with a similarity value equals to 0 appears.
NOTE : This behavior is simulated using a STUB library where the similarity starts from 0 when the detection phase is started and increments with the signal count. Once the similarity is reached to 100 it resets to 0. One can see that the anomalies are not reported when similarity is between 90 and 100.
5.2.1. Additional parameters in condition monitoring
For user convenience, the CLI application also provides handy options to easily fine-tune the inference and learning processes. The list of all the configurable variables is available by issuing the following command:
$ neai_get all signals = 0 sensitivity = 1.00 threshold = 90 timer = 0 ms sensor = 7
Each of the these parameters is configurable using the neai_set <param> <val>
command.
This section provides information on how to use these parameters to control the learning and detection phase. By setting the "signals" and "timer" parameters, the user can control how many signals or for how long the learning and detection is performed (if both parameters are set the learning or detection phase stops whenever the first condition is met). For example, to learn 10 signals, the user issues this command, before starting the learning phase as shown below.
$ neai_set signals 10 signals set to 10 $ start neai_learn NanoEdgeAI: starting learn phase... $ NanoEdge AI: learn CTRL: ! This is a stubbed version, please install NanoEdge AI library ! {"signal": 1, "status": "need more signals"}, {"signal": 2, "status": "need more signals"}, ... {"signal": 9, "status": "need more signals"}, {"signal": 10, "status": "success"}, End of execution phase
If both of these parameters are set to "0" (default value), the learning and detection phases run indefinitely.
The threshold
parameter is used to report any anomalies. For any signal which has similarities below the threshold value, an anomaly is reported. The default threshold value used in the CLI application is 90. Users can change this value by using neai_set threshold <val>
command.
Finally, the sensitivity parameter is used as an emphasis parameter. The default value is set to 1. Increasing this sensitivity means that the signal matching is to be performed more strictly, reducing it relaxes the similarity calculation process, meaning resulting in higher matching values.
For further details on how NanoEdge™ AI libraries work users are invited to read the detailed documentation of NanoEdge™ AI Studio.
5.3. n-class classification with NanoEdge™ AI
This section provides an overview of the classification application provided in FP-AI-MONITOR2 based on the NanoEdge™ AI classification library. FP-AI-MONITOR2 includes a pre-integrated stub which is easily replaced by an AI classification library generated using NanoEdge™ AI Studio. This stub simulates the NanoEdge™ AI-classification-related functionality, such as running the classification by simply iterating between two classes for ten consecutive signals on the edge.
Unlike the anomaly detection library, the classification library from the NanoEdge™ AI Studio comes with static knowledge of the data and does not require any learning on the device. This library contains the functions based on the provided sample data to best classify one class from another and rightfully assign a label to it when performing the detection on the edge. The classification application powered by NanoEdge™ AI can be simply started by issuing a command $ start neai_class
as shown in the snippet below.
$ start neai_class NanoEdgeAI: starting classification phase... $ CTRL: ! This is a stubbed version, please install the NanoEdge AI library! NanoEdge AI: classification {"signal": 1, "class": Class1} {"signal": 2, "class": Class1} : : {"signal": 10, "class": Class1} {"signal": 11, "class": Class2} {"signal": 12, "class": Class2} : : {"signal": 20, "class": Class2} {"signal": 21, "class": Class1} : : End of execution phase
The CLI shows that for the first ten samples the class is detected as "Class1" while for the upcoming ten samples "Class2" is detected as the current class. The classification phase can be stopped by pressing the ESC key on the keyboard or simply by pressing the [USR] button.
NOTE : This behavior is simulated using a STUB library where the classes are iterated by displaying ten consecutive labels for one class and then ten labels for the next class and so on.
5.4. Dual-mode application with STM32Cube.AI and NanoEdge™ AI
In addition to the three applications described in the sections above the FP-AI-MONITOR2 also provides an advanced execution phase which we call the dual application mode. This mode uses anomaly detection based on the NanoEdge™ AI library and performs classification using a prebuilt ANN model based on an analog microphone. The dual-mode works in a power saver configuration. A low power anomaly detection algorithm based on the NanoEdge™ AI library is always running based on vibration data and an ANN classification based on a high-frequency analog microphone pipeline is only triggered if an anomaly is detected. Other than this both applications are independent of each other. This is also worth mentioning that the dual-mode is created to work for a USB fan when the fan is running at the maximum speed and does not work very well when tested on other speeds. The working of the applications is very simple.
To start testing the dual application execution phase, the user first needs to train the anomaly detection library using the $ start neai_learn
at the highest speeds of the fan. Once the normal conditions have been learned the user can start the dual application by issuing a simple command as $ start dual
as shown in the below snippet:
Whenever there is an anomaly detected, meaning a signal with a similarity of less than 90%, the ultrasound-based classifier is started. Both applications run in asynchronous mode. The ultrasound-based classification model takes almost one second of data, then preprocesses it using the mel-frequency cepstral coefficients (MFCC), and then feeds it to a pre-trained neural network. It then prints the label of the class along with the confidence. The network is trained for four classes [ 'Off', 'Normal', 'Clogging', 'Friction' ] to detect fan in 'Off' condition, or running in 'Normal' condition at max speed or clogged and running in 'Clogging' condition at maximum speed or finally if there is friction being applied on the rotating axis it is labeled as 'Friction' class. As soon as the anomaly detection detects the class to be normal, the ultrasound-based ANN is suspended.
6. Generating the AI models
6.1. Anomaly detection with NanoEdge™ AI
The following section shows how to generate an anomaly detection library using NanoEdge™ AI Studio and install and test it on STEVAL-STWINBX1 using FP-AI-MONITOR2. The steps are provided with brief details in the following figure.
6.1.1. Data logging for normal and abnormal conditions
The details on how to acquire the data are provided in the section data logging using HSDatalog.
6.1.2. Data preparation for library generation with NanoEdge™ AI Studio
The data logged through the datalogger is in the binary format and is not user readable nor compliant with the NanoEdge™ AI Studio format as it is.
Using the provided Python™ utility scripts on the path /FP-AI-MONITOR2_V1.0.0/Utilities/AI-resources/NanoEdgeAi/
.
- The Jupyter Notebook
NanoEdgeAI_Utilities.ipynb
provides a complete example of data preparation for a three-speed fan library generation running in normal and clogged conditions. In addition, there is aHSD_2_NEAISegments.py
script provided if the user wants to prepare segments for given data acquisition. This script is used by issuing the following command for data acquisition withISM330DHCX_ACC
sensor. >> python HSD_2_NEAISegments.py ../Datasets/HSD_Logged_Data/Fan12CM/ISM330DHCX/normal/1000RPM/
command generates a file named asISM330DHCX_Cartesiam_segments_0.csv
using the default parameter set. The file is generated with segments of length1024
and stride1024
plus the first512
samples are skipped from the file.- If multiple acquisitions are used to acquire the data for the normal and abnormal conditions once the files
*_Cartesiam_segments_0.csv
are generated for different acquisitions, all the files for normal can be combined in a single file, and all the files for the abnormal in another file. This way the user has to provide only one normal and abnormal file to Studio.
6.1.3. Library generation using NanoEdge™ AI Studio
Running the scripts in FP-AI-MONITOR2_V1.0.0/Utilities/AI_Resources/NanoEdgeAi/NanoEdgeAI_Utilities.ipynb
generates the normal_WL1024_segments.csv
and clogged_WL1024_segments.csv
files in FP-AI-MONITOR2_V1.0.0/Utilities/AI_Resources/Datasets/HSD-Logged_Data/Fan12CM/ISM330DHCX/
. This section describes how to generate the libraries using these normal and abnormal files.
The NanoEdge™ AI Studio can generate libraries for four types namely:
- Anomaly Detection
- 1-Class Classification
- n-Class Classification
- Extrapolation.
To generate the anomaly detection library the first step is to create the project by clicking on the button for AD as shown in the figure below. The text shows the information on what Anomaly Detection is good for, and the project can be created by clicking on the CREATE NEW PROJECT button.
The process to generate the anomaly detection library consists of seven steps as described in the figure below:
- Project Settings
- Choose a project name and description.
- Hardware Configurations
- Choosing the target STM32 platform or a microcontroller type: STEVAL-STWINBX1 Cortex-M4 is selected by default. If that is not the case select STEVAL-STWINBX1from the list provided in the drop-down menu under Target.
- Maximum amount of RAM to be allocated for the library: Usually, a few Kbytes is enough (but it depends on the data frame length used in the process of data preparation, 32 Kbytes is a good starting point).
- Putting a limit or no limits for the Maximum Flash budget
- Sensor type: 3-axis accelerometer is selected by default. If that is not the case select 3-axis accelerometer from the list in the drop-down under Sensor type.
- Providing the sample contextual data for normal segments to adjust and gauge the performance of the chosen model. Two options are available:
- Provide directly an acquisition directory generated from the HSDatalog, (with all the
*****.dat
andDeviceConfig.json
files unchanged), or - Provide the
normal_WL1024_segments.csv
generated using Jupyter notebook,
- Provide directly an acquisition directory generated from the HSDatalog, (with all the
- Providing the sample contextual data for abnormal segments to adjust and gauge the performance of the chosen model. Two options are available:
- Provide directly an acquisition directory generated from the HSDatalog, (with all the
*****.dat
andDeviceConfig.json
files unchanged), or - Provide the
clogged_WL1024_segments.csv
generated using Jupyter notebook,
- Provide directly an acquisition directory generated from the HSDatalog, (with all the
- Benchmark the available models and choose the one that complies with the requirements and provides the best performance. At the end of the process, the best library is selected for the setup under experimentation. At this stage, an indication of the minimum number of samples to learn is also provided. To get stable results user must run
neai_learn
for at least this many signals. - Validating the model for learning and testing through the provided emulator which emulates the behavior of the library on the STM32 target.
- The final step is to compile and download the libraries. In this process, the flag
"Float abi"
has to bechecked
for using libraries with hardware FPU. All the other flags can be left to the default state.- Note for using the library with μKeil also check -fshort-wchar in addition to Float abi.
Detailed documentation on the NanoEdge™ AI Studio.
6.2. n-class classification with NanoEdge™ AI
The following describes how to generate the NanoEdge™ AI-based classification library and download it. The figure below shows a full flow of generating the library, integrating and installing it with the firmware, and testing it on the sensor-tile to classify different conditions.
6.2.1. Data logging for different conditions
The details on how to log the data are provided in the section Datalogging using HSDatalog. Using these steps the user needs to a separate acquisitions for each of the conditions/classes the user wants to monitor. For the simplicity purposes FP-AI-MONITOR2 provides the sample data for a USB fan in four different conditions namely [ Off, Normal, Clogging, Friction]. This data is measured using ISM330DHCX and IMP23ABSU sensors and can be found in FP-AI-MONITOR2_V1.0.0/Utilities/AI_Resources/Datasets/HSD_Logged_Data/Fan12CM/ISM330DHCX+IMP23ABSU
directory. For the configurations we used ACC subsensor of ISM330DHCX running at ODR = 1666 samples/sec and FS = 4G, and IMP23ABSU running at ODR = 192,000 samples/sec.
6.2.2. Data preparation for n-class classification with NanoEdge™ AI Studio
The data logged through the datalogger is in the binary format and is not user readable nor compliant with the NanoEdge™ AI Studio format as it is. To convert this data to a useful form, for the ease of the users we provided Python™ utilities to prepare this data to be ready to generate the n-class classification libraries using NanoEdge™ AI Studio. These scripts are provided in the form of a Jupyter Notebook and can be found in /FP-AI-MONITOR2_V1.0.0/Utilities/AI-resources/Training Scripts/Anomaly Classification/NanoEdgeAI_ACC/DataPreparation.ipynb
.
- Running all the sections of this notebook generates the NanoEdge™ AI segments for all the acquisitions in the datalog folders which can be inputted to the NanoEdge™ AI Studio in the next step.
6.2.3. Generation n-class classification library NanoEdge™ AI Studio
Running the scripts in Jupyter Notebook generates the ISM330DHCX_Cartesiam_segments_0.csv
csv files in each of the four datalog folders. This section describes how to use these files to generate the n-class classification library with NanoEdge™ AI Studio.
To generate the classification library the first step is to create the project by clicking on the button for nC as shown in the figure below. This modifies the display and shows what n-Class Classification libraries are good for and how it works. Create a new project by clicking on the CREATE NEW PROJECT button.
- Project Settings
- Choose a project name and description.
- Hardware Configurations
- Choosing the target STM32 platform or a microcontroller type: STEVAL-STWINBX1 Cortex-M4 is selected by default. If that is not the case select STEVAL-STWINBX1 from the list provided in the drop-down menu under Target.
- Maximum amount of RAM to be allocated for the library: Usually, a few Kbytes is enough (but it depends on the data frame length used in the process of data preparation, 64 Kbytes is a good starting point).
- Putting a limit or no limits for the Maximum Flash budget (we chose the no limits option)
- Sensor type: 3-axis accelerometer is selected by default. If that is not the case select 3-axis accelerometer from the list in the drop-down under Sensor type.
- Providing the sample data for all four classes. Two options are available:
- Provide directly an acquisition directory generated from the HSDatalog, (with all the
*****.dat
andDeviceConfig.json
files unchanged), select ISM330DHCX>ACC from the sensor list and enter 1024 in the signal length field. Press CONTINUE button and then IMPORT button. Or - Provide the
ISM330DHCX_Cartesiam_segments_0.csv
generated using Jupyter notebook, directly
- NOTE: Assign a class label to the imported data in the Name field once the data is imported. This label is used to differentiate the classes and is used in the emulation to show the predicted class.
- Repeat the process for all four classes.
- Provide directly an acquisition directory generated from the HSDatalog, (with all the
- Benchmark the available models and choose the one that complies with the requirements and provides the best performance.
- Validating the model performance through the provided emulator which emulates the behavior of the library on the STM32 target.
- The final step is to compile and download the libraries. As in FP-AI-MONITOR2, we support multiple NanoEdge™ AI libraries, this step requires a few precise settings to work with FP-AI-MONITOR2:
- Check the Multi-library check-box and provide ncc in the suffix name field. (ncc = n-Class Classification)
- Check the
"Float abi"
flag for using libraries with hardware FPU. All the other flags can be left to the default state.
.
Detailed documentation on the NanoEdge™ AI Studio.
6.3. X-CUBE-AI models
This section explains how to generate the code for a pre-trained AI models using STM32 X-CUBE-AI. As the FP-AI-MONITOR2 runs two pre-trained AI models namely, USC and HAR, for the simplification and optimization purposes, the code is generated for both pre-trained models at the same time. We can either generate the code for the combination of har_IGN.h5
and usc_4_class.tflite
or har_svc.onnx
and usc_4_class.tflite
. These pre-trained models are available in FP-AI-MONITOR2_V1.0.0/Utilities/AI_Resources/models
directory. As the package already contains the code for the HAR_SVC + USC combination, in the section below a step-by-step process is provided for the code generation for the HAR_IGN and USC combination.
Step1 : Open the STM32CubeMX and click on the ACCESS TO BOARD SELECTOR
button as shown in the image below.
Step2 : Create a new project for STEVAL-STWINBX1:
- Confirm the board selector tab is selected,
- Search for the right board, and in our case it is the
STEVAL-STWINBX1
, by typing the name in the search bar, - Select the board by clicking on either the board image or the name of the board,
- Start Project, and
- Chose
NO
for the Peripheral initialization option as this is not required for our purpose.
and check "without TrustZone activated" option
Step3 : Configuring hardware
- Click on the connectivity option in the left menu
- Select USART2
- Enable the "Asynchronous mode" by selecting it in the drop-down menu.
- check PD5 and PD6 pins are selected
- Click on the Power end Thermal option in the left menu
- Select PWR
- Enable the "SMPS" by selecting it in the drop-down menu.
- Click on the System Core option in the left menu
- Select ICACHE
- Enable the "2-ways set associative cache" by selecting it in the drop-down menu.
Step4 : Add the X-CUBE-AI in the software packs for the project
- Click on the
Software Packs
, and select theSelect Components
option - Click on the
STMicroelectronics X-CUBE-AI
. UseVersion 7.3.0
as preference but any version from 7.3.0 or later can be used, - Click on checkbox in front of
Core
to add the X-CUBE-AI code in the software stack. - Expand the
Device Application
menu and from the drop-down menu under selection column selectSystemPerformance
. - Click
OK
button to finish the addition of the X-CUBE-AI in the project.
Step 5 : Platform Settings
- Click on
Software Packs
, - Choose STMicroelectronics.X-CUBE-AI,
- Confirm clock and peripherals settings for best perfomance
- Select the the Platform Settings tab,
- Select
USART: Asynchronous
option for the COM Port, - Select USART2 in "Found Solutions" drop-down.
Step6 : Adding the networks for code generation This step require the users to add two networks. HAR and USC. This can be done using following steps
- Adding HAR model
- Click on the add network button,
- In the first text field provide the text har_network as the network name. This is used to differentiate the name space of the model when code for multiple models is generated at once.
- From drop down select the type of the network. X-CUBE-AI allows the user to generate code for the
Keras
,ONNX
, andTFLite
models. For usinghar_IGN.h5
file select the Keras option. - Click on the
Browse
button to select the model. - The
har_IGN.h5
is located underFP-AI-MONITOR2_V1.0.0/Utilities/AI_Resources/models
. Select the model and click Select.
- Adding USC model
- Click on the add network button,
- In the first text field provide the text usc_network as the network name. This is used to differentiate the name space of the model when code for multiple models is generated at once.
- From drop down select the type of the network as
TFLite
model. - Click on the
Browse
button to select the model. - The
usc_4_class.tflite
is located underFP-AI-MONITOR2_V1.0.0/Utilities/AI_Resources/models
. Select the model and click OK.
Step7 : Generating the C-code
- Go to
Project Manager
- Assign a "Project Name", in the figure below it is
AI-Code-Gen
- Choose a Project Location, in the figure below it is C:/Temp/
- Under Toolchain/IDE option select STM32CubeIDE (or your required toolchain), and
- Click on the GENERATE CODE button. A progress bar starts and shows progress across the different code generation steps.
- Upon completion of the code generation process the user sees a dialog as in the figure below. This shows completion of the code generation. Click on the Open Folder button to open the project with the generated code.
- The files present for the network model that have to be replaced in the provided project are located in the following directory:
FP-AI-MONITOR2_V2.1_AI-Code-Gen/X-CUBE-AI/App/
as shown in the figure below.
The next section shows how these files are used to replace the existing model embedded in the FP-AI-MONITOR2 software step-by-step and install it on the sensor board.
7. Updating the AI models
7.1. Anomaly detection with NanoEdge™ AI
Once the libraries are generated and downloaded from NanoEdge™ AI Studio, the next step is to link these libraries to FP-AI-MONITOR2 and run them on the STWIN. The FP-AI-MONITOR2, comes with the library stubs in the place of the actual libraries generated by NanoEdge™ AI Studio. This is done to simplify the linking of the generated libraries. In order to link the actual libraries, the user needs to copy the generated libraries and replace the existing stub/dummy libraries and header files NanoEdgeAI.h
, and libneai.a
files present in the folders Inc
, and lib
, respectively. The relative paths of these folders are /FP-AI-MONITOR2_V1.0.0/Middlewares/ST/NanoEdge_AI_Library/
.
Once these files are copied, the project must be reconstructed and programmed on the sensor board to link the libraries correctly. For this, the user must open the project in STM32CubeIDE located in the /FP-AI-MONITOR2_V1.0.0/Projects/STWINL4R9ZI-STWIN/Applications/FP-AI-MONITOR2/STM32CubeIDE/
folder and double click .project file .
To build and install the project click on the play button and wait for the successful download message as shown in the section Build and Install Project.
Once the sensor board is successfully programmed, the welcome message appears in the CLI (Tera Term terminal). If the message does not appear try to reset the board by pressing the RESET button.
7.1.1. Testing the anomaly detection with NanoEdge™ AI
Once the STWIN is programmed with the FW containing a valid library, the condition monitoring libraries are ready to be tested on the sensor board. The learning and detection commands can be issued and now the user does not see the warning of the stub presence.
To achieve the best performance, the user must perform the learning using the same sensor configurations which were used during the contextual data acquisition. For example in the snippet below users can see commands to configure ISM330DHCX sensor with sensor_id 2 with following parameters:
- enable = 1
- ODR = 1666,
- FS = 4.
$ sensor_set 2 enable 1 sensor 2: enable $ sensor_set 2 ODR 1666 nominal ODR = 1666.00 Hz, latest measured ODR = 0.00 Hz $ sensor_set 2 FS 4 sensor FS: 4.00
Also, to get stable results in the neai_detect
phase the user must perform learning for all the normal conditions to get stable results before starting the detection. In the case of running the detection phase without performing the learn first, erratic results are displayed. An indication of minimum signals to be used for learning is provided when a library is generated in the NanoEdge™ AI Studio in Step 4 of library generation.
7.2. n-class classification with NanoEdge™ AI
The FP-AI-MONITOR2, comes with the library stubs in the place of the actual libraries generated by NanoEdge™ AI Studio. This is done to simplify the linking of the generated libraries. In n-Class classification library the features for the classes are learned and required in the form of the knowledge.h
file in addition to .h
and .a
files. So unlike the anomaly detection library, in order to link the classification libraries, the user needs to copy two header files NanoEdgeAI_ncc.h
and knowledge_ncc.h
, and the library libneai_ncc.a
file to replace the already present files in the folders Inc
, and lib
, respectively. The relative paths of these folders are /FP-AI-MONITOR2_V1.0.0/Middlewares/ST/NanoEdge_AI_Library/
.
In addition to this the user is required to add the labels of the classes to expect during classification process by updating the sNccClassLabels
array in FP-AI-MONITOR2_prj/Application/Src/AppController.c
file:
/**
* Specifies the label for the two classes of the NEIA Class demo.
*/
static const char* sNccClassLabels[] = {
"Unknown",
"Off",
"Normal",
"Clogging",
"Friction"
};
Note that the first label is "Unknown" and it is required to be left as it is. The real labels for the classification come after this. The order of the labels [Off, Normal, Clogging, Friction] has to be the same as was used to provide the data in the process of library generation in NanoEdge™ AI Studio.
After this step, the project must be reconstructed and programmed on the sensor board to link the libraries correctly. To build and install the project click on the play button and wait for the successful download message as shown in the section Build and Install Project.
Once the sensor board is successfully programmed, the welcome message appears in the CLI (Tera Term terminal). If the message does not appear try to reset the board by pressing the RESET button.
7.2.1. Testing the n-class classification with NanoEdge™ AI
Once the STWIN is programmed with the FW containing a valid library, the condition monitoring libraries are ready to be tested on the sensor board.
To achieve the best performance, the user must perform the learning using the same sensor configurations which were used during the contextual data acquisition. For example in the snippet below users can see commands to configure ISM330DHCX sensor with sensor_id 2 with following parameters:
- enable = 1
- ODR = 1666,
- FS = 4.
$ sensor_set 2 enable 1 sensor 2: enable $ sensor_set 2 ODR 1666 nominal ODR = 1666.00 Hz, latest measured ODR = 0.00 Hz $ sensor_set 2 FS 4 sensor FS: 4.00
After the configurations of the sensor are completed, the user can start the NEAI classification by issuing the command, $ start neai_class
.
7.3. X-CUBE-AI models
The CLI example has two prebuilt models integrated with it. One for HAR and another for the USC. Following the steps below the user can update these models. As described in the code generation process, for sake of simplicity, the code for both models is generated at once. In this example the provided code for the combination of SVC and USC models(USC_4_Class_+_SVC_4_Class) is replaced with the prebuilt and converted C code from the HAR (CNN) and USC CNN models provided in the /FP-AI-MONITOR2_V1.0.0/Utilities/AI_Resources/models/USC_4_Class_+_IGN_4_Class/
folder.
To update the model, the user must copy and replace the following files in the /FP-AI-MONITOR2_V1.0.0/Projects/STWIN.box/Applications/FP-AI-MONITOR2/X-CUBE-AI/App/
folder:
- app_x-cube-ai.c,
- app_x-cube-ai.h,
- har_network.c,
- har_network.h,
- har_network_config.h,
- har_network_data.h,
- har_network_data.c,
- har_network_generate_report.txt,
- usc_network.c,
- usc_network.h,
- usc_network_config.h,
- usc_network_data.h,
- usc_network_data.c, and
- usc_network_generate_report.txt.
After the files are copied, the user must open the project with the CubeIDE. To do so, go to the /FP-AI-MONITOR2_V1.0.0/Projects/STWIN.box/Applications/FP-AI-MONITOR2/STM32CubeIDE/
folder and double click .project file. Once the project is opened, go to FP-AI-MONITOR2_V1.0.0/Projects/STWIN.box/Application/FP-AI-MONITOR2/X-CUBE-AI/App/app_x-cube-ai.c
file and comment the following lines of the code as shown below:
#include "app_x-cube-ai.h"
//#include "bsp_ai.h"
//#include "aiSystemPerformance.h"
#include "ai_datatypes_defines.h"
/* USER CODE BEGIN includes */
/* USER CODE END includes */
/* IO buffers ----------------------------------------------------------------*/
//DEF_DATA_IN
//
//DEF_DATA_OUT
/* Activations buffers -------------------------------------------------------*/
AI_ALIGNED(32)
static uint8_t pool0[AI_USC_NETWORK_DATA_ACTIVATION_1_SIZE];
ai_handle data_activations0[] = {pool0};
ai_handle data_activations1[] = {pool0};
/* Entry points --------------------------------------------------------------*/
//void MX_X_CUBE_AI_Init(void)
//{
// MX_UARTx_Init();
// aiSystemPerformanceInit();
// /* USER CODE BEGIN 5 */
// /* USER CODE END 5 */
//}
//
//void MX_X_CUBE_AI_Process(void)
//{
// aiSystemPerformanceProcess();
// HAL_Delay(1000); /* delay 1s */
// /* USER CODE BEGIN 6 */
// /* USER CODE END 6 */
//}
7.3.1. Building and installing the project
Then build and install the project on the STWIN sensor board by pressing the play button as shown in the figure below.
A message saying Download verified successfully indicates the new firmware is programmed in the sensor board.
8. FP-AI-MONITOR2 Utilities
For the ease of the users FP-AI-MONITOR2 comes with a set of utilities to record and prepare the datasets, and generate the AI models for different supported AI applications. These utilities are in the FP-AI-MONITOR2_V1.0.0/Utilities/
directory and contain two sub-directories,
AI_Resources
(all the Python resources related to AI), andDataLog
(binary and helper scripts for High-Speed Datalogger).
This following section briefly describes the contents of the AI_Resources
folder.
8.1. AI_Resources
FP-AI-MONITOR2 comes equipped with four AI applications, and AI_Resources contains the Python™ utilities contains the sample datasets or dataset placeholders, and the code to prepare these datasets and generate the AI models for these applications.
In the AI_Resources
there are following subdirectories:
- Dataset: Contains different datasets/holders for the datasets used in the function pack
- AST, a small sample from an ST proprietary dataset for HAR by STMicroelectronics.
- HSD_Logged_Data, different datasets logged using High-speed Datalogger binary.
- Fan12CM, Datasets logged on 12CM USB fan using different on-board sensors of STEVAL-STWINBX1.
- HAR, Human activity recognition dataset acquired using the STEVAL-STWINBX1.
- WISDM, a placeholder for downloading and placing the WISDM dataset for HAR.
- models: Contains the pre-generated and trained models for HAR and USC along with their C-code
- USC_4_Class_+_IGN_4_Class contains a combination of CNN for HAR and CNN for USC.
- USC_4_Class_+_SVC_4_Class contains a combination of SVC for HAR and CNN for USC.
- NanoEdgeAi: Contains the helper scripts to prepare the data for the NanoEdge™ AI Studio from the HSDatalogs
- signal_processing_lib: Contains the code for various signal processing modules (there is equivalent embedded code available for all the modules in the function pack)
- Training Scripts: Contains the Python scripts for HAR and AnomalyClassification.
- HAR subdirectory at the path
FP-AI-MONITOR2_V1.0.0/Utilities/AI_Resources/Training Scripts/HAR/
contains three Jupyter notebooks:- HAR_with_CNN.ipynb (a complete step-by-step code to build an HAR model based on Convolutional Neural Networks),
- HAR_with_SVC.ipynb (a complete step-by-step code to build an HAR model based on Support Vector Machine Classifier), and
- HAR_with_NEAI.ipynb (a complete step-by-step code to build NanoEdge™ AI Studio compliant files for all activities).
- AnomalyClassification contains two subdirectories for two different was to perform anomaly classification.
- Ultrasound directory contains the Python scripts to prepare the dataset and create a CNN based model for the anomaly classification using the ultrasound data logged through IMP23ABSU sensor (an analog microphone).
- NanoEdgeAI_ACC contains the python code to prepare the .csv files for ACC data for different conditions on the fan for the anomaly classification library generation from NanoEdge™ AI Studio.
- HAR subdirectory at the path
9. Data collection
The data collection functionality is out of the scope of this function pack, however, to simplify this for the users this section provides the step-by-step guide to logging the data on STEVAL-STWINBX1 using the high-speed data logger.
Step 1: Program the STEVAL-STWINBX1with the HSDatalog FW
In the scope of this function pack and article, the STEVAL-STWINKT1 can be programmed with HSDatalog firmware using the binary provided in the function pack.
To simplify the task of the users and to allow them the possibility to perform a data log, the precompiled HSDatalog.bin
file for FP-SNS-DATALOG2 is provided in the Utilities
directory, which is located under path /FP-AI-MONITOR2_V1.0.0/Utilities/Datalog/
. The sensor tile can be programmed by simply following the drag-and-drop action shown in section 2.3.
Step 2: Place a DeviceConfig.json
file on the SD card
The next step is to copy a DeviceConfig.json
on the SD card. This file contains the sensors configurations to be used for the data logging.
The users can simply use one of the provided some sample .json
files in the package in FP-AI-MONITOR2_V1.0.0/Utilities/Datalog/STWIN_config_examples/
directory.
Note : The configuration files are to be precisely named DeviceConfig.json
or the process does not work.
Step 3: Insert the SD card into the STWIN board
Insert an SD card in the STEVAL-STWINBX1.
Note : For data logging using the high speed datalogger user needs a FAT32-FS formatted microSDTM card.
Step 4: Reset the board
Reset the board. Orange LED blinks once per second. The custom sensor configurations provided in DeviceConfig.json
are loaded from the file.
Step 5: Start the data log
Press the [USR] button to start data acquisition on the SD card. The orange LED turns off and the green LED starts blinking to signal sensor data is being written into the SD card.
Step 6: Stop the data logging
Press the [USR] button again to stop data acquisition. Do not unplug the SD card, turn the board off or perform a [RESET] before stopping the acquisition otherwise the data on the SD card are corrupted.
Step 7: Retrieve data from SD card
Remove the SD card and insert it into an appropriate SD card slot on the PC. The log files are stored in STWIN_###
folders for every acquisition, where ###
is a sequential number determined by the application to ensure log file names are unique. Each folder contains a file for each active sub-sensor called SensorName_subSensorName.dat
containing raw sensor data coupled with timestamps, a DeviceConfig.json
with specific information about the device configuration (confirm if the sensor configurations in the DeviceConfig.json
are the ones you desired), necessary for correct data interpretation, and an AcquisitionInfo.json
with information about the acquisition.
9.1. DeviceConfig.json file
The DeviceConfig.json file contains the configurations of all the onboard sensors of STEVAL-STWINBX1 as JSON format. The object consists of three attributes deviceInfo, sensor, and tagConfig.
{
"UUIDAcquisition": "287cddd8-3f95-4449-9350-799d16296c2b",
"JSONVersion": "1.1.0",
"device": {
"sensor": [ ],
"tagConfig": { }
}
}
deviceInfo identifies the device.
{
"UUIDAcquisition": "287cddd8-3f95-4449-9350-799d16296c2b",
"JSONVersion": "1.1.0",
"device": {
"deviceInfo": {
"serialNumber": "000900115652500420303153",
"alias": "STWIN_001",
"partNumber": "STEVAL-STWINBX1",
"URL": "www.st.com\/stwin",
"fwName": "FP-SNS-DATALOG2",
"fwVersion": "1.2.0",
"dataFileExt": ".dat",
"dataFileFormat": "HSD_1.0.0",
"nSensor": 9
"sensor": [ ],
"tagConfig": { }
}
}
sensor is an array of attributes to describe all the sensors available on-board. Each sensor has a unique ID a name and sensorDescriptor and sensorStatus.
"sensor": [
{
"id": 0,
"name": "IIS3DWB",
"sensorDescriptor": { },
"sensorStatus": { }
},
{
"id": 1,
"name": "HTS221",
"sensorDescriptor": { },
"sensorStatus": { }
},
:
:
sensorDescriptor describes the main information about the single sensors through the list of its subSensorDescriptor. Each element of the subSensorDescriptor describes the main information about the single sub-sensor, such as the name, data type, sensor type, odr and full scale available, samples per unit of time supported, and measurement unit.
{
"id": 0,
"name": "IIS3DWB",
"sensorDescriptor": {
"subSensorDescriptor": [
{
"id": 0,
"sensorType": "ACC",
"dimensions": 3,
"dimensionsLabel": [
"x",
"y",
"z"
],
"unit": "g",
"dataType": "int16_t",
"FS": [
2,
4,
8,
16
],
"ODR": [
26667
],
"samplesPerTs": {
"min": 0,
"max": 1000,
"dataType": "int16_t"
sensorStatus describes the actual configuration of the related sensor through the list of its subSensorStatus. Each element of subSensorStatus describes the actual configuration of the single subsensor, meaning whether the sensor is active or not, the actual odr(output data rate), fs (full scale), etc.).
"sensorStatus": {
"subSensorStatus": [
{
"ODR": 26667,
"ODRMeasured": 0,
"initialOffset": 0,
"FS": 16,
"sensitivity": 0.000488,
"isActive": false,
"samplesPerTs": 1000,
"usbDataPacketSize": 3000,
"sdWriteBufferSize": 43520,
"wifiDataPacketSize": 0,
"comChannelNumber": -1,
"ucfLoaded": false
}
]
}
For us the only important configurations are isActive, odr, and fs. For details readers are invited to refer to the user manual of FP-SNS-DATALOG2 package.
- FP-AI-MONITOR2: Multi-sensor AI data monitoring framework on wireless industrial node, function pack for STM32Cube
- Quick Start Guide: QSG for FP-AI-MONITOR2
- How to perform anomaly detection using FP-AI-MONITOR2 : A step-by-step guide to implement an Anomaly Detection solution for a USB powered fan.
- STEVAL-STWINBX1: STWIN SensorTile Wireless Industrial Node development kit
- STM32CubeMX: STM32Cube initialization code generator
- X-CUBE-AI : expansion pack for STM32CubeMX
- NanoEdge™ AI Studio: NanoEdge™ AI the first Machine Learning Software, specifically developed to entirely run on microcontrollers.
- DBxxxx: Data brief for STEVAL-STWINBX1.
- UM2777: How to use the STEVAL-STWINBX1 SensorTile Wireless Industrial Node for condition monitoring and predictive maintenance applications.