Index by title

10 ChannelAnalog to Digital Converter with push buttons to change LCD display

Download demo file ADC10Ch.7z

1 MultiChannel ADC Examples

Purpose

To measure the voltage with a 10-channel analog to digital module and display the reading on the LCD display. With the help of a switch, readings from different channels can be seen as in Figure 1‑1.


Figure 1-1: Measuring voltage using 10 channels ADC and displaying it through the LCD.

Figure 1‑2 shows a Simulink Model for 10 channels ADC and displaying the voltage readings through LCD display. Subsystem model consists of a following attributes.

  1. Subsystem is used to define a variable to hold the voltage reading up to 10 channels.
  2. Subsystem settings for LCD display.
  3. Subsystem for displaying the values ​​obtained through the LCD.
  4. This subsystem can adjust the LCD display (page = 0 to 2) and receive input signal from the switch.
  5. Updating the page number of the current page after pushing the switch.
  6. Subsystem for the LCD display, showing the readings from channels 0-3.
  7. Subsystem for the LCD display, showing the readings from channels 4-7.
  8. Subsystem for the LCD display, showing the readings from channels 8-9.
  9. Digital input signal from the switch SW1 and SW2.
  10. Read the voltage from the 10 channel analog input.


Figure 1-2: Simulink Model for reading voltage using 10-channel and displays the results through the LCD

After downloading the model into STM32F4DISCOVERY, the module will start reading the voltage at 10 channels every 0.1 seconds. The values of the voltages will be stored in 10 variables (V1, V2, … , V10). This is shown in Figure 1‑3.


Figure 1-3: Subsystem for reading the voltage from 10 channel analog input

There are 10 readings which need to be displayed on a single LED screen and this is not possible. Therefore subsystem is made so to display readings from 0 to 3 at the start-up page. With the help of the switch, the display can be changed.


Figure 1-4: Subsystem for displaying the readings of the channels (0 to 3) on the LCD display

Figure 1‑5 shows the subsystem for adjusting the page number on display and receive input signal from two switching ports to see the next page and previous page. The subsystem will not work if no swtich is pushed.


Figure 1-5: Subsystem for adjusting the LCD display


About Matlab and Simulink

MATLAB is a programming platform designed specifically for engineers and scientists. The heart of MATLAB is the MATLAB language, a matrix-based language allowing the most natural expression of computational mathematics.

Simulink® is a block diagram environment for multidomain simulation and Model-Based Design. It supports system-level design, simulation, automatic code generation, and continuous test and verification of embedded systems. Simulink provides a graphical editor, customizable block libraries, and solvers for modeling and simulating dynamic systems. It is integrated with MATLAB®, enabling you to incorporate MATLAB algorithms into models and export simulation results to MATLAB for further analysis.

Waijung 2 is Aimagin's 2nd generation Simulink blockset. Waijung 2 blockset currently supports ESP32 microcontrollers by Espressif. Waijung 2 can be used to develop programs for ESP32 using Matlab / Simulink environment.

For more information visit,

What is Matlab?
What is Simulink?
Simulink documentation
Getting started with Matlab
Getting started with Simulink for controls
Waijung 2

Previous: System Requirements
Next: How to get Waijung 2?


ADC Block

How this block appears in a Simulink model?

appearance.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
ADC Module 1--2 The ADC driver API supports ADC1 (8 channels, attached to GPIOs 32 - 39), and ADC2 (10 channels, attached to GPIOs 0, 2, 4, 12 - 15 and 25 - 27).
ADC Resolution 9Bit--10Bit--11Bit--12Bit Specify sample time for the block
ADC attenuation 0DB--2.5DB--6DB--11DB Select attenuation
Select ADC channels Select channel pins

When to use this block?

Use this block for the application which need to process analog signal by software. Example, reading level of analog sensor (Temperature, Pressure, etc.), measure voltage and current from sensing circuit.

How does this block work?

This block will setup ADC reading function and return the reading value in every time step.

Demo

ADC demo

Previous : I2C Block
Next : DAC Block


ADC demo

Demo file : esp32_adc_demo.slx

Description

This demo shows how to read ADC value and control a digital output pin according to the ADC value using ADC Block and Digital Output Block.

Hardware Setup

Connect the variable resistance output to the ADC pin(GPIO33) and connect the digital output pin (GPIO2) to a LED.

What should be happening?

When the input voltage to the ADC pin is below 1.65V the LED will OFF and if it is above 1.65V the LED will turn ON.

Previous : I2C demo
Next : DAC demo


Advanced Table

ตัว module อยู่ที่ amgApi.coreLib.analytics.advancedTable2

Quick start
  1. การเรียกใช้โดยการส่งข้อมูล in-memory ตรงๆ
    const tableContainer = document.querySelector('.table-container')
    tableController = await amgApi.coreLib.analytics.advancedTable2({
        container: tableContainer,
        data: [
            ['col1', 'col2', 'col3', 'col4'],
            ["c1r1", "c2r1", "c3r1", "1"],
            ["c1r2", "c2r2", "c3r2", "2"],
            ["c1r3", "c2r3", "c3r3", "3"],
            ["c1r4", "c2r4", "c3r4", "4"],
            ["c1r5", "c2r5", "c3r5", "5"],
            ["c1r6", "c2r6", "c3r6", "6"]
        ],
    //columnLabel : ['customcol1', 'customcol2', 'customcol3', 'customcol4'],
    //init : false
    })
    
  2. การเรียกใช้โดยการดึงข้อมูลจาก Sqlite
    const tableContainer = document.querySelector('.table-container')
    tableController = await amgApi.coreLib.analytics.advancedTable2({
        container: tableContainer,
        data: {
            callback_getData: function (config, callback) {
                amgApi.sqlite.all({
                    sql: `SELECT * FROM ${tableName} ${config.getFullSQL()}`
                }, (getDataResponse) => {
                    callback(getDataResponse.rows)
                })
            },
            callback_getColumn: function (columnName, callback) {
                amgApi.sqlite.all({
                    sql: `SELECT ${columnName} FROM ${tableName}`
                }, (getDataResponse) => {
                    callback(getDataResponse.rows)
                })
            },
            callback_getCount: function name(config, callback) {
                amgApi.sqlite.all({
                    sql: `SELECT COUNT(*) FROM ${tableName} ${config.getWhereSQL()} `
                }, (countResponse) => {
                    const rowCount = Object.values(countResponse.rows[0])[0]
                    callback(rowCount)
                })
            }
        }
    })
    
  3. การเรียกใช้โดยปิด feature : checkbox คอล๊มปื , columnFilter , sort , responsive( พับคอลัมป์เมื่อย่อจอ )
    const tableContainer = document.querySelector('.table-container')
    tableController = await amgApi.coreLib.analytics.advancedTable2({
        container: tableContainer,
        data: [
            ['col1', 'col2', 'col3', 'col4'],
            ["c1r1", "c2r1", "c3r1", "1"],
            ["c1r2", "c2r2", "c3r2", "2"],
            ["c1r3", "c2r3", "c3r3", "3"],
            ["c1r4", "c2r4", "c3r4", "4"],
            ["c1r5", "c2r5", "c3r5", "5"],
            ["c1r6", "c2r6", "c3r6", "6"]
        ]
    }, {
        tableUI: {
            checkbox: false,
            sortFilter: false,
            columnFilter: false,
            responsive : false
        }
    })
    
  4. การเรียกใช้โดยการเพิ่มปุ่มที่ button bar ด้านบนตาราง
    const tableContainer = document.querySelector('.table-container')
    tableController = await amgApi.coreLib.analytics.advancedTable2({
        container: tableContainer,
        data: [
            ['col1', 'col2', 'col3', 'col4'],
            ["c1r1", "c2r1", "c3r1", "1"],
            ["c1r2", "c2r2", "c3r2", "2"],
            ["c1r3", "c2r3", "c3r3", "3"],
            ["c1r4", "c2r4", "c3r4", "4"],
            ["c1r5", "c2r5", "c3r5", "5"],
            ["c1r6", "c2r6", "c3r6", "6"]
        ]
    }, {
        buttonBar: {
            additionButton: [{
                id: "add1",
                side: "right",
                getDOM: function () {
                    return $(`<button class="btn btn-secondary btn-sm " data-toggle="title" title="addition 1" >ADD!</button>`)[0]
                }
            }]
        },
        tableUI: {
            checkbox: false,
            sortFilter: false,
            columnFilter: false,
            responsive: false
        }
    })
    
  5. การปรับหน้าตาของตาราง
    const tableContainer = document.querySelector('.table-container')
    tableController = await amgApi.coreLib.analytics.advancedTable2({
        container: tableContainer,
        data: [
            ['col1', 'col2', 'col3', 'col4'],
            ["c1r1", "c2r1", "c3r1", "1"],
            ["c1r2", "c2r2", "c3r2", "2"],
            ["c1r3", "c2r3", "c3r3", "3"],
            ["c1r4", "c2r4", "c3r4", "4"],
            ["c1r5", "c2r5", "c3r5", "5"],
            ["c1r6", "c2r6", "c3r6", "6"]
        ]
    }, {
        buttonBar: {
            additionButton: [{
                id: "add1",
                side: "right",
                getDOM: function () {
                    return $(`<button class="btn btn-secondary btn-sm " data-toggle="title" 
                                        title="addition 1" >
                                    ADD!
                            </button>`)[0]
                }
            }]
        },
        tableUI: {
            checkbox: false,
            sortFilter: false,
            columnFilter: false,
            responsive: {
                toggleIcon: {
                    expand: () => $(`<span ><i class="fas fa-plus"></i></span>`)[0]
                },
                visibleColIndex: [2],
                collapse: {
                    container: () => $(`<div class="row bg-danger border-top pt-2 mt-2 ml-0" ></div>`)[0],
                    col: () => $(`<div class="col-6 bg-success font-weight-bold"></div>`)[0],
                    row: () => $(`<div class="col-6 bg-warning"></div>`)[0]
                }
            },
            table: ({
                preElement,
                model
            }) => {
                return $('<div class="card "></div>')[0]
            },
            header: {
                container: ({
                    preElement,
                    model
                }) => {
                    return $('<div class="card-header text-center tableUI-sticky-top p-0  bg-success" ></div>')[0]
                },
                colContainer: ({
                    preElement,
                    data,
                    model
                }) => {
                    return $('<div class="row "></div>')[0]
                },
                col: ({
                    preElement,
                    data,
                    colIndex,
                    model
                }) => {
                    return $(`<div class="col border pt-2" >${data}</div>`)[0]
                }
            },
            body: {
                container: ({
                    preElement,
                    model
                }) => {
                    return $('<div class="card-body bg-dark"></div>')[0]
                },
                rowContainer: ({
                    preElement,
                    data,
                    rowIndex,
                    model
                }) => {
                    return $('<div class="row  pb-4 bg-danger" ></div>')[0]
                },
                row: ({
                    preElement,
                    data,
                    rowIndex,
                    colIndex,
                    model
                }) => {
                    const elementContainer = $(` <div class="col border rounded text-center px-3 py-2 bg-white text-dark align-middle" 
                                                    style="width:100px;cursor:pointer;">
                                                        <span>${data}</span>
                                                </div>`)
                    elementContainer.hover((e) => {
                        elementContainer.toggleClass(["bg-dark", "text-white"])
                        elementContainer.toggleClass(["bg-white", "text-dark"])
                    })
                    return elementContainer[0]
                }
            }
        }
    })
    

    Parameter
    ในการใช้งาน advTable จะมีพารามีเตอร์เป็น Object 2 ตัว
    advancedTable2({}, {})
    

Advanced Table Widget

Parameter
// กำหนดหน้าตาของตารางทั้งหมด ในแต่ละส่วน ตามที่ต้องการ
setParameter("table", "CellStyle", {
    // <table></table>
    table: {
        class: ["table-hover", "text-left"],
    },

    header: {
        // <thead></thead>
        container: {

            onCreateDOM: ({
                preElement,
                element,

            }) => {
                return $('<thead ></thead>')[0]
            }
        },
        col: {
            style: {
                "box-shadow": "none",
                "border-top": "none",
                "background-color": "white" 
            },
            class: ["lead"],

        },
    }

})

Aimagin Analytics Wiki

การใช้งาน Python scheduler

ตัวอย่างการวิเคราะห์ข้อมูลแบบครบวงจรด้วย Aimagin Analytics ใน 10 นาที

การเชื่อมโยงฐานข้อมูล


Aimagin Connect Block

How this block appears in a Simulink model?

appearance_internally.PNG

appearance_externally.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
MISO pin 0 to 33 Select MISO pin
MOSI pin 0 to 33 Select MOSI pin
SCK pin 0 to 33 Select SCK pin
CS pin 0 to 33 Select CS pin
SSID Enter preferred WiFi SSID.
Password Enter preferred WiFi password
IP Address Enter the preferred IP address
Max connections Enter the maximum number of connections allowed to be connected to the WiFi network.
Output User Active Status Check--Uncheck This parameter is used to check whether the user is active on the client side or not. To use this feature, client should be configured accordingly using Aimagin Connect.

When to use this block?

This block can be used to convert an ESP32 to a server that could host a web application created using Aimagin Connect.

How does this block work?

To use this block initially a web application should be designed using Aimagin Connect. It could be then exported and transferred to an SD card connected to an ESP32. Finally, this block should be uploaded to the ESP32 using Matlab Simulink. Then the user can access the created web application using the ‘IP Address’ specified in this block.
For this block to function, WiFi network should be setup in AP mode. This block automatically checks whether,
  1. ‘esp32_wifi_setup’ block is available in AP mode.
  2. ‘esp32_sd’ setup block is available.
    If either is not available, the mask of the block autonomously transforms itself allowing the user to configure the parameters of the missing block.

Demo

Create embedded web application with Aimagin Connect

Previous : SD Card Append Block
Next : SQLite Retrieve Data


Aimagin Connect Wiki

การสร้าง Aimagin Connect components

How to develop Aimagin Connect page that retrieve values from database

SMC IOT Terminal Design Case study

Advanced Table

File_API

SQL_Examples

UploadedFiles

Pivot_Widget

Advanced_Table_Widget

Map_Widget

htmlToPdf API

Database design


Welcome to Aimagin support portal.

There are two main public sources to get information and assistance for Aimagin's products and services, namely wiki and forum.

  1. Use this Wiki which contains reference documentation for the followings.
    1. Current systems
      1. Waijung 2 User Guide
      2. Smart Sensor User Guide
      3. Aimagin Analytics Wiki
      4. Aimagin Connect Wiki
    2. Legacy systems
      1. Waijung 1 online user guide
      2. Waijung 1 application notes
      3. Waijung 1 patches
      4. Smart sensor system
      5. RapidSTM32
  2. Use the Forum to ask questions and get support from the community. Specifically:
    1. Waijung 2 forum (ESP32)
    2. Waijung 1 forum (STM32, nRF51)
Note:
  1. To create a post in our forum you must complete the following steps.
    1. Register to use our support system here. Registration is not required to read the forum.
    2. Important!!! Activate your account by following the instructions sent to your registered email.
    3. After a successful registration sign in from here.

aMG 4-20 mA to WIFI Data Logger

Click to visit aMG 4-20mA to WiFi Data Logger product page.

Hardware Connections

The following pictures show aMG 4-20 mA to WIFI Data Logger and its components.

Component Functions Description
A Sensor input ports aMG 4-20 mA to WIFI Data Logger consists of four channels allowing the user to connect upto four sensors simultaneously. Each channel consist of two ports namely I in and I out that should be connected to a 4-20mA signal wire. Note that correct polarity must be observed.
B Power supply ground Both ports are interconnected and should be connected to the power supply GND.
C Power supply VCC Both ports are interconnected and should be connected to the power supply VCC (9-24 VDC).
D Status LED Power status indicator. Only one (bottom right) LED is functional. Other three LED are not in service.
E WIFI Antenna Antenna input connection.
F Enclosure locks This groove on either side of the device could be used to open the casing in order to access the SD card or any other internal component.

Technical Specifications

Electrical Specifications

WIFI Specifications

Inputs

SD card slot

Minimum requirements

  1. A WIFI access point to which aMG 4-20 mA to WIFI Data Logger will be connected, to sent data to a database server.
  2. A database server with RESTful API ready to receive data from aMG 4-20 mA to WIFI Data Logger.

How the device work

aMG 4-20 mA to WIFI Data Logger has two operating modes:

  1. Configuration mode
  2. Running mode

Configuration mode

aMG 4-20 mA to WIFI Data Logger always automatically enters this mode for at least 30 seconds after power up. This mode is for a user to configure aMG 4-20 mA to WIFI Data Logger as explained in Setting up the device section.

Therefore, whenever a user wants to edit configuration settings, power aMG 4-20 mA to WIFI Data Logger OFF and then ON again, by disconnecting and re-connecting the power supply, to enter configuration mode.

Running mode

When aMG 4-20 mA to WIFI Data Logger is powered on, it will enter Configuration mode automatically. The device will switch to Running mode as a result of one of the following,

In Running mode, aMG 4-20 mA to WIFI Data Logger will read the user defined configuration parameters and set it up accordingly. After the setup, aMG 4-20 mA to WIFI Data Logger will perform the following steps:

  1. Take measurements of ALL four input channels at the specified sample time.
  2. Convert the 4-20 mA raw readings to physical values as specified by the data conversion settings.
  3. Save both raw and converted data to the database in aMG 4-20 mA to WIFI Data Logger's SD card.
  4. Send both raw and converted data to the remote database server specified in settings.

Connect to aMG 4-20 mA to WIFI Data Logger

To configure aMG 4-20 mA to WIFI Data Logger, a user must connect to its WIFI hotspot which becomes available only in Configuration mode.
To enter Configuration mode, a user has to cycle the device power OFF then ON. The WIFI hotspot SSID for aMG 4-20 mA to WIFI Data Logger will become visible in any smartphone or computers WIFI scan.

As an example, if the uid of the device is 8caab59f1d80, the SSID will be 4-20mA-8caab59f1d80.

Note: DO NOT wait until the status of the WIFI connection is set to be " Connected " in the smartphone or the notebook computer. Once WIFI connection to the device is made, enter the following IP address 192.168.10.10 in a web browser right away. The connection takes time because the host system may look for internet connection, which is not possible with aMG 4-20 mA to WIFI Data Logger.

To login to aMG 4-20 mA to WIFI Data Logger, use the following username and password.

The current aMG 4-20 mA to WIFI Data Logger firmware does not allow changes to SSID, password, username and password.

Setting up the device

To setup aMG 4-20 mA to WIFI Data Logger, connect to it as described in Connect to aMG 4-20 mA to WIFI Data Logger.

The following configurations should be completed to setup aMG 4-20 mA to WIFI Data Logger.

  1. WIFI setting (So that aMG 4-20 mA to WIFI Data Logger can post data to database server. - Not needed if there is no need to log data to a database server.)
  2. Target server setting¶ (Specify web service API of the database server. - Not needed if there is no need to log data to a database server.)
  3. 4-20 mA conversion setting (To convert raw 4 - 20 mA measurements to meaningful physical values.)
  4. System setting (To set the measurement sample time and other parameters.)

WIFI setting

The WIFI settings can be configured using the WIFI configuration page as shown below. The user have to provide the SSID, password and other IP settings of a WIFI access point.
This feature allows aMG 4-20 mA to WIFI Data Logger to send data to any " RESTful API webservice enabled " database server that is connected to the same network.

Target server setting

The URL of the database server with RESTful API should be provided in this Target Server page

Note: If there is a secret key for the RESTful API database server, it should be provided in the Secret key section. The final URL of the server will be [ server url ]/[ secret key ]. If there is no secret key, the final server URL will be [ server url ]
If there is no database server or the target server setting is incorrect, data will not be sent to the database server and aMG 4-20 mA to WIFI Data Logger will only operate as a local data logger to its local SQLite database stored in the SD card.

4-20 mA conversion setting

This configuration section is used to define a conversion formula (in linear relationship format) that converts measured raw current data (4-20mA) to physically meaningful values. Conversion formulas are generally available and vary with sensor types. Consult the manufacturer of your sensor for this information. The configuration page is shown below.

Each channel has its own conversion setting. As an example consider the data conversion relationship of the SMC ISE30A-C6H-A pressure switch shown in the datasheet below.

If the pressure range is -0.1 - 1MPa, the required data to the above page is as below.

Note: The conversion assumes linear relationship.

System setting

This configuration page is used to setup system sample time interval, which is used for:

  1. Taking sensor readings.
  2. Logging data to the SD card.
  3. Uploading data to a database server.

This version of the firmware does not allow the setup of independent sample time for each channel. All three functions above are performed at the same sample time for all four channels.

Additionally, the two parameters setting of JSON data format, namely, organization id and table, corresponds to table name of the database server.

Note: Each sample time that the data is logged to the SD card and to the database server, the timestamp is stored in UNIX format.

Advanced topics

Example database server setup with Node Js and SQLite database

This is NodeJS example for creating a web service to store data submitted from client to SQLite database.
Client posts data to server at URL: http://localhost:8080/U4tfcUMqnwMxWrGLwNZKdWDMx2XGYfGgb2LzpZJdY6dVdQQ9ReJ377aJEBht6Rkk/insert (This url is only for local testing. http://localhost:8080 should be changed to correct URL.).
The data is in JSON format as shown below

{
  "id": "esp32",
  "table": "test_table",
  "column": [
    "c1",
    "c2" 
  ],
  "rows": [
    {
      "c1": 1,
      "c2": 982
    },
    {
      "c1": 2,
      "c2": 985
    },
    {
      "c1": 3,
      "c2": 988
    }
  ]
}

id is organization ID
table is table name
column is columns of data in rows.
rows is data to be inserted into table

**NodeJS must be installed.

To run this code:
1. extract web_service.zip
2. install sqlite3 using command: npm install sqlite3
3. start server using command: node server.js

To keep this web service running on server:
1. install pm2 on server using command npm install pm2
2. start the process using command pm2 start server.js

In web_server.zip,
./esp32/db/database.db
./server.js

In this case, the organization ID is parent folder that contains the SQLite database named database.db. Server.js is nodeJS code for creating web service.

In server.js:

const http = require('http');
const url = require('url');
const sqlite3 = require('sqlite3').verbose();

http.createServer(function(req, res){
    var qpath = url.parse(req.url, true).pathname;
    var data = "";
    res.setHeader("Access-Control-Allow-Origin", '*');
    req.on('data', chunk=> {
        data += chunk;
    }).on('end', ()=> {
        data = JSON.parse(data);
        if (qpath == '/U4tfcUMqnwMxWrGLwNZKdWDMx2XGYfGgb2LzpZJdY6dVdQQ9ReJ377aJEBht6Rkk/insert') {
            var params = [], values = [];
            data.rows.forEach(function(row) {
                params = params.concat(data.column.map(d=>row[d]));
                values = values.concat('('+data.column.map(d=>'?')+')');
            });
            var db = new sqlite3.Database("./"+data.id+"/db/database.db");
            db.run(`INSERT INTO ${data.table} (${data.column}) VALUES ${values}`, params, (err)=>{
                if(err) {
                    res.write("Failture: "+err.message);
                } else {
                    res.write("Success");
                }
                res.end();
            });
            db.close();
        } else {
            res.write(null);
            res.end();
        }
    });
}).listen(8080);

refs
https://www.npmjs.com/package/sqlite3
https://www.npmjs.com/package/pm2
https://nodejs.org/en/download/

Example database server setup with PHP and MySQL database

This is a PHP example for creating a web service to store data submitted from client to MySQL database.
Client posts data to server at URL: 127.0.0.1:8080/[work directory] (This url is only for local testing. http://l127.0.0.1:8080 should be changed to correct URL.).
The data is in JSON format as shown below

{
  "id": "esp32",
  "table": "test_table",
  "column": [
    "c1",
    "c2" 
  ],
  "rows": [
    {
      "c1": 1,
      "c2": 982
    },
    {
      "c1": 2,
      "c2": 985
    },
    {
      "c1": 3,
      "c2": 988
    }
  ]
}

id is organization ID
table is table name
column is columns of data in rows.
rows is data to be inserted into table

To install PHP and MySQL:
- on Window : https://codebriefly.com/how-to-setup-apache-php-mysql-on-windows-10/
- on Ubuntu : https://www.hostway.co.th/lamp/

To run this code:
1. Go to the working directory.
2. Start server using command: php -S 127.0.0.1:8080

In index.php:
To receive and decode posted data to query string example:

PHP service for one by one (one hardware one table)

<?php

# databaseconnect
$servername = "localhost:3306";
$username = "root";
$password = "test1234";
$dbname = "test_db";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

header('Access-Control-Allow-Origin: *');

if ($_SERVER['REQUEST_METHOD'] == "POST") {
    if ($_GET["id"] == "Du81QXQGE6uswzRxXUnagKarauJL80w6/insert") {

        # input json
        $inputJSON = file_get_contents('php://input');
        $data = json_decode($inputJSON, TRUE); //convert JSON into array

        # convert data
        $column = "";
        $values = [];
        $values_string = "";

        $column = implode(", ", $data['column']);

        foreach ($data['rows'] as $row) {
            $r = "";
            foreach ($data['column'] as $i => $col) {
                if ($i + 1 === count($data['column'])) {
                    $r .= '"' .  $row[$col] . '")';
                    array_push($values, $r);
                } else if ($i === 0) {
                    $r .= '("' . $row[$col] . '",';
                } else {
                    $r .= '"' . $row[$col] . '",';
                }
            }
        }

        $values_string = implode(", ", $values);

        # query sql
        $sql = 'INSERT INTO ' . $data['table'] . ' (' . $column . ') VALUES ' . $values_string;
        // print_r($sql);

        # insert to db mysql
        if (count((array)$data['rows'][0]) > 0) {
            if ($conn->query($sql) === TRUE) {
                echo "New record created successfully";
            } else {
                echo "Error: " . $sql . "<br>" . $conn->error;
            }
        }
    }
}

$conn->close();

PHP service more hardware for one table

<?php

# databaseconnect
$servername = "localhost:3306";
$username = "root";
$password = "test1234";
$dbname = "test_db";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
//echo 'Connected successfully';

header('Access-Control-Allow-Origin: *');

if ($_SERVER['REQUEST_METHOD'] == "POST") {
    if ($_GET["id"] == "Du81QXQGE6uswzRxXUnagKarauJL80w6/insert") {
        # input json
        $inputJSON = file_get_contents('php://input');
        $data = json_decode($inputJSON, TRUE); //convert JSON into array

        # convert data
        $column = "";
        $values = [];
        $values_string = "";

        $new_str = substr($data['table'], 11);

        array_push($data['column'], "hw_id");

        if (count((array)$data['rows'][0]) > 0) {
            for ($i = 0; $i < count($data['rows']); $i++) {
                $data['rows'][$i]['hw_id'] = $new_str;
            }
        }

        $column = implode(", ", $data['column']);

        foreach ($data['rows'] as $row) {
            $r = "";
            foreach ($data['column'] as $i => $col) {
                if ($i + 1 === count($data['column'])) {
                    $r .= '"' .  $row[$col] . '")';
                    array_push($values, $r);
                } else if ($i === 0) {
                    $r .= '("' . $row[$col] . '",';
                } else {
                    $r .= '"' . $row[$col] . '",';
                }
            }
        }

        $values_string = implode(", ", $values);

        # query sql
        $sql = 'INSERT INTO ' . substr($data['table'], 0, 10) . ' (' . $column . ') VALUES ' . $values_string;

        # insert to db mysql
        if (count((array)$data['rows'][0]) > 0) {
            if ($conn->query($sql) === TRUE) {
                echo "New record created successfully";
            } else {
                echo "Error: " . $sql . "<br>" . $conn->error;
            }
        }
    }
}

$conn->close();

. htaccess for rewrite URL


RewriteEngine On

RewriteBase /esp32_multi
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?id=$1 [L,QSA]

Default JSON format for web service messages

The JSON format of the data which sends from the device to the database server is as below.

{
   "id":"esp32",
   "table":"test_table",
   "column":[
      "datetime",
      "CH1_raw",
      "CH1_conv",
      "CH2_raw",
      "CH2_conv",
      "CH3_raw",
      "CH3_conv",
      "CH4_raw",
      "CH4_conv" 
   ],
   "rows":[
      {
         "datetime":"1606190122",
         "CH1_raw":0.000,
         "CH1_conv":0.000,
         "CH2_raw":0.000,
         "CH2_conv":0.000,
         "CH3_raw":0.000,
         "CH3_conv":0.000,
         "CH4_raw":0.000,
         "CH4_conv":0.000
      }
   ]
}

How to upgrade device's firmware

A new firmware may be provided on the corresponding product page to improve its functionalities or fix bugs.
To upgrade the firmware, the user have to be in Configuration mode. Once logged in to the device, go to firmware upgrade page as shown below.

Then browse the provided .bin file using file explorer by clicking on ADD FILE.

Once the file is selected click on Upgrade firmware button to upgrade.

It will automatically upgrade the firmware and reboot the device once the firmware upgrade button is clicked.

How to retrieve data from the SD card

Retrieve data using DB Browser for SQLite

aMG 4-20 mA to WIFI Data Logger is shipped with a SD card that is used to store both system data and measurement data ( data_table table in database.db) in SQLite databases.

Since web services may be interrupted, the data database stored in the SD card serves as a backup and can be accessed anytime by following the steps below.

  1. Remove the SD card from the device as described in How to replace the SD card
  2. Attach the SD card to a SD card reader and connect it to the computer.
  3. Download and install DB Browser for SQLite
  4. Open DB Browser for SQLite.
  5. Click Open Database . Browse and select the .../systems/system1/database.db file in the SD card.

  6. Click the Browse Data tab and select the Table : data_table. Here you can find the saved data from the device.
  7. To use an SQL query to filter data, click Execute SQL tab, type the command and click run icon

NOTE: The data stored in SD card are always stored with UNIX timestamp. The following SQL command is an example of retrieving data using human-readable date time format.

select timestamp,CH1_raw
from data_table
where datetime(timestamp, 'unixepoch', 'localtime')
between '2020-10-22 18:15:30' and '2020-10-22 18:18:30';

Export the database as a CSV file

Measurement data is stored in data_table table of the database.db, which can be exported as a CSV file using the following steps.

  1. Open the database.db file with DB Browser for SQLite.
  2. Select File->Export->Table(s) as CSV file...
  3. Select the table: data_table and click Save .
  4. A window will pop up where you could select the name and location of the CSV file to be saved.
  5. The user could use Microsoft Excel or any other similar software to open the CSV file.

How to replace the SD card

aMG 4-20 mA to WIFI Data Logger is shipped with a SD card. To replace the SD card with a new one, perform the following steps.

  1. Format a new SD card using FAT32 file system.
  2. Follow the instructions in How to remove the SD card, to remove the SD card.
  3. Copy all files and folders from the old SD card as shown in the following picture to the new SD card. If not all files and folders appear as shown in the picture, try view hidden file in Windows Explorer setting.
  4. Insert the new SD card to the device and reattach the casing.

NOTE: All files in the SD card are important for the functionality of aMG 4-20 mA to WIFI Data Logger and are 'hidden' by default except for the database.db file. Do not manually alter the content of any files because this can break the functioning of the device. In case if any files are accidentally deleted or damaged, the user can replace everything by downloading and extracting AMG_4-20mA.7z file inside the root of the SD card. Do Not put the extracted files within a subfolder in the SD card.

How to remove the SD card

To remove the SD card:
  1. Power off the device
  2. Open the casing from point F and remove the FiO Glide ESP32 board from the main board.
  3. At the back of the FiO Glide ESP32 is where the SD card is attached. Push the SD card to remove it as shown in the follwoing picture.

How to send data to Google sheets

Objective

This tutorial will demonstrate how to log data from ESP32 on a google sheet using the Waijung2 block-set.

Setting up the Google Sheet as server.

Step 1

Log in to your Google account and open a blank Google Spread Sheet.

Step 2

Change the document name and the sheet name as preferred and create the required columns.
In this example:

Step 3

Now the google sheets needs to be published as a web application which will be listening to web requests. For that we use Google Script. Now go to Tools -> Script editor. This will open up a new window to write the script. Copy and paste the code in the GScriptCode.txt file to the Google Script editor. Save the script with a preferred name. (Example: ESP32_Data_Log_Script).

Click here to find more information regarding Google Script.

Step 4

Go to Publish -> Deploy as web app.

In the pop-up window make the configurations as shown in the picture.

Click Deploy.

From the pop-up window click Review Permissions. This will open up a new windows to sign in to your Google account.

After Signing in the page in the new window will re-direct to a warning page. There click Advanced and click Go to yourscriptname (unsafe).

Then the page in the new window will direct to another page where you will be asked for permission to run the app. Click Allow .

Step 5

Copy and save the URL and click OK .

Your URL will look something like this:

https://script.google.com/macros/s/{yourkey}/exec

The yourkey is a unique key for that specific Google Sheet you created. Therefore do not share this key.

Step 6

To test the server open a browser and enter the URL below.

https://script.google.com/macros/s/{your-key}/exec?id=Sensor_Data&Sensor1=100&Sensor2=100

If everything is correct, the word 'success' will be shown on your web page.

Now if you go back to your google sheet you will be able to see your data (sensor1 = 100, sensor2 = 100) been logged.

Congratulations you have successfully setup your Google sheet as the server!

Setting up the ESP32 as the client

Now we just need to replicate what we did in Step 6 using ESP32. Download and open the data_logger.slx and make the following changes.

Save and upload the code to the ESP32 board.

In this example, as sensors a constant block and a counter block is used to simulate the program. You can replace them with your sensor readings.

Result

After uploading you will be able to see the sensor values being updated every 5 seconds to the Google Sheet.

Previous : HTTP Server demo
Next : How to connect a hardware to a Wi-Fi Access Point


Basic Image Processing for Moving Object Tracking

Download the tutorial files: moving_object_tracking_tutorial.7z (Note: Among other things you will need to have the Computer Vision System Toolbox to run these demos)

This tutorial aims at demonstrating how to use image processing to track a moving object.

We make these tutorials for use to test the up coming camera and image processing utility blockset for Waijung 13.11a, to be release in Nov 2013. So stay tuned…

This tutorial follows the Student Dave’s Tutorials! Basic Image Processing with Matlab, but in Simulink instead of Matlab m-file implementation.

We were able to watch just the 2 video tutorials by Student Dave’s (items 2 and 3 below) and implement this in Simulink in just 1 day without any prior image processing knowledge.

So the explanation is extremely comprehensive, easy-to-understand and, hence, highly recommended.

The Student Dave’s Tutorials! site also contains other simple-to-understand tutorials on such topics as Kalman filtering, Extended Kalman filtering, and Particle filtering.

If you have time, visit the Student Dave’s Tutorials! site and help make some donations to fuel these great tutorials with coffee and Ramen. :)

The followings summarize resources related only to this basic image processing tutorial.

  1. The main basic image processing tutorial site http://studentdavestutorials.weebly.com/basic-image-processing-with-matlab.html
  2. Excellent short Youtube video part 1 of 2 on the same topic: http://www.youtube.com/watch?v=8RbD4X8y65A
  3. Excellent short Youtube video part 2 of 2 on the same topic: http://www.youtube.com/watch?v=c-ZWNfoQmTA
  4. Image source files: https://docs.google.com/open?id=0BwvRg6SCVt_ndTFBUjJOT0F4Q0k
  5. Matlab source files: http://studentdavestutorials.weebly.com/uploads/1/3/1/3/13139014/find_hexbug.m

The followings summarize steps for moving object tracking:

  1. Subtract still background image from current image to keep only the moving (alien) object.
  2. Apply Guassian filter to smooth the image of the object.
  3. Apply Histrogram Thresholding to identify moving object more precisely.
  4. Compute object position in pixel XY co-ordinate.

Note: we used MakeAVI (http://makeavi.sourceforge.net/) to convert the original video file to individual images.

The followings display different Simulink model files for studying the algorithm progressively.

1) ex01_object_tracking_static_demo.mdl


Test moving object detection algorithm using static picture.


Tracking result

2) ex02_object_tracking_dynamic_demo.mdl


Track moving object from video.

Simulation results

3) ex03_object_tracking_offline_demo.mdl


The same as ex02_object_tracking_dynamic_demo above except that the background image is computed by averaging images from the first few seconds.

See this article http://aimagin.com/blog/real-time-moving-object-tracking-stm32f4-image-processing-algorithms/ for a real-time system implementation.


Bootloader and IAP protocol with Waijung blockset

Overview

This demo showing an example of implementation the run-time firmware upgrade, mostly used in the product that need features update, bugs fix at end user or located on network. Waijung Blockset provide blocks function to develop this features, demonstration here tested with STM32F4 Target. The demo files are available for commercial and academic licensed users only.

Features

Flash memory organization (STM32F4, 1MB Flash)

Flash sector memory re-mapping

Communication type

IAP communication is data channel for receiving the new upgrade ROM. Depending on implementation in main program (user application) running, it can be UART, CAN or other.

Entry point and Sector validation (Sector B and C)

Sector B and C can be be validated by CRC32 and firmware signature, by using binary converter software to embedded these value into binary for upgrade ROM

CRC32 calculation

Polynomial: 0x4C11DB7
Initial value: 0xFFFFFFFF

const unsigned int crc_table[256] = {
0x00000000,0x04C11DB7,0x09823B6E,0x0D4326D9,0x130476DC,0x17C56B6B,0x1A864DB2,0x1E475005,
0x2608EDB8,0x22C9F00F,0x2F8AD6D6,0x2B4BCB61,0x350C9B64,0x31CD86D3,0x3C8EA00A,0x384FBDBD,
0x4C11DB70,0x48D0C6C7,0x4593E01E,0x4152FDA9,0x5F15ADAC,0x5BD4B01B,0x569796C2,0x52568B75,
0x6A1936C8,0x6ED82B7F,0x639B0DA6,0x675A1011,0x791D4014,0x7DDC5DA3,0x709F7B7A,0x745E66CD,
0x9823B6E0,0x9CE2AB57,0x91A18D8E,0x95609039,0x8B27C03C,0x8FE6DD8B,0x82A5FB52,0x8664E6E5,
0xBE2B5B58,0xBAEA46EF,0xB7A96036,0xB3687D81,0xAD2F2D84,0xA9EE3033,0xA4AD16EA,0xA06C0B5D,
0xD4326D90,0xD0F37027,0xDDB056FE,0xD9714B49,0xC7361B4C,0xC3F706FB,0xCEB42022,0xCA753D95,
0xF23A8028,0xF6FB9D9F,0xFBB8BB46,0xFF79A6F1,0xE13EF6F4,0xE5FFEB43,0xE8BCCD9A,0xEC7DD02D,
0x34867077,0x30476DC0,0x3D044B19,0x39C556AE,0x278206AB,0x23431B1C,0x2E003DC5,0x2AC12072,
0x128E9DCF,0x164F8078,0x1B0CA6A1,0x1FCDBB16,0x018AEB13,0x054BF6A4,0x0808D07D,0x0CC9CDCA,
0x7897AB07,0x7C56B6B0,0x71159069,0x75D48DDE,0x6B93DDDB,0x6F52C06C,0x6211E6B5,0x66D0FB02,
0x5E9F46BF,0x5A5E5B08,0x571D7DD1,0x53DC6066,0x4D9B3063,0x495A2DD4,0x44190B0D,0x40D816BA,
0xACA5C697,0xA864DB20,0xA527FDF9,0xA1E6E04E,0xBFA1B04B,0xBB60ADFC,0xB6238B25,0xB2E29692,
0x8AAD2B2F,0x8E6C3698,0x832F1041,0x87EE0DF6,0x99A95DF3,0x9D684044,0x902B669D,0x94EA7B2A,
0xE0B41DE7,0xE4750050,0xE9362689,0xEDF73B3E,0xF3B06B3B,0xF771768C,0xFA325055,0xFEF34DE2,
0xC6BCF05F,0xC27DEDE8,0xCF3ECB31,0xCBFFD686,0xD5B88683,0xD1799B34,0xDC3ABDED,0xD8FBA05A,
0x690CE0EE,0x6DCDFD59,0x608EDB80,0x644FC637,0x7A089632,0x7EC98B85,0x738AAD5C,0x774BB0EB,
0x4F040D56,0x4BC510E1,0x46863638,0x42472B8F,0x5C007B8A,0x58C1663D,0x558240E4,0x51435D53,
0x251D3B9E,0x21DC2629,0x2C9F00F0,0x285E1D47,0x36194D42,0x32D850F5,0x3F9B762C,0x3B5A6B9B,
0x0315D626,0x07D4CB91,0x0A97ED48,0x0E56F0FF,0x1011A0FA,0x14D0BD4D,0x19939B94,0x1D528623,
0xF12F560E,0xF5EE4BB9,0xF8AD6D60,0xFC6C70D7,0xE22B20D2,0xE6EA3D65,0xEBA91BBC,0xEF68060B,
0xD727BBB6,0xD3E6A601,0xDEA580D8,0xDA649D6F,0xC423CD6A,0xC0E2D0DD,0xCDA1F604,0xC960EBB3,
0xBD3E8D7E,0xB9FF90C9,0xB4BCB610,0xB07DABA7,0xAE3AFBA2,0xAAFBE615,0xA7B8C0CC,0xA379DD7B,
0x9B3660C6,0x9FF77D71,0x92B45BA8,0x9675461F,0x8832161A,0x8CF30BAD,0x81B02D74,0x857130C3,
0x5D8A9099,0x594B8D2E,0x5408ABF7,0x50C9B640,0x4E8EE645,0x4A4FFBF2,0x470CDD2B,0x43CDC09C,
0x7B827D21,0x7F436096,0x7200464F,0x76C15BF8,0x68860BFD,0x6C47164A,0x61043093,0x65C52D24,
0x119B4BE9,0x155A565E,0x18197087,0x1CD86D30,0x029F3D35,0x065E2082,0x0B1D065B,0x0FDC1BEC,
0x3793A651,0x3352BBE6,0x3E119D3F,0x3AD08088,0x2497D08D,0x2056CD3A,0x2D15EBE3,0x29D4F654,
0xC5A92679,0xC1683BCE,0xCC2B1D17,0xC8EA00A0,0xD6AD50A5,0xD26C4D12,0xDF2F6BCB,0xDBEE767C,
0xE3A1CBC1,0xE760D676,0xEA23F0AF,0xEEE2ED18,0xF0A5BD1D,0xF464A0AA,0xF9278673,0xFDE69BC4,
0x89B8FD09,0x8D79E0BE,0x803AC667,0x84FBDBD0,0x9ABC8BD5,0x9E7D9662,0x933EB0BB,0x97FFAD0C,
0xAFB010B1,0xAB710D06,0xA6322BDF,0xA2F33668,0xBCB4666D,0xB8757BDA,0xB5365D03,0xB1F740B4
};
unsigned int crc32_update(unsigned int initial, const unsigned int *data, int count)
{
int i;
unsigned int accum = initial;
for (i=0; i<count; i++) {
accum = (accum<< 8)^ crc_table[((accum>> 24)^ (data[i]>> 24))& 0xFF];
accum = (accum<< 8)^ crc_table[((accum>> 24)^ (data[i]>> 16))& 0xFF];
accum = (accum<< 8)^ crc_table[((accum>> 24)^ (data[i]>> 8 ))& 0xFF];
accum = (accum<< 8)^ crc_table[((accum>> 24)^ (data[i]>> 0 ))& 0xFF];
}
return accum;
}

Binary conversion tool

[sta,msg] = amg_iaptool_binconvert('source file','size','output file')

Example, run command at Matlab Command Window:

[sta,msg] = amg_iaptool_binconvert('stm32f4_user_app_stm32f4\stm32f4_user_app.bin','256k','stm32f4_user_app_convert.bin')

Bootloader startup sequence

Bootloader Demo

Model file

this demonstration imModel file, this demonstration implementing the Bootloader firmware. This model file will be program into sector A (Boot sector).

Demo model file: stm32f4_boot_256k.mdl

When “Boot” block located in the model and after build model, Waijung will generate call to function SYSTEM_BOOTLOADER() at file main.c.

Program Bootloader to device

This firmware will be program once from Auto Compile and Download or manual program via ST-Link tool.

User application and IAP protocol demo

Model file

File: stm32f4_user_app.mdl, this demo model disable auto compile and download.
The protocol of communication can be customized, in this demo use CAN Bus (CCP slave) for download ROM to upgrade.

Build and compile model file

This model need only compile, auto download will be disabled. The track build process show as below picture:

Target Setup

Configuration subsystem

Configure the CAN bus interface and memory used by CCP slave handler.

CCP Handler subsystem

Basic implementation for CCP slave. Only some command support in this demo.

CRO MTA Parser subsystem

Handle the memory transfer address.

Command Processing subsystem

This subsystem enabled only after receive CCP connect command. List of command support implemented in this demo:

Program the bootloader and user application firmware

  1. [sta,msg] = amg_iaptool_binconvert('stm32f4_user_app_stm32f4\stm3
    2f4_user_app.bin','256k','stm32f4_user_app_convert.bin')

The binary conversion tool will generate output file stm32f4_user_app_convert.bin with embedded CRC32 at the end of memory sector (256kB size).

  1. [err,msg]=system('"C:\Program Files (x86)\STMicroelectronics\STM32 ST-LINK Utility\ST-LINK Utility\ST-LINK_CLI.exe" -p "stm32f4_user_app_convert.bin" 0x8020000 -v -Q -rst')

IAP protocol demo

When the target run in User Application (programming done at previous step), then it is now able be handle the IAP protocol.

Overview

To program the Target board via IAP (CAN), Host PC need another STM32F4 or STM32F0 board with CAN interface to convert the UART command to CAN message, and also receive CAN message then convert to UART response back to Host PC. As shown below diagram.

CAN-Serial bridge

Build model file stm32f4_can_serial_bridge_binary.mdl to run as CAN-Serial Bridge device. The protocol is similar to below URL except the target board is STM32F4: http://waijung.aimagin.com/index.htm?can_to_serial_bridge.htm

Note for USB Converter used for USB to serial conversion

If use “aMG_USBConverter-N” or “aMG_USBConnect” for serial conversion, time for IAP may be reduced by set Latency to 1ms. Follow this instruction: http://waijung.aimagin.com/index.htm?latency_time_setting.htm

CAN bus message used in IAP demo

IAP testing (Via CAN-Serial Bridge)

Command line:

  1. [sta,msg] = amg_canserial_bridge(‘<function>’, <canid>,’<filename>’,’<sectorsize>’)

At Matlab command windows, run command as show in below picture.

Wait until IAP process to finish.


Camera Block

How this block appears in a Simulink model?

appearance.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
Stream mode to Aimagin Connect--to Matlab--to Target Select whether the camera feed should be streamed to Aimagin Connect, to Matlab Simulink or to Target ESP32.
Camera Module AIMAGIN Camera--Custom Camera Select the camera module.
Camera Pins Enter the camera pin connections.
XCLK frequency (Hz) Enter the clock frequency
LEDC TIMER Enter the LEDC TIMER
LEDC CHANNEL Enter the LEDC CHANNEL
Image Format RGB565--YUV422--GRAYSCALE--JPEG--RGB888--RAW--RGB444--RGB555 Select the image format.
Frame Size QQVGA--QCIF--HQVGA--QVGA--CIF--VGA--SVGA--XGA--SXGA--UXGA--QXGA Select the frame size of the camera feed.
JPEG quality 0 to 63 Enter the required quality of the image.
Number of frame buffers to be allocated Enter the number of buffer frames to be allocated.
Sample time (sec) -1 (inherited) or specify Specify the sample time

When to use this block?

This block can be used to stream the camera feed to,

How does this block work?

Demo

Camera demo

Reference

This block is based on the esp32-camera driver by Espressif.

Previous : vTaskDelay Block
Next : Mesh Setup


Camera Data Receiver Block

How this block appears in a Simulink model?

appearance_receiver.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
URL Enter the URL of the video stream. In the Camera Block mask description it is shown how the URL is generated.
Frame Width Enter the width of the expected frame of the video feed.
Frame Height Enter the height of the expected frame of the video feed.
Sample time (sec) -1 (inherited) or specify Specify the sample time

When to use this block?

This block is used to receive the video, streamed from the Camera Block via Matlab Simulink. Th is can also be used to receive the video feed from any IP camera to Matlab Simulink as well.

How does this block work?

This block only works for simulation and does not support code generation. For this block to function Host Setup Block block is required.

Demo

Stream video to Matlab Simulink

Previous : String Processing Block
Next : Host Setup Block


Camera demo

Stream video to Matlab Simulink
Stream video to Aimagin Connect
Stream video to Target


Circular Buffer Block

How this block appears in a Simulink model?

appearance.PNG

What can be configured?

Mode: Setup

Mode: Write

Mode: Read

Configuration Parameter Selectable Option/Value Description
Mode Setup--Write--Read Select the operation mode
Buffer Name Allocate the name of the circular buffer
Length of the buffer Number of dataset rows to be held
Input Format Data types of each data in a dataset row
Sample time (sec) -1 (inherited) or specify Specify sample time

When to use this block?

This block can be used to temporarily hold data to ensure no data loss when saving the data (for example: to a database) due to a blocking process.

How does this block work?

The number of datatypes the user specify in the Input Format parameter is the number of circular buffers which the block would create. All of these circular buffers will have a common head and tail index trackers. Length of the buffer parameter specify the number of indexes for each circular buffer. The circular buffer block will only work when activation signal input port is connected to Boolean 'true' signal.

Demo

Circular Buffer demo

Previous : Host Setup Block
Next : Digital Output demo


Circular Buffer demo

Prerequisites

Create a database in the SD card using an Database browser. The following query can be used.

CREATE TABLE "smc_4_20mA_data" (
    "timestamp"    INTEGER,
    "CH1_raw"    TEXT,
    "CH1_conv"    TEXT,
    "CH2_raw"    TEXT,
    "CH2_conv"    TEXT,
    "CH3_raw"    TEXT,
    "CH3_conv"    TEXT,
    "CH4_raw"    TEXT,
    "CH4_conv"    TEXT
);

Demo file : esp32_circular_buffer_demo.slx




Description

This demo shows a simple use case scenario for the circular buffer block. In this example data of 8 sensors (not actual sensors. Matlab Simulink blocks were used to mimic sensors) along with the UNIX timestamp needs to be inserted to the database. Inserting large amounts of data to a database could be a blocking process. Thus to ensure sensor readings are recorded every 1 second a circular buffer is used to hold the sensor data as an intermediate before writing to the database using the SQLite block.

Change the following configuration parameters in the model file.

In the WIFI Block In the SQLite NonRetrieveData

Hardware Setup

  1. ESP32 module with SD card reader
  2. WiFi connection with internet access

What should be happening?

When running the user could monitor INSERT commands to the database using a serial monitor. After a while the user could connect the SD card to a PC and check the sensor readings using a Database browser.

Previous : HTTP Server demo
Next : LEDC demo


Create embedded web application with Aimagin Connect

Objective

This tutorial shows how to use Aimagin Connect to design web applications and export it to ESP32 Aimagin Connect server

Designing web application on Aimagin Connect

Publish the web applications on Aimagin Connect

Once the web application is saved in Aimagin Connect, go to Save as Web app to create it as a web application as in the following figure and give a name for the web application

Then go to Web app under System Settings as in the following figure.

Click on create to create a publish a new web application.

Then give a name to publish the web application and select the web app that you want to publish and click on update to save the data

Next go to Permission page under System Settings to give the permission to the new web application

Then select your role and go to edit

Check the new web application under Web app | Permission and give the full permission by click on All button and Click on update to save the configuration. Then refresh the web page and the new web app will appear under the Web App in the left menu.

Export the web application to ESP32 Aimagin Connect

Once all the web applications are designed and published on Aimagin Connect go to export page to get all the web applications and other data to your device (laptop or desktop computer).

Then click on Export button to save the export folder.

Next extract the downloaded zip file. The extracted file directory should be as follows

Copy those folders to the root directory of the SD card and insert in to the ESP32.

Note: to tun the web applications on ESP32 a simulink model with Aimagin connect server in WiFi Access point mode is required.

Use the following test model to test the web applications on Aimagin Connect on ESP32.

aimagin_connect_test.slx

Previous : Integrate Legacy C code to Waijung 2 using s-function builder
Next : Modify Simulink generated C code


Creating and Using a Library (*a) for STM32F4 MCU with GNU GCC Compiler

Download demo file stm32f4_digital_output_demo_stm32f4.7z

How to Create a Library (.a) File

Objective: Combine waijung_hwdrvlib.c and stm32f4_digital_output_demo.c into libcustom_lib.a.

It is assumed that the source code were generated with Waijung Blockset. Hence, all the source code, make file, and autoexec (.bat) file are automatically generated and available.

Step 1 Create object file ( *.o) from the source ( *.c) file

Example Command

D:\waijung\trunk\waijung\utils\gnu_tools_arm_embedded\bin\arm-none-eabi-gcc -I . -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16 -ffast-math -Wall -Wextra -Ofast -std=c99 -c waijung_hwdrvlib.c stm32f4_digital_output_demo.c

Do not forget to change your working directory from DOS command prompt to where the source file resides.

Note

  1. D:\waijung\trunk\waijung\utils\gnu_tools_arm_embedded\bin\ is the path to GNU GCC bin files. In short, this is waijungroot\utils\gnu_tools_arm_embedded\bin\
  2. A lot of warning messages may appear. Ignore them for now.

As a result waijung_hwdrvlib.o and stm32f4_digital_output_demo.o are created.

Step 2 Convert the object ( *.o) file to a Library ( *.a) file

Example Command

D:\waijung\trunk\waijung\utils\gnu_tools_arm_embedded\bin\arm-none-eabi-ar -r libcustom_lib.a waijung_hwdrvlib.o stm32f4_digital_output_demo.o

combines waijung_hwdrvlib.o stm32f4_digital_output_demo.o in to libcustom_lib.a.

As a result libcustomcode.a is created.

Note

The library file must always begin with the word “lib”.

How to Include the Library in the Build Process

Step 1 Modify the Make File

Modify the make file (*.mk) as shown below.

Note

  1. Important!!! Ignore the prefix lib and the extension .a when including the library after the -l flag.
  2. -L. indicate that the path of the library is the current directory.

Step 2 Build

Build the system by running the bat file.

Example Command

stm32f4_digital_output_demo.bat

The binary file is generated and can be loaded to the target as usual.


DAC Block

How this block appears in a Simulink model?

appearance.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
Select DAC output pins GPIO 25--GPIO 26 Select the output pin/pins
Sample time (sec) -1 (inherited) or specify Specify sample time for the block

When to use this block?

Use the Digital to Analog Convertor (DAC) Block to generate analog signals.

How does this block work?

The DAC block takes inputs as raw data (between 0 - 255) and generated output analog signals according to the following equation.

Analog output voltage = VREF x INPUT / 255

Demo

DAC demo

Previous : ADC Block
Next : WIFI Block


DAC demo

Demo file : esp32_dac_demo.slx

Description

This demo shows how to use the DAC module with DAC Block. The DAC pin (GPIO25) generates a Sinusoidal Waveform with 0 - 2.56v with a frequency of 10 rad/sec.

Hardware Setup

Connect the DAC pin (GPIO25) to an oscilloscope to observe the wave form.

What should be happening?

The generated waveform should be as below

Previous : ADC demo
Next : WIFI demo


Database design

ชื่อ ตาราง
-เป็นตัวใหญ่ทั้งหมด
-ใช้ underscore ขั้นระหว่างคำ

ชื่อ field
-ชือเต็ม
-เป็นตัวใหญ่ทั้งหมด
-ใช้ underscore ขั้นระหว่างคำ

4 fields มาตรฐานที่ต้องมีในทุกตาราง
ชื่อ field : field description (คำอธิบาย)
ชื่อข้อมูล_ID: ไอดีของ... (ไม่ใช้คำว่ารหัสเพื่อป้องกันการซ้ำกับจำพวก CODE)
CREATED_DATE: วันที่สร้าง (ISO date ex. 2020-12-03 21:02:00)
MODIFIED_DATE: วันที่แก้ไข (ISO date ex. 2020-12-03 21:02:00)
CREATED_BY: สร้างโดย (กรณีระบบนำเข้าข้อมูลใส่ SYSTEM)
MODIFIED_BY: แก้ไขโดย (กรณีระบบนำเข้าข้อมูลใส่ SYSTEM)


DC Motors Control

Download demo file Motor_Encoder.7z

1 DC Motor Control

1.1 Introduction

DC motor is a device that converts electrical energy into mechanical energy. DC motor structure consists of two main parts: a permanent magnet and a coil. There is also a brush which is connected to an external electric power to the coils of the motor. When coil is powered on, there is a magnetic field around the coil.


Figure 1-1: Example of DC motor

Figure 1‑1 shows the basic structure of DC motor. There are two lines of the motor i.e. black (negative polarity) and red (positive polarity). Rotation of the motor is based on the application of the voltage polarity applied to the lines of the motor. Motor can rotate in clock and anti-clock wise direction. The speed of the motor can be decreased by controlling the voltage of the power supply. The DC motor is cheap and easy to use. Use of DC motor is widely found in daily use items such as small toys, electric bikes, robotic arms and industrial projects etc.

DC motors typically operate at a voltage level which is not suitable for microcontroller to work. Therefore, DC motor cannot be directly connected to the microcontroller but with the help of current driver.

1.2 Drive Current for DC Motor

DC motor drive current is mostly an H-Bridge circuit which consists of a transistor which acts as a switch of 4 units (Q1 to Q4) via a dedicated DC motor. Figure 1‑2 (a) shows the position of the transistors in the H-bridge which are responsible for controlling the current in the motor. When sending the control signal to Q1 and Q4, Q2 and Q3 will be disabled and the current will flow from A to B which will enable the motor to rotate in one direction. This is shown in Figure 1‑2 (b)

When the control signal is sent to Q2 and Q3, Q1 and Q4 transistors will be disabled and current will flow from B to A and the motor will rotate in reverse directions. This is shown in Figure 1‑2 (c).


Figure 1-2: H-Bridge circuit for controlling the rotation of DC motor

H-bridge circuit can be easily found in integrated circuit form such as L293D or L298N which helps in the reduction of size and make it easy to use. PWM direction control signals can be of 1 bit or 2 bits as shown in Figure 1‑3.


Figure 1-3: Connecting microcontroller with DC motor via control circuit

1.3 Equipment used in the Experiment

Figure 1‑4 shows aMG MotorCtrl2 board which is used in this experiment with a variable speed DC-Motor having a PWM signal on board which can drive current up to 1 A and can control the speed and direction of DC motor.


Figure 1-4: aMG MotorCtrl2 board

Figure 1‑5 shows how to control the direction of a DC motor using a control signal with the help of 2 bits which have 4 modes. These four modes are forward, reverse, brake and standby.


Figure 1-5: Using IC LB1836M [1, p. 3]

As far as choice of motors is concerned in this experiment, aMG MotorCtrl2 recommends using the interactive servo motor from Lego Mindstrom NXT. Following are the technical features of the motor.

  1. Gear set 1 : 48 for reducing the speed drive and increase torque at the tip;
  2. Encoder disc has 12 pulses per round. One round rotation can produce 180 pulses;
  3. The motor can run with a power supply of 7.5 – 9.0 V;
  4. Have RJ12 connector having current driver wire and also encoder signal wire.


Figure 1-6: Interactive Servo Motor (Image provided by LEGO education)

1.4 Adjusting the Speed of DC Motor with PWM.

Aim


Figure 1-7: Device for adjusting the speed of motor

Figure 1‑7 shows the devices used for controlling the speed of the motor. The procedure for conducting this experiment is as follows.

  1. Install aMG MotorCtrl2 board on aMG F4 Connect If have no aMG F4 Connect board, can connect 3.3V and GND with STM32F4DISCOVERY
  2. Stand-by voltage for motor should be from transformer (5 to 9.0 V) connected on the aMG MotorCtrl2 board at pin VS and pin GND3.
  3. Connect the pin PA5 Potentiometer to adjust the Duty Cycle of the PWM (pin PA0).
  4. Connect PA0, PC0 and PC1 with pin Pa, Da1 and Da2 respectively.
  5. Lego Motor connected to the port CN1.

Figure 1‑8 shows the Simulink model for the experiment for controlling the speed of the motor. It consists of PMW with fine duty cycle (with the help of variable resistor). SW1 and SW2 switches are used to control the direction of rotation of the motor.


Figure 1-8: Simulink model for testing the speed of the motor

Download the Simulink model on STM32F4DISCOVERY board and connect the power supply with external power source. When SW1 switch is press and hold, the motor will start rotating in one direction as shown in Figure 1‑9. When SW1 is released, the motor will gradually stop (Standby). When SW2 is press and hold, the motor will start rotating in opposite direction. When both switches (SW1 and SW2) are pressed, the motor will halt suddenly (Break).


Figure 1-9: Indicates the direction of rotation with respect to the switches

Question: If user wants to use Potentiometer to adjust both speed and direction of DC motor without push button switch?

If the read value is more than 1.75V (which is the middle position of the potentiometer), start forward rotation and rotate it at maximum speed (the read value will be 3.3V at maximum speed). If the read value is less than 1.75V, start reverse rotation and rotate it at maximum speed (at maximum speed the read value will be 0V).


Figure 1-10: Simulink model for controlling the motor with a potentiometer

To analyze the condition, Simulink model is shown in Figure 1‑10 and the description is as follows.

  1. When reading, the value turns out to be in between 0 and 4095. In order to remove the midpoint (which is defined at 2047), the switching of potentiometer is done during 2048-2047.
  2. The direction of rotation can be determined by examining the logic, if the reading is greater than or equal to 0, then motor will rotate in forward direction and if the value is less than 0 then motor will rotate in reverse direction.
  3. The rotation speed adjustment can be done through duty cycle of basic PWM block, however, the value of the duty cycle turns out to be in the range of 0 to 100. Therefore, the value read from DC module must be divided into two cases as shown in Figure 1‑10.

2 Reading for Software Encoder

Position control or motion with the help of motor have many applications in the field of automation and robotics. In order to improve the speed and accuracy of the work, feedback control system is very important. The data form the motor speed reading is fed back to the processor to adjust the appropriate control signals.

2.1 About Rotary Encoder

Rotary encoder is an electro-mechanical device that measures the angular position or speed of rotation of the axes. It consists of a circular plate which is mounted to the spindle. Light sensor and photo detector array reads the optical pattern that results from the disc’s position at any one time which is shown in Figure 2‑1. The resolution measurement depends on the number of slots per cycle such as encoders with 180 number of channels can measure an angle up to 360/180 = 2.0 degrees.


Figure 2-1: Structure of Rotary Encoder

When encoder’s axis starts rotation, channels on the disc will run through the light sensor. The photo detector on the receiving end will sense the light signal and when the sensor is connected with the signal circuit, the system can recognize how many degrees the motor has rotated.

From Figure 2‑1, one can observe that the discs are translucent in 2 rows and are overlapped. To detect the direction of rotation, such as the motor is rotating in clockwise (CW) direction or counter clockwise (CCW) direction, can be done by measuring the phase difference between the Channel A and Channel B signals. If the signals from Channel A is leading from signals of Channel B then the motor is moving in clockwise direction and if the signals from Channel A is lagging behind Channel B, then the motor is moving in counter clockwise direction and this is shown in Figure 2‑2.


Figure 2-2: Characteristics of the signals from encoder with a phase difference of 90 degree

In order to detect the direction of rotation, pulse requires two sets of decoder circuits to indicate the rotational direction. The CW and CCW rotation have 0 and 1 values respectively. Based on the readings of the decoder, the count signal will be increased or decreased.

In addition, another advantage of using signals with the phase difference of 90 is that the user can adjust the resolution of the count which is shown in Figure 2‑3.


Figure 2-3: Signal encoder interfaces Quadrature

Channel A signal is chosen to be a reference signal. When the rising and falling edges of the channel A is equal to 3 then the count is (x1). When the rising edges and falling edges of the signal is equal to 6 (which is two times the number of pulses of the signal) then the count is (x2). When the rising and falling edges of the signal is 12 then the count is (x4) which is actually four times the number of pulses of Channel A signal.

If the encoder disc has 180 channels then how to count four times? Since the number of channels per cycle is equal to 180 x 4 = 720 slots thus the lowest possible resolution is 360/720 = 0.5 degrees and so on.

STM32 microcontroller family with a detection module and external signal read signals from encoder software which is the part of timer module. When connected to a signal from the encoder, both Channel A and Channel B to the microcontroller, the counter will count up or down to the rhythm of the received signal. This allows the user to reduce the process of programming. Just set the timer modules per line and then the counter that counts is immediately applied.

In this section, description will be given, how to read values from STM32F4DISCOVERY board with encoder module and timer. All 15 modules that can interface with the encoder has 6 sets of timer 1, 2-5 and 8

This lesson will show how to read values from the STM32F4DISCOVERY board, encoder module with Timer, but all 15 modules that can interface with encoder has 6 sets of Timer 1, 2 – 5 and 8 [2].

2.2 How to use Encoder Read

The encoder block is in Simulink library >> Waijung Blockset >> STM32F4 target >> On Peripheral Chip >> TIM and have the following characteristics and properties.


Figure 2-4: Characteristics of Encoder Read Block

The purpose of Encoder Read Block is the count the signals from the encoder both from Channel A and B. If both channels are selected then the maximum count will be equal to 4 x pulse per revolution (PPS). The output direction is the direction of rotation which is either 0 or 1. If ‘reset counter after every count read’ is selected then the counter will be reset to zero after reading the count.

2.3 Reading the Angle of Rotation of the Motor

Aim


Figure 2-5: Circuit for experimenting with the encoded signal from encoder software

Figure 2‑5 shows devices which are used in this experiment for reading the signals from encoder with same set-up steps as in previous section experiment on speed adjustment but add the signal link, encoder and aMG USB Converter N board for sending position read from encoder through USB.


Figure 2-6: Simulink model for reading the signals from encoder software

Figure 2‑6 shows a Simulink model for this experiment to read signal from the encoder. It contains Subsystem block for controlling the speed of motor with Potentiometer and push button switch as in Figure 1‑8. The value from Encoder Read Block is unsigned 16 bit integer. Figure 2‑7 shows an example of converting read value to signed integer.


Figure 2-7: Method for converting Encoder Read Block to be a signed integer

Download the model on STM32F4DISCOVERY and then connect the USB cable to the computer and switch on the motor. The reading of the encoder will be displayed in TeraTerm window as shown in Figure 2‑8.


Figure 2-8: TeraTerm window reading the encoded signal

Value is in the unit of count pulses. To change the display unit such as degrees, user need to learn from the manual about the number of channels of the decoder end plate and then gain ratio of the transmission is adjusted accordingly.

For example, rotation of 1 revolution (360 degrees) of the pulse multipled by 4×180 to get 720 pulses per cycle if user wants to get the value in degrees.

Gain = 360 / number of pulses per revolution = 0.2.

To show the value of the unit.

Gain = 1 / number of pulses per revolution = 0.0014.

Signal oscilloscope is used to inspect the signal from pin Enc A1 and Enc A2 of aMG MotorCtrl2 board and is shown in Figure 2‑9.


Figure 2-9: Signal from the encoder measured at the oscilloscope

3 References

  1. ONSemiconductor, “LB1836M Low-Saturation Bidirectional Motor Driver for Low-Voltage Drive,” 2013.
  2. STMicroelectronics, “STM32 F407xx Datasheet-production data [Online],” 2013.
  3. STMicroelectronics, “RM0090: STM32F40xxx Reference Manual [Online],” 2013.
  4. Bartelt, Industrial Control Electronic: Device, Systems & Applications, Newyork: Thomson Delmar Learning, 2006.
  5. Denney, “Incremental Optical Encoder,” [Online]. Available: http://thedenneys.org/pub/robot/encoders/. [Accessed Wednesday February 2002].
  6. Hurbain, “NXT motor internals,” [Online]. Available: http://philohome.com/nxtmotor/nxtmotor.htm. [Accessed 11 June 2014].

Develop simple web application that retrieves values from database

Following example is based on retrieving the data from the selected table in the database. For this example, consider a database table with two columns (ID and name) and the web page which has two components; a drop-down menu and a text field. The drop down menu is used to select the ID. The content of ID drop down is automatically populated with ID data from the database. The Name text filed content automatically shows the corresponding name according to the selected ID, using change event callback. This example can be divided in to two sections.

  1. Creating the table
  2. Designing the web page

First login to the Aimagin Connect system using [Link]

Creating Table

To create a table in the database, go to Transnational database under Database in Tool Box.

Then go to create as in the following figure.

Then name the table as 'example' an add two columns ID and Name to the table and update the table as follow (NOTE: if the example table is already in the system use another name or use that created table because the table name cannot be duplicated in the system ).

Likewise add the Name column as ID column

Then update the table to create it.

Next the data should be added to the table. For that go to Data tab, find the table and click on insert to add data.

There are two records in this table. For the first row ID: 1 and Name: Mr.A and for the second row ID: 2 and Name: Mr.B as in the figure. Insert the data as follows.
Once the data is inserted to the each row, update it.

The final table should be as follows.

Now creating table section is completed. Next task is to design the web page.

Designing the Web Page

To design the web page, go to Aimagin Connect under Tool Box.

Then add a new page to the project and give a name to the page as in the following figure.

Then add the required components from the components pane. For this example, there are two main components; drop down menu and a text field. In addition to that put those two components under a container and add the text component under a row component and a column component as in the following figure. Change the label of the drop down menu in Parameter section to ID and the label of the text field to Name. And change the ID of the drop down menu and the text field as in the figure.

To automatically add the required ID numbers to the drop down menu, a callback function should be required. Initialize following function to the init callback to add the ID numbers from the database.

The ID data from the database should be saved as an array to add them to the drop down menu using 'setParameter'. The ID data can be acquired from the database using 'AmgCnt.SQLite.read.all'. The source code is as follows. The function 'AmgCnt.SQLite.read.all' is consisted with main parameter 'sql' to call the required sql.

var id_array = [];
var dropid = this.id;
AmgCnt.SQLite.read.all({
    sql: "select ID from example ",
    params: []
}, (res) => {
    if (res.rows != undefined) {         
        for (var i = 0; i < res.rows.length; i++) {
           id_array[i] = res.rows[i].ID;         
       }     
      setParameter(dropid, 'Options', id_array);
    }
console.log(res);
}); 

Note: if the table name is not as above change table in sql

 sql: "select ID from 'table_name' ",

Next add a function to change callback of the drop down menu to get the name of the person which corresponds to the selected ID number and show it in the text field when the selection of the drop down menu is changed. The callback function is as follows. The selected data in the drop down menu can be get using 'getParameter' and show the corresponding data in text field using 'setParameter'.

The source code for change callback function is as follows.

AmgCnt.SQLite.read.get({
    sql: "select * from example where ID = ?",
    params: [getParameter('dropId', 'Value')]
}, (res) => {

    if (res.row != undefined) {

        setParameter('txtName', 'Content', res.row.Name);
    }

    console.log(res);
});
 

In the callback function, first get the corresponding name from the database using 'AmgCnt.SQLite.read.get' function. Add the required SQL to the function. For this example write the sql to get data which is related to the selected ID value. After that, the acquired data should be displayed in the text field. For that, if the data is available display the name of the person using the 'setParameter' function.

The function 'AmgCnt.SQLite.read.get' is used to get the data from a single row and the function 'AmgCnt.SQLite.read.all' is used for getting data from all rows. Once the web designing is finished save the project using save button

If the web page is previewed and select an ID from the drop down menu it should be as in the following figure.


Develop web application for ESP32 to setup WiFi Station mode

This example shows how to design a web page to setup the WiFi configuration in station mode for ESP32 and another web page for showing some data using widgets.

Web Page Designing

Web page designing in Aimagin Connect is very user friendly and easy to use with dragging and dropping components and can be designed advanced web pages using it with a minimum knowledge on web designing. Developing most of the web pages for SMC on Aimagin Connect can be divided in to two sections.

  1. Designing the web page
  2. Creating the database table for data representation on web pages

Following documentation demonstrates developing each web page on Aimagin Connect step by step.

Developing WiFi Configuration page

Database table is used to save the WiFi configuration data to connect the ESP32 to the internet via wifi router to upload the data to a server. There are seven user input parameters(SSID, Password, Static or Dynamic selection, IP address, Subnet mask, Gateway and DNS) on this page. For each parameter, there should be a separate column in database table. Creating a new database table in Aimagin Connect is as follows.

Once login in to the Aimagin Connect server on the web go to Transnational database under Database in Tool Box as in the following figure.

Then go to create as in the following figure to create a new table.

Change the name of the table to wifi_config and click Add to add required columns to the table (Note: if the table cannot be named as wifi_config use another name.)

In column setting, add the required Column name and the suitable data type. In this scenario set the column name as SSID and the data type as TEXT. And then click OK to add that column to the table as in the following figure.

Likewise add the required remaining columns for the wifi_config table as follows and click Update to finalize the table.

For designing a web page go to Aimagin connect under Tool Box as in the following figure

Then click New and select New page on top menu to add a new page to the current project

Change the title of the page under property as in the figure. The title of the page will be displayed on the web browser tab.

The required components and widgets are in the Components section

First add a topic to the page. For that drag and drop a container on to the page. The container is under Grid in Components. Then drag and drop a Row on to the Container. If the Row component is dropped on the Container it will make a row inside the Container. Then drag and drop a Col component on the Row component to create a column inside the row. And after that drag and drop a Div component on the Col (column) component. Set the text align as center in Property panel of the Div component to align the text center. Then drop a Label component on the Div component. Click on the added label component and change the Content on Property panel to WiFi Configuration and change the other parameters as required as follows. The component tree will be as in the following figure.

Then add the required text fields, radio buttons and buttons to the WiFi config page. There are six text fields , two radio buttons and two buttons in this page. The six text fields are used to display and let the user to input SSID, Password, IP Address, Subnet Mask, Gateway and DNS. The two radio buttons are used to select the WiFi configuration in Static or Dynamic and the two buttons are used to submit and clear the form data. Before add those components, add a Container component and then add the other components as below. Change the labels and the IDs of the text fields and the radio buttons as in the figure below. The label for text fields can be changed in the Label parameter under the Parameter in text field property pane.

To add the options to the radio button, click on the radio button and go to edit in options under property panel.

Then add two custom options by clicking on Add custom options and name it as Dynamic and Static and save as follows.

Once the web designing is completed the connection between the database table and the web page components should be established. The main feature in this WiFi configuration page, Target Server page and the Analog input configuration page is once the page is loaded it will automatically show the saved data from the database table. For that a callback function should be implemented as follow.

First click on the page and click on the edit on init under event callback.

Add the callback function as below. Once the function is implemented click Save.

AmgCnt.SQLite.read.get({
    sql: "select * from wifi_config where ROWID = ?",
    params: ['1']
}, (res) => {
    setParameter('txtSSID', 'Content', res.row.SSID);
    setParameter('txtPassword', 'Content', res.row.Password);
    setParameter('rdiAccessPoint', 'Value', res.row.Access_P);
    setParameter('txtIP', 'Content', res.row.IP);
    setParameter('txtSubnet', 'Content', res.row.Subnet_m);
    setParameter('txtGateway', 'Content', res.row.Gateway);
    setParameter('txtDNS', 'Content', res.row.DNS);
    console.log(res);
});

In this callback function, the web page acquires data of the first row from the wifi_config table using AmgCnt.SQLite.read.get function with the suitable SQL and each column data from the table will be shown in the each web page component with the setParameter function. In this setParameter function the first parameter should be the Name of the component, the second parameter will be the parameter that you are going to change; for the text fields the parameter is the Content. The third parameter is the value; in this case the particular column data from the database table.

In the WiFi configuration the user select Dynamic in radio buttons the IP Adderss, Subnet mask, Gateway and DNS text fields should be disabled. It should enable when the user select Static in wifi configuration. For that a callback function should be implemented when the selection of the radio button is changing. Click on the radios component and click on the edit in the change event under event callback.

The callback funtion should be as follow. It basically disable those text fields if the selection is Dynamic. Otherwise it will enable the text fields.

var v = getParameter('rdiAccessPoint', 'Value');
!setParameter('txtIP', 'Enable', v=="Static");
!setParameter('txtSubnet', 'Enable', v=="Static");
!setParameter('txtGateway', 'Enable', v=="Static");
!setParameter('txtDNS', 'Enable', v=="Static");

Next the callback function for the Update button. For this the data in each text fields and the radio buttons should be inserted to the wifi_config table. Click on the Update button component and go to Edit of the mouseclick event under Event callback as follow.

Add the following functions to the mouseclick event

AmgCnt.SQLite.read.get({
    sql: "select SSID from wifi_config ",
    params: []
}, (res) => {
    if (res.row == undefined) {
        AmgCnt.SQLite.create.run({
            sql: "insert into wifi_config (SSID, Password, Access_P, IP, Subnet_m, Gateway, DNS) values(?, ?, ?, ?, ?, ?, ?)",
            params: [getParameter('txtSSID', 'Content'),getParameter('txtPassword', 'Content'),getParameter('rdiAccessPoint', 'Value'),getParameter('txtIP', 'Content'),getParameter('txtSubnet', 'Content'),getParameter('txtGateway', 'Content'),getParameter('txtDNS', 'Content')]
        }, (res) => {
            alert("Data has been inserted");
        });

    } else {
        AmgCnt.SQLite.update.run({
            sql: "update wifi_config set SSID = ? ,Password = ?, Access_P = ?,IP = ?, Subnet_m = ? ,Gateway = ?, DNS = ? where ROWID = ?",
            params: [getParameter('txtSSID', 'Content'),getParameter('txtPassword', 'Content'),getParameter('rdiAccessPoint', 'Value'),getParameter('txtIP', 'Content'),getParameter('txtSubnet', 'Content'),getParameter('txtGateway', 'Content'),getParameter('txtDNS', 'Content'),'1']
        }, (res) => {
            alert("Data has been updated");
        });
    }

    console.log(res);
});

In this event, the data in all components is gathered and saved in the wifi_config table. First the client checks whether the data is already in the first row in the wifi_config table. If it is not, the data will be inserted to the first row. If the data is already in the first row, it will update the first row with the current data. AmgCnt.SQLite.create.run function is used to insert the data to the table and AmgCnt.SQLite.update.run function is used to update the data with the current data. getParameter function is used to get the user entered data form the web component (from the text field or from radio button).

The last callback function is used to clear the data of the web page using the clear button. For that click on the clear button and go to mouseclick event of that button and add the following function to clear the data on each component (in text fields and radio buttons).

setParameter('txtSSID', 'Content', '');
setParameter('txtPassword', 'Content', '');
setParameter('rdiAccessPoint', 'Value', '');
setParameter('txtIP', 'Content', '');
setParameter('txtSubnet', 'Content', '');
setParameter('txtGateway', 'Content', '');
setParameter('txtDNS', 'Content', '');

Once the web page designing is finished save the project using the save button and preview the designed web page using preview button as in the following figure.

The final web page looks as follow. Try with adding data to the web page and submit those data. Once you load the page again it will show the last submitted data that you entered.

Previous : Develop simple web application that retrieves values from database
Next : Modify Simulink generated C code


Digital Input Block

How this block appears in a Simulink model?

appearance.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
Settings interface Basic--Advanced Allow user to adjust the level of control over the specified pins.
Select input pins Pino 0 to Pin 39 Select the output pins to be configured.
Pin mode None (floating)--Pull-up--Pull-down--Pull-up and Pull-down Only pins that support both input & output have integrated pull-up and pull-down resistors. Input-only GPIOs 34-39 do not.
Pin hold Enable--Disable The GPIO pad hold function works in both input and output modes but must be output capable GPIOs. If pad hold enabled: in output mode: the output level of the pad will be force locked and cannot be changed. in input mode: the input value read will not change, regardless the changes of input signal.
The state of digital GPIO cannot be held during Deep-sleep, and it will resume the hold function when the chip wakes up from Deep-sleep. If the digital GPIO also needs to be held during Deep sleep, gpio_deep_sleep_hold_en should also be called.
Deep sleep pin hold Enable--Disable Enable/Disable deep sleep pin.
Sample time (sec) -1 (inherited) or specify Specify sample time of the block

When to use this block?

This block implements Digital Input Module to generate digital input logic from MCU pin.

How does this block work?

Each block is used to configure pins of a specified block.

You can have as many Digital Input Blocks as you need in a model, to configure different pins of the MCU.

Demo

Digital Input demo

Previous : Digital Output Block
Next : GPIO Interrupt Block


Digital Input demo

Demo file : esp32_digital_input_demo.slx

Description

This example shows how to use the Digital Input Block on ESP32. The state of the digital input pin (GPIO 4) will be represented on the digital output pin (GPIO 2).

What should be happening?

Once the digital input pin is connected to a button and the digital output pin is connected to a LED when running the demo on ESP32 , the LED turns on when the button is pressed and the LED turns off when the button is released.

Previous : Digital Output demo
Next : GPIO Interrupt demo


Digital Output Block

How this block appears in a Simulink model?

appearance.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
Settings interface Basic--Advanced Allow user to adjust the level of control over the specified pins.
Select output pins Pino 0 to Pin 34 Select the output pins to be configured.
Initialize the above pins Check--Uncheck
Pin mode Push pull--Open drain
Drive capability Weak--Decent--Normal--Strongest Select drive strength of the pins.
Pin hold Enable--Disable Even though the GPIO pad hold function works in both input and output modes, it must be output capable GPIOs. If pad hold enabled: in output mode: the output level of the pad will be force locked and cannot be changed. in input mode: the input value read will not change, regardless the changes of input signal.
The state of digital GPIO cannot be held during Deep-sleep, and it will resume the hold function when the chip wakes up from Deep-sleep. If the digital GPIO also needs to be held during Deep sleep, gpio_deep_sleep_hold_en should also be called.
Deep sleep pin hold Enable--Disable

When to use this block?

This block implements Digital Output Module to generate digital output logic from MCU pin.

How does this block work?

Each block is used to configure pins of a specified block.

You can have as many Digital Output Blocks as you need in a model, to configure different pins of the MCU.

Demo

Digital Output demo

Previous : Target Setup Block
Next : Digital Input Block


Digital Output demo

Demo file : esp32_digital_output_demo.slx

Description

This example shows how to use the Digital Output Block on ESP32. The Counter Limited block is used to control the four digital output pins. The upper limit of the counter is 4.

What should be happening?

Once the four digital output pins (GPIO2, GPIO4, GPIO5 and GPIO18) are connected to the LEDs and when the demo file is running on ESP32, the LEDs should turn on and off with the following sequence with 1s per state

  1. State 1: GPIO 2 pin ON, all other OFF
  2. State 2: GPIO 4 pin ON, all other OFF
  3. State 3: GPIO 5 pin ON, all other OFF
  4. State 4: GPIO 18 pin ON, all other OFF
  5. State 5: all OFF

Previous : Host Setup Block
Next : Digital Input demo


File API

มี API สำหรับการอ่านไฟล์ให้

1. amgApi.coreLib.file.readCSV(fileObject, json)
สำหรับใช้อ่านไฟล์ CSV
มี parameter 2 ตัวคือ
1. fileObject เป็น Object ของ File ที่อ่านขึ้นมา
2. json เป็นตัวบอกว่าต้องการผลลัพธ์เป็น Array 2D หรือ Array ของ json

ตัวอย่างการใช้งาน

var files = getParameter('file-widget', 'Value');//ตัวอย่าง อ่าน value ของ file upload component จะได้ object ของ files หลาย files
amgApi.coreLib.file.readCSV(files[0], true).then(function(result) {
/*
result เป็น array 2D หรือ array ของ json ขึ้นอยู่กับการ set true/false ใน parameter ตัวที่ 2
json = true จะได้เป็น [{'col1':'value1', 'col2':'value2'}, ...]
json = false จะได้เป็น [['col1', 'col2'], ['value1', 'value2']]]
*/
});

2.amgApi.coreLib.file.readXLSX(fileObject, json)
สำหรับใช้อ่านไฟล์ XLSX (Excel)
มี parameter 2 ตัวคือ
1. fileObject เป็น Object ของ File ที่อ่านขึ้นมา
2. json เป็นตัวบอกว่าต้องการผลลัพธ์เป็น Array 2D หรือ Array ของ json

ตัวอย่างการใช้งาน

var files = getParameter('file-widget', 'Value');//ตัวอย่าง อ่าน value ของ file upload component จะได้ object ของ files หลาย files
amgApi.coreLib.file.readXLSX(files[0], true).then(function(result) {
/*
result เป็น array 2D หรือ array ของ json ขึ้นอยู่กับการ set true/false ใน parameter ตัวที่ 2
json = true จะได้เป็น [{'col1':'value1', 'col2':'value2'}, ...]
json = false จะได้เป็น [['col1', 'col2'], ['value1', 'value2']]]
*/
});

FiO2 and aMG Labkit – Blinky demo

1 Overview

2. Software requirements

3. Power on the board and checking ST-Link connection

Note: after finish checking the ST-Link connection, ST-Link Utilities must be closed, to prevent connection error while Waijung run the Auto Compile and Download process during model build

4. Build and Run existing demo file (provided in Waijung packet)

The demo files for STM32F4 is located in the demo directory: waijungroot\targets\stm32f4_target\stm32f4\demo\
To run the existing demo for LED blinky, follow below steps:


Note: Waijung root and model file path mode not containing space or unicode (non-English) character.

5. Demo for Create new model


FiO Glide – ANT – LDR-ADCDigital IO Demo

download all demo files: RF_ADC_IO.7z

Introduction

This demo will show you how you can use FiO Glide[name RF2] to read ADC value from LDR (aMG Photocell-A) then control an IO that drive an LED. Then send the read values (ANT protocol) to the second FiO Glide[name RF1], while RF1 also read its ADC value from LDR (another aMG Photocell-A) to control another LED. This second FiO Glide[name RF1] then gather all four values (ADC1,LED1,ADC2,LED2) and send via ANT protocol to the third FiO Glide[name RF0]. RF0 then read all values and send to PC via serial communication, then we use Simulink tools to display and plot values on scope.

Tools used

  1. Three FiO Glide
  2. Three aMG USB Connect with three USB cables
  3. Two aMG Photocell-A
  4. Two LEDs
  5. Some connecting wires

Connection Diagram for RF1 and RF2

Detail Explanation for RF1 and RF2

The Vin for aMG Photocell-A module is connect to +3.3V (Pin38) and GND to Pin25. Vsense is then connected to ADC port Pin22 (AIN7), user can connect ADC to other pin if needed. The output pin is Pin20 (AIN5 configured as IO output), this drive LED at the anode, the cathode then connect to GND. Since FiO Glide can drive current up to 5 mA, it is safe to drive an LED with out a current limiting resistor.

Expected Result

When user connect USB power to the three boards, LEDs will light up on RF1 and RF2 at office lighting condition. If user put a flash light on LDR with light intensity high enough, then LED will go OFF, and ON again if you remove flash light. This behaviors go the same on RF1 and RF2 modules. The values are sent to host PC and plot on Simulink scope. ADC values show in Volt and LED status show 1 and 0, representing ON and OFF status.

RF2 Model

RF1 Model

RF0 Model

Host Model

Limitation and Purpose

  1. The maximum data transmitting rate is 8 Hz (ANT protocol limitation)
  2. ANT protocol is best for multiple nodes communication on a network
  3. Each ANT TX/RX block can send/receive up to 8 bytes, for more data, please use more blocks
  4. For mobile application, user can provide 3V battery to FiO Glide and remove aMG USB Connect
  5. ANT protocol consume very little power from battery
  6. For point to point communication, user can use RF block which can provide much higher transmitting rate(100Hz and beyond)
  7. RF blocks consume much higher power from battery (more than 20x compared to ANT protocol)

Flash program to ESP32

Please follow video tutorial found in (https://drive.google.com/file/d/1ri3UblJqNCHNO0CJDECyfvXyqoCwTAe9/view?usp=sharing) or (svn\quasense\esp32 flash tools and video\)

1.Turn ON and connect ESP32 to the PC via USB

2.Download ESP32 flash download tools (https://www.espressif.com/en/support/download/other-tools)

3.Open the application and select ESP32 download tool

4.Download ESP32 bin files (provided by Aimagin separately)

5.Select the files and their offset values as shown in the video

6.Check the COM port typically use the lower value COM port

7.Apply correct COM port and buad rate and other settings as shown in video

8.Click start, this will show connection to board in the DETECTED INFO section (it is done just to verify connection to the board), if this step doesn't work please change COM port to the other one and try this step again

9.Now Select all the tick boxes for bin files and click START again

10.Wait for FINISH message, and then reset ESP32 (press reset button or turn off ESP32 and turn on ESP32)


Frequently Asked Questions

1 How can I get started?

This tutorial aims at teaching beginners how to use RapidSTM32 Blockset in ONE DAY (approximately 6 hours). After completing the tutorials, you will have enough basic knowledge to use the Blockset to implement a variety of basic but useful applications such as:

Yes!! all those within 6 hours, no kidding. We are truly taking about Rapid Prototyping. That's Why our duck can peel banana skin? :)

2 What is RapidSTM32?

RapidSTM32 LogoRapidSTM32 is a Simulink device driver blockset and tool suite for STM32 microcontroller family.

Ultimately, the blockset is expected to enable users to transfer their designs from Simulink, with just one click, to a working embedded system (based on STM32 microcontrollers) without the need to write a single line of C or Assembly code.

The blockset works by taking advantage of the Mathworks Inc.'s products, i.e. Real-Time Workshop and Real-Time Workshop Embedded Coder, code generation capability.

The blockset is not intended to be a comprehensive embedded target, allowing users to adjust every single bit in every single register.

Rather, its focus is on helping users (especially beginners in embedded systems) implement such complex systems or algorithms as event-driven real-time applications or Kalman filtering as Fast-Easy-Fun as possible without the need to understand RTOS or perform low-level device configuration or debugging.

Rapid STM32 bridges the gap between the high-performance graphical programing language, real-world applications, and the users with low-cost moderate-performance hardware.

3 Why RapidSTM32? Who needs it?

Ideally, RapidSTM32 is for anyone who needs to make use of an embedded system, a kind of a miniature computer on a single piece of Printed Circuit Board (PCB), but don't know how to or do not want to write a low-level program for it.

Basically, if you already know Matlab and want to do one of the following tasks:

  1. Bring in real world data from any kind of sensors into a PC.
  2. Control external hardware from a PC.
  3. Create an intelligent embedded system for any kind of stand alone applications such as.

Then RapidSTM32 is definitely for you.

RapidSTM32 can convert your Matlab program to a working system in just a few mouse clicks. All you need is standard Matlab tool suite, RapidSTM32 Blockset and FiO evaluation board. You do not need to write a single line of code.

Additionally, for students and lecturers in automatic control or DSP courses, RapidSTM32 Blockset will definitely help students:

Additionally, for students and lecturers in automatic control or DSP courses, RapidSTM32 Blockset will definitely help students:

Pictures are worth a thousand words.


The conventional Way of developing embedded systems.


The RapidSTM32 Way.

4 Why banana in RapidSTM32 Logo?

In Thailand, there is a saying "as easy as peeling a banana skin".

Our goal for RapidSTM32 is to make using microcontrollers as easy as peeling banana skin.

Thank you Viree for the Design.

Download our logo

Small Medium Large

5 What is STM32?

STM32 is a family of 32-bits ARM Cortex-M3 microcontrollers developed and marketed by STMicroelectronics.

ARM Cortec-M3 is based on ARMv7-M architecture which is not the same as ARM7. ARM7 microcontrollers are based on ARMv4 architecture.

Basically, ARM Cortex-M3 has been designed to improve upon and overcome several limitations of ARM7.

Read a Cortex - M3 white paper (An Introduction to the ARM Cortex-M3 Processor) from ARM Inc

This article reports a simple speed test between STM32 and other MCU.

6 RapidSTM32 Features

RapidSTM32 Blockset is offered with two sets of features:

  1. Limited-feature (Demo)
  2. Full-feature

Full-feature set is available only when FiO family of Evaluation Board (EVB) is physically connected to the host PC. FiO is a family of EVB that has been specifically designed to work seamlessly with RapidSTM32 Blockset and is offered at an affordable cost. In this respect, in addition to being an evaluation board, FiO is also a hardware key that enables the full features of RapidSTM32 Blockset.

Nevertheless, the generated source code is available for both full and limited features. "Therefore, in theory, even with limited-feature set you can modify the source code in anyway you like to suit your needs."

The following table lists and compares the features of RapidSTM32 Blockset.

Limited-feature Full-feature
Clock speed max. 24 MHz Unlimited
Digital IO Unlimited Unlimited
ADC 2 channels max. Unlimited
DAC 1 channel max. Unlimited
PWM 2 channels max. Unlimited
RTC Unlimited Unlimited
USART 2 element max. Unlimited
USB Virtual COM No Yes
USB HID No Yes
Character LCD Yes Yes
SD card No Yes
GPS NMEA Parser No Yes
GPS Simulation Blockset Yes Yes
Auto Compile No Yes
Auto Download No Yes
USB In Application Programming No Yes
USART In Application Programming No Yes

7 How does STM32 compare with other DSP microcontrollers?

Our choice to adopt STM32 is based on trade offs between price, performance, and ease-of-use.

We classify microcontrollers roughly in 3 groups.

In terms of performance TI C2000 is very powerful with 300MIPS (Delfino) and hardware floating point unit. However, it is neither cheap to get started (eZdsp kits start from $500+) nor easy to use in custom board with high pin counts (176+) LQFP or BGA package.

8-bits or 16-bits microcontrollers are cheap (starter kits may start from about $40) and they are easy to use in custom board. However, the performance is limited, e.g. 16-bits and 40MIPS max. for dsPIC33.

In our opinion, ARM Cortex-M3 offers the best compromise. It is comparable to 16-bits microcontrollers in terms of price (ARM Cortex-M3 development kits start from about $20) and ease-of-use in custom board. Additionally, with 32-bits and 90MIPS, it offers superior performance to 8/16-bits systems.

We did a simple test. We declare two variable a = 1.1 and b = 2.2. We time how fast the program execute this single line c = a*b; using built-in stop watches in MPLAB IDE and Keil RealView MDK. The results are as follows.

Time taken in micro sec (10^-6) to execute a single line of code "c = a*b"; where a = 1.1; and b = 2.2;

IDE MPLAB Keil RVMDK
Settings Optimization Level 3 Optimization Level 3 use MicroLIB Optimization Level 3 do not use MicroLIB
CPU (Running Speed) dsPIC33 (40MIPS) STM32F103RE (90MIPS) STM32F103RE (90MIPS)
a,b,c data type IEEE float (32 bits) 3 2.58 2.13
a,b,c data type IEEE double (64 bits) 8.125 5.88 2.54

Remark

  1. dsPIC float and double is the same (IEEE 32 bits) to declare IEEE 64 bits use long double.
  2. RVMDK - ARM 4.10

8 Minimum requirements

  1. Matlab 2009a (version 7.8)
  2. Simulink 2009 (version 7.3)
  3. Real-Time Workshop 2009 (version 7.3)
  4. Real-Time Workshop Embedded Coder 2009 (version 5.3)
  5. RealView MDK for ARM version 4.0
  6. Microsoft Windows XP SP2
  7. .Net Framework version 3.5

9 How much does RapidSTM32 Blockset cost?

RapidSTM32 Blockset itself is free and is released under BSD license.

At present, however, RapidSTM32 is NOT opensource.

RapidSTM32 Blockset is offered with two sets of features:

  1. Limited-feature
  2. Full-feature

Full-feature set is available only when FiO family of Evaluation Board (EVB) is physically connected to the host PC. FiO is a family of EVB that has been specifically designed to work seamlessly with RapidSTM32 Blockset and is offered at an affordable cost. In this respect, FiO EVB may be viewed as a hardware key that enables the full features of RapidSTM32 Blockset.

Nevertheless, the generated source code is available for both full and limited features. "Therefore, in theory, even with limited-feature set you can modify the source code in anyway you like to suit your needs."

For a comprehensive list of feature comparison please see RapidSTM32 Features.

10 Can the Blockset be used with non FiO boards?

Yes. But with some limitations.

See this demonstration on How to.

Basically, just select "Generic" target board and then select your MCU.


Configuring RapidSTM32 for uses with Non FiO

11 Where does the name FiO come from?

When we started works on the Blockset and the evaluation board, we noticed that it can perform the following FOUR functions:

  1. Data acquisition
  2. Signal generation
  3. Data logger
  4. Custom stand-alone applications

So, we called it Four in One (FiO).


Frequently Asked Questions (FAQ)


Getting Started with Waijung & STM32F4 Target

1 Introduction

In the previous chapter, we have discussed about MATLAB and Simulink, how we can use them and what are the advantages using these tools. In this chapter our prime objectives will be

We will start this chapter with minimum requirements.

2 Minimum Requirements

We can categorize the minimum requirements into two sections based on the software requirements and hardware requirements.

2.1 Software Requirements

Software requirements can be further classified into three categories and they are:

2.1.1 Operating System Requirements

Above mentioned operating system can either 32 bits or 64 bits.

2.1.2 MATLAB Tool Suite

Mathworks Inc. software suite consisting of the following toolboxes and blocksets.

Table 1: Required tools for MATLAB/Simulink

2.1.3 Waijung Blockset

Please note that Waijung Blockset supports both 32-bits and 64-bits operating systems, as well as, MATLAB 32-bits and 64-bits versions.

https://launchpad.net/gcc-arm-embedded

https://www.keil.com/demo/eval/arm.htm

http://supp.iar.com/Download/SW/?item=EWARM-KS32

2.1.4 STM Microelectronics ST Link Utility

ST Link Utility enables automatic flash programming directly after the build process as well as in-circuit debugging. Details regarding installation of ST Link Utility will be discussed in Hardware Requirements section.

2.2 Hardware Requirements

Waijung Blockset and STM32F4 Target support a complete range of STM32F4 family of Hi-Performance & Digital Signal Processing (DSP) Microcontroller Unit (MCU). However, the cheapest and fastest way to get started is to test out the blockset with the STM32F4 DISCOVERY Kit which is a low-cost development Kit from STMicroelectronics. For as low as US$ 15, STM32F4DISCOVERY Kit can be purchased directly from Aimagin website from the following link.

https://www.aimagin.com/stm32-f4-discovery.html


Figure 1: STM32F4 Discovery

Following are the features of STM32F4 Discovery

3 Installation of Drivers for aMG USB Converter – N

The aMG USB Converter – N consists of two chips which are stacked together. On the left hand side of Figure 2, reader can see the two chips stacked together and in the middle and right hand side, reader can see both chips separately. The drivers for aMG USB Converter comes along with the package of Waijung but it is recommended to install the most up to date Virtual COM driver from FDTI website from the following link depending upon which operating system the user is using.

http://www.ftdichip.com/Drivers/VCP.htm


Figure 2: aMG USB Converter – N

Now the question comes, why we need to do this. The answer is very simple. It is very essential for Hardware Inter Loop (HIL) test and help the MATLAB/Simulink to communicate with the embedded target in real time for open loop and close loop up to 2 KHz and 1 KHz respectively. However actual performance depends on computer and software running on the system.

Once the drivers are installed, the user need to check whether the drivers are installed properly. This can be done by going to Device Manager of the operating system and looking at the Ports (COM & LPT). This hardware has two serial to USB port. By default aMG USB Converter N will be connected to channel 1 (normally the smaller port number).


Figure 3: Device manager showing two COM ports


Figure 4: Checking if the device is working properly

In order to make the embedded target work HIL in real-time environment, we need to change the port setting by going to USB Serial Port properties ->Port Settings -> Advanced. In the advanced settings of USB Serial Port properties, change the Latency Timer to 1.


Figure 5: Advanced settings for USB


Figure 6: Hardware connection

4 ST Link Utility Installation

Now the next step is to install ST Link Utility on the operating system. There is a slight difference while installation of ST Link Utility installation on Windows 7 and Windows 8 in terms of drivers as shown in Figure 7 but rest of the procedure is the same.

Before the user proceed further, he/she must make sure that installation of MATLAB/Simulink as mentioned in software requirements is complete. The first step is the download and install ST Link Utility which allows the communication between the target (STM32F4 board) and Simulink or PC. Furthermore ST Link Utility is also useful for programming the flash memory. ST Link Utility V2 can be downloaded from STMicroelectronics website. The direct link to download is as follows.

http://www.st.com/web/en/catalog/tools/FM146/CL1984/SC724/SS1677/PF251168

When the user will click on the page, then user need to scroll down where description as shown in Figure 7 will be given.


Figure 7: ST Link Utility Download options

Respective drivers can be downloaded based on the operating system installed on the computer and proceed with the installation. When the installation is done, connect the target. The target can be:

For STM32F4 Discovery, connect the target with the computer via USB as shown in Figure 8. STM32F4 Discovery has ST Link V2 debugger on the board.


Figure 8: Computer and STM32F4 Discovery connection

However FiO2 requires a separate debugger ST Link V2 which can be purchased from Aimagin website from the following link.

https://www.aimagin.com/st-link-v2.html

Go to the installed ST Link Utility and click on Connect to Target.


Figure 9: STM 32 ST Link Utility

If the target is not connected properly or/and hardware is malfunctioning, then error will be displayed which is shown in Figure 10.


Figure 10: Displaying error while connecting STM 32 ST Link Utility with the target

If everything is fine, then user can see window as shown in Figure 11.


Figure 11: Successful connection between STM 32 ST Link Utility and the target

Next is to go to ST-LINK->Update Firmware update. A new window will open as shown in Figure 12.


Figure 12: Updating Firmware

Then click on Device Connect as highlighted in red in Figure 12. If the firmware is not up to date it will give an option to update. Click on Yes to do so. Please note that if the user get error while updating the firmware then just unplug the target from the computer and connect it again. Re-try then.

5 Installing Waijung

Run MATLAB as administrator.

Go to the location on the local hard drive where waijung14_03a is available. Inside that folder there will be file named install_waijung.m. Open the file using MATLAB and click on Run.

Now the installation process will begin and it will take some time. If everything is OK then the user can see something similar like Figure 13. At the end of installation, MATLAB will pop-up Enable Automatic Update checking window will appear. It is strongly recommended to click Yes on that.


Figure 13: Waijung Installation

At the end, the use need to check if Waijung can communicate with the target. For that purpose, user should type waijung.checkTargetConnection and it will give options to select the target as shown in Figure 14.


Figure 14: Checking target connection using Waijung

There is a trick if waijung.checkTargetConnection is not working. Type waijung then press Tab button from the keyboard, it will display all possible functions using Waijung as shown in Figure 15.


Figure 15: Waijung functions

6 Recommendations

Following are the recommendations which users need to follow


GPIO Interrupt Block

How this block appears in a Simulink model?

appearance_GPIO.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
GPIO pin 0 to 15 Select GPIO pin to attach interrupt.
Trigger type Rising edge--Falling edge--Both edges--Low level--High level Select the interrupt trigger.
Interrupt priority level Auto--Level 1--Level 2--Level 3 Select the priority level of the interrupt

When to use this block?

This block can be used to set up an Interrupt Service Routine (ISR) that could be triggered by an input signal to one of the digital pins.

How does this block work?

Depending on the input trigger configuration, when the specified trigger conditions are met the block will output a logic ‘true’ signal that could activate a function call subsystem in Simulink.

Demo

GPIO Interrupt demo

Previous : Digital Input Block
Next : Timer Interrupt Block


GPIO Interrupt demo

Demo file : sp32_gpio_interrupt_demo.slx

Description

This demo shows how to use the GPIO Interrupt Block. A simple GPIO toggle function for the GPIO2 is implemented using Digital Output Block. This function will be invoked in every rising edge signal on GPIO5. GPIO4 pin is used to generate a square-wave pulse to test the the GPIO5 pin.

Hardware Setup

The digital output pin (GPIO2) should be connected to a LED to observe the status of the pin.

What should be happening?

The status LED (GPIO2) will be changed in every 1s period.

Previous : Digital Input demo
Next : Timer Interrupt demo


Host PC demo

Demo file : esp32_uart_hostpc_target_demo.slx

Description

This demo shows the UART communication between the host pc and the target ESP32 using UART Blocks. The user can send the string data (commands) to control or quarry data from ESP32 via COM port.

Software Setup

In this demo, the Docklight software is used to monitor the transmitted and received data from the host computer. The software can be downloaded from this link https://docklight.de/downloads/. The serial port configuration for this software is as below.

The transmitting data from the host computer

Hardware Setup

  1. ESP32 module
  2. aMG USB Converter-N
  3. Host PC

What should be happening?

There will be a response from the target module for each command from the host PC. For the command

Previous : Timer Interrupt demo
Next : UART two boards demo


Host Setup Block

How this block appears in a Simulink model?

appearance.PNG

When to use this block?

This block is used to setup the environmental variables required for Camera Data Receiver Block .

Demo

Stream video to Matlab Simulink

Previous : Camera Data Receiver Block
Next : Circular Buffer Block


How to configure device to connect to a Wifi Access Point

Objective

This tutorial shows how to use a web application to setup the ESP32 WiFi connection in Station mode to send data to a web server. It can be separated in to two steps.

  1. Design the web application in Aimagin Connect.
  2. Implement the Simulink model

Design the web application in Aimagin Connect

The designing of the web page is described step by step in Develop web application for ESP32 to setup WiFi Station mode.
Refer Webapp publishing and Exporting to ESP32 sections to get a better understanding about publishing a web application on Aimagin Connect and export those web apps to ESP32 Aimagin Connect server.

The final web page is as below

Implement the Simulink model

The procedure for this tutorial is as follows:

First the ESP32 should be initialized the WiFi in Access Point mode to initialize the Aimaigin Connect server. Then the user an be able to access the Aimagin connect server and configure the WiFi configuration using the created wep page in ESP32 for Station mode to connect to the internet to send the data to a server. After submitted the configuration data and logout from the Aimagin connect the ESP32 will get the WiFi configuration data from the database and switch the WiFi mode from Access Point mode to Station mode. Then the ESP32 connect to the internet and send the data to the target server.

Following figure shows how to setup the WiFi in AP mode

In the Subsystem the Aimagin Connect Server is setup and once the user is logged out from the server the output status from the Aimagin Connect server block goes to 0 and then the Aimagin Connect server stops. Then the SSID and Password data is acquired from the database which the user configured using the web page in the database subsystem as follows.

Databse subsystem:

In sending data to the server subsystem some dummy data is sent to the target server as in the following figure.

The results of the sent data to the server is as follows

The Simulink model file can be found below

wifi_station_setup.slx

Previous : Automatic Logging of data to Google sheets from ESP32
Next : Scheduling mechanism in Waijung 2


How to develop Aimagin Connect page that retrieve values from database

Following example is based on retrieving the data from the selected table in the database. For this example, consider a database table with two columns (ID and name) and the web page which has two components; a drop-down menu and a text field. The drop down menu is used to select the ID. The content of ID drop down is automatically populated with ID data from the database. The Name text filed content automatically shows the corresponding name according to the selected ID, using change event callback. This example can be divided in to two sections.

  1. Creating the table
  2. Designing the web page

Creating Table

To create a table in the database, go to SQLite under system settings.

Then go to create as in the following figure.

Then name the table as 'example' an add two columns ID and Name to the table and update the table as follow.

Next the data should be added to the table. For that go to insert to add data to the table.

There are two records in this table. For the first row ID: 1 and Name: Mr.A and for the second row ID: 2 and Name: Mr.B as in the figure.

Now creating table section is completed. Next task is to design the web page.

Designing the Web Page

To design the web page, go to Aimagin Connect under System Settings. Then add a new page to the project and give a name to the page as in the following figure.

Then add the required components from the components pane. For this example, there are two main components; drop down menu and a text field. In addition to that put those two components under a container and add the text component under a row component and a column component as in the following figure. Change the label of the drop down menu in Parameter section to ID and the label of the text field to Name. And change the ID of the drop down menu and the text field as in the figure.

To automatically add the required ID numbers to the drop down menu, a callback function should be required. Initialize following function to the init callback to add the ID numbers from the database.

The ID data from the database should be saved as an array to add them to the drop down menu using 'setParameter'. The ID data can be acquired from the database using 'AmgCnt.SQLite.read.all'. The source code is as follows.

var id_array = [];
var dropid = this.id;
AmgCnt.SQLite.read.all({
    sql: "select ID from example ",
    params: []
}, (res) => {
    if (res.rows != undefined) {         
        for (var i = 0; i < res.rows.length; i++) {
           id_array[i] = res.rows[i].ID;         
       }     
      setParameter(dropid, 'Options', id_array);
    }
console.log(res);
}); 

Next add a function to change callback of the drop down menu to get the name of the person which corresponds to the selected ID number and show it in the text field when the selection of the drop down menu is changed. The callback function is as follows. The selected data in the drop down menu can be get using 'getParameter' and show the corresponding data in text field using 'setParameter'.

The source code for change callback function is as follows.

AmgCnt.SQLite.read.get({
    sql: "select * from example where ID = ?",
    params: [getParameter('dropId', 'Value')]
}, (res) => {

    if (res.row != undefined) {

        setParameter('txtName', 'Content', res.row.Name);
    }

    console.log(res);
});
 

In the callback function, first get the corresponding name from the database using 'AmgCnt.SQLite.read.get' function. Add the required SQL to the function. For this example write the sql to get data which is related to the selected ID value. After that, the acquired data should be displayed in the text field. For that, if the data is available display the name of the person using the 'setParameter' function.
If the web page is previewed, it should be as in the following figure.


How to Drive a 7-Segment LED

download all demo files: Led7s4d.7z

1 Use of Peripheral Components

This chapter discusses the use of display devices such as LCD display and numeric display (7-segment display) using digital I/O along with STM32DISCOVERY and Waijung blockset

1.1 Introduction to 7-Segment Display

7-segment display consists of 7 LEDs which are arranged in trapezoidal or hexagonal shape as shown figure below. 7-segment comes in many colors and sizes in the market including one digit number, two digit number and four digital number which are widely used. Display information such as temperature, pressure, clock time can be seen easily with the help of 7 segment display.


Figure 1‑1: 7-segment display with common cathode and common anode

7-sergment display can be categorized into two types i.e. common anode and common cathode. Decoding for 7-segment display is shown in Table 1‑1 for common cathode. Supply voltage is set to be logic HIGH to turn ON the LED.


Table 1‑1: Decoding of 7-segment display for common cathode configuration

It is left as an exercise for the reader to make a decoding table for 7-segment display if the configuration is common anode.

2 Experiments for 7-segment Display

2.1 Equipment Used in this Experiment

Figure 2‑1 shows two aMG LEDs4d board which includes a 4 digit numeric display and 7 segment display which has a common cathode configuration (LTC-4727 JS series of LITE-ON. Figure 2‑2 shows the use of aMG LED7s4d with STM32F4DISCOVERY.


Figure 2‑1: aMG LEDs4d board [1] and pin positioning [2]


Figure 2‑2: 7-segment display using STM32F4DISCOVERY

2.2 Experiment with 7-segment Display Utilizing One Digit

Purpose


Figure 2‑3: Subsystem block for 7-segment display

The subsystem consists of multiport switch for selecting values in order to turn of the LEDs on the 7-segment as per Table 1‑1. For example, when input port is set to 3, multiport switch will send the value 0x79 or 1111001 to the output port. Default values for the LEDs is set to be 0x7E and there are 10 multiport switches available.

After creating a Simulink model for the 7-segment, numbers are shown from 0 to 9 (up-counting) with each second incrementing the counter. For accessing the Counter Block, user need to go to Simulink >> Waijung Blockset>> Misc. Use the number to display on 7-segment. The counting will keep on repeating.


Figure 2‑4: Simulink model for the experiment of single digit 7-segment

It is left on the user to find the answer if someone wish to do down-counting i.e. 9, 8, 7,…, 0 instead of up-counting.

2.3 Experiment – 7-segment Display with Two Digits

Purpose

Download the program as shown in Figure 2‑5 in STM32F4DISCOVERY. The program will count from 00 to 99 and counter will increment after every 1 second. Simulink model divides this task in two parts. In part A, the numbers from 0 to 99, the value of Counter Block is split. For example, 15 = 1×10 + 5. So index 0 of multiport switch is 5 and the first index is 1.

In part B, its function is to select the data to the subsystem block and the active common cathode by using counter limited block (upper limited: 1, sample time: 0.005) as a reference. If the value of the counter limited block is equal to 0, the subsystem block will display 5 and then the port K5 of a 7-segment will be activated. Therefore, a 7-segment will display 5 at the first digit. On the other hand, if the value of the counter limited block is equal to 1, the subsystem block will display 1 instead and the port K4 of a 7-segment will be activated and it will show 1 at the second digit, as shown in Figure 2‑6. For example, by operating the counter limited block at 200 Hz, the observer will obtain 15 at the 7-segment.


Figure 2‑5: Simulink model for the experiment of two digit 7-segment


Figure 2‑6: 7-segment representation for double digits

2.4 More Examples

This experiment is the application of STM32F4DISCOVERY to be used as a digital voltmeter by using an analog-to-digital converter module in order to obtain the voltage from an adjustable resistance and the obtained voltage will be displayed on a 7-segment. Moreover, the user can adjust the decimal position by using a switch. For example, the displayed value of 2.564 V will be displayed as 2.56 and 2.6 by applying the switch button once and twice, respectively.

A Simulink Model, shown in Figure 2‑7, is used for a voltage measurement and its value will be displayed on a 7-segment. It is consisted of many subsystem blocks as shown below.


Figure 2‑7: Simulink model for creating digital volt meter


Figure 2‑8: Subsystem model for adjusting the display of decimal places


Figure 2‑9: Subsystem block for factorizing integers


Figure 2‑10: Subsystem model for reading voltage

For a decimal number representation, 7-segment is able to adjust the data into an integer form and then open the LED DP or decimal point in an appropriate position. The value of 1.258 in mode 2 is shown in Figure 2‑11 (two digit decimal 1.258*100 = 125.8) can transform into 126.

For DP, by applying an output at port PD7 and display the decimal digit respected to the mode, the user will obtain 1.26 on a 7-segment.


Figure 2‑11: Digital volt meter using STM32F4DISCOVERY

Tips: from the experiment, the value which is lower than 1 (0.75 as an example) will be displayed as 00.75 for the two digit decimal or 000.8 for the case of one digit decimal. What should we do in order to obtain one zero on a 7-segment?

3 References

  1. Aimagin Co., Ltd. “aMG LED7s4d A Datasheet,” 2011. [Online]. Available: www.aimagin.com/amg-led7s4d.html

How to Drive a Character LCD

Download all demo files: clcd.7z

1 Using LCD Display

Computer users can read messages or see pictures via monitor such as Cathode Ray Tube (CRT), Liquid Crystal Display (LCD) and high resolution Light Emitting Diode (LED) monitors. It is not feasible to connect embedded systems such as microcontroller with big screens.

LCD display module as shown in Figure 1‑1 display simple text such as status of the sensor, temperature/pressure of an environment etc. This direct connection is easy to do and energy efficient as well.

1.1 Understanding the LCD Display

The LCD display includes a liquid crystal screen and control display (LCD controller). LCD controller is responsible for controlling the message on the display screen such as line spacing, line breaks and an ON-OFF pixel to represent a character or image. Character and language which is displayed on the screen depends on the manufacturer. For example, Hitachi HD44780 LCD controller supports English as well as Japanese characters [1].The LCDs which are connected to the microcontroller can be categorized into two types i.e. character LCD and image (graphical LCD) as shown in figure below.


Figure 1‑1: Character and graphical LCD­­­

It is worth mentioning that LCD has more features as compared to 7-segment display still it is easy to connect the LCD with the microcontroller as compared to 7-segment, although LCD costs more as compared to 7-segment display.

In Thailand, text LCD controller are more popular and graphical LCDs do not support Thai characters.

2 Experiment with LCD

2.1 Equipment Used for the Experiment

Figure 2‑1 shows the experimental set up for using aMG CLCD2, which includes a LCD display of size 16×4 and the board. When connecting the STM32F4DISCOVERY with aMG CLCD2, STM32F4DISCOVERY and aMG F4 Connect2 need to be powered through the adapter for fully functional display (normally STM32F4DISCOVERY is operational when powered through USB).


Figure 2‑1: aMG CLCD2 board

2.2 Two Line LCD Display

Purpose

In Waijung Blockset block, there is a related module called aMGCLCD2 in the library which can be accessed via Waijung Blockset>> Hardware Modules >> Character LCD. Figure 2‑2 shows the block parameters of Character LCD Setup. GPIO has two ports. One port can be used for sending control commands and other port can be used for sending text.


Figure 2‑2: Block parameters for Character LCD Setup

Now the question comes, how LCD knows where to send the data from the user within the LCD? The answer is simple. User need to mention the coordinates (xpos, ypos). (0, 0) is the point at the top left corner of the screen (which is the starting and reference point) and (15, 3) is at the bottom right corner, which is the last one.


Figure 2‑3: Characteristics of Character LCD Write Block

Character LCD Write Block is a text input block for display and is used for message passing using a two line LCD volatile data storage block. It is located in Simulink Library >> Misc >> Data Storage.


Figure 2‑4: Simulink model for two line LCD display

Figure 2‑5 shows the use of character LCD Write Block in two ways.

In variable ‘str1’, the default text is ‘Hello…’ and message ‘Welcome to Waijung’. Str2 contains number of letters and spaces.


Figure 2‑5: Two line LCD display

2.3 Experiment for Color LCD Display

Purpose

This experiment will display a text stored in a constant. User need to edit the model and download it again if wish to display data which changes over time such as counting the number or reading and displaying the value of sensor at regular intervals of time. This feature is not available for Character LCD Write Block because the type of the variable.

Print Block, located in the Library >> Waijung Blockset >> Misc serves as a decimal number converter (Double and Float) or an integer. It means that string can be displayed on the LCD. The Simulink model for the example explained above is shown in Figure 2‑6. Following are the settings for Printf Blocks.


Figure 2‑6: Simulink block for color LCD Display

CLCD and LCD display settings are shown in Figure 2‑7 and Figure 2‑8 respectively.


Figure 2‑7: Default settings for CLCD and assigning a string


Figure 2‑8: For color LCD display line


Figure 2‑9: Experimental results for color LCD display

The first two lines shown in in Figure 2‑9 are set to be fixed with no change throughout the experiment. The working of STM32F4DISCOVERY starts from line 3. The 4th line reflects the changes in the voltage when the value of variable resistor is changed.

2.4 Text Button Experiment

Purpose

Simulink model shown in Figure 2‑10 consists of Enabled Subsystem Block which can be found in the Simulink Library i.e. Simulink >> Ports & Subsystems. The program will work within Enabled Subsystem when the switch button in the Enabled Subsystem Block is ON. 4 lines are printed as shown as follows and information about the subsystem block is shown in Figure 2‑11.


Figure 2‑10: Simulink model for displaying text with keypad


Figure 2‑11: Subsystem block information

Download Simulink model into STM32F4DISCOVERY. When SW1 is ON message ‘FiO boards and Waijung Blockset is for anyone” will be displayed. When SW2 in pressed then the message “Embedded system is just a mini computer system” will be displayed on the LCD as shown in Figure 2‑12.


Figure 2‑12: Displaying different messages on LCD by pressing Switch buttons


How to Drive Stepper Motors and RC Servo Motors

download all demo files: stepper.7z

1 General Use of Peripheral

This article discusses the use of powered devices such as stepper motors and RC servo motor using STM32F4DISCOVERY and Waijung Blockset.

1.1 Introduction to Stepper Motor

Stepper motor is a motor with a step rotation. It is a brushless DC electric motor that divides a full rotation into number of equal steps. Step size can be of 0.9, 1.8, 5, 7.5, 15 or 45 degree per step which is controlled by using a Digital Signal Controller (DSC). DSC is also responsible for controlling the direction and speed of the motor. Applications of stepper motors can be found in many ways of life such as printer, motion control positioning system, plotters, slot machines, camera lens etc. Stepper motor has the following features;

Typical stepper motors (two phase stepper motors) can be divided into two categories: Unipolar and Bi-polar as shown in Figure 1‑1 and Figure 1‑2 respectively. A unipolar stepper motor has one winding with center tap per phase. Each section of winding is responsible (switched on) for each direction of magnetic field. A bi-polar motors have a single winding per phase and current in the winding need to be reversed in order to reverse a magnetic pole which makes the driving circuit little complex as compared to unipolar motors.


Figure 1‑1: The external and internal structure of unipolar stepper motor


Figure 1‑2: The external and internal structure of bi-polar stepper motor

Control rotation of Uni-polar stepper motor can be performed by controlling the current which is sent to coil of each phase in certain order. If we want to let current flow in any phase, that phase will have logic state “1”. We can control rotation of stepper motor by 3 approaches.

Single Phase Rotation Control or Wave Drive: To transfer current into coil of stepper motor, one by one as the sequence shown in Table 1‑1 (1 means voltage transferred into the coil, 0 means no voltage). So currents in coils will have same direction. This style will have result as low drive force in stepper motor, so it is not famous approach.

Table 1‑1: Single phase rotation control

Two Phase Rotation Control or Full Step Drive: To transfer current in both coils at the same time and transfer current consecutively as per Table 1-2. This technique gives more current to the motor and motor will have more power.

Table 1‑2: Two phase rotation control

Half Step Rotation Control: To transfer as Two Phase and Single Phase alternatively. This is shown in Table 1‑3.

Table 1‑3: Half Step rotation control

Speed ​​of rotation of the stepper motor axes is based on the time delay. If the time delay is less than the core will rotate faster and if the time delay is more than the core rotation will be slow.

1.2 Introduction to RC Servo Motor

Radio Control (RC) servo motor consists of a small electric motor driving a train of reduction gears. A potentiometer is connected to the output shaft which is responsible for measuring the position of the output. These values are then compared continuously with the commanded position of the radio control and in case of any difference between the output value and the commanded value, error signal is generated which instructs the motor to change its position accordingly. Due to RC servo motor light weight and cheap price, their applications can widely found in small scale robotics, steering of a car etc.


Figure 1‑3: Internal components for RC servo motor

2 Experiment for Controlling Stepper Motor

2.1 Equipment Used for this Experiment

Control devices such as stepper motor can be used to create a high driving torque flow. Microcontroller cannot be directly connected with the motor (as microcontroller pins cannot provide the required amount of current to run a motor) therefore current driver is placed between the motor and the microcontroller. For example, the board aMG Step Motor Driver IC ULN2003 can supply up to 500 mA current for controlling a unipolar stepper motor.


Figure 2‑1: Characteristics and features of stepper motor used for this experiment


Figure 2‑2: Using stepper motor with STM32F4DISCOVERY

2.2 Experimenting the Rotation Axis of Stepper Motor

Purpose of the Experiment


Figure 2‑3: Simulink model for controlling the rotation of single phase stepper motor

Table 2‑1: Simulink block model for controlling the rotation of single phase stepper

When users download Simulink model into STM32F4DISCOVERY aMG F4 Connect, the LED lights on the board (aMG Step Motor) will run in a sequence. The axis of the stepper motor will rotate at a constant speed (counterclockwise). Users can adjust the values of the Counter Limited Block Sampling time. This section will enable the users how to create Subsystem Block in Simulink for the use of stepper motors. Compared to writing a program in C for Subsystem Block, it is very convenient to do using Simulink as user only need to set the Input and Output ports. Creating and using Subsystem Block for the stepper motor involves the following steps;


Figure 2‑4: Creating Subsystem Block in Simulink


Figure 2-5: Subsystem model for controlling stepper motor (single phase)


Figure 2-6: Simulation model for controlling the stepper motor Subsystem Block

If users want to control the two phase rotation, this can be achieved by fixing the value of the Constant Block as shown in Table 1‑2: Two phase rotation control, Figure 2‑7 respectively.


Figure 2-7: Simulation model for controlling the stepper motor (two phase

If users want to control the phase rotation, this can be achieved by increasing the number of data ports in the Multiport Switch and fix the value of the Constant Block as shown in Figure 2‑8 and Table 1‑3.


Figure 2‑8: Simulation model for controlling the stepper motor (half phase)

2.3 Experiment for adjust rotation direction of stepper motor.

Objective of the Experiment:


Figure 2-9: Subsystem Model for Counter Up/Down

For block that is the important part to increase or decrease are Increment Real World and Decrement Real World (Library Simulink >> Additional Math & Discrete >> Additional Math: Increment – Decrement)

From Simulink (Figure 2‑10) set Constant Block Value = 3 to set CntUpdown to count value between 0-3 (note: If want to control half-phase, set Value = 7) and set Sampling Time = 0.005.


Figure 2-10: Simulink Model for rotation direction of stepper motor by push button switch

When Simulink model is downloaded into STM32F4DISCOVERY, then the Digital Input Block will read logic state from SW1 and SW2 (connected to pin PB2 and PB15) every 100ms and then send the signal to CntUpDown Block to control rotate direction. Results will be:

2.4 Experiment for adjust rotation speed of stepper motor with DIP switch.

Objective of experiment:

Rotation speed of stepper motor can be performed by time delay in each step. The disadvantage of Simulink model is users are unable to adjust Sample Time of Source Block in the model after downloaded into STM32F4DISCOVERY.

We can set the value of Subsystem Block to start or execute internal program when have external signal by put the Trigger Block in Subsystem Model (Fig. 2-11)


Figure 2-11: Adding Trigger Block in Subsystem Model

Add Digital Input Block to read signals from DIP Switch and Multiport Switch to select signal from Pulse Generator Block that have a pulse width 50% and setting period values as in Figure 2‑12.


Figure 2-12: Simulink Model for adjusting rotation speed of stepper motor with DIP switch

User can set DIP Switch as shown in table (in the above figure) to adjust rotation speed. For example, when all positions are set to OFF, CntUpDown Block will work every 0.005 second (positive edge signal will occur every 0.005 second) and stepper motor will rotate when SW1 switch is press and hold. When set DIP Switch all “ON”, system will go to Default condition then CntUpDown Block will be working every 0.02 second therefore the stepper motor will rotate slower.

2.5 Experiment for control position of rotor axis with push button switch.

Objective of experiment:

To study structure and able to control position of rotor axis with push button switch by rotating the axis 90 degree clockwise when SW1 is pushed and rotate the axis 90 degree clockwise when SW2 is pushed.

Controlling the axis is an open loop system because no signal from the sensor is sent back into microcontroller. Thus the system can know the position of rotor axis by number of steps that has been sent to stepper motor to let STM32F4DISCOVERY identify the current position of stepper motor’s axis. User can add the position calculation part into CntUpDown Subsystem Block (Figure 2‑13)


Figure 2-13: Subsystem Model for count step that sent to Stepper Motor

Position controlling of axis of stepper motor can follow these steps:

StepToGo = Desired Step – Current Step

From the properties of stepper motor in the experiment, Step Angle: 5.625 degree / 64 means motor rotate 1 step the axis will rotate 0.0879 degree, so if we want to rotate 90 degree.

Desired Step = 90 / 0.0879 = 1024 Step


Figure 2-14: Simulink Model for control position of the axis of Stepper Motor

After downloading the Simulink model into STM32F4DISCOVERY, the motor axis will rotate 90 degree counterclockwise or +90. When push reset, the current position will be deleted from memory so the motor will rotate again to the position +90.


Figure 2-15: Simulink Model for control position of axis of Stepper Motor with push button switch

3 Experiment for control RC Servo

3.1 Equipment for experiment


Figure 3-1: Using of Servo with STM32F4DISCOVERY

RC Servo receive digital signal to change the axis’s angle in the form of Pulse Width Modulation (PWM). Position controlling module of RC Servo will check time of signal at state “ON” or pulse width then adjust the position as programmed by its manufacturer. Figure 3‑2 shows the estimated width of ON signal for controlling the SG90 RC Servo with signal period 20ms. If user use other model of RC Servo they should study its detail in datasheet especially its voltage and pulse width.


Figure 3-2: Width of signal ON or %Duty Cycle for control position of RC Servo

3.2 How to use basic PWM Block

In the section Digital Input/Output is described using Pulse Generator Block to generate signal that user can only set the %Duty Cycle in the block. In this section, we will also describe how to use Basic PWM Block to generate PWM using Timer of STM32F4DISCOVERY. User can select Timer and Channel to send signal to external devices such as RC Servo or DC Motor controller and able to configure the %Duty by Simulink.

The basic PWM Block is in Simulink library >> Waijung Blockset >> STM32F4 target >> On Peripheral Chip >> TIM that has the properties as given below.


Figure 3-3: Properties setting of Basic PWM Block

3.3 Experiment for control RC Servo position with DIP switch

Objective:


Figure 3-4 Simulink Model for control RC Servo position by DIP switch

Figure 3‑4 shows Simulink model for control RC Servo position by DIP switch. Digital Input Block read the signal from DIP-SW1 and DIP-SW2 which are connected to PE3 and PE4 respectively. Received signals will be translated to decimal form (between 0-3). Multiport Switch will select %Duty Cycle related to Index and then send to Basic PWM Block.

After downloading the program into STM32F4DISCOVERY, PWM signal will be sent to RC servo. As a result, the motor will rotate to the position of %Duty Cycle of PWM signal. When all DIP switch are at the position “OFF” – rotated to the -90 degree position. When all DIP switch are “ON” – rotated to the +90 degree position. When SW1 is ON then motor will rotate to -45 degree and when SW2 is ON the motor will rotate to the 0 degree or origin.

Problem: If user wants to set RC Servo to be at 0 degree (Pulse Width = 1.5ms), what %Duty Cycle of PWM is needed if signal frequency = 60 Hz?

Answer: Signal = 60 Hz means Period = 16.67 ms. Then %Duty Cycle can be calculate => 1.5ms x 100/16.67ms = 9.0 %


Figure 3-5: Experiment for control RC Servo with DIP Switch

3.4 Experiment for control RC Servo with Potentiometer

Objective:


Figure 3-6: Simulink Model for control position of RC Servo with variable resister

Figure 3‑6 shows Simulink model for controlling the position of RC servo with variable resister. ADC read electrical voltage at pin PA5 then that value will be transformed to %Duty Cycle by linear relation equation between ADC Value (0 – 4095) and %Duty Cycle as shown in Figure 3‑7.


Figure 3-7: Linear relation between ADC value and %Duty Cycle

RC Servo will rotate to any position depending upon the voltage value. When resistor is connected to the GND, motor will rotate to -90 degree position (%Duty Cycle = 2.5). When resister is connected to VDD (or 3.3 V), motor will rotate +90 degree position (%Duty Cycle = 12.5). Figure 3‑8 shows the positions of RC Servo at each value of voltage read from A5 pin.


Figure 3-8: Experiment to control RC Servo with potentiometer

4 References

  1. Kiatronics, “28BYJ-48 Stepper Motor,” [Online]. Available: http://www.sensors.co.nz/datasheet/28BYJ-48 Stepper Motor.pdf.
  2. The MathWorks, “Documentation Center,” The MathWorks, Inc., [Online]. Available: http://www.mathworks.com/help/simulink/ug/creating-subsystems.html
  3. Laidman, “Stepper Motors and Control, Part I – Unipolar Stepper Motor and Control,” 1999. [Online]. Available: http://www.stepperworld.com/Tutorials/pgUnipolarTutorial.htm.

How to get Waijung 2?

Visit Waijung 2 download page for instructions.

Previous: About Matlab / Simulink
Next: Waijung 2 installation


How to identify and use Microcontrollers’ pins

All microcontrollers have multiple pins and each pin is assigned for some specific task. It is therefore very important to know the pin configuration of each microcontroller before using it. Some of the common features of microcontroller pins are as follows.

In order to set each pin’s function, user must set the functionality in the software by setting value in registers (it is similar to setting the functions in machine but machine has buttons or switches, but microcontroller has no button or switch, so we must set them by the software directly into the memory). It is the manufacturer who decides which pin is allowed to do what function(s). Although this document explain how to look pin function of microcontroller of type STM32F4, this technique can be applied to other types of microcontroller as well. Some basic things to note in a microcontroller are:


Figure 1‑1: How to analyze pins of microcontroller?

It can be observed that datasheet plays a fundamental role in finding information about the pins. In advanced microcontrollers, user might need to consult more than one relevant document together to extract the correct information.


Figure 1‑2: To check microcontroller belongs to which family


Figure 1‑3: To see which model of microcontroller STM32F407VG and with how many pins


Figure 1‑4: MCU STM32F407VG pins functionality


Figure 1‑5: To see which pin is 29 on the board

1.1 References

  1. STM32F4DISCOVERY Discovery kit for STM32F407/417 line Data brief http://www.st.com/st-web-ui/static/active/en/resource/technical/document/data_brief/DM00037955.pdf
  2. STM32F4DISCOVERYDatasheet http://www.st.com/st-web-ui/static/active/en/resource/technical/document/datasheet/DM00037051.pdf

How to Read Thermocouples

Download demo file Thermocouple_demo.7z

1 Use of Transducing Thermocouple

1.1 Introduction

Transducers, which are used for measuring the temperature, are of many types such as RTD, thermistor, and temperature sensing ICs etc. Thermocouples have exceptional properties which are mentioned as follows

Therefore it is a popular device [1] both for daily use applications and industrial purpose, for example, measuring the temperature inside the oven, gas turbine machine, diesel machine, and industrial process.

Some disadvantages of thermocouple are: very less linearity compared to RTD or specific designed IC (those are more sensitive and accuracy). Moreover, output signal of thermocouple is very low (estimated 40 mV/°C for K-Type thermocouple). Users have to use complex signal adjustment circuit for high resolution, signal amplification, signal compensation, etc [2].

Despite of the disadvantages mentioned above, the advantages prevail and they are very popular choice now days.

1.2 What is a Thermocouple?

Thermocouple is a device which is used for measuring differential temperature. Thermocouples are made up of two different metals. One is set to be positive type metal and another one is set to be negative in nature. Table 1‑1 shows the properties of each thermocouple [3]. Each type has different range of measurement.

Table 1‑1: Types and properties of each thermocouples

If we connect two different type of metals as shown in Figure 1‑1, electric voltage that is created in the circuit due to difference of temperature between two points is known as “Seebeck”. The process to convert temperature into electric voltage is given in equation (1).


Figure 1‑1: Working of thermocouple that results from Seebeck phenomenon

Figure 1‑2 shows the principal of general thermocouple. Two lines of metal are connected from the end and another end is left open, having connection to third metal (copper wire). Copper wire is the electrical medium between the two metals and the system which results in an additional connection point. As long as the temperature of the two connections and copper wire are equal, there is no effect on the output voltage (Vout)


Figure 1‑2: Principle of general thermocouple

Following relations govern the principle of thermocouple.

V out = V H – V C ........................................................(1)

V out = α(T H – T C) ....................................................(2)

where;

Thermocouple, which is shown in Figure 1‑2, the output voltage is the function of product of difference between temperature at hot and cold junction and Seebeck coefficient and is expressed in (2). Thus when we know the temperature at the cold junction and output voltage, we can know the real temperature at hot junction.

Considering a simple example, if the temperature at cold junction is 0°C (Tc = 0°C) then Vout = V H. In this case, the measured temperature will be the same as that of hot junction. Referring to the National Bureau of Standards (NBS) which lists the relationship of electric voltage and temperature of each thermocouple with reference to the cold junction at 0°C.

Setting the cold junction at 0°C is not easy in the real world, so if the temperature is not 0°C, we have to know the value of temperature at the cold junction to calculate the measured temperature (at hot junction). Then the output voltage have to compensate this discrepancy. This process is called “Cold-Junction Compensation).

Thermocouples have different types depending on the purpose of use as shown in Figure 1‑3.


Figure 1‑3: Example of K-type thermocouple

1.3 Thermocouple Selection

Because thermocouple has many good properties as mentioned earlier, so it is very common commodity in many industrial applications. Selection of suitable thermocouple has to consider the following factors:


Figure 1‑4: Popular thermocouples for industries use

2 Introduction to aMG Sense-Thermocouple

aMG Sense-Thermocouple is a module for receiving analog signals from thermocouple and transform them into 14 bits digital signal. These 14 bits digital signal becomes the input of the microcontroller that has a SPI interface having signal conditioning circuit and cold-junction compensate function to make the temperature measurement more accuracy.


Figure 2‑1: Digital temperature measurement circuit, aMG Sense-Thermocouple

General Information about aMG Sense-Thermocouple is as follows.

Applications can be found in general equipment, industries, temperature control system, HAVC vehicles etc.

2.1 Basic Connection

aMG Sense-Thermocouple, temperature measuring module, has 2 signal connection points. P1 is output signal module which will be connected to the microcontroller through SPI protocol. P2 is signal receiving point which receives output signal from thermocouple. Connections at each point must ensure that poles are correct.


Figure 2‑2: Functions of each connect points on the board


Figure 2‑3: Connection between module and microcontroller

2.1.1 Recommendation for Use:

To prevent the failure of the device, following things must be noted.

2.2 Principle of Working

This module comes with built-in signal conditioning circuit and cold-junction compensator which makes the use of the device easy for the users. Module comes in a small compact size and also have the ability to reduce noise from signal guide from thermocouple. Before the measured data is translated into the temperature values at the measured point, compensation for the difference between cold junction sides must be taken into account. For type-K thermocouple, the relation is given by equation (3).

VOUT = (41.276µV/°C) x (TH – TC) (3)

Where

In this function, when the temperature at cold-junction is changed, the measured value is still accurate. The principle to measure temperature at measure point (-270°C to +1800°C) of this module is that – first measure the temperature inside the chip (-40°C to +125°C) via precise measurement assuming that the value should be equal at all cold-junction points. Then measure the output voltage of thermocouple through ADC module. All the measured values will be used to solve equation (3) to find TH, the already compensated value and transformed to signed binary data. Notice that at some range, the value at hot-junction is lower than cold-junction.

From the principle above, to make highly efficient measurement, we must prevent heat that might affect the chip (temperature should be same in all area of the module) to prevent the measurement error.

2.3 Data Connection in Serial SPI

Data communication between the module and the microcontroller is uni-directional SPI, as in Figure 2‑4. Read only begin at microcontroller creates logic LOW at CS pin and generate a clock signal at 5 MHz into SCK pin. Module will send processed data at SO pin. The measured value and already compensated value need 14 clock signals. All data need 32 clock signals. The first sent out bit is the 31st bit (sign bit of thermocouple temperature). Error and temperature value will be updated when logic at CS pin is HIGH again.


Figure 2‑4: Protocol for SPI module

From Table 2‑1, measured temperature begins from bit D[30:18] ordered from MSB to LSB bit. D16 is normally in LOW state and will be HIGH if error occurs such as no connection to thermocouple, short circuit between thermocouple and VCC or GND. Reference temperature data has 12 bits begins from D15. If input point + and – of module has no connection with thermocouple, the D31 bit will be 0 and D[30:18] will be 1. Bit D0, D1, and D2 normally is in LOW state. Bit D2 will be HIGH when connector of thermocouple is short circuit with VCC. D1 bit will be HIGH when thermocouple is short circuit with GND and D0 bit will be HIGH if there is no connection between thermocouple and module.

Table 2‑1: Format of output signal from module

Table 2‑2: Example of data read from thermocouple

Table 2‑3: Example of data read from reference point

3 Experimenting with the Module

In these examples, aMG Sense-Thermocouple is used along with aMG Lab Kit – F4 with type-K thermocouple (-270 to +1372).

3.1 Experiment 1 – Reading the Data for processing it on PC

Devices to be used:

Assemble STM32F4DISCOVRY board and aMG USB COnverter-N2into master aMG F4 Connect 2 board and then connect type-K thermocouple to input of aMG Sense-Thermocouple (check the poles carefully). Use jumper wires to make circuit as shown in Figure 3‑1.


Figure 3‑1: Circuit for experiment 1


Figure 3‑2: Software at MCU

The pin PE3 of MCU board is set to HIGH state in order to cancel other sensors information which were used before. SPI Read Box will read data and store information in 8 bit variable. Thus, if the user wants to read 32 bits data, then user need to have 4 variables for that. First read position is LSB, but if the user wants first position to be MSB then Send Data Box need to be re-arranged as shown in Figure 3‑3.


Figure 3‑3: Rearrangement of data in Send Data Box

From the manual reference [3], it is known that the maximum time to process data is 100 msec so sample time of SPI read is set to update every 0.1 seconds.

Software at host PC is shown in Figure 3‑4. Receiver on PC uses 32 bits variable. To extract the required data bits, Extract Bit Command Box is used. To converse signed binary into decimal, user can use Data Type Conversion box and then multiply by the Gain as in Table 2‑1.


Figure 3‑4: Software at host PC

3.2 Experiment 2 – Reading the Data from 2 Thermocouples and Process it on PC.

In this experiment, the same equipment will be used as used in experiment 1 but one additional aMG Sense-Thermocouple board and a thermocouple will be used.

Connect the devices as in Figure 3‑5. These two modules use common VCC, GND, SO, SCK and connect to MCU at the same pins. CS pin of the existing module still uses D12 pin but the new module use D11 pin. Software at MCU is shown in Figure 3‑6.

With the help of Counter Limited and logical operator (NOT), alternatively HIGH-LOW signal is generated between pin D11 and D12 to choose the connection at the module. Logic LOW is used for data reading and logic HIGH is used for not to read the data.


Figure 3‑5: Circuit for experiment 2


Figure 3‑6: Software at MCU

Software at host PC uses Compare to Constant to detect that data coming from which module? If the data is the same, it will sent output data “1” to display the received data.

When the temperature value is being displayed, the user can try pulling the thermocouple out or using a copper wire to short circuit the connection points of VCC and GND and observe the changes at bits 0, 1, 2 and 16. There should be 1 for each test condition.


Figure 3‑7: Software at host PC

3.3 Experiment 3 – Reading the Data from 2 Thermocouples and Display the Data on the LCD.

Devices and connections for this experiment are same as in experiment 2 with an addition of aMG CLCD 2 and aMG USB converter – N2 is removed from the circuit. The experimental layout is shown in Figure 3‑8 and example software at host PC is shown in Figure 3‑9. If user wants to have a clearer display of LCD then LCD must be connected to external power supply.


Figure 3‑8: Circuit of experiment 3 and LCD display


Figure 3‑9: Software at MCU

3.4 Connection with more than two thermocouples

This example describes only idea about software when more than two thermocouples are connected. Let’s assume that there are five thermocouples then software will be as in Figure 3‑10.

MATLAB function box for software at PC side has an sample program to find the mean (average) of measured temperature from each module.


Figure 3‑10: Software at MCU


Figure 3‑11: Software at PC side


How to Use Analog to Digital and Digital to Analog Conversion

download all demo files: AdcDac.7z

1 Analog I/O Pins Usage

Applications of embedded systems are in all domain of life including control and instrumentation system, robotics and electrical appliance. In detecting a physical quantity, sensors play an important role by detecting/measuring a physical quantity such as distance, speed, force, pressure, humidity, light intensity, temperature etc. and then change these properties into the electrical signals which are mostly analog voltage (0-5V) or current (4-20mA).

These physical cannot only be detected by the analog pin of a microcontroller but can also be detected by a digital I/O depending upon the need of application. For example, a photodiode is a device which converts the light energy to current. That current can be fed to analog I/O or digital I/O. If that current is applied to the analog I/O then the I/O pin will read the value between 0-1024 which can be then interpreted between 0-5V by scaling. If the photodiode current is applied to the digital I/O, it will classify it either ‘0’ or ‘1’ based on the threshold defined.

Data received from the sensor or the data which is being processed inside the microcontroller sometime requires the analog to digital conversion or digital to analog conversion. This makes the data fit to become the input or output of certain module. This requires the presence of a module Analog to Digital Convertor (ADC) or Digital to Analog Convertor (DAC) inside the microcontroller. Most of the modern MCUs have these modules and Fio2 STM32F4DISCOVERY is no exception to it.

1.1 Number of Channels

Users can see the number of channels of analog signals from the data sheet of respective microcontroller. Below the figure highlights the pins for ADC to read the voltage from an external device and DAC to send voltage to external devices.


Figure 1‑1: ADC and DAC modules for STM32F4DISCOVERY[1, p. 14]


Figure 1‑2: Analog channel modules for FiO2 [2, p. 14]

1.2 Voltage Characteristics

Figure 1‑3 shows the voltage characteristics of ADC. Conversion of voltage range should be between 0V to V REF+ . Power reference voltage should not increase 3.6V and should not be less than 1.8V.


Figure 1‑3: ADC characteristics [1, p. 129]

To read a voltage which is less than 0V (negative) or more than 3.6V, signal conditioning circuit should be used and aMG-SIGCON suits well for this application. Before connecting aMG-SIGCON with the microcontroller [4], it is highly recommended to see the characteristics of aMG-SIGCON from the following website.

http://waijung.aimagin.com/index.htm?amg_sigcon_a.htm

Figure 1‑4 shows the electrical characteristics of DAC module. The maximum output voltage of DAC module is maximum analog supply voltage V DDA – 0.2, where max. V DDA is 3.6V. Operational amplifier is used to reduce the output impedance as shown in [1, p. 137]Figure 1‑5.


Figure 1‑4: Electrical characteristics of DAC [1, pp. 136-137]

Please note that output of DAC cannot be 0 or exactly V DDA. The buffer gap is about 200mV which is the trade-off for not using operational amplifier.


Figure 1‑5: Buffered and non-buffered DAC [1, p. 137]

2 Analog Input Experiments

2.1 How to use Regular ADC Block?

Regular ADC block converts the analog signal into digital data. Users can select the channels and sample rate (sample time) of ADC module for the blockset in Simulink library>>Waijung Blockset>>STM32F4 target>> On Peripheral Chip >>ADC. Regular ADC block has the following characteristics.


Figure 2‑1: Regular ADC block characteristics

2.2 Experiment to Control LED using Light Sensor

Objective

The sensor aMG Photocell-A is shown in Figure 2‑2. It measures the light intensity. Voltage divider rule can be applied to find the which is governed by the following relationship.


Figure 2‑2: Circuit board for aMG Photocell-A

Table 2‑1:aMG Photocell-A power characteristics


Figure 2‑3 shows a Simulink model for switching the LED. Regular ADC block is used. The working of the model is described as follows;


Figure 2‑3: Simulink Model for LED switching using Light sensor

Digital data from ADC module has 12-bit resolution. It is not convenient to display the values from 0 to 4095 on STM32F4. The values from 0 to 4095 does not give us meaningful information therefore it is better to translate this information from 0 to 3.3V with the help of simple transfer fuction (By multiplying with the gain of 3.3/4095.

Figure 2‑4 shows the relationship between the digital values and the actual output. On the x-axis, the digital values are given and on y-axis the corresponding analog voltage value is given.


Figure 2‑4: Relationship between digital value and actual voltage

In Figure 2‑4, we can see a red line. For example, the value of ADC is 3060 and we want to obtain its corresponding voltages. To get the corresponding voltages, value of ADC is multiplied by the gain factor i.e.

3060* (3.3/4095) = 2.465V

2.2.1 Using the Display of LCD

The data processed through ADC can be visualized through the LCD panel available on the microcontroller. This can be shown in Figure 2‑5.


Figure 2‑5: Simulink model for displaying the value of light sensor using LCD display


Figure 2‑6: Controlling the LED using light sensor

3 Using the Analog Output

3.1 How to use regular DAC block

Regular DAC block acts via signal DAC1_OUT (pin PA4) or DAC2_OUT pin PA5) for the blockset to control analog output on STM32F4DISCOVERY board. In Simulink library, DAC block can be accessed as Simulink library >>Waijung Blockset >>STM32F4 target >> On Peripheral Chip >> DAC. Regular DAC block has the following features.


Figure 3‑1: Characteristics and settings of Regular DAC Block

3.2 Experiment to Create a Periodic Signal

Objective

This experiment uses STM32F4DISCOVERY to generate a periodic signal. It has two inputs. The first input is Saw Tooth to pin DAC1 (A4) which has a voltage level between 0V to 1V. The second input is given at pin DAC2 (A5) which has an analog signal frequency of 20 Hz and the voltage level between 0 to 2.5V.


Figure 3‑2: Simulink Model for the Experiment

With the help of the oscilloscope, the signals can be observed. The results are shown below.


Figure 3‑3: Experiment to generate periodic signal

From the example of Regular DAC Block mentioned above, we use a signal source from Simulink >> Source and its limitation is depended on elapsed time during the trigonometry function calculation. For instance, a sinusoidal waveform of 20 kHz which its period is 50 micro second need to compute the voltage every 5 micro second in order to obtain 10 samples of voltage per pulse and therefore, it may cause the other system not working. Hence, we should use Arbitrary Waveform Generator instead in order to generate high frequency signal that will be discussed later.

3.3 Usability of Arbitrary Waveform Generator

The Arbitrary Waveform Generator developed by Aimagin allows the user to define the dataset. To create a model of the desired signal, the information is downloaded in the memory of STM32F4DISCOVERY. The Arbitrary Waveform Generator has the potential to create a high frequency signal (up to 2MHz frequency from ADC module). Following are the steps to generate a signal from Arbitrary Waveform Generator.

X = 0:1:49; then press ENTER

Y1 = sin(2 × pi × x/50) + 1.5; then press ENTER

Y2 = 4 × (sin(2 × pi ×x/50) + sin(3 × 2 × pi × x/50) + sin(5 × 2 × pi × x/50)/5)/pi + 1.5; then press ENTER


Figure 3‑4: Simulink Model for generating signals using Arbitrary Waveform Generator


Figure 3‑5: Parameters setting for Arbitrary Waveform Generator


Figure 3‑6: Results generated by high frequency analog signal

4 Miscellaneous Tasks

4.1 Module to Read Analog Value from Digital Signal

Objective


Figure 4‑1: Simuink model to read values from analog signal to digital signals

The Simulink model of this experiment consists of two parts: reading the analog input and displaying the results on LCD screen and creating a digital signal using 4 Pulse Generators with a period of 0.001 second (frequency 1 KHz) each and duty cycle of 25, 50, 75 and 99%.

Digital signal is called Duty Cycle Pulse Width Modulation which is a popular technique for controlling the speed of the motor or adjusting the light bulb. The user can generate the PWM signals using basic PWM or Advanced PWM blocks in Simulink library >> Waijung Blockset >> STM32F4 target >> On peripheral Chip >> TIM.

After downloading the program to STM32F4DISCOVERY, pin D15 will send a digital signal with a frequency of 1 KHz. User can select the duty cycle of the digital signal by setting DIP switch as shown in Table 4‑1. Pin D15 is to be connected with an RC circuit which serves as a first order filter for the signal as shown in Figure 4‑2. Signal after filtration will be sent to the LCD for display.

Table 4‑1: DIP switch for changing the duty cycle


Figure 4‑2: Reading Analog Value from Digital Signal

Values of the RC circuit will vary depending on the selection of the duty cycle. For this experiment, the values are taken to be R = 10 Kohm and C = 0.1uF.

4.2 Digital Input Analog Voltage Reading

Purpose

In this experiment, potentiometer (variable resistor) is used for analog signals. Pin PA5 is configured so that it received analog signals and pin D15 is configured to have a digital input form. Figure 4‑3 shows in the Simulink model which includes the LCD setup and LCD display. PD14 is the digital output which is connected to LED3 which can be act according to the signals on PD14.


Figure 4‑3: Simulink model for analog signals to digital input

After downloading the program on STM32F4 DISCOVERY, the voltage of the potentiometer can be observed on the display LCD. The blinking of LED3 and LED4 is controlled by the following table.

Table 4‑2: Results


Figure 4‑4: Reading digital input signal

4.3 Selection of Sampling Rate

To convert an analog signal to digital one, sampling time plays a crucial rule. Sampling time determines at which time the sample should be taken. For example, if sampling time is set to be 0.01 sec, this means that the signal is measured and converted the analog to digital signal after every 0.01 second i.e. 100 Hz (Sampling frequency).

Choosing an appropriate sampling rate is very important. If the sampling rate is very less then error introduced in the system will be more. If the sampling rate is very high, then it requires high computation power and memory [7]. In order to have an appropriate sampling rate, Nyquist criteria determines the frequency. According to the Nyquist theorem, the sampling frequency should be twice the frequency of the signal. If there are multiple frequencies in the signal then sampling frequency should be twice to the maximum frequency of the signal [8].

One thing should be remembered that the sampling frequency also depends on the requirement of the application. If the bandwidth requirements are not strict then there is no harm to exceed Nyquist sampling frequency. Nyquist theorem only tells the minimum requirement of the sampling frequency. If the sampling frequency is below Nyquist theorem, then signal cannot be reconstructed. In some applications, the sampling frequency is taken to be 20 times the maximum frequency of the signal to be very close to the original signal.

In this experiment, the sampling time of ADC module is taken to be 0.01 second (which can be changed to desired value) and this sampling time is used to read the analog sinusoidal waveform with different frequencies of 5Hz, 20Hz, 50Hz and 60Hz (User can use Function Generator to create the above mentioned frequencies instead of using Regular DAC block y setting the minimum and maximum voltage of 0.5 – 2.5V). Following are the steps to accomplish this experiment.


Figure 4‑5: Analog to Digital Conversation


Figure 4‑6: Simulink model for reading voltage


Figure 4‑7: Sample rate selection for Simulink model

Table 4‑3: Sample rate selection for the host


Figure 4‑8: Waveforms of 5, 20, 40, 50 and 60 Hz with sampling frequency of 100 Hz

The above figure shows the waveforms for different frequencies from 5 Hz to 60 Hz. The sampling rate for all the waveforms is set to be 100 Hz. From the Nyquist criteria, it is known that for 60 Hz waveform, 100 Hz sampling frequency is not high enough to reconstruct the signal. For practical purpose, the sampling frequencies are taken to be 20 times more than the maximum frequency of the signal.

5 References

  1. STMicroelectronics, STM32 F407xx Datasheet-production data [Online], 2013
  2. STMicroelectronics, STM32 F417xx Product-Specification [Online], 2013
  3. STMicroelectronic, UM1472: STM32F4DISCOVERY User Manual [Online], 2012 .
  4. Aimagin, Signal Conditioning Design Guideline, [Online]. Available: http://waijung.aimagin.com/signal_conditioning_design_gui.htm.
  5. Aimagin, aMG Photocell – A, [Online]. Available: https://www.aimagin.com/amg-photocell-a.html
  6. E. W. Weisstein, “Fourier Series. From MathWorld–A Wolfram Web Resource.,” [Online]. Available: http://mathworld.wolfram.com/FourierSeries.html.
  7. R. G. Lyons, Understanding Digital Signal Processing, New Jercy: Prentice Hall PTR, 2001
  8. S. J. Orfanidis, Introduction to Signal Processing [Online]. Available: www.ece.rutgers.edu/~orfanidi/intro2sp, 2010.
  9. STMicroelectronics, RM0090: STM32F40xxx Reference Manual [Online], 2013

How to Use Data Logger

Download demo file datalogger.7z

1 External SD-Card

1.1 Introduction

In this article, description about how to read and write data on flash memory using a microcontroller is given. The limitation of this technique is that only data less than 1MB can be stored thus not suitable for big data processing.

SD cards are used for storing data (storage is non-volatile) and can retain the data in the memory without power as well. SD cards are often used in mobile phones, digital cameras etc. There are many types of SD cards available in the market. SD cards can be divided into three types which are shown in Figure 1-1.


Figure 1-1: Identifying the types of SD cards

Figure 1‑2 shows the class of SD cards based on their speed of data transmission so that user can select these SD cards based on the requirement of the application whether the user is using it for recording high definition (HD) movie or general purpose storage.


Figure 1-2: General Information on SD and Micro SD Cards

SD cards are compact and small is size and for this reason, they are the favorite choice to be used as a data storage device in embedded systems. SPI communication can be used to receive data from the SD card but STM32F4ISCOVERY has a STM32F407VG microcontroller which has specific management system of Secure Digital Input/Output (SDIO) [1]. Pin description of SDIO interface is given in Figure 1‑3.


Figure 1-3: Input/Output port SDIO Interface

Each pin has the following functions.

Pin SDIO_CMD is for sending commands by CE-ATA to SD card and have the default settings of the SD card.

As a SDIO interface, the cable has a multi-bit SDIO interface so that it can transfer data faster than the SPI interface. Figure 1‑4 shows the pin layout of the SD card when it communicates with SDIO interface using 4 bits.


Figure 1-4: Pin Layout of SD, MiniSD and MicroSD Card in SDIO mode

2 Preliminary Experimentation with Data Logger

2.1 Introduction

Data logger is a device which is used to store data from various sensors. Generally data logger devices can be connected to the sensors directly. Data can be saved into the memory of SD card with the time stamp and users can access the data from the data logger later. Computers can also be used for reading the data from the memory and display it in various forms such as tables, graphs etc. Data logger devices can also be connected to the computers directly.


Figure 2-1: Applications of embedded devices to data logger

Data logger devices can be used in a number of ways such as recording the humidity of certain place or the temperature or the location of the vehicle using GSP etc. Data logger devices can operate in a stand-alone manner and able to read the signals from the sensor and save the information in their memory without the use of any additional software or peripherals to the computers. They are designed in such a way so that they can be installed easily where required.

Application of an embedded data logger is presented as an option because of their small size. Microcontrollers like STM32F4 family can receive the signals in a number of ways for example from analog to digital module, I2C, SPI UART, etc.

This article explains how to use the data logger block and how it can be used to record the voltage reading from ADC module into the memory of SD card and read the data from the SD card on the computer with the help of Microsoft Excel and Notepad ++. MATLAB is used to obtain the graphs.

2.2 Equipment used in the Experiment

For this experiment, a user must know the socket available for MicroSD card in aMG F4 Connect board and aMG CLCD2 which is shown in Figure 2-2.


Figure 2-2: Sockets for MicroSD card

If the user has a separate SD card reader, then it can be connected to STM32F4DISCOVERY as shown in Figure 2-3.


Figure 2-3: Circuit for connecting MicroSD card

Note that Waijung blockset is not compatible with SD card SPI model. Users can read and write to SD card module that works with SPI interface.

2.3 How to use Data Logger Block

In Simulink library >> Waijung Blockset >> STM32F4 target >> On Peripheral Chip >> SDIO contains blockset for recording on SD Card.


Figure 2-4: Characteristics and features of the Data Logger Block Ascii.

2.3.1 Cautions and Restrictions of use

2.4 Experimenting Data logger with Ascii.

Aim


Figure 2-5: Simulink model for storing/writing the data in SD card

In this example, experiment will be conducted for logging the Ascii data logger which is actually a signal from pin PA5, PA6 and PA7 to the SD card. Sampling will be done every 0.5 second. Download the model into STM32F4DISCOVERY. The red light will flash (symbolizing error), if there is no SD card.


Figure 2-6: Insert SD card in the respective socket of aMG F4 connect board

When user inserts the SD card into the aMG F4 Connect or aMG CLCD2 (as shown in Figure 2-6) for recording the data on the SD card, the green LED starts flashing (symbolizing success). With the help of a computer or laptop, open the file as shown in Figure 2-7. A word of caution is, whenever the SD card is inserted or removed, the board should be powered off.


Figure 2-7: Recorded data from three pins and displaying it using Microsoft Excel


Figure 2-8: Simulink Model for real-time data recording on MicroSD card

Data / time Subsystem Block module is used to read the digital clock using I2C serial communication. Real-time readings are converted into String text format.


Figure 2-9: Subsystem Block module for reading the time from a digital clock


Figure 2-10: Devices used in the experiment are data on the SD card and digital clock module

When it comes to SD card, with the help of computer or laptop, browse the file and open it with Mircosoft Excel. File will be containing data similar to Figure 2-11.


Figure 2-11: Information containing date, time and readings from the three channels

3 Experimenting with Data Logger in High Speed Mode

3.1 Introduction

High bandwidth storage applications such as signals from the brain or muscles or the application which requires higher sampling rate (greater than 1kHz) requires high speed mode of the data logger. For such purpose, the transmission of the SD card should be fast enough (class 4 or higher type of SD cards). Sometimes, the Ascii characters storage may not be suitable because the CPU requires more processing time.

So in the SDIO Waijung Blockset block has special support for high speed data writing on the SD card. The Ascii and the binary logging requires the installation of Notepad ++ so that the users can see the data in binary format.

3.1.1 Installing Notepad ++.

The information should be used as a Binary File Notepad ++. Users can Download and install it from http://notepad-plus-plus.org/download/v6.6.8.html HEX-Editor plugin, which includes the following steps.

After you install Notepad ++, select the Plugins >> Plugin Manager >> Show Plugin Manager and follow the Figure 3-1.


Figure 3-1: HEX-Editor plugin installed on windows Notepad ++.

Plugin Manager window will appear, select the first tab ‘Available’ and check HEX-Editor and click on install (computer must be connected to internet in order to install the plugin) and is shown in Figure 3-2.


Figure 3-2: How to install the program HEX-Editor.Plguin of Notepad ++.

3.1.2 Using the Notepad ++ and HEX-Editor Plugin


Figure 3-3: Binary data display in Notepad++


Figure 3-4: Binary data in Notepad ++ program with HEX-Editor plugin

3.2 How to use High Speed SD Card Write Block

In Simulink library >> Waijung Blockset >> STM32F4 target >> On Peripheral Chip >> SDIO contains blockset for recording data in a high-speed SD card. This includes indicator for SD card as well.


Figure 3-5: Characteristics and properties of a High Speed SD Card Block Ascii

3.2.1 When Data Collection will End?

3.2.2 Limitations of Use

3.2.3 Considerations during Design Phase

Setup involves consideration of the following points.

  1. Data transmission speed of the SD card (for example 4MBytes/sec, 10MByte/sec or more).
  2. Size of Buffer (typically around 32k if you use more than that user must install SDRAM).
  3. Random write.
  4. Sample size for one.

Condition

  1. The size of the data to be saved must be less than the size of buffer.
  2. The writing speed must be less than the speed of data transmission of SD card.

For example, to calculate the speed of the SD card;

If user wish to save data that contains 32 bit counter, data received from ADC 2 channels will be of 8 bytes (4 byte + 2 byte + 2 byte) and use 50 microsecond per sample to save the data. So the data writing speed will be 8 bytes per 50 microseconds or 160000 bytes per second.

File size calculation

Let N be the number of data to be recorded, thus the size of the File = N × record size.

To calculate the amount of time required to save the data.

Let N be the number of data to be recorded, so the time needed to record (s) = N × sample time.

The indicator

  1. Busy LED indicator will be ON for the initial configuration of the Open Card Format and space for storage.
  2. Progress indicator LED will flash at a frequency of 5 Hz during recording and LED will be flashing at a frequency of 0.25 Hz when the recording is finished. The user can then remove the SD card.
  3. LED indicator for the error will be ON when there is an error during recording process.

Upon completion of the data recording, users can view the recording including the SD Card Error in the MSG.TXT.

SDIO has a block which deals with the saving of data to the SD card. Properties of Data logger and high speed SD card write are described in Table 3‑1.

Table 3-1: Difference between Data Logger with High speed SD card write

3.3 Data logger Experiment-ASCII High-Speed Mode

Aim


Figure 3-6: Simulink model for storing data on SD card


Figure 3-7: LED indicators on the SD card

After inserting the SD card into the respective socket, download the model into STM32F4DISCOVERY. Users can observe the LED indicators as shown in Figure 3-7.

  1. At the beginning of the data collection, indicator LED Busy (blue) is ON and blinks during the data collection stage. It takes around 10 sec to few minutes depending upon the size of data which needs to be recorded.
  2. During write process, the LED Progress (green) will blink at a frequency of 10 Hz (every 0.1 seconds)
  3. When the data write process is complete, the LED Progress (green) starts blinking at the frequency of 0.25 Hz (every 2 seconds). Now user can remove the SD card. From the socket.
    Note the time it takes to collect data for this example (after Initialization) is about 60000 × 100e-6 = 6 seconds.
  4. When user wish to see the data in the SD card, the SD card needs to be connected to a computer and then see file MSG.txt which contains the confirmation message of data logging, the recorded information and the sampling rate.


Figure 3-8: Message in MSG.TXT when writing/recording is finished


Figure 3-9: Data recorded in Data0.txt


Figure 3-10: Data recorded in the last Data0.txt.

If the user removes the SD card before LED Progress (green) start blinking at 0.25 Hz then following message will be displayed (as shown in Figure 3-11).


Figure 3-11: MSG.TXT messages in case of errors during data recording

3.4 Experimenting Binary Data logger for high-speed mode.

Aim


Figure 3-12: Simulink Model for saving binary data to SD Card at high speeds

After the user puts SD card in the socket, download the model into STM32F4DISCOERY, data can be viewed from MSG.txt. The recorded data can be seen from Figure 3-13. The data is written at a very high speed i.e. 1 million bits per second.


Figure 3-13: MSG.TXT contains binary text after writing process is complete

For reading the saved binary data, the user should use Notepad++ program at HEX Editor plugin as shown in Figure 3-14. Format of each set is a value which is obtained from 4 channels of ADC. Each channel has 16 bits or 2 bytes (so in total there are 8 bytes), 4 bytes are used for bit indexing and 4 bytes are used to identify dataset.


Figure 3-14: Format of binary data recorded in the first period

Users can observe the final data set recorded from the index 0x0F423F or 99,999,910 as shown in Figure 3-15.


Figure 3-15: Final binary recorded data

In this example, the size of the file is:
N = 999,999 and the data size per sample = 12 bytes.
Therefore, the file size is equal to 12 x 999,999 = 119,999,988 bytes or 11.44 Mb.
Note 1 kB = 1024 Byte, 1MB = 10242 = 1,048,576 Byte.

3.5 Experiment to Abort Writing/Recording with Manual STOP

Aim

In case, user wants to stop data recording, user can send signal (data) for example external input signal from Digital Input Block to STOP port of High Speed SD Card Write Block.


Figure 3-16: Simulink model for aborting the recording process on SD card with push button

After inserting the SD card into the socket, download the model into STM32F4DISCOVERY. It will start recording the data and the LED indicator (busy process) will flash at a frequency of 10 Hz. The user can press the blue button (which is actually pin PA0) to stop the recording process.

The LED indicator will start flashing at a rate of 0.25 Hz. The user can then remove the SD card. User can see the recorded data in the MSG.txt file and is shown in Figure 3-17.


Figure 3-17: Results recorded after manual stop

This examples shows that the user cannot set certain dataset (because of switch pushing time). Figure 3-18 shows the index value from Counter Block (named RecordID) which is compared to the number of dataset that has been set. User can set many values by adjusting the DIP switch.


Figure 3-18: Simulink model for the data stored on the SD card when stop with DIP switch.

The position of the DIP switches will determine the length of the data which will be recorded from the dataset.

Table 3-2: Position of switch for specified number of data

I feel that in Table 3-2 one set of 12 bytes predict the size of recorded data

4 Using MATLAB for Reading Binary Files

4.1 Introduction

Opening .bin file on Notepad++ may cause problem in program memory in case the size of the file is too big (>1GB). MATLAB can be used to open such big (.bin) files and can transform data to decimal number and arrange the data in matrix/array format. Now the data is ready for further processing such as graph plotting etc.

MATLAB has set of instructions in order to read data from the binary file and users can get more information from the following link in which data is read from DATA0.BIN file which has a size of 1.11 GB. The process is shown in Figure 4-1.

http://www.mathworks.com/help/matlab/low-level-file-i-o.html


Figure 4-1: MATLAB window to set the instruction for reading .bin file

fopen command is used to open a binary file. fread is used to read the file which is open in the first line of the command. The parameters of the fread are the FileID and the way the file should be read i.e. (6, 10000000) and converts the data into unit16 data format and finally storing the information in a variable A. It is worth mentioning here that the way the file should be read must be the same the way the file in written in terms of type of information else the readings will be varied.


Figure 4-2: Description about fopen and fread functions

Data read form the command fread is stored in a variable A and MATLAB can be used for data graphical representation as in Figure 4-3.


Figure 4-3: Graphs from data read from ADC channel 4

4.2 Sample Applications

Aim

Download the model as shown in Figure 4-4 on STM32F4DISCOVERY board. The model will take readings from the ADC module channels 4 to 7 every 10 msec. The readings obtained from channel 4 and 5 will be converted to hexadecimal or raw data in voltage and the readings obtained from channel 6 and 7 will be saved as raw data.


Figure 4-4: Simulink model for storing binary data in various formats

When it reaches 1,000,000 (which is the total size of the data), the user can remove the SD card from socket and can observe the results as in Figure 4-5 using Notepad ++.


Figure 4-5: Recorded results

One dataset contains the values read from AN4 and AN5 (4 bytes data saved as single), AN6 and AN7 (2 byte data saved as unit16) and value from RecordID block (4 bytes saved as unit32).

Since one dataset contains different data types (single, unit16, unit32), Figure 4-6 shows the MATLAB instructions to read file from .bin file stored as different data type and save them to variables AN4, AN5, AN6 and AN7 for which are basically the magnitudes of voltage of channel 4, 5, 6, and 7 respectively.


Figure 4-6: Set of instructions for reading data from a .bin file

When the user will type the following lines of command, the graphs will be plotted for each ADC channel (from 4 to 7) between data read and time.

subplot(2,2,1),plot(n*1e-6, AN4),grid <Press Enter>
subplot(2,2,2),plot(n*1e-6, AN5),grid <Press Enter>
subplot(2,2,3),plot(n*1e-6, AN6),grid <Press Enter>
subplot(2,2,4),plot(n*1e-6, AN7),grid <Press Enter>

These MATLAB commands will show the graphs of the deta read from various ADC channels and they are shown in Figure 4-7.


Figure 4-7: Graphs of the data read from ADC channels 4 to 7

5 References

  1. STMicroelectronics, “STM32 F407xx Datasheet-production data [Online],” 2013.
  2. STMicroelectronics, “User manual: STM32 ST-LINK Utility software description [Online],” 2014.
  3. Wikipedia, “Secure Digital,” [Online]. Available: http://en.wikipedia.org/wiki/Secure_Digital.STMicroelectronics, “RM0090: STM32F40xxx Reference Manual [Online],” 2013.
  4. http://www.amazon.com/gp/feature.html?ie=UTF8&docId=1000633771
  5. Wisco Industrial Instruments, “Data Logger Technical Knowledge,” 2013. [Online]. Available: http://www.wisco.co.th/main/sites/default/files/articles/Logger_Knowledge_0.pdf
  6. http://www.mathworks.com/help/matlab/low-level-file-i-o.html
  7. http://notepad-plus-plus.org

How to use demo files?

Objective

This documentation will show the user how to use the example demo files provided with the Waijung2 block-set

Tutorial

It is recommended that you copy a demo file and built it in a different folder than the original distributed demo folder. This will keep your original demo file unaffected while you evaluate demo files.

All demo files are located at: [waijung2_installation_directory]\waijung2\targets\esp32\demo

Move the Current Folder of Matlab to the directory where you want to build the demo.

Type this command in the command window: status = copyfile('D:\waijung2_installation_directory\waijung2\targets\esp32\demo\digital_input_demo', pwd);

The command will copy the files in the "[waijung2_installation_directory]\waijung2\targets\esp32\demo\digital_input_demo" folder to the current working directory.

Now you can open the file, build the source code, and upload the program to your ESP32. Your original demo file will not be affected.

Previous: Where to go from here?
Next: Digital Output demo


How to Use Digital Input Output

Download all demo files: DigitIO.7z

1 Digital Input / Output

Typical applicatons of microcontroller involves the tranfer of data to and from the MCU to external device. Figure 1‑1 shows a microcontroller which can be used for transfer of information. Data transfer can be achieved by utilizing input and output pins (I/O pins). Input pins are responsible for receiving the information from the external devices which is then sent to the memory for storage or/and processing. Output pins are responsible for sending information to the external devices. This information may come either from the memory or by processing the information within MCU.


Figure 1‑1: Transmission and reception of data between microcontroller and external device

Digital I/O is a form of a signal which only have two states or logic levels.

So basically Digital I/O transfer/receive data to/from an external device which is binary in nature. Digital output is used to control devices such as frame relay or LED lamps that requires only turn on and off signals. Digital input is used to read data from a device such as switch or button that is turned on and off. (In contrast there is also an Analog I/O).

Now the question comes, how we can classify logic level low and logic level high? The answer to this queston is very simple. In electronics, if the voltage level is above certain level, it is classified as low and if is below certain level, it is classified as low. Figure 1‑2 shows the digital logic levels for STM32F4 (STMicroelectronics, DS8626: STM32 F407xx Datasheet-production data [Online], 2013, p. 110).

When using the Transistor Transistor Logic (TTL)

When using the CMOS technology, logic LOW and HIGH are determined based on power supply voltage V DD. For example when V DD = 3.3V

For determining the logic levels of a microcontroller, datasheet must be referred.

Hysteresis refers to the difference in the voltage levels between the detection of the transistion level from high to low and vice versa. Hysteresis is very useful technique to overcome the issue of noise. If we define a simple criteria that above 0.5V is high and below 0.5 is low then becuase of noise effect, a 0.49V signal can go to 0.51V thus logic is inverted from the original. Hysteresis gives protection and robustness against such surges. Compared with TTL technology, it gives a range of voltages to be LOW or HIGH.


Figure 1‑2: Digital logic levels for STM32F407xx

1.1 Input Circuit

Each pin of STM32F4 can be characterized as one of the three types i.e. Pull-Up, Pull-Down and Floating (In addition, some pins are particularly 5V Tolerance. Users need to refer to the datasheet of specific MCU to see if it is 5V tolerance).

1.1.1 Pull-Up Circuit

Figure 1‑3 shows a pull-up input which is basically is a pull-up resistor connected to VDD or power supply. Pull-up circuit serves the purpose of reading the status automatically in the microcontroller. If pull-down is disconnected then the state is HIGH i.e. “1” all time and if it is connected then the state is LOW i.e. “0” (Active Low). When the switch is pressed then MCU pin goes LOW. Circuit pull-up is better as compared to circuit pull-down as former is more robust to noise.


Figure 1‑3: Pull-up circuit

1.1.2 Pull-Down Input Circuit­­

Figure 1‑4 shows the condition when the pull-up resistor is disconnected from VDD and pull-down resistor is connected to the ground while reading the automatic status from MCU. For the given condition, the circuit will read LOW i.e. “0” all the times and when the switch is pressed it will start reading HIGH “1”.


Figure 1‑4: Pull-down input circuit

1.1.3 Floating Input Circuit

Setting pin value to floating has the same idea as pull-up / pull –down but no internal pull-up and pull-down resisters is required. User must connect the pull-up or pull-down externally so it is suitable for some device that already has external Pull-Up or Pull-Down.

1.2 Output Circuit

The output of STM32F4 are of two types i.e. Push-Pull or Open-Drain. User can choice either of them.

1.2.1 Push-Pull Output Circuit

STM32F4 can be set as a Push-Pull output. Internal circuit of microcontroller has two types of MOSFET: the P-MOS that connected between V DD and output pin for transferring current (Source Current) and N-MOS that is connected between output and ground for receiving current (Sink Current). This is shown inFigure 1‑5. The automatic connection control can described below:

From Figure 1‑5, we can see that when connecting a LED between output pin and ground, a resister is used to limit the current. LED will work when output state is “1” (Active High Output). Because of the output has voltage level VDD so the current can flow from microcontroller through LED to the Ground.


Figure 1‑5: Push-Pull output circuit current for sourcing system

When connecting a LED between output pin and external V DD, resister is used for limiting the current as see in Figure 1‑6. LED will work when output state is “0” (Active Low Output) because the current can flow from V DD through LED to output pin (Ground)


Figure 1‑6: Push-Pull output circuit current for sourcing system

The advantage of Push-Pull output is that it can quickly change its state, so it is suitable for such a situation which requires high frequency switching (e.g. visible light communication [4]) and it can directly transfer current to device. The disadvantage of this type is the limitation of current source/sink. User must study pin’s maximum current and voltage values from datasheet of each microcontroller. These information are very important to prevent device from damage and to improve the system reliability. For example, each pin of STM32F4 can sink/source maximum current at 25 mA except PC13 – PC15 can sink at 3 mA [1, p.77] and can sink/source maximum of all pins not more than 150mA as shown in Fig 2-7. Thus when bias the LED with Push-Pull I/O (assume that VDD = 3.3 V) we can use R = 660 Ohm (from R = V/I = 3.3/5m = 660) to limit current at 5mA that enough to make the LED bright and not exceed the 25mA maximum value.


Figure 1‑7: STM32F415xx-417xx Absolute maximum ratings: Current characteristics [2, p. 73]

1.2.2 Open-Drain Output Circuit

When setting the output of STM32F4 to Open-Drain, internal circuit in each pin of microcontroller will be controlled automatically as below:

So the Open-Drain output must connect to external electric source Vext as shown in Figure 1‑8 that the device will work at output state “0”


Figure 1‑8: Open-Drain output circuit

Since the Open-Drain circuit doesn’t use power from microcontroller, it can be advantageous because devices are using external power which can have a voltage might be higher than V DD. However user must be careful about maximum current must not exceed 25mA. Furthermore this type is suitable with bus system such as I2C too.

2 Digital I/O Experiment

2.1 Experimental Devices

Experiment of digital I/O uses basic devices such as LED to display digital output state, switch button (ON-OFF), and dip switch to create logic of input signal to digital input. These devices (LED etc.) can be easily purchased and they are not expensive.

The board aMGF4 Connect2 developed by Aimagin can be used with STM32F4DISCOVERY. FiO2 has 4 LEDs, 3 ON-OFF swithes and 8-pin dip switch as shown in Figure 2‑1.

The board STM32F4DISCOVERY developed by STMicroelectronics uses microcontroller series. STM32F4 number STM32F407V6T6 has 100 pins and able to use digital I/O maximum at 82 pins. It has 6 ports: PA, PB, PC, PD, PE and PH, having 16 pins in each port (except PH, has 2 pins) each pin can be set as output or input. For example, we can set PD1 to be pull-up input and PD7 to be push-pull output (details can be found in the microcontroller datasheet about each pin). The board FiO2 uses the microcontroller number STM32F417IG that has many more pins but the principle is the same.

Be careful that when using STM32F4DISCOVERY, some pins may be already connected with other device on the board so we have to study the datasheet wisely.


Figure 2‑1: Tool on aMG F4 Connect 2 for testing Digital I/O


Figure 2‑2: LED circuit on aMG F4 connect board


Figure 2‑3: Push/Pull switching circuit on aMG F4 connect board


Figure 2‑4: DIP switching circuit on aMG F4 connect board

2.2 How to Use Digital Output Blockset­

The blockset used to control digital I/O is in STM32F4DISCOVERY can be found from Simulink library >> Waijung Blockset >> STM32F4 target >> On Peripheral Chip >> I/O by Digital Output block. It has the following characteristics as shown in Figure 2‑5.


Figure 2‑5: Characteristics and settings of digitial output block

2.3 Blinking LED

Purpose


Figure 2‑6: Simulink Model – Testing the blinking of LED 1

Table 2‑1: Simulink blocks used in blinking LED experiment

In setting parameters of Pulse Generator Block there is an important parameter called Period or the period of waveform. Pulse width gives the information that for how long the LED will be in ON state and for how long it will be in OFF state for a given time. For example, user wants to switch on the LED for 1 sec and switch off the LED for 3 sec and this process keeps on going. For the given case, the pulse width can be calculated by using relation below.

% Pulse Width = (Time for which LED is ON) x 100 / Period

Here Period corresponds to switch ON + switch OFF time i.e. 1 + 3 = 4 sec. So the answer is:

= (1) x 100 / 4 = 25 %

We can simulate the Pulse Generator Block as shown inFigure 2‑8. Pulse type is selected as time based, amplitude is choosen to be 1, period is taken to be 4 sec with 25% pulse width. Click on start simulation by clicking on the Run Icon as shown inFigure 2‑7. Double click on the Scope to see the simulated waveform as shown inFigure 2‑8. The user will not be able to see any LED blinking apparently. But the user must think in mind what does this waveform mean and how to interperet this waveform in terms of hardware? The positive pulse means that the connected LED (right now in simulation not connected) will be ON and when there is no pulse then the LED will be OFF. Furthermore user can observe that for 1 cycle, the LED will be ON 25% of the time and will be OFF for 75% of the time.


Figure 2‑7: Understanding three icons of Simulink


Figure 2‑8:Setting the Pulse Generator Block and blinking LED experiment results

When the user is satisfied that in simulation, the program is working well then the next step is to download the program in the target. Downloading of the program to the target can be done either by pressing CTRL+D or by clicking the icon Update Diagram and then pressing CTRL+B or clicking icon Build and Download as shown inFigure 2‑7. If the downloading of the program is successful to the target then LED6 of STM32F4DISCOVERY and LED4 of aMG F4 will be switched ON for 1 sec and switched OFF for 3 sec and this process keep on repeating. Now it is left on the user to do some experimentation by changing the amplitude, period and pulse width and see the effect on the simulated waveform and verify the similar effect on target LED.

2.4 Running LEDs

Purpose


Figure 2‑9: Simulink Model – Controlling 4 LEDs simultaneously

Table 2‑2: Simulink block required resources

In this simulation, four LEDs are used. These LEDs are switched ON and OFF in a pre-determined manner as given in the table. Let’s assume that we need to complete 8 steps in 2 seconds. It means that each step is for 0.25 sec. When 8 steps are completed, the system will again go to step 1 and this process keeps on happening. If the user observes the steps table carefully thenuser can know that each LED is ON for 0.25 × 4 = 1 sec and for the same time it is OFF. This implies that the pulse width of all LEDs is 50%. Pulse Generator Block has a period 2 sec.

Another information which can be extraced from the table is in the first step only LED1 is on. In second step LED 1 and LED 2 is ON. In third step LED 1, 2 and 3 is ON and in fourth step all LEDs are ON. This means that there is some time delay between these LEDs. Time delay of LED 2 is more than LED1. Time delay of LED 3 is more than LED1 and 2. Time delay of LED4 is more than LED 1, 2 and 3. We can also write that:

For this example, block from Simulink Source Library such as Counter Free Running Block or Pulse Generator Block will be used as controlling signal for open-close output. When external signal is needed (for example: switch) user can use Digital Input Block to receive signal that is in Simulink Library >> STM32F4 target >> On Peripheral Chip >> I/O.

2.5 How to Use Digital Input Blockset

For Blockset controlling Digital I/O of STM32F4DISCOVERY board, go to Simulink Library >> Waijung Blockset >> STM32F4 target >> On Peripheral Chip >> I/O. Digital Input block and it has the following characteristics.


Figure 2‑10: Settings of digital input block

Further more users can define a sampling time and enable custom port labels to name the input port according to their wish.

2.6 Controlling LED from Push Button

Purpose


Figure 2‑11: Simulink model ON OFF switching of LED with push button

Table 2‑3: Simulink block for contolling LED switching using push button

When user has downloaded model into STM32F4DISCOVERY, 4 LEDs will ON when pressing the SW3 and OFF SW3 is not pressed. So the Jog is programmed so that it always send output when the button is pushed and stop sending when button is not pressed. This scheme is suitable for control manual machine such as crane or lifting machine.

2.6.1 What is Bouncing/De-bouncing?

Bouncing is the non-ideal behavior of mechanical switches which creates multiple electric transitions when a single input from the user is entered. It takes some time for the input to reach at a stable state. The bouncing effect is shown inFigure 2‑12. From the figure, we can see that in the begninning the switch is in ON state. When user enter the input to switch it OFF, then it takes around 0.01 to 100 msec before the switch is actually switched OFF. A similar effect can be observed when the switch goes from OFF state to ON state.


Figure 2‑12: Bouncing effect

Bouncing is an undesirable effect so it must be removed when designing a circuit. There are number of ways by which we can avoid bouncing. The process of avioding bouncing is called de-bouncing. The most easy and commonly used technique for debouncing is analog filtering. A resistor capacitor (RC) circuit is used to filterout the rapid changes in the switch output. Depending on the nature of the switch, the values of RC circuit is chosen in such a way that input threshold is not crossed while bouncing is still occuring.


Figure 2‑13: RC circuit for debouncing

Other than hardware techniques available to overcome debouncing, software programming can also help to aviod it. This will eliminate the need to additional RC circuit. In RC block, the user can also set the time interval in Waijung Blockset have Debounce block in Simulink Library: Waijung Blockset >> STM32F4 Target >> On-chip Peripherals >> IO by setting parameter of Debounce block.

Mode can be selected as Normal, Single End and Toggle Latch. The user can change working mode and observe the behavior of LED when pushing the button and debounce counting. Toggle mode is the program to always send output when push the button at a time, and stop sending when pushes it again. Thus the program should check the status of output, and send new status of output when the button is pushed. The Toggle is suitable for on-off electrical device.

Debouncing block can be added in between digital input and digital output as shown in Figure 2‑14.


Figure 2‑14: Simulink model for LED control using push button (Toggle mode)

2.6.2 Self Practice Exercise

2.7 Experiment to switch LED via Dip Switch

Purpose


Figure 2‑15: Simulink Model to switch LED via dip switch

Table 2‑4: Simulink block used to control switching of LED from DipSwitch


In this experiment, switching of the LED is controlle via dip switch1. Pin PE3 is connected to switch block which will be selected according to the conditions. (This is true when input signal is not equal to 0) Figure 2‑15 shows when condition is true, signal from Pulse Generator is used to control switching of LED.

When dip switch is ON then LED will blink for every 0.5 second and when the dip switch is OFF then LED will be ON when SW3 switch is pressed. This task can be achieved with multiple mode of operations such as automatic mode or manual mode.

3 Digital I/O

Purpose

Design a program such that it switches ON one LED in each round from the four LEDs using counter and bit operation (Be able to look Model from digital output demo stm32f4_digital_output_demo.mdl)

Explanation

When the program starts running, the counter is reset after every 500 msec. Counter starts counting from 0 to 2n-1 which is the highest number in counting. It will again count from 0 and the counter will AND it’s output with constant 3 so that the counter value is in interval 0 to 3 only. After that, it uses block compare to constant to assign the switch ON the LED1, LED2, LED3, LED4 when the value of the counter is 0, 1, 2 and 3 respectively.

The following table explains the working of the program. Each step is for 0.5 seconds. When the step 2 is completed, the program is returned to step 1.

Design a driver for LED 4 working as follows.

4 Frequently Asked Questions (FAQs)

Question: STM32F4DISCOVERY and FiO2 are with how many I/O pins?

Answer: STM32F4DISCOVERY that use microcontrolller STM32F407VGT6 or use FiO2 that use microcontroller STM32F417IGT6, users can see the information from Datasheet Product Specification. For example the number of GPIO or (I/O pin) of STM32F407Vx is 82 (STMicroelectronics, DS8626: STM32 F407xx Datasheet-production data [Online], 2013, p. 14) STM32F417Ix has 140 pins [2, p. 14]


Figure 4‑1: Shows the number of I/O pins of all STM32F40xxx models

Question: Which I/O pin to be used?

Answer: User should find the type and characteristics of I/O pins from datasheet.

Question: What I/O pins can supply?

Answer: Voltage up to 3.6 V and current not exceeding 25 mA except PC13 and PC15 which can give maximum current of 3mA.


Figure 4‑2: Table shows the maximum driveable current from STM32F4DISCOVERY

(STMicroelectronics, DS8626: STM32 F407xx Datasheet-production data [Online], 2013, p. 77)

5 References

(STMicroelectronics, DS8626: STM32 F407xx Datasheet-production data [Online], 2013) STMicroelectronics. (2013, Jun). STM32F407xx Product-Specifications [Online]. Available: http://www.st.com/web/en/resource/technical/document/datasheet/DM00037051.pdf

[2] STMicroelectronics. (2013, Jun). STM32F417xx Datasheet – production data [Online]. Available: http://www.st.com/st-web-ui/static/active/en/resource/technical/document/datasheet/DM00035129.pdf

[3] STMicroelectronics. (2013, Feb). RM0090: STM32F40xxx Reference Manual [Online]. Available: http://www.st.com/st-web-ui/static/active/en/resource/technical/document/reference_manual/DM00031020.pdf

Saadi, M., L. Wattisuttikulkij, Y. Zhao, and P. Sangwongngam. “Visible light communication: opportunities, challenges and channel models.” International Journal of Electronics & Informatics 2, no. 1 (2013). Available: http://www.cennser.org/IJEI/eiV02N01/ei020101.pdf


How to Use I2C Communication Port

download all demo files: I2C.7z

1 I2C Communication Port

1.1 Introduction to I2C

I2C stands for Inter-Integrated Circuit invented by Philip semiconductor now days known as NXP semiconductor. I2C is intended for low-speed data transfer between devices such as assessing low speed ADC and DAC, reading real time clock etc. The EEPROM memory as an I2C communication feature is connected to the system bus and transfers data between the devices. Using only two signal lines as shown in Figure 1-1, which can reduce the number of cables and accessories. It is popular in small embedded systems.

I2C communication uses digital transmission. A bidirectional open-drain line which can transfer data in line with 2 sets of Serial Data Line (SDA) and is responsible for sending the data and Serial Clock Line (SCL) that transmits the clock signal. The speed of data transfer depends on the frequency of the clock (SCL) of STM32F4 (100 kHz bus frequency is considered as standard frequency and 400 kHz is considered fast) [1, p. 575].


Figure 1-1: Connecting an I2C device [2, p. 1]

The signal of the device is open-drain voltage, which is equal to GND (logic zero) and for high impedance the logic is one. Hence there is a need for pull-up resistors and external power supply VDD (3.3V or 5V).

Figure 1‑1 shows an example of connecting devices to the I2C bus. In the figure, we can see that there is one Master (for transferring the data) and three Slaves (to receive the data). Master specifies the command that you want to read information (Read) or send information (Write) to the Slave device. Device identification of the Slave in needed for communication which is established by using a 7-bit or 10-bit address and is set by the manufacturer. Information about the address is listed in the datasheet of the device and can be defined either in software or hardware.

Figure 1‑2 shows the communication pattern and data transmission process. Details are mentioned below.

  1. To start the communication status, I2C Master device sends the START command, which makes all the Slave device ready to receive data from the bus data line (SDA).
  2. Master device sends the 7-bit address command followed by a read or write (Read / Write) a 1 bit.
  3. Information on the Slave bus will be read and determine whether or not they match the address of the corresponding 1 bit address and sends an ACK back to the Master and prepare to proceed.
  4. Data transmission between Master and specified Slave address is performed continuously in case the Master Slave devices send commands to Read a series of data sets of 8 bits (1 byte) when the Master device receives ACK signal upon receipt of each byte.
  5. Master device sends STOP command to end the communication I2C.


Figure 1‑2: I2C communication pattern

Figure 1‑3 shows an example of reading the temperature measured by the humidity sensor (HIH6130). Data is of 2 bytes.


Figure 1‑3: Sample reading measured by humidity sensor

1.2 How to Use I2C Blockset

Waijung I2C Blockset includes I2C Master Setup Block which is shown in Figure 1‑4. User need to select 3 pins i.e. SDA, SCL and the frequency.


Figure 1‑4: Characteristics and user settings for I2C Master Setup Block

I2C Master Read/Write Block is shown in Figure 1‑4 have functions to receive or send data to Slave device with I2C using STM32F4DISCOVERY as Master device. User can set 7 bit Address of Slave device that want to communicate via I2C.


Figure 1‑5: Characteristics and settings for I2C Master Read/Write Blockset

2 Using Humidity/Temperature Sensor HIH6163

2.1 Equipment Used


Figure 2‑1: aMG Humidity/Temperature sensor

Figure 2‑1 shows the board measuring humidity / temperature. Install the sensor HIH6131-021-001 from Honeywell, which has the following features.

Alarm feature: This provides the ability to monitor whether the RH level has exceeded or fallen below predetermined and critical levels within the application. (See the work [4]).

When users want to read both the humidity and temperature, sensor must submit a Request to Address in the specified format as shown in Figure 2‑2.


Figure 2-2: Shows an I2C communication for humidity and temperature readings [2, p. 1]

After that, the Master device starts reading from the sensor and read data is of 4 bytes (32 bits), which includes the status of the sensor (2-bits), humidity (14-bits) and temperature (14-bits).


Figure 2-3: : I2C communication for humidity and temperature sensor [2, p. 2]


Figure 2-4: Sensor status

Digital Readout can be converted to units% RH and Celsius. According to the following equation:

Humidity (%RH) = 14bit_HumidityData x 100 / (2 14 -2)...........................................(1)

Temperature (◦C) = [14bit_TemperatureData x 165 / (2 14 -2)] – 40........................ (2)

Figure 2‑5 shows the aMG ​​Sense Humidity / Temperature board with aMG F4 Connect. Furthermore connection with power supply, SCL, SDA and GND are also highlighted. The user must select the I2C module 1 and address. The active SDA pin is PB7 and for SCL is PB8.


Figure 2-5: Connections between aMG Sense Humidity / Temperature with aMG F4 Connect

2.2 Measurement of Humidity and Temperature Content

Purpose


Figure 2-6: Simulink Model for humidity and temperature through I2C communication

Figure 2-6 shows the Simulink model for reading the humidity and temperature from HIH6131 sensor through an I2C communication and display the results to LCD. The description of work is as follows:


Figure 2-7: Enable subsystem block of request

The display data (that has to be converted to) relative humidity and temperature which has been mentioned in equation above is shown via LCD display.


Figure 2-8: Enable Subsystem Model for readings from sensor and operation of Binary Operation

Experimental results show the relative humidity and temperature readings from sensors HIH6131 communication through I2C and LCD display updates the display every 0.5 seconds.


Figure 2-9: Experimental results of humidity and temperature readings from sensors HIH6163

Waijung Blockset version 13.12a has a block to read data from HIH6131 sensor in Simulink library: Waijung Blockset >> Hardware Modules>> aMG Sense Temp Humid. Figure 2 10 shows an example of using HIH6131 block. User have to put I2C Master Block on main model. Data which is received from HIH6131 are relative humidity and temperature. User can immediately use them to display or record data.


Figure 2-10: Simulink Model for humidity and temperature readings using HIH6131 block

3 Using Pressure Sensor MPL3115A2

3.1 Equipment Used for Experiment


Figure 3-1: aMG Sense Pressure / Altitude board

Value of Slave address, 7 bit Address of MPL31152A, is 0x60 [5, p. 6] or ‘1100000’ when combined with Read/Write bit the binary will be ‘11000000’ or 0xC0

Flow chart of using and reading data as polling is shown in Fig [5, p. 12] . Read data as air pressure to use as Barometer [5, p. 32]


Figure 3-2: Flow chart for settings the sensor

Pressure and temperature data can be converted digitally to the air pressure in Pascal and the temperature in degrees Celsius. The next experiment describes this phenomena.

3.2 Measurement of air pressure.

Purpose


Figure 3-3: Simulink model for reading air pressure and communicates through I2C

Figure 3-3 shows the Simulink model for the reading of the air pressure using MPL3115A2 sensor and communicates through an I2C and displays the results on a LCD screen. In this example, we will read the air pressure and the reading of the Polling which have to start from the default settings by subsystem block which is shown in Figure 3-4.


Figure 3-4: Subsystem model for the initial setup of the sensor MPL3115A2

Subsystem in Figure 3‑4 will check that MPL3115A2 has set the values as in Figure 3‑2 or not. Register 0x26 of sensor must be equal to 0x39 and register 0x13 must be equal to 0x07. If the setting is correct, the ON signal will be sent to start reading and if not correct then follow as shown in Figure 3‑5.


Figure 3-5: Subsystem Model for initial configuration MPL3115A2 Sensor with I2C Master Write

When completed, the sensor began to read the air pressure and temperature which are identified in Figure 3‑6. Address of the registers of the sensor (in the registers address 0x00) to read the air pressure and temperature which are 3-byte, 2 bytes, respectively.


Figure 3-6: Enable Subsystem Model for reading data from sensors MPL3115A2

When status of sensor has data which is not ready to be sent (DATA_VALID = 1), value of air pressure will be in digital data (20 bit unsigned). Data’s (always positive) first 18 bits will come from P_LSB and last 2 bit in position 5-4 of P_LSB showing decimal value [5, p. 23]. All data will be converted into pressure value in Pascal by Convert Subsystem Block that shown in Figure 3‑7. Figure 3‑8 shown example of Convert Subsystem Block.


Figure 3-7: Enable Subsystem Block for converting pressure units from digital form into Pascal

In order to display temperature data from MPL31152A user have to create Subsystem Model for convert read data in digital data to 12 bit data in 2’s complement. First 8 bits come from T_MSB and last 4 bits in 7-4 of T_LSB for display decimal value.


Figure 3‑8: Example to convert Subsystem Block

Figure 3‑9 shows experimental results showing the air pressure readings from sensors MPL3115A2 communication through I2C and then displayed through the LCD.


Figure 3‑9: The results of the pressure sensor readings MPL3115A2 communication through I2C

If the user wants to read the height above sea level (Altitude), this can be done by setting up a working sensor MPL3115A2 as an Altimeter Model (registers 0x26 sensor be equal 0xB9) then create Subsystem model for conversion. The height above sea level readings are in the form of digital data. Data is a 20-bit 2’s complement (positive and negative), the first 16-bit data from the P_MSB and P_CSB bit of P_LSB 7-4 showing the decimal places (resolution 0.0625 m) [5, p. 23].

In Waijung Blockset version 13.12a, block for reading data from MPL3115A2 sensor is available in the Simulink library: Waijung Blockset >> Hardware Modules >> aMG Sense Pressure. Figure 3-10 shows an example of using MPL3115A2 block. Users must place the I2C Master Block Model. Primary data from MPL3115A2 block is the air pressure. The information can then be used to display or record it immediately.


Figure 3‑10: Simulink Model for checking the air pressure using MPL3115A2 Block

4 Using light sensor MAX44009

4.1 Equipment Used in this Experiment

In this section, an example is demonstrated for intensity of light from LDR sensor using analog signal [6]. The resistance of LDR sensor will vary in accordance with the variation in the light intensity. However LDR sensor is not suitable to measure light intensity because conversion of voltage to light intensity unit (LUX) is dependent on the electric voltage and resistance which are affected by external temperature.


Figure 4‑1: aMG Sense Light2

Figure 4‑1 shows aMG ​​Sense Light2 board for photometric and sent over the I2C sensors from MAX44009 (Manufacturer: Maxis Integrated). This board has the following features.

User can select Slave address of MAX44009 by connecting supply voltage )VDD) or Ground (GND) at pin A0 (Pin3) of MAX44009 when connected to supply voltage (address is 0x96) or Ground (Address is 0x94) respectively.


Figure 4‑2: Map of Slave address MAX44009 [7, p. 16]

To read data from sensors, users must read from I2C by address of the Register within MAX44009. Figure 4‑3 shows that the intensity of light measured in digital format in Address 0x03 and 0x04 with an exponent of Exponential [E3-E0] and the Mantissa [M7-M0]. Light intensity in Lux can be obtained from the following equations.


Figure 4‑3: Diagram of the MAX44009 register address [7, p. 7]

4.2 Reading the photometric MAX44009.

Purpose


Figure 4‑4: Simulink Model for photometric readings and communication through I2C

After downloading the model into STM32F4Discovery, light intensity reading will start at the address of register of sensor we want to read. By start reading at value of sensor at register address 0x02 the readings of light intensity value (2 bytes) will be in register address 0x03 and 0x04 respectively.

Then convert data into “Lux” unit by Subsystem Model as Figure 4‑5. Since Simulink Block for power calculation cannot work with GNU compiler so user should use custom code block or MATLAB function Block. This example use MATLAB Function Block in Simulink library: Simulink >> User-Defined Functions.


Figure 4‑5: Subsystem for converting digital data into a unit Lux

Figure 4‑6 shows experimental result of the experiment in which the intensity of the light is measured using MAX44009 sensor by reading every 1 second. Reading of light intensity is increased when the light is very bright (up to 188,000 Lux when it gets direct sunlight).


Figure 4‑6: Results of photometric readings from the sensor MAX44009

In Waijung Blockset version 13.12a, reading data from MAX44009 block can be done via Simulink library >> Waijung Blockset >> Hardware Modules >> aMG Sense Light. Figure 4-7 shows an example of using the MAX44009 Block. User must place I2C Master Block Model. Users can use this module for displaying and recording the information immediately.


Figure 4‑7: Simulink Model for reading the light intensity using MAX44009 Block

5 Using Digital Clock Module DS3231

Time is money. Human life is dependent on time. We set our schedule for everyday life to match with the present life demands. So we can say that human life style is associated with time. There are many units of time by volume. The smallest unit of time is second and 60 seconds makes a minute. 60 minutes makes an hour and 24 hours makes one day which defines our life routine. 30 or 31 days makes a month and 12 months constitutes a year. These all definitions are related with the rotation of the Earth around the Sun.

The SI definition of second is “the duration of 9192631770 periods of the radiation corresponding to the transition between the two hyperfine levels of ground state of the Caesium 133 atom”. In embedded system, crystals are used to create a defined frequency signal with a fixed frequency. For example, in the CPU or computers and microcontrollers, timing is determined by crystal circuit which gives a very precise frequency and is less affected by outside temperature.

Time is necessary in personal computer system especially in data storage that has to keep date, month, year. Time reference can be used in small embedded system too, for the example: store data from sensors with date, month, and year, or setting a timer to on and off automatic devices.

5.1 Equipment Used in this Experiment


Figure 5‑1: aMG high precision RTC

Figure 5‑1 shows the display board aMG ​​High Precision RTC DS3231 from Maxim Integrated Raid which is a digital clock module. The module has a crystal inside having a signal frequency of 32kHz, which is used to count the seconds, minutes, hours, days, months and years of a calendar in order to adjust the date, the leap year (1 year = 366 days) till the year 2100. [8, p. 1]. All data is sent via the I2C communication module which can be connected to a battery backup to maintain the time no matter power of microcontroller goes off.

Slave device address of the IC DS3231 is 0xD0 [8, p. 17]. To read a clock and calendar, users must read that from the specified I2C address register of the DS3231 as shown in Figure 5‑2. Address of 0x00 to 0x06 is to keep the clock and the date correct. The data format is Binary-coded Decimal (BCD).


Figure 5‑2: Memory map of digital clock module [8, p. 11]

5.2 Time Setting Clock Module DS3231

In Simulink Library >> Waijung Blockset >> Hardware Modules >> aMG High Precision RTC Block for DS3231 through I2C interface consists of the following.

5.2.1 How to use DS3231 Configure Block

After putting the battery back-up or start the DS3231 clock for the first time, the calendar data and time is will be shown as 01/01/00 00:00:00 (day / month / year. Hours: minutes: seconds), so it is necessary to set the clock. DS3231 Configure Block is Subsystem Block included in DS3231 Blockset so that the user can set the time by pressing buttons (Digital).


Figure 5‑3: DS3231 configure block

Input port of the DS3231 Configure Block has the following functionalities.

5.2.2 Sample Time Setting Clock Module DS3231

Purpose


Figure 5‑4: Simulink Model for the initial setup of the module clock DS3231

Download model on the microcontroller and setup procedure is as follows.

5.3 View the time, day, month, year of a digital clock module DS3231.

Purpose

5.3.1 How to use DS3231 Get Date / Get Time Block.

When users put the battery back-up and set the digital time clock module, users can read the time and date of DS3232 Get Time and DS3232 Get Date respectively. Figure 5‑5 shows Blockset for reading the time and date of the DS3232 which communicates through I2C so the user must place the I2C Master Block.


Figure 5‑5: (a) DS3231 Get Time Block, (b) DS3231 Get Date Block

DS3231 Get Time Block display the time read from the DS3231 digital clock module and the characteristics are as follows.

DS3231 Get Date Block displays the date on the calendar to read from DS3231 digital clock module are as follows.

5.3.2 Example of Reading the Time, Day, Month, Year of a Digital Clock Modules


Figure 5‑6: Time for reading date from the module clock

Figure 5‑6 shown Simulink Model to read time and date from digital clock module by adding controlling part to ON-OFF external device by clock and change displayed date format.

After downloading the model into microcontroller, LCD shows calendar by Month. Character Subsystem Block in Figure 5‑7 will get month value and display in English format. Ex: data read from Month = 2, display will show it as Feb.


Figure 5‑7: Subsystem for displaying the month in English

Furthermore, user can apply DS3231 to use as Timer to ON/OFF external device. For example, when reading Hour, if the value is in between 12 and 13, digital output signal at PD12 will be ON so the LED1 will be on at 12:00:00 to 12:59:59 as shown in Figure 5‑8.


Figure 5‑8: Results – Reading the DS3231 clock, clock module and LED ON-OFF

5.4 Setting the Date and Time for Clock Module DS3231.

Purpose

5.4.1 How to use DS3231 Set Date / Set Time Block.

When setting the digital time clock module, users can set the time and date on DS3232 Set Time and DS3232 Set Date Block respectively. Figure 5 9 shows Blockset to set the time and date of the DS3231 and it communicates through I2C. The input for DS3232 is Slave address, hour, minute and second and for DS3231 Set Date Block the input is Slave address, Date, Month, Year.


Figure 5‑9: (a) DS3231 Set Time Block, (b) DS3231 Set Date Block

Following are the attributes of DS3231 Set Time Block. and Set Date Block.

Following are the attributes of DS3231 Set Date Block.

5.4.2 Example of Setting the Date of Communication through UART.

For this experiment users should pursue peripheral control via serial communication.


Figure 5‑10: Simulink Model for setting time and date of DS3231 via UART communication

Download Simulink model as shown in Figure 5‑10 into the microcontroller. The LCD display will show the time and date which is read from the DS3231 module. To set the clock, user must type respective commands on programs like TeraTerm or Putty terminal window like T = hours: minutes and then press Enter to Activate Subsystem in Figure 5‑11. An acknowledgement message of Ok will be sent and the clock settings will be complete and the LCD display will be showing the updated time.


Figure 5‑11: Subsystem model for clock setting

To set the calendar, users need to type the command D = Date – Month – Year, and then press Enter to Activate Subsystem as in Figure 5‑12 which is a Subsystem Model for the calendar. Ok acknowledgment signal will be sent and setting of calendar will be complete. LCD will now be showing the data.


Figure 5‑12: Subsystem model for the calendar

Figure 5‑13 shows the equipment used in this study. Computer is connected to the aMG ​​USB Converter-N Adapter. If not battery backed clock module is available then the LCD display will show the date as 1 January 2000 and start the clock at 0:00.


Figure 5‑13: Experiment for clock setting via computer

Figure 5‑14 shows the clock setting. After typing the command in Teraterm program, the program will communicate with the computer via serial port. Users can set the clock or calendar. When the clock is set, seconds start counting from 0 every time.


Figure 5‑14: Results of clock setting through UART communication

5.5 Reading Temperature from DS3231 Module

Purpose

Digital clock DS3231 module have a temperature sensor installed inside to reduce the error caused by temperature to external crystal circuit. As a result, the clock signal is the most accurate for temperature measurement. Figure 5‑15 shows DS3231 using DS3231Temperature Block, located in the Simulink Library >> Waijung Blockset >> Hardware Modules >> aMG High Precision RTC.


Figure 5‑15: Simulink model for the temperature reading from DS3231 and it communicates through I2C

Download model into the microcontroller and LCD display will show the temperature measurement. The precision of the reading is +/- 3 ° C [8, p. 1].


Figure 5‑16: Results from measuring the temperature using DS3231 (communicates through I2C)

6 Example of I2C Device to Bus

Objective:

This example introduces the use of sensor for measuring humidity, temperature air pressure and light intensity at the same time by connecting SCL and SDA of the aMG board (Sense Humidity/Temperature, aMG Sense Pressure/Altitude and aMG Sense Light)2 in Bus is shown as Figure 6‑1.


Figure 6‑1: Connection kit for detection of humidity, temperature, air pressure and light intensity

Figure 6‑2 shows a Simulink model for measuring temperature, humidity, air pressure and light intensity. Communication is using I2C and LCD screen displays time and date. Digital clock DS3231 modules are connected on the aMG ​​F4 Connect board. The time and date information will be updated every 0.5 seconds.

  1. HIH6131 block for measuring humidity and temperature.
  2. MPL3115A2 block for measuring air pressure.
  3. MAX44009 block for measuring light intensity.
  4. DS3231 Get Time and DS3231 Get Date Block read time and calendar.

If one sensor is pulled off, LCD still display latest read value of that sensor and model still reads value from sensor.


Figure 6‑2: Simulink Model for measuring temperature, humidity, air pressure and light intensity

Figure 6‑3 shows the experimental measurements from sensors connected to the system bus. As discussed in Figure 6‑1, when connecting the power supply and 3.3V to SCL SDA GND pin of aMG F4 Connect to the sensor, the data (temperature, humidity, air pressure and light intensity) will be displayed on the LCD display and it will be updated every 0.5 seconds.

When installing the digital clock module (DS3231) that was to set clock value on aMGF4 Connect, first line of LCD will show present date and time.


Figure 6‑3: Results of sensor measurements and communication via I2C

References

  1. STMicroelectronics, RM0090: STM32F40xxx Reference Manual [Online], 2013
  2. Honeywell, I2C Communication with the Honeywell HumidIcom Digital Humidity/Temperature Sensors [Online], 2012.
  3. Totolphase, I2C Background, . [Online]. Available: http://www.totalphase.com/support/articles/200349156#theory, [Accessed 31 October 2013]
  4. Honeywell, Using Alarms on the Honeywell Hunidlcom Digital Humidity/Temperature Sensors: HIH-6130/6131 Series [Online], 2012 .
  5. Freescale Semiconductor, Data Sheet: Advance information I2C Precision Altimeter [Online], 2012.
  6. Aimagin, การใช้งานอนาล็อก IO, 2013. [Online]. Available: http://aimagin.com/blog/adc-dac/?lang=th.
  7. Maxim Integrated, MAX44009 Industry’s Lowest-Power Ambient Light Sensor with ADC, 2011
  8. Maxim Integrated, DS3231 Extremely Accurate I2C-Integrated RTC/TCXO/Crystal, 2013.

How to Use Internal Flash Memory

download all demo files: Flash.7z

1 Internal Flash Memory

1.1 Introduction

In embedded systems, it is very important to have a memory which can store the information. Programs (set of instructions) are used to make an embedded system behave in such a manner according to the user requirements. Our programs are written in C or Waijung Blockset which compiles the set of instructions. Microcontroller uses flash memory which can be erased and re-programmed. Some space of the memory can be re-programmed and some space of the memory is fixed (i.e. cannot be re-programmed) and it depends on the manufacturer of the microcontroller how they manages the memory allocations.

STM32F4DISCOVERY board have a STM32F407VGT6 microcontroller which has a capacity of 1 MByte flash memory. The flash memory of the microcontroller has been divided into the sectors and each sector have its respective starting and ending addresses. Some sectors are of small size and some are of large size. Allocation of flash memory space is shown in Figure 1‑1.


Figure 1-1: Allocation of flash memory space within the STM32F407 [1, p. 54]

The allocation of internal flash memory of STM32F407 is as follows.

The Waijung library has a blockset for using Internal Flash Memory Block having an option of erasing read and write data. The use is limited from sector 5 to 11.

1.2 How to use Flash Memory Block

Simulink library >> Waijung Blockset >> STM32F4 target >> On Peripheral Chip >> FLASH contains a blockset for managing the data in the flash memory. Flash Erase block parameters are shown in Figure 1‑2 which is used for deleting the data from the sectors. It takes about 1 to 2 seconds to erase the data from 128 KB memory [2, p. 106].


Figure 1-2: Features of Flash Erase Block

Block parameters of Flash Read are shown in Figure 1‑3. It is used to read the data from specified memory. For example, if used wants to read the address: 0x080E0500, following are the steps.

Thus Offset = 0x80E0500 – 0x80E0000

= 0x0000500 = 20480 (in decimal)


Figure 1-3: Characteristics of Flash Read Block

Flash Write block is shown in Figure 1-4. It is used for write data to the memory offset of specific sector id. The procedure for assigning the address and specifying the offset address is same as that of Flash Read Block as described above.


Figure 1-4: Characteristics of Flash Back Block

2 Testing the Flash Memory

2.1 Equipment used in the Experiment

http://www.st.com/web/catalog/tools/FM146/CL1984/SC724/SS1677/PF251168.

2.2 Experiment for Saving and Deleting Data

Objective


Figure 2-1: Simulink model for writing and erasing the data from flash memory

This experiment is conducted to write or erase flash memory address at 0x080E0500 using Simulink model as shown in Figure 1‑1 which consists of a three major blocks.


Figure 2-2: Within Flash Erase Subsystem model


Figure 2-3: Within FlashWritingSeq Subsystem model

While writing in the flash memory, it is good to erase the already existing information on that sector which can be done by using Flash Erase Block which will delete the information of the entire sector.

After the Simulink model is downloaded into STM32F4DISCOVERY board, LED1 which is connected with PD12 will blink. To observe the changes in the flash memory, this experiment uses STM32 ST-Utility program and have the following main steps.

2.2.1 Procedure for Connecting STM32 ST-Utility


Figure 2-4: STM32 ST-Link Utility window after connecting with STM32F4DISCOVERY


Figure 2-5: Core panel window

2.2.2 How to use Memory Display

Data in memory will be shown in hexadecimal format in a table form. Rows and columns show the position of address. User can adjust the memory display as follows.


Figure 2-6: Window displaying data in the memory (Data Width 32 bits or 4 Bytes)

When user set the Data Width = 8 bits on the memory display then the display will change as shown in Figure 2‑7. Now the size of address is 8 bits value (00 to FF).


Figure 2-7: Window displaying data in memory (Data Width 8 bits or 1 Byte)

2.2.3 Experiment with Writing and Erasing


Figure 2-8: Windows displaying the data in memory after writing


Figure 2-9: Window displaying the data in memory after deletion

2.3 Experimental data from Flash Memory

Objective


Figure 2-10: Simulink Model for reading data from Flash Memory and displayed through the LCD

From the example, in this experiment, users can observe data by STM32 ST-Utility connected to a computer with USB cable. Furthermore, user can observe data that has been record via LCD.

This experiment uses the model as shown in Figure 2‑10 for reading data from the flash memory and display it on the LCD which is an additional part when compared with the model shown in Figure 2‑1. Switch SW3 is used for updating the value read from flash memory and then display it on LCD. Figure 2‑11 shows internal subsystem model for reading data at address: 0x080E0500.


Figure 2-11: FlashRead Subsystem Model for reading data from Flash Memory

If user wants to write multiple data sets, user can edit Block in FlashWriteSeq Subsystem as in Figure 2‑13. In this example, 3 sets of data are written which have different type of variables (uint8, uint32 and single). User can add Flash Write Block and set any address within range of 4 Bytes


Figure 2-12: Values read from Flash Memory through the LCD display

If user wants to write multiple data sets, user can edit Block in FlashWriteSeq Subsystem as in Figure 2‑13. In this example, 3 sets of data are written which have different type of variables (uint8, uint32 and single). User can add Flash Write Block and set any address within range of 4 Bytes.


Figure 2-13: Subsystem model for writing or recording in multiple Flash Memory

So in the example, if the value read from the DIP switch is set to 12. Information address: 0x080E504 is equal to 12000 and address: 0x080E508 is equal to 1481.40 so users can check in flash memory window which displays the data in memory as shown in Figure 2‑14.

Figure 2-14: Window displaying data in the memory

Users can learn how to convert a decimal number to binary floating-point arithmetic from the following link http://www.h-schmidt.net/FloatConverter/IEEE754.html. This is known as IEEE-754 standard.

Figure 2‑15 is an example of subsystem for reading 3 data sets of different type of variables (uint8, uint32 and single). User can add the Flash Read Block and set address that want to read.


Figure 2-15: Subsystem for reading data of multiple types

Download the model and information stored in DIP switch, SW1 switch and SW2 switch will be displayed on the LCD display which is shown in Figure 2‑16.


Figure 2-16: Reading value from multiple data sets of flash memory and display it on the LCD

Although user can turn ON-OFF the electric power or download model into STM32F4DISCOVERY again, data in sector 5 – sector 11 will still remain unchanged. So using internal flash memory is suitable for working with data which is not changed so often, for example security or setup section.

3 References

  1. STMicroelectronics, “RM0090: STM32F40xxx Reference Manual [Online],” 2013.
  2. STMicroelectronics, “STM32 F407xx Datasheet-production data [Online],” 2013.
  3. STMicroelectronics, “User manual: STM32 ST-LINK Utility software description [Online],” 2014.
  4. Olaf Pfeiffer and Andrew Ayre, “Using Flash Memory in Embedded Applications,” [Online]. Available: http://www.esacademy.com/en/library/technical-articles-and-documents/8051-programming/using-flash-memory-in-embedded-applications.html.
  5. IEEE, “IEEE Standard for Floating-Point Arithmetic”, 2008
  6. http://en.wikipedia.org/wiki/IEEE_754-1985

How to Use SPI Communication Port

download all demo files: SPI.7z

1 Using SPI Communication Port

1.1 Knowing SPI

Serial Peripheral Interface or SPI is another form of Serial Synchronous Communication. In this type of communication one device works as Master while another acts as a Salve. Master device initiates the data frame and there can be multiple slave devices. SPI works in full duplex mode. Signals between Master and Slave can be sent simultaneously. One of the biggest advantage of SPI protocol is that the complete protocol has flexibility for the bits transfer and not limited to 8-bit words. There can be arbitrary choice of message size content and purpose.

Here are few examples for the devices which uses SPI communication


Figure 1‑1 shows the connection between SPI Master and Slave. The link have four lines/wires

Master device’s function is to control all communications with clock signal and signal line SS. The Master will decide whether to receive or send data into slave device signal line SS (Slave Select) in case of having more than one slave by make signal level of that SS LOW. If we want to connect to particular SS, just set the signal level of that SS to LOW as shown in Figure 1‑2.


Figure 1-2: SPI communication between Master and Slave

When comparing the SPI communication with I2C communication, the former one has higher throughput and is ideal for low speed data communications such as EEPROM memory module or digital clock.

SPI communication has an advantage of full duplex communication that is able to transmit and receive simultaneously for particular cable. Typically SPI has lower power requirements than I2C due to simple hardware interface. Slaves use the master’s clock and do not require precision oscillators. SPI is not limited to any maximum clock speed, enabling potentially high throughput.

1.2 Using SPI Blockset

Waijung Blockset consists of SPI Master Setup Block as shown in Figure 1‑3. To set any Register values related to SPI communications i.e. select SPI module in STM32F4DISCOVERY up to three sets, select pin MOSI/MISO/SS and set frequency of clock signal in SCLK.


Figure 1-3: Characteristics of settings of SPI Master Setup Block

SPI communication has no certain pattern, in order to set communication pattern of Master device to match with Slave we have to do the following things:

  1. Set communication direction, Full Duplex (receive and transmit data in same time) Half Duplex Tx (transmission only), Half Duplex Rx (receive only)
  2. Data receiving and sending format 8 or 16 bit, can select first bit to send either most significant bit (MSB) or lowest significant bit (LSB)
  3. Form of clock signal edge to setting tempo of receiving – sending data. There are 4 types:


Figure 1-4: Data is received or sent when CPOL = 0 and CPHA = 0 0 [1, p. 800]

When the clock polarity is LOW and clock phase 2nd edge (CPOL_Low/CPHA_2Edge), the system will start reading first bit when found second edge of signal (negative edge) as shown in Figure 1‑5.


Figure 1-5: Data receiving and sending when CPOL = 0 and CPHA = 1 [1, p. 800]

When the clock polarity is HIGH and clock phase 1st edge (CPOL_High/CPHA_1Edge) is at the initial state (clock signal will be in HIGH state), the system will start reading first bit when found first edge of signal (negative edge) as shown in Figure 1‑6


Figure 1-6: Data receiving and sending when CPOL = 1 and CPHA = 0 [1, p. 800]

When the clock polarity is HIGH and Clock phase 2st edge (CPOL_High/CPHA_2Edge), the system will start reading first bit when found second edge of signal (positive edge) as Figure 1‑7


Figure 1-7: Data receiving and sending when CPOL = 1 and CPHA = 1 0 [1, p. 800]

SPI Master Read/Write Block as shown in Figure 1‑8 receives or sends data into slave device by SPI. STM32F4DISCOVERY is used as Master device and user can set number of byte which need to be sent.


Figure 1-8: Properties and setting the values of SPI Master Read/Write Block

2 Example of using DAC with SPI communication

This section describes how to use SPI communication to control devices. This example given below uses IC LTC1661 (from Linear Technology). Signal converter module is used to convert 10 bits to 2 analog channels. Although STM32F4DISCOVERY has 2 DAC channels, users can use this device if they want to add more analog voltage supply channel.


Figure 2-1: IC PINs of LTC1661 [2]

Figure 2‑2 shows the data of LTC1661 through SPI to adjust the voltage. When looking at clock signal pattern, in Idle state, the signal is LOW and reads data bit on MOSI when the positive edge is found (1st edge capture). One data set has 16 bits containing a digital value. 10 bits are needed to convert the voltage value and 4 bits control code for controlling IC LTC1661 and last two bits are don’t care bits as shown in Figure 2‑3. Maximum frequency of clock signal that IC LTC1661 can work properly is 16.7 MHz [2, p. 3].


Figure 2-2: SPI Communication of IC LTC1661 [2, p. 9]


Figure 2-3: Description table of Control Code of IC LTC1661 [2, p. 9]

2.1 Experiment Devices


Figure 2-4: Installation of signal generator with IC LTC1661

Figure 2‑4 shows connection between STM32F4DISCOVERY and IC LTC1661 on the aMG F4 Connect board having port to connect SPI device by setting PA15 pin as Slave Select (NSS), PB3 pin as SCLK, PB4 pin as MISO and PB5 pin as MOSI. IC LTC1661 receives data from Master device only. Users just have to connect transmission line for MOSI data.

Table 2-1: Connection between STM32F4DISCOVERY and IC LTC1661

2.2 Experiment to Use IC LTC 1661 on SPI Communication

Objective:


Figure 2-5: Simulink Model to generate one channel analog signal with ICLTC1661

Figure 2‑5 shows Simulink model for creating one channel analog signal with IC LTC1661 through SPI communication. After downloading the model into STM32F4DISCOVERY, the value of Control Code = 1001 and value from Counter Limited Block will be exported and Counter Limited Block will start counting from 0 to 1023 every 0.1 ms to Slave device for DAC. After 0.1 second, the value of Counter will start from 0 again (So the signal frequency is 10 Hz). Figure 2‑6 shows the signal measured from pin 8 (Vout A) of IC LTC1661 using Oscilloscope.

The measurements from Figure 2‑6 shows the signal frequency of 9.766 Hz or has signal period = 0.102 seconds and maximum signal value is around 3.04 V.


Figure 2-6: Experiment result of analog signal generation with IC LTC1661

Figure 2‑7 shows a Simulink Model for constructing two channels of analog signal. Control Code = 10 is used for sending DAC to B channel, and Pulse Generator Block is used for selecting data to send to SPI.

When the value of Pulse Generator Block is 0 and the value of Control Code = 1010, a constant value of 256 will be sent thus VoutB = (259 / 1023) x 3 = 0.826V (can measure by Digital Multimeter). When Pulse Generator Block = 1 and value of Control Code = 1010 and value of Counter will be sent alternatively every 0.05 ms.


Figure 2-7: Simulink Model to generate two channels analog signal with multiplexer technique

3 Reading the Value of Linear Accelerometer LIS302DL

Nowadays, the use of linear accelerometer has been increased tremendously in smart control systems such as screen adjustment of LCD in smartphones and notebooks, vibration detector, burglar alarm and subsystem of navigational system in unmanned aerial vehicle (UAV).

When we are on earth surface and drop an object to the earth, that object will fall into the ground with constant acceleration known gravitational acceleration (g). The value of g is known to be 9.8 m/s. If we measure an object with 3g acceleration, it means it is travelling with the speed three times than the gravitational acceleration.

3.1 Experiment Devices

This experiment uses STM32F4DISCOVERY as shown in Figure 3‑1 installed with accelerometer LIS302DL developed by STMicroelectronics. Properties of LIS302DL are:


Figure 3-1: Device installation for reading data from LIS302DL sensor through SPI communication

In order to read data from SPI, user need to read the communication format of LIS302DL from Datasheet [3]. Data reading formats of LIS302DL has two ways to read, one byte (8 bits data) and multiple bytes per time. Number of bytes depends on command. Figure 3‑2 shows the data format of LIS302DL. Master device send the command and address of internal register of LIS302DL.


Figure 3-2: Data reading form of LIS302DL through SPI 1 byte per time [3, p. 22]

Multiple bytes reading can be done by setting M/S = 1 and define the initial start address. Data from LIS302DL will be sent to Master device on the tempo of SCLK signal. When 8 bits are sent already, LIS302DL will send data from next address until the Master device stop data reception.


Figure 3-3: Data reading form of LIS302DL through SPI, multiple bytes (in this example 2 bytes)

Writing data into LIS302DL has two ways too. In Figure 3‑4 and Figure 3‑5 shows data writing to LIS302DL one byte and multiple bytes per time respectively. Master device send writing command and address of internal register of LIS302DL then data is sent to set value in that register.


Figure 3-4: Data writing form of LIS302DL through SPI one byte per time [3, p. 22]


Figure 3-5: Data writing form of LIS302DL through SPI multiple bytes [3, p. 23]

Figure 3‑6 shows the address of internal register of LIS302DL. Each register has different functions, such as controlling the functionality of the sensor, store variable values and store the measured linear acceleration value etc.


Figure 3 6: Address of internal register of LIS302DL [3, p. 24]

Simulink model for reading acceleration values in three axis of LIS302DL sensor is shown in Figure 3‑7. The model in figure below has three main functions:


Figure 3-7: Simulink Model for reading data from LIS302DL sensor through SPI communication

After downloading model into STM32F4DISCOVERY, the program will read initial state of LIS302DL by subsystem as in Figure 3 8. That is the one byte data reading as SPI from CTRL_REG Register at (Address 0x20). If the read value is not equal to 0xC7, the data is written as SPI at CTRL_REG Register.


Figure 3-8: Subsystem model for setting up initial value of LIS302DL

Then LIS302DL Read Subsystem starts to read the acceleration values of the three axis. All data are in Out_X, Out_Y and Out_Z Register (Address 0x29, 0x2A and 0x2D) respectively. Figure 3‑9 shows data reading as SPI 6 bytes and set Out_X to be starting address.


Figure 3-9: Subsystem Model for reading acceleration value of three axes from LIS302DL

The read value is int8 type, signed integer 8 bit (value -127 to 127) and display it via UART communication every 0.02 seconds or 50 Hz. Figure 3‑8 shows settings of Full Scale selection (FS) = 0. That’s means measuring linear acceleration in interval ±2g thus linear acceleration (unit: g m/s2) can be calculated from equation:Then LIS302DL Read Subsystem starts to read the acceleration values of the three axis. All data are in Out_X, Out_Y and Out_Z Register (Address 0x29, 0x2A and 0x2D) respectively. Figure 3‑9 shows data reading as SPI 6 bytes and set Out_X to be starting address.

Acceleration = 2 x measured value/ 127

When the Z-Axis of sensor is in the line of the gravity, the measured acceleration is 1g or the value = 64

Figure 3‑10 shows linear acceleration via TeraTerm program on STM32F4DISCOVERY. Acceleration value in Z-axis will be maximum because of gravitational acceleration and the value in X-Y axis will be minimum because they are parallel with earth surface.


Figure 3-10: Experimental results of linear acceleration data reading

3.2 Example of Acceleration Detection in case of Crash.

When an object is crashed, the acceleration will be changed in short time and we can use the sensor to detect it and bring that value to alarm or control any devices for further processing. For the examples, burglar alarm, vibration detector, safety airbag, etc.

Figure 3‑11 shows Simulink model to display the value of linear acceleration in real time. This model is working on computer (Don’t need to download into STM32F4DISCOVERY) when connected STM32F4DISCOVERY via USB and press Run icon. This program will read linear acceleration value from STM32F4DISCOVERY through USB cable.


Figure 3‑11: Simulink model to display result of linear acceleration in real time

Note: You should close all serial communication programs before running this model.


Figure 3-12: Devices preparation for experimenting with linear acceleration in real time

After double clicking the Scope Block, graph of linear acceleration in 3 axis will appear in real time, it mean the pattern of graph will change if STM32F4DISCOVERY changes its position as in Figure 3‑13.


Figure 3‑13: Graph of real time linear acceleration measured by LIS302DL

4. References

  1. STMicroelectronics, “RM0090: STM32F40xxx Reference Manual [Online],” 2013.
  2. STMicroelectronic, “LIS302DL MEM motion sensor,” 2008.
  3. Linear Technology, “LTC1661 Micropower Dual 10-Bit DAC in MSOP,” 1999.
  4. K. a. R. Kalinsky, “Introduction to Serial Peripheral Interface,” Embedded.com, UBM Electronics, 2002. [Online]. Available: http://www.embedded.com/electronics-blogs/beginner-s-corner/4023908/Introduction-to-Serial-Peripheral-Interface.
  5. P., “การติดต่อสื่อสารด้วย SPI : Serial Peripheral Interface,” [Online]. Available: http://www.123microcontroller.com/Hardware-Interfacing/SPI-Serial-Peripheral-Interface-communication. [Accessed 27 February 2014].

How to Use UART Communication Port

download all demo files: UART.7z

1 Using UART Communication Port

Modern embedded systems are often based on microcontroller which can be connected to various external devices which enables the embedded system to send and receive information to external devices.


Figure 1‑1: Parallel data transmission between FiO2 and aMG Camera INF

Communication between microcontroller and external device can be classified into two types:

In STM32F4DISCOVERY, there are many types of communication module UART, I2C, SPI, USB, CAN bus and Ethernet etc. In this section, UART module will be discussed.

1.1 Introduction to UART Communication Module

UART stands for Universal Asynchronous Receiver Transmitter that will connect and communicate with serial devices such as computers, RFID, GPS, GSM module, Wi-Fi module etc.

The advantages of using asynchronous communication is availability of full duplex communication i.e. it can send and receive data between the transmitter and receiver simultaneously and do not require clock synchronization for data transfer. The universal designation indicates that the data format and transmission speeds are configurable.


Figure 1‑2: Communication model for Universal Asynchronous Receiver Transmitter [1]

Figure 1‑2 shows the format of UART communication with users to define these properties Following are some typical configurations;

In addition, users should consult the voltage level of the signal required by UART communication.

Figure 1‑3 shows the connection between the serial communication Transmit Data (Tx) pin of transmitter with Received Data (Rx) pins of the receiver to send and receive the data. Transmitter and receiver should have a common ground. If the devices are connected with different voltage levels then additional electronic components like MAX232 [2] should be added in path to adjust the voltage level.


Figure 1‑3: UART connection

The blockset responsible for transfer of data via UART protocol in STM32F4DISCOVERY can be accessed from Simulink library >> Waijung Blockset >> STM32F4 Target >> On Peripheral Chip >> UART consisting of UART setup, UART Tx and UART Rx block

If users want to use UART STM32F4DISCOVERY, then users need to have UART Setup Block in Simulink model.

  1. Enable pin GPIO clock for Tx, Rx, RTS and CTS;
  2. Set the pin STM32F4 for Tx, Rx, RTS and CTS;
  3. Select the UART Module Clock;
  4. Set up the UART;
  5. Enable DMA clock;
  6. Setting the Direct Memory Access for accessing information.

The UART Setup Block features are shown in Figure 1‑4. In the settings, serial communication port UART module 3 is used and PD8 and PD9 are used for Tx and Rx respectively. Baud rate is set to be 115200 with no parity bit, 1 stop bit.


Figure 1‑4: UART setup configuration

2 Experiment using UART Communication Port

2.1 Equipment used in this Experiment

In this section, introduction to aMG USB Converter-N-Adapter is given which has FT2232H high speed USB 2.0 (480 Mbps), a UART/FIFO two channels [3]. Such type of hardware is ideal to be used for Hardware In Loop (HIL) simulation.


Figure 2‑1: Characteristics of aMG USB Converter-N-Adapter [3]


Figure 2‑2: STM32F4DISCOVERY and PC connection

When aMG F4 Connect is connected with the power supply and aMG USB Converter-N Adapter with the PC for the first time, the user must make sure to follow the below mentioned procedure.

Go to Start Menu, right click on Computer icon and selection the properties. A new window will appear as shown in Figure 2‑3.


Figure 2‑3: Pop up window

Go to device manager, expand the Ports (Com & LPT) which is managing the computer’s parallel ports and serial communication which is shown in Figure 2‑4.


Figure 2‑4: Device manager window to confirm port number

In addition to the above check of port number, the user need to set the Com Port Latency Time to higher speed which will help in improvement of data transmission speed which is essential in Hard in Loop Latency Timer setting. This can be done by following way.


Figure 2‑5: Advanced settings for Com Port connected with aMG USB Converter-N Adapter


Figure 2‑6: Changing the Latency Timer for Com Port

After reviewing the Com Port number and Latency Timer, next is to set the Com Port on the Host Serial Blockset (when using Hard In the Loop Simulation) or serial communications ports. In the next section, we will introduce Freeware programs to communicate through the serial port.

2.2 Using Serial Communication port

Tera Term is a freeware program which can be used for serial communication. The program can be downloaded from http://www.ayera.com/teraterm/. This program works only with Microsoft Windows operating system. Users can configure the communication ports and the procedure is as follows:


Figure 2‑7: Selecting communication port in Tera Term


Figure 2‑8: Setting terminal window in Tera Term program


Figure 2‑9: Serial port settings

PuTTY is a client program for the SSH, Telnet and Rlogin network protocols. Commands from the clients can be sent to the server through internet via serial communication port. PuTTY can work on Windows and Linux platforms and can be downloaded from http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html

Following steps are helpful in while using the serial port with putty


Figure 2‑10: Putty configuration


Figure 2‑11: Terminal settings in Putty

Serial port settings for Putty are shown in Figure 2‑12. The baud rate is set to be 115200 bps with no parity bit and one stop bit.


Figure 2‑12: Serial port settings for Putty

2.3 How to use UART Tx Block

UART Tx Block is used to send data out of the microcontroller to the external devices via Tx pins and provides a convenient way for the transfer of data. There are three Packet Modes available and user can choose any one of them. These modes are ASCII Mode, Binary Mode and String Buffer Mode.


Figure 2‑13: UART Tx Block settings

2.4 Experimental Demonstration of Message Transmission from STM32F4DISCOVERY to Computer

Purpose


Figure 2‑14: Simulink model for UART Tx

When the program is downloaded in STM32F4DISCOVERY, the text included in ASCII Format Dialog and End of Packet i.e. ‘Greeting from Waijung \n \r \ n’ will appear in Tera Term window and the same message will repeat after every 1 second (sampling time). This is shown in Figure 2‑15.


Figure 2‑15: Tera Term display message received via UART communication port

Question : What should be done if user want to set UART Tx Block messages immediately after newline?

Answer : “\n” is the newline. The example shown above ASCII Format is ‘Greeting from Waijung\n’ and End of Packet is CRLF (0x0D 0x0A – “\r\n”).


Figure 2‑16: Simulink model for sending messages in Packet mode

Simulink Model in Figure 2‑16 is an example of the Enable Subsystem for sending messages using Packet Mode or to read the digital signal. Dip-Switch is an optional mode of operation and is functionality is as follows.

When the program is running, the terminal window will display “Greeting from Waijung” every 5 seconds.


Figure 2-17: Subsystem Block for sending messages using the Packet Mode and String Buffer

When DIP-SW1 is set to OFF and DIP-SW2 is ON signal from the switch activates Sub System “SendMessage Bin”, which is an example of using the UART TX Binary Packet Mode. Figure 2‑18 contains the Sub System.


Figure 2-18: Subsystem Block for sending messages using the Binary Packet Mode

The Terminal window displays a character-only (ASCII Printable Character) from The ASCII Code Table [3]. In Figure 2‑19 hexadecimal code 0x00 to 0x1F which are used as an example. ASCII Control Character 0x0A is for the new line. ASCII Printable Character starts from 0x20.

When the program is running in the TeraTerm window, characters will be displayed after every 1 second as shown in the table without newline (because there is no “\ n” or 0x0A) but begins to the left every time.


Figure 2-19: ASCII table [3]


Figure 2-20: Subsystem Block for sending messages using the ASCII Packet Mode

Figure 2‑21 shows the Enable Sub System Block. Users can configure the UART Tx Block Packet Mode and sampling time.

Figure 2-21: Terminal displays messages received via the UART communication mode

2.5 How to Use UART Rx Block

UART Rx Block is used to receive data from external devices through the Rx pins. ASCII mode is selected for the Packet mode however user can choose from the three modes available.


Figure 2-22: Settings while using UART RX Block in ASCII Mode

2.6 Experiments using Computers

Purpose


Figure 2-23: Simulink model for data transmission between UART Rx Blocking and computer


Figure 2-24: Simulink model for data transmission between UART Rx Non-Blocking and computer

Figure 2‑23 and Figure 2‑24 show Simulink model for the experiment for the transfer of data from computer in Blocking and Non-blocking mode respectively. The Simulink model need to be downloaded into STM32F4DISCOVERY. User can open Tera Term window and type the text “Hello Waijung” on the Terminal window. This message will appear on the LED attached with STM32F4DISCOVERY via USB when Enter key is pressed. This is shown in Figure 2‑25.


Figure 2 25: Receiving messages from the computer

When user presses Enter to specify that the message is finished, 0x0d will appear on the display but it will not appear on the LCD display of the microcontroller.

In this example, users can observe the different behavior of UART_RX Block with Blocking and Non-Blocking. UART_RX block with blocking wait for completion of the running command before running another therefore LED2 is not flashing.

For the model in Figure 2‑24, when the user selects a UART_Rx Block with Non-Blocking, the ready signal will indicate that the message has been complete. It means that the model can accept other commands while the text is still not complete without blocking the incoming messages (note that LED2 light is flashing).

2.7 Peripheral Controller via Serial Communication

Purpose


Figure 2-26: Simulink model for Peripheral control via Serial Communication

Notice that users can use the same UART Rx Module with multiple blocks but within the same Packet Mode

Download Simulink model on STM32F4DISCOVERy and connect with Tera Term. Users can type the following command.

When send command LED1=1, press Enter UART Rx Block check the received message is “LED1=%u\r” which Activate Subsystem Block then the value %u will be sent to Subsystem Block as shown in Figure 2‑27. Inside of the system containing Digital Output Block to control ON/OFF for LED1 that is connected to PD12 pin. LED will be ON if the read value is not equal to zero, so set LED1=0 then Enter, the LED1 will off and UART Tx Block send response “>>OK” to user.


Figure 2-27: Subsystem block for light controlled LED

When printing ADC% u? Press Enter UART Rx1 Block, check the messages received is “ADC% u \ r” to Activate Subsystem1 Block then it will display the voltage reading.


Figure 2-28: Subsystem block for displaying voltage reading at pin PA5

When command Input is given followed by a number and then Enter , UART Rx2 Block verify received message “Input%f\r” to Activate Subsystem2 Block and then the read value (%f) will be sent to Subsystem Block as in Figure 2‑29 then prompt the text Your Input is: and the input number.


Figure 2 29: Subsystem block for displaying input number

Figure 2‑30 the message shown on terminal screen of program TerTerm is “>>OK” after ON-OFF the LED. Show value of voltage that read from PA5 and the received number in floating type.


Figure 2‑30: Result of peripheral control by computer

3 Experiment to Demonstrate Communication between Microcontrollers

Serial communication between the microcontrollers can happen directly. Therefore, users must make sure that the voltage levels between sender and receiver (in this case both are microcontrollers) are the same. This example use 2 set of microcontroller board. The first board is STM32F4DISCOVERY and the second board is FiO2 that uses microcontroller model STM32F417IG installed on board aMG F4 Connect. Both boards have voltage in serial cable approximately 3.3V.

3.1 Experiment for communication between Microcontrollers in Blocking type.

Objective:

To make users understand serial communication between microcontroller


Figure 3‑1: Simulink model for message blocking for board 1

After downloading the Simulink model into STM32F4DISCOVERY, the numbers 0 and 1 will be sent alternatively in Packet Binary by UART Module 1 via PB6 pin. And message ‘Value=%u\n’ will be sent by UART Module 6 via PC6 pin every 0.25 seconds.

Second board will be receiver. User must download model in Figure 3‑2 into FiO2 that have two blocks of UART RX Block. The first block will receive binary data and the second block will receive Ascii data. Blocks will receive data every 0.01 second. In order to make received data correct, the receiver should have double frequency rate to transmitter.

The received data from UART will use to control ON/OFF LED1 and LED2 on aMG F4 Connect. Both LEDs will blink every 0.25 second.


Figure 3‑2: Simulink model for text blocking on board 2

User can freely choose UART module for send and receive data by selecting module in UART Setup Block then connect Tx-Rx that matched to selected module. Figure 3‑3 shows the serial cable connections between microcontrollers. Both boards use UART Module 1 and 6.


Figure 3‑3: Communication between the microcontrollers (blocking)

3.2 Experiment for Communication between Microcontroller in Non-Blocking type.

Objective:


Figure 3‑4: Simulink Model for send data in Non-Blocking type in Board 1

Simulink model shown in Figure 3‑4 have 3 blocks of Non-Blocking UART TX. Each block will send different Ascii data and different frequency. After downloading model into STM32F4DISCOVERY, the first board will send “LED1=%u\n” every 0.125 second. UART Tx2 Block will send “LED2=%u\n” every 0.25 second and UART TX3 Block will send “LED3=%u\n” every 0.5 second via only PB6 pin.

Second board will be a receiver. User must download model in Figure 3‑5 into FiO2 that have 3 blocks of Non-Blocking UART RX Block. Each block will read Ascii data in every 0.001 second. When received the messages value, that value will be used to control ON/OFF LED within Enable Subsystem Block. In order to make the received data correct, the receiver should have double frequency rate to transmitter, same as in Blocking type.


Figure 3‑5: Simulink Model for receive data in Non-Blocking type in Board 2

Figure 3‑6 shows serial connection between microcontroller using UART module 1 for board 1 and board 2.


Figure 3‑6: Communication between microcontrollers (non-blocking)

4 References

  1. STMicroelectronics, RM0090: STM32F40xxx Reference Manual [Online], 2013
  2. Texas Instruments, MAX232-Dual EIA-232 driver/receivers [Online]. Available: http://www.ti.com/lit/ds/symlink/max232.pdf. [2004]
  3. Future Technology Device International, FT2232H DUAL HIGH SPEED USB TO MULTIPURPOSE UART/FIFO IC [Online]. Avaible: http://www.ftdichip.com/Support/Documents/DataSheets/ICs/DS_FT2232H.pdf. [2012].
  4. Aimagin, aMG USB Converter – N2 [Online]. Available: https://www.aimagin.com/amg-usb-converter-n2.html. [Accessed 18 February 2014].
  5. CommFront, ASCII Table / ASCII Chart – Standard and Extended ASCII Codes [Online]. Available: http://www.commfront.com/ascii-chart-table.htm [Accessed 9 January 2014]
  6. Jimbo, RS-232 vs. TTL Serial Communication- SparkFun Electronics, Sparkfun Electronics:, 23 November 2010. [Online]. Available: https://www.sparkfun.com/tutorials/215
  7. Ayera Technologies , TeraTerm 3.1.3 – Telnet, SSH2, SSL Client with built in Web Server 2002. [Online]. Available: http://www.ayera.com/teraterm/
  8. Tatham, PuTTY: A Free Telnet/SSH Client, [Online]. Available: http://www.chiark.greenend.org.uk/~sgtatham/putty/

HtmlToPdf API

API สำหรับแปลง HTML เป็น PDF
AmgCnt.Python.htmlToPdf(DataObject, Callback)
amgApi.coreLib.python.htmlToPdf(Object, Callback)
1. DataObject เป็น Object ของ HTML และ Options ต่างๆ
2. Callback เป็นฟังก์ชันสำหรับรอรับ object ผลลัพธ์การแปลง html เป็น pdf

ตัวอย่างการใช้งาน

AmgCnt.Python.htmlToPdf({
html: `
<div style="text-align: center;">Hi PDF</div>
`,
options: {
'css': ``,
'orientation': 'p',
'header-font-name': 'TH-SARABUN-PSK',
'margin-top': 10,
'margin-right': 8,
'margin-bottom': 10,
'margin-left': 8,
'footer-center': 'หน้า [page] ของ [toPage] หน้า',
'footer-font-size': 9,
'footer-spacing': 2,
},
dwn_file: 'file_name.pdf'
}, function(res) {
console.log(res);
})

DataObject จะมีโครงสร้างดังต่อไปนี้
html เป็นเนื้อหาที่จัดอยู่ในรูปแบบ html
options เป็น option object ที่กำหนดการแสดงผล HTML
dwn_file เป็นชื่อไฟล์ที่จะทำการตั้งให้ pdf (ต้องตามด้วย .pdf)

var DataObject = {
html: String,
options: OptionObject,
dwn_file: String
}

OptionObject ที่มีให้ใช้งาน
ชื่อ option ประเภทตัวแปร คำอธิบาย ค่าเริ่มต้น หมายเหตุ
css string css style ที่เสริมเข้าไปเพื่อควบคุมรูปแบบของข้อมูลก่อนการปริ้น -ใช้ word-wrap แทน break-word
-ไม่รองรับ CSS3
page-size string ขนาดหน้ากระดาษ
A3
A4
A5
Letter
A4 -ขึ้นต้นด้วยตัวใหญ่
orientation string การวางแนวของไฟล์ PDF
p คือแนวตั้ง
l คือแนวนอน
p
grayscale - ปรับ pdf ให้ออกมาเป็นขาวดำ -ไม่ใส่จะปริ้น pdf แบบมีสี
footer-left string ปริ้นช่วงซ้ายล่างของกระดาษทุกหน้า -ห้ามใช้ ' ในข้อความ
[page] จะถูกแทนที่ด้วยเลขหน้าปัจจุบัน
[toPage] จะถูกแทนที่ด้วยเลขหน้าทั้งหมด
footer-center string ปริ้นช่วงกลางล่างของกระดาษทุกหน้า ข้อจำกัดเดียวกับ footer-left
footer-right string ปริ้นช่วงขวาล่างของกระดาษทุกหน้า ข้อจำกัดเดียวกับ footer-left
footer-font-size number ขนาดของตัวหนังสือช่วงล่างของกระดาษ
footer-spacing number ขนาดของช่องว่างระหว่างเนื้อหาและตัวหนังสือช่วงล่างของกระดาษ ในหน่วย mm
footer-line - เพิ่มเส้นแนวนอนระหว่างเนื้อหาและตัวหนังสือช่วงล่างของกระดาษ -ไม่ใส่จะไม่ปริ้นเส้นลงใน pdf
header-left string ปริ้นช่วงซ้ายล่างของกระดาษทุกหน้า -ห้ามใช้ ' ในข้อความ
[page] จะถูกแทนที่ด้วยเลขหน้าปัจจุบัน
[toPage] จะถูกแทนที่ด้วยเลขหน้าทั้งหมด
header-center string ปริ้นช่วงกลางบนของกระดาษทุกหน้า ข้อจำกัดเดียวกับ header-left
header-right string ปริ้นช่วงขวาบนของกระดาษทุกหน้า ข้อจำกัดเดียวกับ header-left
header-font-size number, pixel ขนาดของตัวหนังสือช่วงบนของกระดาษ
header-spacing number, millimeter ขนาดของช่องว่างระหว่างเนื้อหาและตัวหนังสือช่วงบนของกระดาษ ในหน่วย mm
header-line - เพิ่มเส้นแนวนอนระหว่างเนื้อหาและตัวหนังสือช่วงบนของกระดาษ -ไม่ใส่จะไม่ปริ้นเส้นลงใน pdf
no-images ไม่ปริ้นรูปใดๆลงใน pdf -ไม่ใส่จะไม่ปริ้นรูปลงใน pdf
margin-top number, millimeter ระยะขอบกระดาษกับเนื้อหาด้านบน -อาจจะมีผลทำให้หัวกระดาษ ไม่ถูกพิมพ์ ให้ทำการปรับจูนค่าร่วมกับ option header-spacing
margin-right number, millimeter ระยะขอบกระดาษกับเนื้อหาด้านขวา 10
margin-bottom number, millimeter ระยะขอบกระดาษกับเนื้อหาด้านล่าง 10 -อาจจะมีผลทำให้หัวกระดาษ ไม่ถูกพิมพ์ ให้ทำการปรับจูนค่าร่วมกับ option footer-spacing
margin-left number, millimeter ระยะขอบกระดาษกับเนื้อหาด้านซ้าย

HTTP Block

How this block appears in a Simulink model?

appearance_http_get.PNG

appearance_http_post.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
HTTP Method GET--POST Specify the request type
Response buffer size 32--64--128--256--512--1024--2048--4096 Select the response buffer size
Enable semaphore control for HTTP block Check--Uncheck Having multiple HTTP blocks in the same model file can cause errors during run time. In such case this parameter should be enabled.
Sample time (sec) -1 (inherited) or specify Specify sample time for the block

When to use this block?

This block can be used to GET or POST HTTP requests.

Demo

WIFI Demo

Previous : WIFI Block
Next : Wireless Communication Block (HIL)


HTTP GET Handler Block

How this block appears in a Simulink model?

What can be configured?

Configuration Parameter Selectable Option/Value Description
Name of the handler Specify the name for the current handler. It should not be repeated.
URI Specify the uri for the handler. In case the enable waildcard for this handler is enabled specify the base uri here.
Enable wildcard for this handler Check--Uncheck Enable or disable the wildcard for this current handler.
Number of requests 1 to 12 Number of requests handle using the current handler. This will be always 1 when the wildcard is false in HTTP Server Setup block.
If request is Specify the request to be handle (uri)
Compare the whole request Check--Uncheck Compare the request uri with the specified partially or fully
Set header type .html--.css--.png--.ico--.txt--.js--.ttf--.woff2--.json Select the correct data type of the response data
Serve data from SD card--Static text input--Dynamic text input The data source. Whether the response data from the sd card or static text from the mask text box or dynamic text from input port
File location Full file path. This option is enabled when the data is served from the SD card
Contains .gz compressed files Check--Uncheck Check, when the files are gz compressed files
Text input This enables when the data is served from a static text input. Insert the data on the text area

When to use this block?

This block is used when there are GET requests from the client.

How does this block work?

This block handles the GET requests from the client. Before using this block, first initialize the server using HTTP Server Setup Block. The data to the input ports should be in string format.

Demo

HTTP Server demo

Previous : HTTP Server Setup Block
Next : HTTP POST Handler Block


HTTP POST Handler Block

How this block appears in a Simulink model?

What can be configured?

Configuration Parameter Selectable Option/Value Description
Name of the handler Specify the name for the current handler. It should not be repeated.
URI Specify the uri for the handler. In case the enable waildcard for this handler is enabled specify the base uri here.
Enable wildcard for this handler Check--Uncheck Enable or disable the wildcard for this current handler.
Number of requests 1 to 12 Number of requests handle using the current handler. This will be always 1 when the wildcard is false in HTTP Server Setup block.
Output request data Check--Uncheck Enable this option to get the POST request body from the output port.
If request is Specify the request to be handle (POST request body)
Compare the whole request Check--Uncheck Compare the POST request body with the specified partially or fully
Set header type .html--.css--.png--.ico--.txt--.js--.ttf--.woff2--.json Select the correct data type of the response data
Serve data from SD card--Static text input--Dynamic text input The data source. Whether the response data from the sd card or static text from the mask text box or dynamic text from input port
File location Full file path. This option is enabled when the data is served from the SD card
Contains .gz compressed files Check--Uncheck Check, when the files are gz compressed files
Text input This enables when the data is served from a static text input. Insert the data on the text area

When to use this block?

This block is used when there are POST requests from the client.

How does this block work?

This block handles the POST requests from the client. Before using this block, first initialize the server using HTTP Server Setup Block. The data to the input ports should be in string format.

Demo

HTTP Server demo

Previous : HTTP GET Handler Block
Next : xTaskCreate Block


HTTP Server Blocks

HTTP Server Setup Block
HTTP GET Handler Block
HTTP POST Handler Block


HTTP Server demo

Simple GET POST web page
Line chart widget with ADC values


HTTP Server Setup Block

How this block appears in a Simulink model?

What can be configured?

Configuration Parameter Selectable Option/Value Description
Enable wildcard True--False Enable or disable wildcard. By enabling this, server accepts multiple uri s in a single handler
Port number Specify the port number which the server operates
Core ID 0--1--ANY Select which core the server should operate
Stack size Specify the stack size for the server task

When to use this block?

Use this block for the application which need to implement a custom http server using ESP32.

How does this block work?

This block will initialize the http server with the given configuration.

Demo

HTTP Server demo

Previous : NTP Block
Next : HTTP GET Handler Block


I2C Block

How this block appears in a Simulink model?

appearance.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
I2C driver port 0--1 Select driver port
Clock Frequency (kHz) 100--400 Specify clock speed of selected I2C module configuration.
SDA pin Select pin for I2C SDA
SDA internal pullup Enable/disable internal pullup
SCL pin Select pin for I2C SCL
SCL internal pullup Enable/disable internal pullup
Bytes write count Specify number of bytes to write to I2C in a transaction.
Bytes read count Specify number of bytes to read from I2C in a transaction.
Enable I2C scan device ESP log message. Enable this to scan all i2c devices connected and display their salve addresses. To use this, feature a serial monitor is required.
Sample time (sec) -1 (inherited) or specify Specify sample time for the block

When to use this block?
This block can be used to communicate with a device suing I2C protocol

Demo

I2C demo

Previous : SPI Block
Next : ADC Block


I2C demo

Target module Demo file : esp32_i2c_4_20mA_demo.slx

Host PC Demo file : udp_host_pc.slx

Description

This demo shows how to use the I2C Block to get the reading from the external I2C ADC module and send the data to the host PC simulink model using a wireless UDP communication with Wireless Communication Block (HIL) in every 1s.

Hardware Setup

  1. aMG ESP32 4-20mA Module
  2. Fio Glide ESP32 with aMG ESP32 2P
  3. Host PC with Simulink and Wifi connection

What should be happening?

Once the host PC simulation is started the data reading from the ESP32 should be shown in the display block.

Previous : SPI demo
Next : ADC demo


Image Concatenate Block

How this block appears in a Simulink model?

appearance.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
Input signal frame width Specify the width of the frame of a single image in the video stream
Input signal frame height Specify the height of the frame of a single image in the video stream

When to use this block?

This block is used concatenate the RGB channels of the video stream from the Camera Block.

How does this block work?

The way the ESP-WHO handle pixel data of an image is different from what Matlab Simulink does. Therefore the Camera Block transmit the video feed after splitting the image to three channels making it compatible with the Simulink Computer Vision Toolbox. After processing the image the three channels could be concatenated using this block.

Previous : System Time Block
Next: Memory Block


Integrate Legacy C code to Waijung 2 using s-function builder

Objective

Enable user to create a Simulink block that can execute a custom C code.

Example

Problem Statement

Create a Simulink block that would act as a conditional statement block to toggle an LED.

Steps to Create the Library File

Using the library block created

Testing

Connect the potentiometer to the Analog Pin 33 and connect an LED to Digital Pin 2. Potentiometer should be connected in a way where the maximum input voltage is 3.3V and the minimum is 0V;

Result

LED will toggle On and Off depending on the potentiometer reading.

Demo files

toggle_led_condition_lib.slx
toggle_led_using_pot.slx

Previous : Scheduling mechanism in Waijung 2
Next : Create embedded web application with Aimagin Connect


Interrupt Blocks

GPIO Interrupt Block
Timer Interrupt Block


Interrupt demo

GPIO Interrupt demo
Timer Interrupt demo


Introduction to Waijung and Matlab & Simulink

This article introduces you to Waijung and Matlab & Simulink for uses in embedded system development, that can be much faster, easier, and more fun.

1 Background

Computer and handheld devices (like smart phones, tablets) have revolutionized the world. Now we can play online games with our friends, share media, manage inventory, analyzing huge stock exchange data and many more things with these devices while sitting at a remote location. Having a video call on social media websites or doing online shopping is now quite easy but how these things are made possible.

Computer is a dump machine in-fact a very dump machine. Computers by itself cannot do anything. It don’t have power to make decisions. They are programmed so that they can act according to our ‘clicks’ and ‘touches’. To program a tablet or a computer to follow the instructions is not that straight forward. A house which looks very clean and beautiful is the result of hard efforts of the cleaner, home décor designer and the architect. An application ‘app’ available on our smart tablets – programmers and developers who work round the clock to deliver it.

1.1 What is a Computer?

A computer is an electronics device which works under the set of instructions stored in its own memory. From this definition we can analyses previously it was mentioned that computer is a dump device and it cannot do anything/make decisions at its own. Whatever is stored inside its own memory, it will work according to that. We can visualize the information process cycle of the computer or related device as in Figure 1.


Figure 1: Information Process Cycle

It is interesting to share information that a computer not only contains electric and electronic components but also some mechanical components [1]. These components are known as hardware. We can categorize the computer hardware as in Figure 2.


Figure 2: Computer hardware

1.1.1 What is an Operating System?

An operating system (OS) is a set of programs containing instructions that work in conjunction with the hardware to perform the desired tasks. Main responsibilities of an OS are:

1.1.2 Classification of Computers

We can broadly classify the computers as:

1.2 What is a Microcontroller?

A micro-controller is an integrated circuit with built-in Central Processing Unit (CPU), programming and non-programmable memory, input/output (I/O) ports, digital to analog convertor and vice versa.

Now a question can come in mind that what is the difference between a microcontroller and microprocessor of general purpose computer. Table 1 will explain this question.

Table 1: Comparison between Microprocessor and Microcontroller

1.3 What is an Embedded System?

An embedded system is a computer system with a dedicated function within a larger mechanical or electrical system, often with real-time computing constraints2. From the definition, it can be observed that an embedded system is different from general purpose computer but may contain similar components.

1.3.1 Why Embedded Systems?

An embedded system can be called as a mini computer which has en ability to work in an intelligent standalone manner. Embedded systems are widely in used because they are:

1.3.2 Examples of Embedded System

Examples of embedded system are as follows:

2 What is MATLAB?

MALTAB is developed by MathWorks which is a leading developer of mathematical computation software. MATLAB® is a high-level language and interactive environment for numerical computation, visualization, and programming [3]. The definition above have two keywords. When we refer to ‘high-level language’ the first thing which comes to mind should be: it is easy to do programming, have a lot of built-in functions and developing a program is simpler and more understandable to human beings. ‘Interactive environment for MATLAB refers to the availability of ‘Apps’, Graphical User Interface (GUI), multi-dimensional visualization.

MATLAB is used by mathematicians and statisticians as it helps them in solving linear and differential equations, applying optimization techniques to solve their problems, availability of statistical and machine learning algorithms for organizing, analyzing and modeling the data etc. MATLAB is used by engineers and scientists as it helps them in modeling an engineering system like vehicular area network, communication system, and aeronautical system. It helps them in signal and image processing, data visualization, control and fuzzy logic systems and many more. MATLAB is used by economists and financiers as functions in MATLAB are available for modeling an economic and financial data. Applications of MATLAB are not exhausted here. MATLAB can be used by any person who wants a computerized solution for his/her problem. As the programming in MATLAB is far easier, people often use MATLAB to write their program in MATLAB and then convert them into C or C++ in which writing code is quite hard as compared to MATLAB. More than 1 million people from industry and academia are using MATLAB – the language of technical computing. By now, reader can feel that MATLAB can be really helpful in solving a simple as well as complex problems.

2.1 Some Examples

Before some very basic examples are introduced in this section, it is assumed that the user has already installed MATLAB correctly and have some fundamental knowledge about programming. While installation, a user might have observed one thing i.e. installation time of MATLAB is significant. This is because of the richness of MATLAB in terms of libraries, built-in functions, variety of toolboxes, coders, blocksets etc. To start with, a MATLAB code to generate a sine wave is given and how we can visualize that sine wave.

2.1.1 Example 1: Generating a Sine Wave using MATLAB

This example shows how sine wave and cosine wave can be generated. Furthermore they are plotted against time to observe their phase difference. In order to do so, we need to know the two important things.

MATLAB Code


Figure 3: Plotting a sine and cosine wave

2.1.2 Example 2: Discrete Fourier Transform and Power Spectral Density Calculations

Moving a step forward, we know that a simple communication system consists of three entities i.e. transmitter, channel and the receiver. Channel can be wired (copper cable, twisted pair, optical fiber) or wireless (air, vacuum) [4]. Channel is the point where most of the noise is introduced in the transmitted signal. In the code below we do the following steps:

We can observe that even after the addition of the noise, FFT enables us to recover back the center frequency of the two signals. At the bottom of Figure 4, we can observe two peaks at 50Hz and 120Hz respectively which are the same as the signal frequency which we choose in the beginning.

MATLAB CODE

% Show the use of the FFT function for spectral analysis.
% Create signal at 50 Hz and 120 Hz
t = 0:.001:.25;
x1 = sin(2*pi*50*t);
x2 = sin(2*pi*120*t);
x = x1 + x2;
% Add some random noise
y = x + 2*randn(size(t));
subplot(611),plot(x1), title(‘Sine wave at 50 Hz’)
subplot(612),plot(x2), title(‘Sine wave at 120 Hz’)
subplot(613),plot(x), title(‘Sine wave at 50 Hz + 120 Hz’)
subplot(614),plot(y), title(‘Noisy time domain signal’)
% Finding the discrete Fourier transform
Y = fft(y,256);
% Compute the power spectral density
Pyy = Y.*conj(Y)/256;
f = 1000/256*(0:127);
subplot(615),plot(y), title(‘Noisy time domain signal’)
subplot(616), plot(f,Pyy(1:128)), title(‘Power spectral density’)
xlabel(‘Frequency (Hz)’)


Figure 4: Discrete Fourier transform and power spectral density calculations

2.1.3 Example 3: Representing Data in Plots

No matter from which domain a researcher is, it is always important for him/her to represent his/her work in a meaningful way. Graphs are one excellent way of representing a large data which can yield a meaningful information. Fortunately, MATLAB is very rich in plotting graphs and have a lot of built-in functions. In the code below, a reader can find ways how a data can be represented using MATLAB. In this example, same data is represented in seven different ways i.e. scatter, stem, polar, error-bar, stair-step, bar and line plot.

MATLAB CODE

clear all, close all
% Scatter Plot
figure; load count.dat
scatter(count(:,1),count(:,2),’r*’)
xlabel(‘Number of Cars on Street A’);
ylabel(‘Number of Cars on Street B’);
title(‘Scatter Plot’)

% Stem Plot
figure; x = 0:0.1:4;
y = sin(x.^2).*exp(-x);
stem(x,y)
title(‘Stem Plot’)

% Polar Plot
figure; t=0:0.01:2*pi;
polar(t,abs(sin(2*t).*cos(2*t)));
title(‘Polar Plot’)

% Errorbar Plot
figure; x=-2:0.1:2;
y=erf(x); e = rand(size(x))/10;
errorbar(x,y,e);
title(‘Errorbar Plot’)

% Stairstep Plot
figure; x=0:0.25:10;
stairs(x,sin(x));
title(‘Stairstep Plot’)

% Bar Plot
figure; x = -2.9:0.2:2.9;
bar(x,exp(-x.*x));
title(‘Bar Plot’)

% Line Plot
figure; x=0:0.05:5;
y=sin(x.^2);
plot(x,y);
xlabel(‘Time’); ylabel(‘Amplitude’)
title(‘Line Plot’)


Figure 5: Different ways of representing data

2.1.4 Example 4: Drawing a Heart

Matlab is not only meant for doing some serious research but something romantic can also be created using few lines of MATLAB. Here is a sample code to create a heart.

MATLAB CODE

close all; clear all; clc
v = -1.5:.02:1.5;
[x,y,z] = meshgrid(v,v,v);
w = (2*x.^2+y.^2+z.^2-1).^3-(1/10)*x.^2.*z.^3-y.^2.*z.^3;
hp = patch(isosurface(w,0));
set(hp,’facecolor’,’r’,’edgecolor’,’none’)
light; lighting phong;
view(99,18)



Figure 6: Drawing a Heart

For more examples, please refer to Section ‘List of Resources’.

2.2 MATLAB TOOLBOXES

By today, MATLAB has more than 40 toolboxes which allows scientist and researchers to complete their tasks with easy. The list of the toolbox can be found from the following link.

http://www.mathworks.com/products/

2.2.1 To check which toolboxes are installed in your MATLAB.

In order to check which toolboxes, blocksets and version of MATLAB is installed in the computer, user need to type command ‘ver’ in command line.


Figure 7: Using command ver to check MATLAB version and installation products

3 What is Simulink?

Simulink is a block diagram environment for multi-domain simulation and Model-Based Design. It supports simulation, automatic code generation, and continuous test and verification of embedded systems [5]. Like MATLAB, Simulink was also developed by Mathworks. Its principal interface is a graphical block tool and a customizable set of block libraries. Simulink can be used in conjunction with the MATLAB. Capabilities of Simulink are as follows:


Figure 8: Simulink capabilities

Aimagin is specialized in utilizing the capability of Simulink to connect with hardware. The later part of this tutorial will leads us to connect Aimagin hardware with Simulink but before tutorial goes into that detail it is very important to understand the Simulink first.

3.1 Start using Simulink

In order to run Simulink, user need to type simulink in the MATLAB command window. MathWorks also provides an icon to Simulink but the icon position and colors may vary with the different versions of MATLAB so for the beginning it is preferred to go by typing Simulink in MATLAB command window which works on all the version of MATLAB. The result is shown in Figure 9.


Figure 9: Starting Simulink

A list of block library will appear. User can select a block of desired characteristics from these libraries. The most commonly use block libraries are:

To create a new model, the user need to do go to File -> New ->Model. In order to open an existing model, user need to go to _ File ->Open ->_ Specify the model location on the hard disk.


Figure 10: Opening a new model

When we click on Model, a new window will open which is shown below in Figure 11.


Figure 11: New model in Simulink

Now, we are all set to create a model. We need to first plan, what actually we want to build and what are the components required. Please keep in mind that just by simply connecting the blocks in the model, things will not work. Input of the second block must be matching with the output of the first block and so on. Indeed drawing modeling in Simulink is far easier than doing programming but don’t think Simulink like Microsoft Visio. Don’t get disappointed if while running the model, you get some error. Read about the block properties, the background knowledge of relevant field and the nature of input/output signals. As like other learning tools, beginning is little difficult but things becomes easier with the passage of time. So we start with a simple case and our agenda is to create a detailed digital communication system.

3.2 Examples using Simulink

3.2.1 Example1: Creating and Observing a Sine-wave

We start with the simplest case. Open a new model. Save a model with a legit name. Now a reader should think before going further, what blocks are required in order to create and sine wave and see the created sine wave. The answer is very simple. Two things i.e. something which can generate a sine wave and something which is like a oscilloscope in the labs to see it. We search for these two items in ‘Simulink Library Browser’. When right choice of component is found, simply drag that block to the new model created.


Figure 12: Dragging appropriate components to the model

Now both the required blocks are with us. Now it’s the time to see if it is possible that by doing so simple task, sine wave can be created and observed. Click on ‘play’ button or Ctrl + T. Simulink will start compiling and when it’s done, double click on scope button the observe the output which is shown in Figure 13. Please note that the properties of Sine wave block (or any other block) can be customized by double click on the block. Similarly, model configuration parameters can be changed from Simulation -> Model Configuration Parameters.


Figure 13: Observing the sine wave

Please note that in order to obtain the results in Figure 13, following customization has been done.


Figure 14: Setting model configuration parameters


Figure 15: Scope parameter properties configuration

3.2.2 Example 2: Integrating a sine wave

Now, we can move forward quickly. For the next example, we require the following blocks.

These blocks are arranged in the following order as shown in Figure 16 and the output is shown in Figure 17.


Figure 16: Integrating a sine wave


Figure 17: Output of the block diagram of Figure 16

Yellow line is for the output after passing through gain and integrator and purple line is for the sine wave generated. It can be observed that it is a simple procedure to apply gain and applying little complex mathematical operation like integration.

3.2.3 Example 3: Inverted Pendulum on a cart

Figure 18 shows the inverted pendulum on the cart. This is a typical engineering problems since ages and it can be modeled and visualized in Simulink with so ease.


Figure 18: Inverted pendulum on the cart

For more examples, please refer to Section ‘List of Resources’.

4 In which programming language MATLAB is written?

After analyzing some program written in MALTAB, a question may come in reader’s mind that in which programming language MATLAB is written? The answer to this question is not that straightforward. MATLAB is not written in a single programming language but in many programming languages which are:

5 Pros and Cons of Using MATLAB/Simulink

5.1 Pros

MATLAB/Simulink have a lot of advantages which engineers, researchers, scientists and students can enjoy [6].

5.2 Cons

It uses a large amount of memory and slow down the computer.

6 What is the Problem?

From the discussion above, reader can realize that the programming in C/C++/Assembly is not very easy however MATLAB/Simulink is a powerful tool to overcome this issue. Specifically talking about Simulink, things can be done by connecting the respective blocks without writing even a single line of code. While designing and analyzing a system like intelligent control system/signal processing/communication system etc. MATLAB/Simulink gives wings i.e. design and analysis process is simple and easy but comprehensive. Simulation using MATLAB/Simulink tools will save time and cost. Furthermore, detailed analysis gives an opportunity to avoid any unwanted situation.

6.1 Real System Implementation

For the real system implementation using MATLAB/Simulink tool, there are two major concerns.

In order to connect hardware with Simulink, Aimagin has made a customized blockset named ‘Waijung’. This provide an opportunity the Aimagin hardware with the Simulink and a user can realize a real system. So with Waijung blockset, from design to implementation, the whole process is fast, easy, fun and not forget to mention …NO C/C++ code is required. We explain the advantage of our blockset with an example. For example a user wants to make a chair. In order to make a chair he/she needs a hammer, nails, sandpaper and wood. Now there are two options available.

Option 1: Make hammer, nails and sandpaper yourself. Go to the forest to cut tree and bring wood. When everything is done, start making chair

Option 2: Buy/use already available hammer, nails, sandpaper and wood in the market and make a chair

Indeed option 2 is better than option 1 in terms of time and skills required.

MATLAB gives a tool to convert a MATLAB written code in C (and other languages) which can fit well in time sensitive applications. Generated code from Matlab contains more overhead than hand coding but the former one is faster a suitable for rapid prototyping. A detailed explanation how a C code can be generated from MATLAB algorithm is given in the following link.

http://blogs.mathworks.com/loren/2011/11/14/generating-c-code-from-your-matlab-algorithms/

6.2 Advise to use Waijung Blockset

Readers should not get an impression that merely connecting Aimagin hardware via USB with a computer will get everything done. For example if a user want to add two numbers using a calculator, then he must know that he should enter first number then press + button and then enter the second number. At the end, the user should press = button the get the output. Similarly using Waijung with hardware, the user must know the mathematics/equations involved while realizing a system, how to use the tools, how to connect the circuit, how circuit works etc.

7 List of Resources

7.1 Resources on Aimagin

Currently significant literature is available online and the company is constantly adding more and more literature, examples, tutorials and videos so that the users can benefit more from Aimagin products. To get hands on and for some mini projects, the users can refer to blog.aimagin.com where they can find more than 20 sample projects and tutorials.

Quick reference for sample project is as under

http://aimagin.com/blog/topics/sample-project-th/?lang=th

Quick reference for mini projects

http://aimagin.com/blog/mini-project-kmutnb-mechatronics-56/?lang=th

Quick reference for tutorials

http://aimagin.com/blog/topics/tutorials-th/?lang=th

Reference Manual about Waijung can be accessed from the below mentioned link. From here Waijung blockset can be downloaded.

http://waijung.aimagin.com/

Video tutorials which gives a great insight about our product can be accessed from

www.youtube.com/rapidstm32

Information about Aimagin previous RapidSTM32 block set can be found from

www.imagin.com/learn

A large resources in terms of tutorials, examples, videos books etc. are available. For instance

7.2 MATLAB Resources on the Web

Here is the list of few tutorials on the MATLAB. Please note that this is not a complete list but only very few references how to get started with MATLAB. After gaining the basic knowledge, the user can search for more resources of the web.

http://ocw.mit.edu/courses/mathematics/18-06-linear-algebra-spring-2010/related-resources/MIT18_06S10_matlab.pdf

http://www.mathworks.com/academia/student_center/tutorials/launchpad.html

http://www.mathworks.com/academia/student_center/tutorials/?s_tid=gn_ac_sv_tu

http://www.math.utah.edu/lab/ms/matlab/matlab.html

http://ctms.engin.umich.edu/CTMS/index.php?aux=Basics_Matlab

http://www.math.mtu.edu/~msgocken/intro/intro.html

http://www.cs.utexas.edu/~grauman/courses/spring2011/matlab.pdf

http://www.matlabtutorials.com/

http://www.youtube.com/watch?v=QbRLoMH9a24

7.3 Simulink Resources on the Web

Same is true for the tutorials for Simulink. The list goes on and here are only few…

http://www.mathworks.com/academia/student_version/learnsimulink_sp3.pdf

http://web.mit.edu/acmath/matlab/course16/slides_16.06_16.07_matlab_simulink.pdf

http://classes.soe.ucsc.edu/cmpe242/Winter14/Simulink.pdf

http://www.youtube.com/watch?v=TfXBw51xKr0

http://faculty.washington.edu/lum/website_professional/matlab/tutorials/Simulink_Tutorial/simulink_tutorial.pdf

http://www.tufts.edu/~rwhite07/PRESENTATIONS_REPORTS/simulink.pdf

http://ocw.usu.edu/Electrical_and_Computer_Engineering/Signals_and_Systems/Simulink_Tutorial.html

7.4 Books on MATLAB and Simulink

Mathworks website is the best tool to search for MATLAB/Simulink books. More than 1500 titles are available.

http://www.mathworks.com/support/books/

http://www.orchardpublications.com/1934404071ex.pdf

http://www.sinawebhost.com/ebooks/matlab/32-Introduction%20to%20Simulink%20with%20Engineering%20Applications.pdf

8 Conclusion

Waijung is a valuable addition to MATLAB/Simulink blockset. Our company works in a modern philosophy ‘Make it work now – optimize later’. Our ultimate goal is to en-power the students to create more complex algorithms in less time. This will be more beneficial to the industry in terms of better products, more values and more business.

With the ambition of making complex and hard to understand process simple, currently our company is mainly focusing on (but not limited to) digital signal and image processing, network monitoring and control systems. We really appreciate new innovative ideas from our users. In a very short period of time, our products are being used and appreciated by good number of researchers and they are quite happy and contented with our products. Some of the testimonials from our valuable users can be found from the following link

https://www.aimagin.com/customer_testimonials/

8.1 Our Hopes

We hope that with our products students will be able to learn and use industrial standards tools. From the students our hopes are:

  1. Understanding of basic principles of studies much better via simulation technology with connections to hardware.
  2. Learn about new industrial trends – the use of model-based design and rapid prototyping technology.
  3. Able to make complex systems work or solve more complex problems in shorter time, creating higher values to product development in shorter cycle to serve real industries.

8.2 Ask Questions

Users can use the following channels to ask question

https://www.facebook.com/pages/Aimagin/263308030369020

9 References

[1]. Shelly, Gary, Glenda Gunter, and Randolph Gunter. Teachers Discovering Computers: Integrating Technology in a Connected World. Cengage Learning, 2011.

[2]. http://www.barrgroup.com/Embedded-Systems/Glossary-A

[3]. http://www.mathworks.com/products/matlab/

[4]. Saadi, M., et al. “Visible light communication: opportunities, challenges and channel models.” International Journal of Electronics & Informatics 2.1 (2013).

[5]. http://www.mathworks.com/products/simulink/

[6]. http://www.csee.wvu.edu/~xinl/courses/ee465/programming_tips.pdf

[7]. http://www.scilab.org/


LEDC Block

How this block appears in a Simulink model?

appearance.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
LEDC Timer LEDC_TIMER_0--LEDC_TIMER_1--LEDC_TIMER_2--LEDC_TIMER_3 Select the timer
Duty Resolution LEDC_TIMER_1_BIT to LEDC_TIMER_20_BIT Select the duty resolution
PWM Frequency (Hz) Select the PWM frequency
Timer Speed Mode LED_HIGH_SPEED_MODE--LED_LOW_SPEED_MODE Select the LEDC driver speed mode
Source Clock If the value for this parameter is LEDC_AUTO_CLOCK, the clock will be selected automatically
Hide unused channel configurations on--off The channels assigned Do not use will be hidden
hpoint specify the hpoint
Duty Cycle Mode Using hardware--Using software Select the duty cycle mode. the Duty cycle mode will also change the input method (from mask or from input port) for this parameter
Fade function ledc_set_fade_time_and_start--ledc_set_fade_step_and_start In the hardware mode the user will be able to select the fade function to be used
Target Duty Specify the target duty. The maximum of this parameter depend on the timer configurations. Check reference for more information
Max Fade Time (milliseconds) Specify the time duration for the fade
Fade Mode LEDC_FADE_NO_WAIT--LEDC_FADE_DONE Select fade mode
Scale Select scale
Cycle Number Select cycle number

When to use this block?

This block is designed to control LED intensity using PWM signals. This block could be used for other similar applications involving PWM signal generation as well.

How does this block work?

Reference

Check LED Control documentation of ESPRESSIF

Demo

LEDC demo

Previous : SD Card Block
Next : MCPWM Block


LEDC demo

Demo file : esp32_ledc_demo.slx

Description

This demo uses LEDC Block to configure four LEDs to repeat four sequences.

Hardware Setup

  1. ESP32 module
  2. 4 LEDs
  3. 4 Resistors (1k ohm)

What should be happening?

The four LEDs will follow the four sequences below.
  1. Gradually increase the intensity to LED ON state
  2. Gradually decrease the intensity to LED off state.
  3. Quick change to On state.
  4. Quick change to OFF state.

Previous : Circular Buffer demo
Next : Automatic Logging of data to Google sheets from ESP32


Lagacy systems

  1. Waijung 1 online user guide
  2. Smart sensor system

Line graph widget with ADC values

Demo file : esp32_http_server_demo2.slx

Description

This demo shows how to use HTTP Server Setup Block, HTTP GET Handler Block and HTTP POST Handler Block by using the custom html web page with a line graph widget. Addition to those blocks, the WiFi Block is used to initialize the wifi in AP mode to access the http server, SD Card Setup Block is used to initialize the SD card to serve the files and ADC Block to read adc pin (GPIO36).

Note : First copy the source_files2.7z and extract the files to the SD card and insert in to the ESP32 module.

What should be happening?

Once the wifi is initialize wifi in AP mode use the following information to connect to the ESP32.

Once the IP address is accessed using the web browser, the web page is as below

The client will request the ADC data from the ESP32 server in every one second and update the graph according to the data.

Source files : source_files2.7z

Previous : Simple GET POST web page
Next : Circular Buffer demo


Make Simulink model work with hardware using Waijung 2

Objectives

This application will allow you to understand how the simple model is uploaded in to the hardware of user's preference. As the introductory sample the blink LED example is explained here,

Required hardware

  1. ESP-WROOM-32
  2. LED
  3. Resistor: 220 ohm

Required software

  1. Matlab
  2. Simulink

Connect the hardware

Note : No need to setup the following hardware configuration, if the ESP32 module has onboard LED which is connected to the GPIO2.

Connect the hardware in the following order. Connect an LED to digital pin 2 of your ESP32 through 1k ohm.

How to create a new model

Step 01
Open Matlab . Change the current folder to the directory where you want to create the model. Click Simulink.

Step 02
Click Blank Model. Save the new model in any name you want without space to avoid any errors as '******.slx'

Step 03
Open Library Browser .

Step 04

Re-arrange the blocks according to the picture by connecting the two blocks . For more details about Building, Simulating and connecting a Simple Simulink Model

Step 05

Change the block configuration parameters as shown in picture by double clicking on each block. Make sure the COM port hardware is connected to the same COM port. Change the ESP32 Flash Size according to the hardware connected, in this example select 4MB. Pin 2 is assigned as the digital output pin for this example in Digital Out blockset. The parameter values are adjusted to get frequency of 1 Hz.

Step 06

Now upload the code. Go to APPS tab and click Embedded Coder. After C CODE tab opens press the drop down menu to UPLOAD the code.

Results

The LED connected to pin5 through 1k ohm resistor will start blinking at 0.5 Hz frequency. The target setup blockset allow you to connect the model with the hardware. The frequency is generated with used of the pulse generator, the digital out blockset allow the signal to be transmited to the LED. In this example the output pin is assigned to GPIO2 in the digital out blockset.

Related Waijung 2 blocks

The following blocks have been used in this model.

  1. Target Setup Block
  2. Digital Output Block

Simulink model

Click to download the HelloWorld.slx model file.

Additional information

In case the user wants to monitor run time serial data, the following options would serve.

Previous: Simulate LED toggle
Next: How to use demo file?


Map Widget

รูปแบบโครงสร้างการตั้งค่าแบบสมบูรณ์

setParameter('my_map', 'Data', {
            source: {
                table: {
                    sql: `SELECT * FROM TABLE`,  //sql สร้างตาราง - จำเป็น
                    database: 'sqlite',//[sqlite,clickhouse] - // ชนิด database - จำเป็น
                    pk: "rowid",//primary key ของตาราง - optional
                    layer: "layer",//layer ของ marker ผูกกับคอลัมน์ของตาราง - optional
                    column: [  //เป็นคอลัมน์ที่จะแสดงใน popup เวลา user click ที่ marker - optional
                    {
                        name: "lat",
                        label: "ละติจูด" 
                    }, {
                        name: "lng",
                        label: "ลองกิจูด" 
                    }, {
                        name: "area",
                        label: "พื้นที่" 
                    }]
                },
                position: {
                    lat: "lat",    // ชื่อคอลัมน์ที่เก็บ Latitude - จำเป็น
                    lng: "lng"    // ชื่อคอลัมน์ที่เก็บ Latitude - จำเป็น
                },
                tooltip: { //กำหนด tooltip ให้กับ markerได้
                    column:'detail', //เป็นชื่อคอลัมน์ที่นำมาทำ tooltip
                    permanent:false, //แสดงเมื่อ hover  ถ้าเป็น true คือ แสดงตลอด
                    direction:'auto'  //ตำแหน่งของ tooltip มี 'top', 'left', 'right', 'bottom', 'auto'
                },
                layer: { //กำหนด layer label กับ color marker ได้  หรือใช้ marker เป็นภาพโดยกำหนด url ได้  ถ้าไม่มี layer แต่พบว่ามีการกำหนดจะใช้ column[0] แทน  และกำหนด markerOpacity ได้
                    column:[{name:"layer-1", label:"LAYER 1", markerColor:"red"}, {name:"layer-2", label:"LAYER 2", markerColor:"green", markerOpacity:0.3}, {name:"layer-3", label:"LAYER 3", markerUrl:"http://maps.google.com/mapfiles/kml/shapes/marina.png"}] 
                },
                circle: {
                    area: "area_col",    // ชื่อคอลัมน์ที่เก็บพื้นที่ของวงกลม - optional
                    fillColor: "fillColor_col",    // ชื่อคอลัมน์ที่เก็บสีของวงกลม - optional
                    fillOpacity: "fillOpacity_col",     // ชื่อคอลัมน์ที่เก็บความทึบของวลกลม - optional
                    opacity: "opacity_col",     // ชื่อคอลัมน์ที่เก็บความทึบของเส้นรอบวง - optional
                    color: "color_col",     // ชื่อคอลัมน์ที่เก็บสีของเส้นรอบวง - optional
                    weight: "weight_col"    // ชื่อคอลัมน์ที่เก็บน้ำหนักของเส้นรอบวง - optional
                }
            },
            custom: {
                circle: {
                    area: 100,  // - กำหนดขนาดของวงกลมทุกวง - optional
                    fillColor: "#FF0000", // - กำหนดสีของวงกลมทุกวง - optional
                    fillOpacity: 0.35,  // - กำหนดความทึบของวงกลมทุกวง - optional
                    opacity: 0.8,  // - กำหนดความทึบของเส้นรอบวงทุกวง - optional
                    color: "#FF0000",  // - กำหนดสีของเส้นรอบวงทุกวง - optional
                    weight: 1 // - กำหนดน้ำหนักของเส้นรอบวงทุกวง - optional
                },
                popup: {
                    callback: function({data}) {//สำหรับวาด popup เอง โดย return html string ออกไป data เป็น json ของ row ที่ select มา
                      return "<p>test</p>" 
                    }
                },
            },
            default: {
                circle: {  // หากไม่มีการผูกวงกลมกับ column ใน source.circle และไม่มีการกำหนด custom.circle ดังนั้น default.circle จะถูกใช้
                    area: 314,  // - ค่า default พื้นที่วงกลมรัศมี 10 เมตร - optional
                    fillColor: "#FF0000", // - ค่า default สีของวงกลม - optional
                    fillOpacity: 0.35,  // - ค่า default ความทึบของวงกลม - optional
                    opacity: 0.8,  // - ค่า default ความทึบของเส้นรอบวง - optional
                    color: "#FF0000",  // - ค่า default สีของเส้นรอบวง - optional
                    weight: 1 // - ค่า default น้ำหนักของเส้นรอบวง - optional
                }
            },
            cluster: {
                disabled:false //true/false ใช้หรือไม่ใช้ cluster ถ้าไม่ใช้ จะแสดงไม่เกิน 1000 จุด เพราะไม่อย่างนั้นแผนที่จะรับไม่ได้ - optional
                Nx:100,  // เป็นจำนวนช่องตามแกน x เพื่อทำ cluster - optional
                Ny:100,  // เป็นจำนวนช่องตามแกน y เพื่อทำ cluster - optional
                min:20,  // เป็นจำนวนตำแหน่งต่ำสุดที่จะรวมเป็น cluster หากต่ำกว่าจำนวนนี้ จะไม่ถูกกระจายเป็น marker และ อาศัยการทำ cluster บน client แทน - optional
            },
            view: {
                visible:true //true/false แสดงหรือซ่อนแผนที่ - optional
                center: [13.736717, 100.523186],  // จุดศูนย์กลางของแผนที่ ในรูปแบบ [lat, lng] - optional
                zoom:5  //ค่าการ zoom - optional
            }
        });

การใช้งานในขั้นพื้นฐานสุดต้องใช้ sql, database, lat, lng
ส่วน พื้นที่วงกลม (area), สีของวงกลม (fillColor), ความทึบของวงกลม (fillOpacity), สีของเส้นรอบวง (color), ความทึบของเส้นรอบวง (opacity), น้ำหนักของเส้นรอบวง (weight) จะขึ้นกับค่า default ของระบบ

setParameter('my_map', 'Data', {
            source: {
                table: {
                    sql: `SELECT * FROM TABLE`,  //sql สร้างตาราง
                    database: 'sqlite',//[sqlite,clickhouse]  // ชนิด database
                },
                position: {
                    lat: "lat",  // ชื่อคอลัมน์ที่เก็บ Latitude
                    lng: "lng"  // ชื่อคอลัมน์ที่เก็บ Longitude
                }
            }
        });

หากต้องการผูกค่า พื้นที่วงกลม (area), สีของวงกลม (fillColor), ความทึบของวงกลม (fillOpacity), สีของเส้นรอบวง (color), ความทึบของเส้นรอบวง (opacity), น้ำหนักของเส้นรอบวง (weight) กับคอลัมน์ให้เพิ่ม field ชื่อ circle ภายใต้ source

setParameter('my_map', 'Data', {
            source: {
                table: {
                    sql: `SELECT * FROM TABLE`,  //sql สร้างตาราง - จำเป็น
                    database: 'sqlite',//[sqlite,clickhouse] - // ชนิด database - จำเป็น
                },
                position: {
                    lat: "lat",    // ชื่อคอลัมน์ที่เก็บ Latitude - จำเป็น
                    lng: "lng"    // ชื่อคอลัมน์ที่เก็บ Latitude - จำเป็น
                },
                circle: {
                    area: "area_col",    // ชื่อคอลัมน์ที่เก็บพื้นที่ของวงกลม - optional
                    fillColor: "fillColor_col",    // ชื่อคอลัมน์ที่เก็บสีของวงกลม - optional
                    fillOpacity: "fillOpacity_col",     // ชื่อคอลัมน์ที่เก็บความทึบของวลกลม - optional
                    opacity: "opacity_col",     // ชื่อคอลัมน์ที่เก็บความทึบของเส้นรอบวง - optional
                    color: "color_col",     // ชื่อคอลัมน์ที่เก็บสีของเส้นรอบวง - optional
                    weight: "weight_col"    // ชื่อคอลัมน์ที่เก็บน้ำหนักของเส้นรอบวง - optional
                }
            }
        });

หากต้องกำหนดค่า พื้นที่วงกลม (area), สีของวงกลม (fillColor), ความทึบของวงกลม (fillOpacity), สีของเส้นรอบวง (color), ความทึบของเส้นรอบวง (opacity), น้ำหนักของเส้นรอบวง (weight) ให้เหมือนกันทั้งหมด กำหนดผ่าน custom ได้ทันที โดยจะ override ค่า default และ หากมีการผูกกับคอลัมน์อยู่ก็จะถูกปรับด้วย

setParameter('my_map', 'Data', {
            custom: {
                circle: {
                    area: 100,  // - กำหนดขนาดของวงกลมทุกวง
                    fillColor: "#FF0000", // - กำหนดสีของวงกลมทุกวง
                    fillOpacity: 0.35,  // - กำหนดความทึบของวงกลมทุกวง
                    opacity: 0.8,  // - กำหนดความทึบของเส้นรอบวงทุกวง
                    color: "#FF0000",  // - กำหนดสีของเส้นรอบวงทุกวง
                    weight: 1 // - กำหนดน้ำหนักของเส้นรอบวงทุกวง
                }
            }
        });

หากต้องการยกเลิกการใช้งาน custom ให้ set null เข้าไป ระบบจะกลับไปใช้ค่าที่ผูกไว้ หากไม่มีค่าที่ผูกไว้จะกลับไปใช้ค่า default
setParameter('my_map', 'Data', {
            custom: {
                circle: {
                    area: null,
                    fillColor: null,
                    fillOpacity: null,
                    opacity: null,
                    color: null,
                    weight: null
                }
            }
        });

ใช้ marker icon ที่มีสีจาก https://github.com/pointhi/leaflet-color-markers

มีตัวอย่าง marker icon ของ google เพิ่มเติมที่ใช้กับ kml ใช้โดยอิง url
http://kml4earth.appspot.com/icons.html

ตัวอย่าง MAP_WIDGET_EXAMPLES.amgcnt ใช้กับ ตาราง TEST_LOC และ TEST_LOC_1 ใน bd2

MCPWM Block

How this block appears in a Simulink model?

appearance.PNG

What can be configured?


Configuration Parameter Selectable Option/Value Description
Timer Tab Timer 0--Timer 1--Timer 2 Each tab has separate configuration parameters for each timer
Activate Timer on--off Each timer if in use should be activated by this checkbox
Frequency Select the PWM frequency
Duty cycle of PWMxA/PWMxB This is the initial duty cycle of PWMxA/B. The user can change this value later using esp32_mcpwm_func block
Counter Mode MCPWM_UP_COUNTER--MCPWM_DOWN_COUNTER--MCPWM_UP_DOWN_COUNTER Select counter mode. Check References for more details
Duty Mode MCPWM_DUTY_MODE_0--MCPWM_DUTY_MODE_1--MCPWM_HAL_GENERATOR_MODE_FORCE_LOW--MCPWM_HAL_GENERATOR_MODE_FORCE_HIGH Select duty mode. Check References for more details
Enable Dead Time on--off Enable/disable Dead Time feature
Dead Time Mode MCPWM_DEADTIME_BYPASS--MCPWM_BYPASS_RED--MCPWM_BYPASS_FED--MCPWM_ACTIVE_HIGH_MODE--MCPWM_ACTIVE_LOW_MODE--MCPWM_ACTIVE_HIGH_COMPLIMENT_MODE--MCPWM_ACTIVE_LOW_COMPLIMENT_MODE--MCPWM_ACTIVE_RED_FED_FROM_PWMXA--MCPWM_ACTIVE_RED_FED_FROM_PWMXB Select Dead Time Mode. Check References for more details.
Rising Edge Delay Enter the rising edge delay
Falling Edge Delay Enter the falling edge delay
Activate CAPx on--off Enable/disable capture component
Capture Edge MCPWM_POS_EDGE--MCPWM_NEG_EDGE--MCPWM_BOTH_EDGE Select capture edge
Number of Pulses Enter the number of pulses

When to use this block?

This block is used to generate PWM signals to control motors.

How does this block work?

ESP32 has two MCPWM units which can be used to control different types of motors. Each unit has three pairs of PWM outputs.

MCPWM_CONFIG is the configuration block that would enable user to configure everything in one MCPWM Unit. MCPWM_FUNC consists various API's created by ESPRESSIF to drive the PWM signal. Therefore the user can have one MCPWM_CONFIG block to configure all the components in a MCPWM unit and several MCPWM_FUNC blocks to create a sequence to drive the motor.

The current version (waijung2_20.11b) of the MCPWM_CONFIG block only allow user to configure one MCPWM Unit per model.

Reference

Check MCPWM documentation of ESPRESSIF

Demo

Previous : LEDC Block
Next : Aimagin Connect Block


Memory Block

How this block appears in a Simulink model?

appearance.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
Mode Setup--Read--Write Select the operation mode
Buffer Name Select the name of the buffer which is going to hold the image data
Inherit from the camera block The Image Source Parameters Will be automatically acquired from the camera block
Image format The format of the image
Frame Width Width of the image frame
Frame Height Height of the frame
Buffer Size Buffer Size = Frame width * Frame height * 3

When to use this block?

This block is used to temporarily hold an image in the external RAM of ESP32.

How does this block work?

Previous : Image Concatenate Block
Next: String Processing Block


Mesh Blocks

Mesh Setup
Mesh Transmitter
Mesh Receiver


Mesh Receiver

How this block appears in a Simulink model?

appearance_receive.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
Output Data Buffer Size 32--64--128--256--512--1024 Select the output buffer size.

When to use this block?

This block can be used to data from other nodes in a mesh network.

Previous : Mesh Transmitter
Next : Printf Block


Mesh Setup

How this block appears in a Simulink model?

appearance_setup.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
Mesh ID Enter a unique mesh ID.
Mesh AP Authentication Mode WIFI_AUTH_OPEN--WIFI_AUTH_WPA_PSK--WIFI_AUTH_WPA2_PSK--WIFI_AUTH_WPA_WPA2_PSK Select the authentication mode.
Mesh AP Password Enter the mesh password.
Mesh AP Connections Enter the number of nodes in the mesh.
Mesh Max Layers 1 to 6 Enter the maximum number of layers which the node hierarchy should be adjusted to.
Router SSID Enter the router SSID.
Router Password Enter the router password.
Channel Enter the router channel.
Mesh Network Status Check--Uncheck Enable/disable status output.

When to use this block?

This block can be used to setup a mesh network between several ESP32 devices.

How does this block work?

Each node in the mesh network should contain this block. This will automatically identify the other nodes in the network and set the hierarchy according to the user configurations depending on the signal strength from router. If ‘Mesh Network Status’ is ‘Checked’ it will indicate the completion of this setup process.

Previous : Camera Block
Next : Mesh Transmitter


Mesh Transmitter

How this block appears in a Simulink model?

appearance_send.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
Number of Receivers Enter the number of nodes at the receiving end.

When to use this block?

This block can be used to data from one node to other nodes in a mesh network.

Previous : Mesh Setup
Next : Mesh Receiver


Modify Simulink generated C code

Objective

This tutorial will show how to edit the C code that gets generated by using the Waijung2 block-set. The user will also be introduced to ESP-IDF development environment as well.

Reference

Previous : Develop web application for ESP32 to setup WiFi Station mode


NTP Block

How this block appears in a Simulink model?

appearance.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
SNTP Server name Enter the SNTP server name
Time Zone Enter the time zone
Country Enter the country

When to use this block?

Simple Network Time Protocol (SNTP) block can be used to get the time from any SNTP server.

Previous : OTA Block
Next : HTTP Server Setup Block


OTA Block

How this block appears in a Simulink model?

appearance_AP.PNG

appearance_STA.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
Mode AP Mode--Station Mode Select mode.
Use Aimagin Connect Check--Uncheck
Sample time (sec) -1 (inherited) or specify Specify sample time.

When to use this block?

This block is used to upgrade firmware over the air.

How does this block work?

This block requires WiFi Block to function. Depending on the WiFi configuration (AP or STA), ‘Mode’ in this block should be set. In Station mode the user can input the direct download URL of the update file saved in any server (Example: Google Drive).

In the AP mode the file can be uploaded from the client’s device. If ‘Use Aimagin Connect’ is ‘Unchecked’, when the client tries to access the web server default web page will be prompted where the user can upload the update file from host device. The URL is: http:// [ assigned IP for esp32 ]/OTA_upgrade/

If ‘Checked’, it means the user has added the firmware upgrade API to their custom web application thus user can use it to upload the file. However, for this method to work ‘esp32_aimagin_connect’ block should be available in the program model file.

Previous : SQLite NonRetrieveData
Next : NTP Block


Patch usbconverter n connect update1

Patch update usbconverter_n_connect
Description:
- Apply to waijung 17.03a
- Fix crashing when communicate with USART block.

Instruction:
1. Close MATLAB program, if it running.
2. Replace (Overwrite) the following file in to directory: \waijung_17_03a\src\blocks
2.1 amg_usbconverter_n_connect.mexw32
2.2 amg_usbconverter_n_connect.mexw64

All patches


Patch waijung 17 03a fix encoder read block error for stm32f4

Fix encoder read block error
Description:
- Apply with waijung 17.03a

Instruction:
1. Close MATLAB program, if it running.
2. Un-zip file.
3. Replace (overwrite the exising) the following files into directory: "\waijung17_03a\targets\stm32f4_target\stm32f4\src\blocks"
3.1 stm32f4_encoderread_callback.p

All patches


Pivot Widget

Parameter
const pivotWidgetID  = "pivot" 
// ตั้งข้อมูลผ่านชื่อ table จาก Sqlite
setParameter(pivotWidgetID  ,"Table",{tableName:"ข้อมูลตารางคนขอเข้าประเทศ2"})

// ตั้งข้อมูลผ่านชื่อ table  จาก Sqlite  และเปลี่ยนชื่อคอลัมป์ "ลำดับรวม" ให้เป็นชื่อ "Number" 
setParameter(pivotWidgetID  ,"Table",{tableName:"ข้อมูลตารางคนขอเข้าประเทศ2",headerLabels:[{colName:"ลำดับรวม",label:"Number"}]})

// ตั้งข้อมูลผ่านชื่อ table จาก clickhouse
setParameter(pivotWidgetID  ,"Table",{tableName:"aa_test",database:"clickhouse"})

// ตั้งข้อมูลผ่าน query statement จาก sqlite
setParameter(pivotWidgetID  ,"Table",{sql:"SELECT * FROM ข้อมูลตารางคนขอเข้าประเทศ2 LIMIT 100"})

// ตั้งข้อมูลผ่าน query statement จาก clickhouse
setParameter(pivotWidgetID  ,"Table",{sql:`SELECT * FROM "aa_test" LIMIT 200`,database:"clickhouse"})
const pivotWidgetID  = "pivot" 
// ตั้งค่า config จาก string ที่ได้จาก getParameter(pivotWidgetID  ,"Config")
setParameter("pivot","Config",`{"orders":{},"mode":[{"id":0,"col":0,"column":"ลำดับรวม","name":"Count of ลำดับรวม"}],"headers":[{"id":0,"label":"ลำดับรวม","selected":false,"filterSelected":false},{"id":1,"label":"ลำดับ","selected":false,"filterSelected":false},{"id":2,"label":"ชื่อเรือ","selected":false,"filterSelected":false},{"id":3,"label":"IMO","selected":false,"filterSelected":false},{"id":4,"label":"เที่ยวเรือ","selected":false,"filterSelected":false},{"id":5,"label":"ประเภทเรือ","selected":false,"filterSelected":false},{"id":6,"label":"ท่าเรือสุดท้ายก่อนเข้าไทย","selected":false,"filterSelected":false},{"id":7,"label":"สัญชาติเรือ","selected":false,"filterSelected":false},{"id":8,"label":"ท่าเรือที่เทียบท่า","selected":false,"filterSelected":false},{"id":9,"label":"จังหวัดที่เทียบท่า","selected":false,"filterSelected":false},{"id":10,"label":"วันที่แจ้งว่าจะเข้าไทย","selected":false,"filterSelected":false},{"id":11,"label":"วันที่มีการยืนยันจากศรชลภาค","selected":false,"filterSelected":false},{"id":12,"label":"การยืนยัน","selected":false,"filterSelected":false},{"id":13,"label":"คำนำหน้าชื่อ","selected":false,"filterSelected":false},{"id":14,"label":"ชื่อสกุลภาษาไทย","selected":false,"filterSelected":false},{"id":15,"label":"ชื่อสกุลภาษาอังกฤษ","selected":false,"filterSelected":false},{"id":16,"label":"หมายเลขบัตรประจำตัวประชาชน","selected":false,"filterSelected":false},{"id":17,"label":"หมายเลขหนังสือเดินทาง","selected":false,"filterSelected":false},{"id":18,"label":"หมายเลขSeamanBook","selected":false,"filterSelected":false},{"id":19,"label":"จังหวัด","selected":false,"filterSelected":false},{"id":20,"label":"อำเภอ","selected":false,"filterSelected":false},{"id":21,"label":"ตำบล","selected":false,"filterSelected":false},{"id":22,"label":"ที่อยู่ในประเทศ","selected":false,"filterSelected":false},{"id":23,"label":"เบอร์โทรศัทพ์","selected":false,"filterSelected":false},{"id":24,"label":"เบอร์โทรศัทพ์สำรอง","selected":false,"filterSelected":false},{"id":25,"label":"ผู้ที่ติดต่อได้","selected":false,"filterSelected":false},{"id":26,"label":"เบอร์ติดต่อของผู้ที่ติดต่อได้ในไทย","selected":false,"filterSelected":false},{"id":27,"label":"เลขที่หนังสือ","selected":false,"filterSelected":false},{"id":28,"label":"มีสภาพร่างกายแข็งแรง","selected":false,"filterSelected":false},{"id":29,"label":"มีอุณหภูมิร่างกายต่ำกว่า37จุด5เซลเซียส","selected":false,"filterSelected":false},{"id":30,"label":"ไม่มีอาการไอมีน้ำมูกเจ็บคอหอบหืดอย่างใดอย่างหนึ่ง","selected":false,"filterSelected":false},{"id":31,"label":"โรคประจำตัวโรคเรื้อรังที่เป็น","selected":false,"filterSelected":false},{"id":32,"label":"ยาที่ใช้ประจำ","selected":false,"filterSelected":false},{"id":33,"label":"localquarantine","selected":false,"filterSelected":false},{"id":34,"label":"PROVINCE","selected":false,"filterSelected":false},{"id":35,"label":"หมายเหตุ","selected":false,"filterSelected":false}],"filters":{},"rowHeaders":["จังหวัดที่เทียบท่า"],"colHeaders":["สัญชาติเรือ","ประเภทเรือ"],"filterHeaders":[],"chart_mode":{"id":0},"page":{"name":"test-pivot","id":"pivot","configType":"pivot.config"},"isAutoUpdate":true,"isShowBlank":false,"source":"pivot.config"}`)

// รับข้อมูล config แบบ string
getParameter(pivotWidgetID  ,"Config")
const pivotWidgetID  = "pivot" 
// เปิดหน้า File upload ให้เลือกไฟล์ config ที่จะใช้จากไฟล์ในเครื่อง
setParameter(pivotWidgetID  ,"ConfigFile")

// โหลดไฟล์ config
getParameter(pivotWidgetID  ,"ConfigFile")
const pivotWidgetID  = "pivot" 

//เปลี่ยนชื่อคอลัมป์ "Project_Name" เป็น "ชื่อโปรเจค" 
//เปลี่ยนชื่อคอลัมป์ "Project_ID" เป็น "รหัสโปรเจค" 
//เปลี่ยนชื่อคอลัมป์ "Team" เป็น "ทีม" 
//เปลี่ยนชื่อคอลัมป์ "Start_Date" เป็น "วันที่เริ่ม" 
setParameter(pivotWidgetID  ,"Label",[
  {colName : "Project_Name",label : "ชื่อโปรเจค"},
  {colName : "Project_ID",label : "รหัสโปรเจค"},
  {colName : "Team",label : "ทีม"},
  {colName : "Start_Date",label : "วันที่เริ่ม"},
])

const pivotWidgetID  = "pivot" 
getParameter(pivotWidgetID  ,"Total")
// => [  {"measure":{"name":"Count of ลำดับรวม","id":0},"value":"155"},
//         {"measure":{"name":"Count of IMO","id":0},"value":"155"}  ]


Printf Block

How this block appears in a Simulink model?

appearance.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
String input type String variable--Character vector Select the input type
Sample time (sec) -1 (inherited) or specify Specify the sample time

When to use this block?

This block can be used to print data to a serial monitor.

How does this block work?

This block serves as the ‘printf’ function in C programming. This block is for advanced users to debug code using a serial monitor. Check Modify Simulink generated C code in ESP-IDF for more information on using a serial monitor.

Previous : Mesh Receiver
Next : System Time Block


RapidSTM32

The content presented in this RapidSTM32 wiki describes our very first blockset and should be used as a concept and historical reference only. The software is no longer available.

Frequently Asked Questions

This section explains a few frequently asked questions.

Learn RapidSTM32 in A Day

This tutorial aims at teaching beginners how to use RapidSTM32 Blockset in ONE DAY (approximately 6 hours). After completing the tutorials, you will have enough basic knowledge to use the Blockset to implement a variety of basic but useful applications such as:

Yes!! all those within 6 hours, no kidding. We are truly taking about Rapid Prototyping . That's Why our duck can peel banana skin? :)

Common "How to"

This section shows basic common "how to" required for most RapidSTM32 projects.

  1. Getting Ready (Setting up for RapidSTM32 Blockset)]]
  2. Create a new model and set it to use RapidSTM32 target
  3. Set FiO Std in USB In Application Programming (IAP) Mode
  4. Initiate the Build Process
  5. Set FiO Std in Run Custom User Program Mode
  6. Set FiO Std in Mass Storage Device Mode

Advanced "How to"

This section shows some useful "how to" for advanced users.

  1. Create a blank template for manual C coding for use with FiO boards
  2. Modify or add custom C code for FiO Boards from Keil RVMDK
  3. Generate and use the generated C code with Non-FiO Boards

RapidSTM32 Blockset Reference

This section provides reference information about the Blockset and its usages.

  1. RapidSTM32 Basics
  2. Command-Line Function Reference
  3. Block Reference

Sample Projects

This section shows various sample projects from basic interfaces to external hardware/peripherals to a complete Automatic Control and Digital Signal Processing (DSP) design and analysis projects. These projects aims at showing the work flow and benefits of Model-based design and Rapid Prototyping at works. Before diving in these sample projects, it is recommended that you familiarize yourself with RapidSTM32 from Learn RapidSTM32 in A Day.

Sample projects are as follows.

RapidSTM32 Training

This page list available training workshop and materials. Example workshop include:

HIL Basic Concept Workshop
RapidSTM32 Community
This section shows:

RapidSTM32 Users List
Contributions from RapidSTM32 community
Download Repository
Blockset download
Demo files download
Training videos download


Real-Time Moving Object Tracking with FiO 2 (STM32F4) and Image Processing Algorithms

This project shows how to design a real-time moving object tracking algorithm in Matlab / Simulink. It also shows how to use Waijung to generate source code and run the algorithm in FiO 2 in real-time. Image data is transmitted to the host PC to visualize algorithm performance via UDP protocol.

The algorithm design is performed in two steps:

  1. Hardware in the Loop Test
  2. Stand-alone Application Test

All demo files are under waijungroot\targets\stm32f4_target\stm32f4\demo\image_object_tracking_demo directory.

Hardware in the Loop Test

The first step we program FiO 2 board (STM32F417IG + external 8Mb SRAM) to acquire image data (resolution 120 x 160 pixels) and send to the host PC via LAN (UDP protocol). The following show hardware setup.


Hardware Setup

See DCMI Installation Guideline for instructions how to connect to connect to different version (1.1 and 1.2) of aMG CameraINF.

The following figure shows a Simulink model for the target. This model programs FiO 2 to acquire image data and send to the host PC via UDP protocol.


Target Model for image acquisition into Simulink in real-time.

The following figure shows Simulink model for the host PC. This model perform object tracking algorithm. In this way, it is very simple to visualize results, analyze performance, and tune the algorithm.

For background information on the algorithm visit http://aimagin.com/blog/basic-image-processing-object-tracking/


Track moving object from streaming video.

Stand-alone Application Test

In this step, the algorithm is moved to run in the FiO 2 board. The detected target XY positions are overlayed on the image using Simulation Computer Vision System Blockset. The resulting image is transmitted to the host PC to display in real-time (around 5Hz update rate). The following summarized necessary steps to make it work in real-time (compare with an ideal algorithm design running in pure Simulation simulation on the host PC).

  1. The Gaussian filter was not implemented. Since it put heavy computation load on the MCU.
  2. The XY position determination was redesigned to reduce execution time.

The following figure shows hardware setup.


Hardware Setup

The following figure shows Simulink model for the target. The moving object tracking algorithm runs in FiO 2 in real-time.


Simulink model file for FiO 2

The following figure shows the Simulink model running on the host PC. This model only receive image data and display on screen.


Simulink model file for the host PC

Note about using STM32F4DISCOVERY board with UDP Cam demo:

  1. At “Target Setup” block, double click to open Mask configuration. Select “STM32F4DISCOVERY Default (HSEOSC-8MHz/HCLK-168MHz)” for clock configuration option.
  2. Remove “FSMC_SRAM Setup” if any (may be located in “Setup Other Hardware” subsystem).
  3. At “Ethernet Link Setup”, change interface pins to “Profile #1”.

Release note

Waijung2_20.11b

Release date: 23 November 2020

What's new?

  1. LEDC Block: To generate PWM signal for LED control.
  2. MCPWM Blocks: To generate PWM signal for motor control.
  3. Circular Buffer Demo.
  4. A mechanism to force code generation in C.

What's improved?

  1. The new operation mode to Target (added in waijung2_20.11a) is modified to let the user stream the video feed to either Simulink or Aimagin Connect webpage after processing it within the Target itself. A new demo is added to depict the said features.
  2. Optimized the HIL Block for higher data transfer rate.

Waijung2_20.11a

Release date: 4 November 2020

What's new?

  1. Capability to upload and monitor the program using ESP-IDF Visual Studio Code Extension
  2. A serial monitor Matlab app.
  3. New blocks
    1. HTTP Server Block: To convert the ESP32 to into a web server that serve custom web pages
    2. Circular Buffer Block: A circular buffer. is used for buffering data streams.

What's improved?

  1. Waijung2 now support from Matlab R2018b upwards
  2. The SQLite Block has been modified to support data input from Circular Buffer Block
  3. A new operation mode to Target has been added to the Camera Block that would enable the user to process the video feed within the ESP32 itself. The following new blocks have been created to support this operation mode
    1. Image Concatenate Block
    2. Memory Block
  4. Real time information will be shown in the Diagnostic Viewer when compiling and uploading model files to ESP32
  5. Configurable sample time is reduced from 10ms to 1ms

Waijung2_20.10a

Release date: 6 October 2020

First release.


Scheduling mechanism in Waijung 2

Objective

The objective of this documentation is to explain the code generation mechanism used by Waijung2.

Pre-requisites

This documentation assumes the reader has a basic understanding about FreeRTOS functionality. Click here to learn more about FreeRTOS types, functions, and macros.

Introduction

Waijung2 block-set is designed to program an ESP32 board using FreeRTOS. The rest of this documentation will describe how Waijung2 implement the features of FreeRTOS when generating code for your model file.

In all model files where Waijung2 blocks are used the Target Setup Block should be present in order to upload the code to an ESP32. The Target Setup Block would adjust the necessary Model Configuration Parameters, acquire hardware specifications of your ESP32 development board in order to generate the SDK file and acquire necessary data to create the base task. The base task is the default FreeRTOS Task created to place the generated code. If all the blocks in the model has the sample time specified as inherited (-1), it will be executed within this task.

When a user specify a sample time to a block (other than -1), Waijung2 generate a separate task for each different sample time in a way that the block gets executed according to the specified frequency. If two blocks share the same sample time the code generated by the two blocks will be executed within the same task created for that specific sample time.

Another way to create a task is to use the xTaskCreate Block. The input to the xTaskCreate block can be of two types.
  1. Function-Call Generator (From Matlab)
  2. Timer Interrupt Block

When using the Function-Call Generator block the user has to specify a sample time for the block. If this sample time is used for another block in the same model, the generated code from that block and the block sequence connected to the output of xTaskCreate block will be executed in the same task. Therefore if there is a block with a blocking process (a process that is waiting for some event, such as a resource becoming available or the completion of an I/O operation), the block sequence connected to the output of the xTaskCreate block will not be executed in the specified frequency. In such case input of the xTaskCreate block should be a Timer Interrupt. This way the generated code for the two processes will be in separate tasks even though they have the same sample time. This is the guaranteed way to ensure a block sequence get executed despite blocking process of another block sequence with the same sample time.

Example

Let's analyze the model show below with the information above. Block sequence 1,2 and 3 sample times are determined by the sample time specified in the Constant block. In block sequence 4, xTaskCreate block takes the input drive from a Function-Call Generator block while block sequence 5 xTaskCreate block takes the input drive from a Timer Interrupt Block.

Here Waijung2 will create 4 tasks. Block sequences 1,2, and 5 will each have there own task at their designated sample times while block sequences 3,4 will be run on the same task with a sample time of 4 sec. Since block sequences 3,4 are in the same task, if the block sequence 3 has a blocking process, it could affect block sequence 4 sample time as well.

Note

The sample times of the compatible blocks can be changed from the Sample time parameter in the block mask.

Previous : How to connect a hardware to a Wi-Fi Access Point
Next : Integrate Legacy C code to Waijung 2 using s-function builder


SD Card Append

How this block appears in a Simulink model?

appearance_append.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
File path Insert the file path.

When to use this block?

This block is used to write data to a file.

How does this block work?

The block search for the file name in the given path. If the file name already exists, it opens that file and add the new data to the file. If the file name does not exist, it creates a new file and the data.

Demo

SD Card demo

Previous : SD Card Write Block
Next : LEDC Block


SD Card Block

SD Card Setup Block
SD Card Read Block
SD Card Write Block
SD Card Append Block


SD Card demo

Demo file : esp32_sdcard_demo.slx

Description

This demo shows how to use the SD Card Block and String Processing Block for data logging to ESP32. In this demo the data will be taken from the ADC pins (GPIO36, GPIO39) with ADC Block and saved into the adc_data.csv with 0.5S per record.

What should be happening?

Once the sd card is inserted to the target module and executed the program, the data will be logged to the sd card. Wait about 10 seconds and remove the sd card and plug in to a Desktop or Laptop computer to view the data from adc_data.csv.

Previous : WIFI demo
Next : Camera demo: Stream video to Matlab Simulink


SD Card Read

How this block appears in a Simulink model?

appearance_read.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
Output data buffer size 32--64--128--256--512--1024--2048--4096 Select the output data buffer size.
File Path Insert the file path.
Example:
/sdcard/’filename’

When to use this block?

This block is used to read data from an already created file. For this block to function ‘SD Card Setup’ block should be present in the Simulink model file.

How does this block work?

The block reads the content saved in the specified file up to the buffer size limit and output the data from the output port.

Demo

SD Card demo

Previous : SD Card Setup Block
Next : SD Card Write Block


SD Card Setup

How this block appears in a Simulink model?

appearance_setup.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
Chip select pin (CS) 0 to 33 Select pin for CS
Clock pin (SCLK) 0 to 33 Select pin for SCLK
Master read (MISO) 0 to 33 Select pin for MISO
Master write (MOSI) 0 to 33 Select pin for MOSI
Format if mount fail True--False If FAT partition cannot be mounted, and this parameter is true, create partition table and format the filesystem.
Base path The block registers given FAT drive in VFS, at specified base path.
Maximum number of files maximum number of files which can be open at the same time
Allocation unit size If ‘format_if_mount_failed’ is set, and mount fails, format the card with given allocation unit size. Must be a power of 2, between sector size and 128 * sector size. For SD cards, sector size is always 512 bytes.

When to use this block?

This block can be used to initialize the SD card connected to ESP32 device before reading and writing files to it.

How does this block work?

ESP-IDF uses the FatFs library to work with FAT filesystems. FatFs resides in the ‘fatfs’ component.

Demo

SD Card demo

Previous : Wireless Communication Block (HIL)
Next : SD Card Read Block


SD Card Write

How this block appears in a Simulink model?

appearance_write.PNG

What can be configured?

Configuration Parameter Selectable Option/Value Description
File path Insert the file path.

When to use this block?

This block is used to write data to a file.

How does this block work?

The block search for the file name in the given path. If the filename already exists, it deletes that file and create a new file with the same name and write the new data to that file. If the file name does not exist, it creates a new file and the data.

Demo

SD Card demo

Previous : SD Card Read Block
Next : SD Card Append Block


Simple GET POST web page

Demo file : esp32_http_server_demo.slx

Description

This demo shows how to use HTTP Server Setup Block, HTTP GET Handler Block and HTTP POST Handler Block by using the custom html web pages. Addition to this blocks, the WiFi Block is used to initialize the wifi in AP mode to access the http server and SD Card Setup Block is used to initialize the SD card to serve the files (.html, ,css and .png).

Note : First copy the source_files.7z and extract the files to the SD card and insert in to the ESP32 module.

What should be happening?

Once the wifi is initialize wifi in AP mode use the following information to connect to the ESP32.

Once the IP address is accessed using the web browser, the web page is as below

The client will sends GET/POST requests according to the button

Model file : esp32_http_server_demo.slx
Source files : source_files.7z

Previous : System Time demo
Next : Line chart widget with ADC values


Simulate LED toggle

Objectives

This document highlight the how to simulate LED using Simulink.

Required software

Simulink model

Step 01
Open Matlab. Change the current folder to the directory where you want to create the model. Click Simulink.

Step 02
Click Blank Model. Save the new model in any name you want without space to avoid any errors as '******.slx'

Step 03
Open Library Browser . This Simulink blockset library allow you to create model that can be used only for simulation , it can not be uploaded to a microcontroller from MATLAB Simulink.
The Simulink blocks used,

Pulse Generator is used to generate a pulse which will be displayed in scope. These blocks are connected to send the signal. Connect the diagram as shown below,

once connected edit the parameters as follows,

Lamp indicator is used from SImulink blockeset library under dashboard section. The signal sent between the two blocks is linked to the lamp as shown in the below picture. For more details about Building, Simulating and connecting a Simple Simulink Model

Add the state as shown in the picture, additional state can be added by clicking on the + button in Block Parameters: Lamp. The color can be adjusted by simply double clicking the color.

Step 05

Now go to Simulation Tab on the left top corner in the window, then adjust the stop time = inf so that it keep on blinking until the stopped button is pressed. Finally press the play button .

Description

The function of this model is to blink led at 1 Hz frequency. The above model is simulated using Simulink blockset and the pulse generator is used to generate an frequency of 1 Hz. That scopes provide methods for displaying simulation data. In this example the pulse is displayed in the scope as shown below,

Result

This shows the two blinking colors blink at 1 Hz frequency.


Simulink model

Click to download the lamp_blink.slx model file.

Previous:Waijung 2 installation
Next:Make Simulink model work with hardware using Waijung 2


Smart Sensor configure display board

Please see attached PDF document for configuration of Display (Smartsensor_Display config.pdf)

Notes:
1. Android application needed for configuration can be downloaded in https://support.aimagin.com/projects/support/wiki/Smart_Sensor_configure_or_monitor_application
2. Follow instructions in the pdf document, and if you are having issues not being able to see the device in the connect list, please view the sensor map of the installation and disconnect turn off the device directly above the display in the sensor map (Contact Aimagin if you need any assistance in doing this step).


Smart Sensor configure or monitor application

Attached below is the application used to configure or monitor smartsensor system.

Please note this is installer package only for android mobile phones


Smart sensor for Heat index monitoring and alert

Aimagin Smart sensor for schools presentation v13.pdf


Smart sensor system

คู่มือการใช้งาน Web application ระบบ Smart sensor

Smart sensor for Heat index monitoring and alert

Smart Sensor temperature control

Smart Sensor update gateway or sensor software

Smart Sensor configure or monitor application

Smart Sensor configure display board

Flash program to ESP32


Smart Sensor temperature control

The smartsensor controller can be configured in 2 ways.

1. Timer control
2. Temperature control + Timer control

1. Timer control

Timer control mode can be configured when the user goes to Temperature control menu and disables/deletes all control related to the related controller UID. Thereby if temperature control for a controller is not set in the temperature control menu, the controller will only follow the timetable (set in controller menu).

2. Temperature control + Timer control

This mode can be configured when the controller UID is set in temperature control menu. It works as follows

If Sensor Temperature is less than Recovery Temperature (Tr) -----> Follow the timetable (Normal state)

If Sensor Temperature is more than High Temperature (Th) -----> Turn ON the controller (High temperature state)

If Sensor Temperature is between Tr and Th ------> No change done

Correctly setting the Th and Tr values are crucial in order for the system to work as expected.

How to determine Th and Tr values? (Please see graph below)

First monitor temperatures recorded by the sensors in normal conditions (when the controllers are working according to the timetable). Therefore if the average normal temperature is about 23℃, please set the Tr to 24℃, this will ensure that if temperature is less than 24℃ the timetable is always followed.

Next determine the desired Th value, this value should always be higher than Tr and recommended to have at least 1℃ of separation from Tr, the reason for the separation is to prevent the controller from fluctuating from Normal state and High temperature state (to prevent fluctuating ON/OFF signals sent to controller).

Please refer Flowchart below for a more detailed explanation on the control logic used.


Smart Sensor update gateway sensor software

Note: Please note software upgrade is only available via android mobile phone

Step 1:

Please download the apk file below (amg_ble_upgrade_ble4.2_v2.0.apk), this is the application used for software upgrade (works with android phones)
Please download the bin file below (if need to upgrade gateway download amg_gateway3_emacs_wifi_iap.bin).

Step 2

Please copy these files to your android mobile phone

Step 3

Please go to the location of amg_ble_upgrade_ble4.2_v2.0.apk file in your mobile phone and click on it to install the application.
Note: Please click allow as necessary, to accept all permissions if needed by the installation process

Step 4

After installed successfully, please open the application aMG BLE Upgrade,

Step 5

After the application is opened, please click on connect as shown below!f1e.PNG!

Next select the appropriate device you want to upgrade firmware (if gateway please select amg_gateway3 or if sensor please select correct sensor based on uid)

Step 6

Please confirm that you have connected to the correct device by the text shown

Step 7

Please click on the upgrade button on the bottom right corner.
Next browse to the location of the .bin file of the device you need to upgrade and click it

Step 8

Now device will begin updating, Status will be shown as percentage,

Step 9


Smart Sensor update gateway or sensor software

Note: Please note software upgrade is only available via android mobile phone
Note: Files are given below under files tab, these can be downloaded as necessary in the steps

Step 1:

Please download the apk file below (amg_ble_upgrade_ble4.2_v2.0.apk), this is the application used for software upgrade (works with android phones)
Please download the bin file below, this is the actual software file (if need to upgrade gateway, please download amg_gateway3_emacs_wifi_iap.bin).

Step 2

Please copy these files to your android mobile phone

Step 3

Please go to the location of amg_ble_upgrade_ble4.2_v2.0.apk file in your mobile phone and click on it to install the application.
Note: Please click allow as necessary, to accept all permissions if needed by the installation process

Step 4

After installed successfully, please open the application aMG BLE Upgrade,

Step 5

After the application is opened, please click on connect as shown below

Next select the appropriate device you want to upgrade firmware (if gateway please select amg_gateway3 or if sensor please select correct sensor based on uid)

Step 6

Please confirm that you have connected to the correct device by the text shown

Step 7

Please click on the upgrade button on the bottom right corner.
Next browse to the location of the .bin file of the device you need to upgrade and click it

Step 8

Now device will begin updating, Status will be shown as percentage, please wait till it reaches 100 % (usually take 5-10 minutes)

Step 9

After it reaches 100% it will automatically disconnect.

Step 10

To verify if successful upgrade, please connect to the device again similar to Step 5 and Step 6

Now click on Check button on bottom left. The firmware version and build date will appear please check whether this is the same version as given in the description of the bin file in download section.


Smart Sensor User Guide

aMG 4-20 mA to WIFI Data Logger


SMC IOT Terminal Design Case study

Requirements

The SMC IOT Terminal is used to upload the sensor data which is connected to the SMC EX-600 system to the Aimagin smart sensor server as well as to the Aimagin connect local database to visualize the sensor data. The SMC IOT Terminal is based on ESP32 module. In the process, first the SMC IOT Terminal initialize the WiFi in AP mode (Access Point mode) to run the Aimagin Connect server. In this SMC project the Aimagin Connect server on ESP32 is used to configure the settings of IOT terminal using interactive forms and visualize the sensor data with widgets (Numeric displays, Bar charts, Multi-axis graphs and etc). The system remains in the AP mode with Aimagin Connect until the user is inactive for 30 seconds or logout from the Aimagin Connect. Once the configuration is finished and the user is inactive or logout from the Aimagin Connect, the IOT Terminal is switched the WiFi from AP mode to Station mode to upload the sensor data to the Aimagin smart sensor using internet and save those sensor data in the Aimagin Connect local database.

There are five different web pages to configure the SMC IOT Terminal and visualize the sensor data.

  1. WiFi Configuration page
    This page is used to configure the WiFi settings (SSID, Password, IP address and etc.) in Station mode to upload the sensor data to the Aimagin Smart Sensor server.
  2. Target Server page
    The usage of Target Server page is to setup the URL of the server which the data is uploaded (in this case: the URL of the Aimagin Smart Sensor server)
  3. Factory Reset page
    It is used to reset data which is saved in above two web pages to default.
  4. Analog Input Configuration page
    This page is used to convert the analog input sensor readings to required units. Usually the SMC analog input sensor readings shows in mA or in V. But it should be converted to a unit which can easily understand.
  5. SMC Dash Board page
    Dash board page shows the sensor reading data with the Aimagin Connect widgets.

Web Page Designing (using Aimagin Connect)

Web page designing in Aimagin Connect is very user friendly and easy to use with dragging and dropping components and can be designed advanced web pages using it with a minimum knowledge on web designing. Developing most of the web pages for SMC on Aimagin Connect can be divided in to two sections.
  1. Designing the web page
  2. Creating the database table for data representation on web pages

Following documentation demonstrates developing each web page on Aimagin Connect step by step.

Developing WiFi Configuration page

Once login in to the Aimagin Connect server on the web go to SQLite under System settings on the left main menu as in the following figure.

Then click Create on SQLite Page to make a new table

Change the name of the table to wifi_config and click Add to add required columns to the table

In column setting, add the required Column name and the suitable data type. In this scenario set the column name as SSID and the data type as TEXT. And then click OK to add that column to the table as in the following figure.

Likewise add the required remaining columns for the wifi_config table as follows and click Update to finalize the table.


Then click New and select New page on top menu to add a new page to the current project

Change the title of the page under property as in the figure. The title of the page will be displayed on the web browser tab.

The required components and widgets are in the Components section

First add a topic to the page. For that drag and drop a container on to the page. The container is under Grid in Components. Then drag and drop a Row on to the Container. If the Row component is dropped on the Container it will make a row inside the Container. Then drag and drop a Col component on the Row component to create a column inside the row. And after that drag and drop a Div component on the Col (column) component. Set the text align as center in Property panel of the Div component to align the text center. Then drop a Label component on the Div component. Click on the added label component and change the Content on Property panel to WiFi Configuration and change the other parameters as required as follows. The component tree will be as in the following figure.

Then add the required text fields, radio buttons and buttons to the WiFi config page. There are six text fields , two radio buttons and two buttons in this page. The six text fields are used to display and let the user to input SSID, Password, IP Address, Subnet Mask, Gateway and DNS. The two radio buttons are used to select the WiFi configuration in Static or Dynamic and the two buttons are used to submit and clear the form data. Before add those components, add a Container component and then add the other components as below. Change the labels and the IDs of the text fields and the radio buttons as in the figure below. The label for text fields can be changed in the Label parameter under the Parameter in text field property pane.

To add the options to the radio button, click on the radio button and go to edit in options under property panel.

Then add two custom options by clicking on Add custom options and name it as Dynamic and Static and save as follows.

Once the web designing is completed the connection between the database table and the web page components should be established. The main feature in this WiFi configuration page, Target Server page and the Analog input configuration page is once the page is loaded it will automatically show the saved data from the database table. And in each page the client checks whether the user alive or not by tracking the key board and the mouse. For that a callback function should be implemented as follow.

First click on the page and click on the edit on init under event callback.

Add the callback function as below. Once the function is implemented click Save.

AmgCnt.SQLite.read.get({
    sql: "select * from wifi_config where ROWID = ?",
    params: ['1']
}, (res) => {
    setParameter('txtSSID', 'Content', res.row.SSID);
    setParameter('txtPassword', 'Content', res.row.Password);
    setParameter('rdiAccessPoint', 'Value', res.row.Access_P);
    setParameter('txtIP', 'Content', res.row.IP);
    setParameter('txtSubnet', 'Content', res.row.Subnet_m);
    setParameter('txtGateway', 'Content', res.row.Gateway);
    setParameter('txtDNS', 'Content', res.row.DNS);
    console.log(res);
});

//Check the user alive
let lastEventTime = Date.now();
const max_idle = 30; /*30 seconds*/
let activeStatus = true;

window.addEventListener('mousemove', function(e) {
    lastEventTime = Date.now();
    //console.log(e);
    //setParameter('id-move', 'Content', "(" + e.pageX + ", " + e.pageY + ")");//
    check()
});

window.addEventListener('keydown', function(e) {
    /*or use keyup, keydown*/
    lastEventTime = Date.now();
    console.log(e); /*check e to see other detail such as, ctrl, shift, ...*///
    //setParameter('id-press', 'Content', e.key + " (" + e.keyCode + ")");//
    check()
});

function updateLastEventTime(e) {
    lastEventTime = Date.now();
    //setParameter('id-press', 'Content', "Touch Event");
    check()
}

window.addEventListener('touchstart', updateLastEventTime);
window.addEventListener('touchend', updateLastEventTime);
window.addEventListener('touchcancel', updateLastEventTime);
window.addEventListener('touchmove', updateLastEventTime);

function check() {
    let dt = Math.round((Date.now() - lastEventTime) / 1000);
    if (dt > max_idle) {
        /*no mouse/keyboard events more than 30 seconds*/
        if (activeStatus == true) {
            //setParameter('id-status', 'Content', "Inactive");//c
            activeStatus = false;
            AmgCnt.Esp32.setClientActive(activeStatus);
        }
    }else {//c
        //setParameter('id-status', 'Content', "Active (Idle: " + (max_idle - dt) + " s)");//c
        if (activeStatus == false) {//c
            activeStatus = true;//c          
            AmgCnt.Esp32.setClientActive(activeStatus, function(e) {//c
              console.log("server response: "+e.data);//c
            });
        }
    }
}

setInterval(check, 1000);

In this callback function, the web page acquires data of the first row from the wifi_config table using AmgCnt.SQLite.read.get function with the suitable SQL and each column data from the table will be shown in the each web page component with the setParameter function. In this setParameter function the first parameter should be the Name of the component, the second parameter will be the parameter that you are going to change; for the text fields the parameter is the Content. The third parameter is the value; in this case the particular column data from the database table.

In the WiFi configuration the user select Dynamic in radio buttons the IP Adderss, Subnet mask, Gateway and DNS text fields should be disabled. It should enable when the user select Static in wifi configuration. For that a callback function should be implemented when the selection of the radio button is changing. Click on the radios component and click on the edit in the change event under event callback.

The callback funtion should be as follow. It basically disable those text fields if the selection is Dynamic. Otherwise it will enable the text fields.

var v = getParameter('rdiAccessPoint', 'Value');
!setParameter('txtIP', 'Enable', v=="Static");
!setParameter('txtSubnet', 'Enable', v=="Static");
!setParameter('txtGateway', 'Enable', v=="Static");
!setParameter('txtDNS', 'Enable', v=="Static");

Next the callback function for the Update button. For this the data in each text fields and the radio buttons should be inserted to the wifi_config table. Click on the Update button component and go to Edit of the mouseclick event under Event callback as follow.

Add the following functions to the mouseclick event

AmgCnt.SQLite.read.get({
    sql: "select SSID from wifi_config ",
    params: []
}, (res) => {
    if (res.row == undefined) {
        AmgCnt.SQLite.create.run({
            sql: "insert into wifi_config (SSID, Password, Access_P, IP, Subnet_m, Gateway, DNS) values(?, ?, ?, ?, ?, ?, ?)",
            params: [getParameter('txtSSID', 'Content'),getParameter('txtPassword', 'Content'),getParameter('rdiAccessPoint', 'Value'),getParameter('txtIP', 'Content'),getParameter('txtSubnet', 'Content'),getParameter('txtGateway', 'Content'),getParameter('txtDNS', 'Content')]
        }, (res) => {
            alert("Data has been inserted");
        });

    } else {
        AmgCnt.SQLite.update.run({
            sql: "update wifi_config set SSID = ? ,Password = ?, Access_P = ?,IP = ?, Subnet_m = ? ,Gateway = ?, DNS = ? where ROWID = ?",
            params: [getParameter('txtSSID', 'Content'),getParameter('txtPassword', 'Content'),getParameter('rdiAccessPoint', 'Value'),getParameter('txtIP', 'Content'),getParameter('txtSubnet', 'Content'),getParameter('txtGateway', 'Content'),getParameter('txtDNS', 'Content'),'1']
        }, (res) => {
            alert("Data has been updated");
        });
    }

    console.log(res);
});

In this event, the data in all components is gathered and saved in the wifi_config table. First the client checks whether the data is already in the first row in the wifi_config table. If it is not, the data will be inserted to the first row. If the data is already in the first row, it will update the first row with the current data. AmgCnt.SQLite.create.run function is used to insert the data to the table and AmgCnt.SQLite.update.run function is used to update the data with the current data. getParameter function is used to get the user entered data form the web component (from the text field or from radio button).

The last callback function is used to clear the data of the web page using the clear button. For that click on the clear button and go to mouseclick event of that button and add the following function to clear the data on each component (in text fields and radio buttons).

setParameter('txtSSID', 'Content', '');
setParameter('txtPassword', 'Content', '');
setParameter('rdiAccessPoint', 'Value', '');
setParameter('txtIP', 'Content', '');
setParameter('txtSubnet', 'Content', '');
setParameter('txtGateway', 'Content', '');
setParameter('txtDNS', 'Content', '');

Once the web page designing is finished save the project using the save button and preview the designed web page using preview button as in the following figure.

The final web page looks as follow. Try with adding data to the web page and submit those data. Once you load the page again it will show the last submitted data that you entered.

Developing Target Server page

Create a new table in SQLite page and name it as target_server. There are two columns in this table; IP and Key. Configure those columns as follow.

Once the columns are added update the table using Update button

In the Target Server page, there are two text fields to insert the URL of the server and the Key and two buttons to update and clear the data. Go to Aimagin Connect page, add a new web page and name it as in following figure. Then add a topic to the page as in the WiFi configuration page and change the label as Target Server.

Then add the two text fields and two buttons in to the page as in the following figure. Change the id of each text field as required.

The labels of each text fields as follows. The label content can be changed by clicking on each text field and changing the Label parameter in the Property pane as in the following figures.

Once all the components for the web page are inserted, the required callback function should be implemented as in the WiFi Configuration page to show the last saved data in the database table once the web page is loaded and to save the latest data in the database table. First implement the functions for displaying the saved data in the database table and check the whether the user is active. For that click the page of the Target Server and edit the init callback under Event callback in the property pane as in the following figure and add the following functions.

AmgCnt.SQLite.read.get({
    sql: "select * from target_server where ROWID = ?",
    params: ['1']
}, (res) => {
    setParameter('txtDomain', 'Content', res.row.IP);
    setParameter('txtSKey', 'Content', res.row.Key);

    console.log(res);
});

//Check the user alive
let lastEventTime = Date.now();
const max_idle = 30; /*30 seconds*/
let activeStatus = true;

window.addEventListener('mousemove', function(e) {
    lastEventTime = Date.now();
    //console.log(e);
    //setParameter('id-move', 'Content', "(" + e.pageX + ", " + e.pageY + ")");
    check()
});

window.addEventListener('keydown', function(e) {
    /*or use keyup, keydown*/
    lastEventTime = Date.now();
    //console.log(e); /*check e to see other detail such as, ctrl, shift, ...*/
    //setParameter('id-press', 'Content', e.key + " (" + e.keyCode + ")");
    check()
});

function updateLastEventTime(e) {
    lastEventTime = Date.now();
    //setParameter('id-press', 'Content', "Touch Event");
    check()
}

window.addEventListener('touchstart', updateLastEventTime);
window.addEventListener('touchend', updateLastEventTime);
window.addEventListener('touchcancel', updateLastEventTime);
window.addEventListener('touchmove', updateLastEventTime);

function check() {
    let dt = Math.round((Date.now() - lastEventTime) / 1000);
    if (dt > max_idle) {
        /*no mouse/keyboard events more than 30 seconds*/
        if (activeStatus == true) {
            //setParameter('id-status', 'Content', "Inactive");
            activeStatus = false;
            AmgCnt.Esp32.setClientActive(activeStatus);
        }
    }
}

setInterval(check, 1000);

Then implement functions for the Update button and the clear button. The parameter configuration for those buttons as follow.

The required functions for the Update buttons is as follow. Those functions should be added to the mouseclick event under Event callback in the property pane of the Update button to save the web page data in the database table.

AmgCnt.SQLite.read.get({
    sql: "select IP from target_server ",
    params: []
}, (res) => {
    if (res.row == undefined) {
        AmgCnt.SQLite.create.run({
            sql: "insert into target_server (IP, Key) values(?, ?)",
            params: [getParameter('txtDomain', 'Content'),getParameter('txtSKey', 'Content')]
        }, (res) => {
            alert("Data has been inserted");
        });

    } else {
        AmgCnt.SQLite.update.run({
            sql: "update target_server set IP = ? ,Key = ? where ROWID = ?",