SK-S7G2 with Connected Weather Demo and AMS Sensor – Quick Start Guide

LEVEL 3:  ADVANCED  |  

Overview

 

This tutorial will show you how to add an AMS Sensor to the Synergy Starter Kit SK-S7G2 and send and visualize the new sensor data in the Renesas IoT Sandbox, by modifying the Connected Weather Panel demo and using the M1 Synergy Cloud Driver.

This is an advanced tutorial that builds on the Quick Start Guide for the Synergy Starter Kit: SK-S7G2 with Connected Weather Demo.  In this tutorial, you will change your project to connect four new sensors –  Air Quality, Color, Temperature/Humidity, and Proximity, detected via the AMS Module. The M1 Synergy Cloud Driver library will be included into the project, allowing you to read and write to the sensors through python code in the Renesas IoT Sandbox. We will also visualize the collected sensor data in the Renesas IoT Sandbox Dashboard.

For the purpose of this tutorial , we will use “ConnectedWeatherPanel-SKS7-20161103” preloaded project.

Using e2 studio, we will update this project to incorporate new sensor and data you wish to process. We will generate new build and flash the board.

In Renesas IoT Sandbox, we will create/update necessary workflow and visualize new data in Dashboard.

What you need to get started:
PREREQUISITES:
  • Understanding of  Renesas e2 studio
  • Understanding of  Synergy Starter Kit: SK-S7G2 with Connected Weather Demo – Quick start guide
  • Activation of your SK-S7G2 Template Project in Renesas IoT Sandbox

Estimated Time to Complete: 2.5 – 3 hrs

 

1. Open Synergy Configuration

(configuration.xml)

In this tutorial, you will use the pre-built Connected Weather Panel project which includes Synergy configuration ‘configuration.xml”.

Open e2 studio, then go to File -> Import -> General -> Existing Projects into Workspace, then click Next:

existprojworkspace

 

Select ‘Select archive file’ and select the file ConnectedWeatherPanel file that you’ve downloaded before then click ‘Finish’:

Under ‘Project Explorer’, open the ConnectedWeatherPanel folder and select ‘configuration.xml’.

 

Switch to ‘Synergy Configuration’ perspective:

synconfig

 

Alternatively, go to ‘Open Perspective’ and select ‘Synergy Configuration’ from there:

openpersp

 

2. Update to the latest SSP version

NOTE: As of 12/09/2016, it is SSP version 1.1.3

Select the ‘BSP’ tab , next to ‘Summary’. Change the SSP version to 1.1.3

sspver

 

3. Change LCD Configuration Driver to use RSPIO.

Now, Select the ‘Threads’ tab and then click ‘HMI Thread’ :

hmithread

 

Remove existing g_spi_lcdc stack:

g_spi_lcdc

 

Create a new r_rspi stack:

r_rspi

 

Configure the r_rspi stack:
  • Enable SPI0 RXI, SPI0 TXI, SPI0 ERI, and SPI0 IDLE interrupts (ex. set to priority 3)
  • Rename to g_spi_lcdc
  • Clock Phase -> Data sampling on even edge, data variation on odd edge
  • Clock Polarity -> High when idle
  • Bitrate -> 250000
  • Callback -> g_lcd_spi_callback

r_rspi_stack

 

g_spi_lcdc_driver

 

Delete DTC Drivers:
  • Delete the following two drivers of r_rspi stack:
    • g_transfer0_Transfer Driver on r_dtc Software Activation 1
    • g_transfer1_Transfer Driver on r_dtc Event SPI0 RXI

deldtc

 

This shows the view once ‘g_transfer0 Transfer Driver on r_dtc Software Activation 1’ is deleted:

g_spi_lcdc_driver_del

 

Switch to Pins tab and configure RSPIO:

In Pins, go to Peripherals -> RSPI, then select SPI0_Pin_Option_A:

  • Operation Mode -> SPI Op
  • MISOA_A -> P100
  • MOSIA_A -> P101
  • RSPCKA_A -> P102

pins_tab

 

Configure Port 1 Pins:

configport1

 

  • P100 -> MISOA_A

p100

 

Repeat for P101 and P102, setting Chip input/output to MOSIA_A and RSPCKA_A respectively:

rspcka

 

4. Configure SCI0 and PMODB

Configure PMODB port pins on SK-S7G2 board to communicate over the I2C protocol with the AMS sensor.

In Pins, go to Peripherals -> SCIO_2_4_6_8, then select SCI0:

configscio

 

The AMS sensor is I2C based, so:

  • Operation Mode -> Simple I2C

scio_config

 

Ensure that RXD0_SCL0_MISO0 and TXD0_SDA0_MOSI0 are set to P410 and P411 respectively, as pointed out in the below picture.

scio_pin

 

5. Add Sensor Thread

threads

 

Rename It, Increase Stack Size, and Change Priority:

Configure New Thread to :

  • Symbol -> sensor_thread
  • Name -> Sensor Thread
  • Stack_size (bytes) -> 4096
  • Priority -> 10

renameit

symbol_sensor

 

6. Add AMS Air Quality Sensor to Sensor Thread

synergy_config

ic2_framework

 

Configure Shared I2C Bus:
  • I2C Implementation -> SCI I2C

share_ic2

 

Add I2C Driver:

add_ic2

 

Configure SCI Common:
  • Simple I2C Mode -> Enabled
  • Simple SPI Mode -> Disabled

sci

 

Configure I2C Driver:Name -> air_quality
  • Name -> air_quality
  • Slave Address -> 0x5A

ic2

 

7. Add AMS Color & Proximity Sensor

amscolor

 

Add Existing Shared I2C Bus:

shareic2

 

Add I2C Driver:

addic2

 

Configure I2C Driver:
  • Name -> color_and_proximity
  • Slave Address -> 0x39

configic2

 

8. Add Temperature & Humidity and Lightning Sensors

Repeat “Add AMS Color & Proximity Sensor” steps twice, once for the temperature & humidity sensor and once for the lightning sensor. Use the following parameters when configuring the I2C driver.

Configure Temperature & Humidity I2C Driver:
  • Name -> temperature_and_humidity
  • Slave Address -> 0x43
Configure Lightning I2C Driver:
  • Name -> lightning
  • Slave Address -> 0x02

sensorthreads

 

9. Add Cloud Driver Command Queue

add_cloud_driver

 

Configure Queue:
  • Name -> Cloud Driver Command Queue
  • Symbol -> g_cloud_driver_command_queue
  • Message Size -> 2
  • Queue Size -> 200

sensorthread

 

10. Add sf_uart_comms

Switch to the Components Tab and Select Latest Version of sf_uart_comms:

uart

 

11. Generate Project Content

Save, then click Generate Project Content:

content

 

12. Switch to C/C++ Perspective

switchcc

In src -> s7g2_sk, open lcd_setup.c file.

Edit lcd_setup.c to use RSPIO

At line 76, replace code with the following code highlighted in BLUE:

tx_semaphore_get(&g_hmi_semaphore_lcdc,TX_WAIT_FOREVER);

g_ioport_on_ioport.pinWrite(LCD_CMD,IOPORT_LEVEL_HIGH);

g_ioport_on_ioport.pinCfg(IOPORT_PORT_01_PIN_02,(IOPORT_CFG_PORT_DIRECTION_OUTPUT | ((g_spi_lcdc.p_cfg->clk_polarity == SPI_CLK_POLARITY_HIGH) ? IOPORT_LEVEL_LOW : IOPORT_LEVEL_HIGH)));

R_BSP_SoftwareDelay(5,BSP_DELAY_UNITS_MICROSECONDS);

g_ioport_on_ioport.pinCfg(IOPORT_PORT_01_PIN_02,(IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_RSPI));

err = g_spi_lcdc.p_api->writeRead(g_spi_lcdc.p_ctrl, dummy_write, data,len,SPI_BIT_WIDTH_8_BITS);

if (SSP_SUCCESS != err)

{

while(1);

}

 

13. Add M1 Synergy Cloud Driver Library to Project

Download M1 Synergy Cloud Driver Library

The ‘Medium 1 Synergy Cloud Drive Library’ zip file contains the following files:

  • libcloud-driver.a
  • m1_cloud_driver.h

The ‘ConnectedWeatherPanel’ project contains the following files (in m1 directory):

  • libm1.a
  • m1_agent1.a

NOTE: When you unzip the ‘m1_synergy_cloud_driver_library.zip’  in the root folder, ensure you don’t accidentally overwrite files already present in this folder.

Unzip  ‘m1_synergy_cloud_driver_library.zip’ file in Root Folder of Project

m1 folder should now contain:

  • libcloud-driver.a
  • libm1.a
  • m1_agent.h
  • m1_cloud_driver.h
Include cloud-driver Library

Right-click project and select Renesas Tool Settings:

 

toolsettings

 

C/C++ General -> Paths and Symbols -> Libraries

Click “Add”:

add

 

Add “cloud-driver” library:

clouddriver

In ‘ConnectedWeatherProject’, go to ‘src’ folder to locate .c files.

 

14. Edit sensor_thread_entry.c

Replace the entire contents of sensor_thread_entry.c with the following:

/*

*  Copyright (c) 2016 Medium One, Inc

*  www.mediumone.com

*

*  Portions of this work may be based on third party contributions.

*  Medium One, Inc reserves copyrights to this work whose

*  license terms are defined under a separate Software License

*  Agreement (SLA).  Re-distribution of any or all of this work,

*  in source or binary form, is prohibited unless authorized by

*  Medium One, Inc under SLA.

*

*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS

*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT

*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS

*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT

*  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,

*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED

*  TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR

*  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF

*  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING

*  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS

*  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*

*/

#include "sensor_thread.h"

#include <m1_agent.h>

#include <m1_cloud_driver.h>

void sensor_thread_entry(void);

/* Sensor Thread entry function */

void sensor_thread_entry(void)

{

ssp_err_t err;

char * cloud_driver_command;

// open PMOD B as I2C (known devices)

err = g_sf_i2c_device0.p_api->open(g_sf_i2c_device0.p_ctrl, g_sf_i2c_device0.p_cfg);

m1_initialize_i2c(&g_sf_i2c_device0);

err = g_sf_i2c_device1.p_api->open(g_sf_i2c_device1.p_ctrl, g_sf_i2c_device1.p_cfg);

m1_initialize_i2c(&g_sf_i2c_device1);

err = g_sf_i2c_device2.p_api->open(g_sf_i2c_device2.p_ctrl, g_sf_i2c_device2.p_cfg);

m1_initialize_i2c(&g_sf_i2c_device2);

err = g_sf_i2c_device3.p_api->open(g_sf_i2c_device3.p_ctrl, g_sf_i2c_device3.p_cfg);

m1_initialize_i2c(&g_sf_i2c_device3);

char rxBuf[700];

while (1) {

tx_queue_receive(&g_cloud_driver_command_queue, &cloud_driver_command, TX_WAIT_FOREVER);

if (m1_handle_message(cloud_driver_command, rxBuf) == M1_SUCCESS_DATA)

m1_publish_event(rxBuf, NULL);

tx_block_release(cloud_driver_command);

}

}

15. Edit hmi_thread_main.c

In the file hmi_thread_main.c, add the following code in GREEN and replace the code in BLUE:

  1. Add #include “sensor_thread.h”
  2. Add the following global definitions:
TX_BLOCK_POOL g_cloud_message_pool;

#define CLOUD_MSG_BLOCKS 6

#define CLOUD_MSG_BLOCK_SIZE 1536

char _cloud_message_pool[CLOUD_MSG_BLOCKS * (CLOUD_MSG_BLOCK_SIZE + sizeof(void *))];
  1. Modify function void subscription_callback(int type, char * topic, char * msg, int length) to reflect the following:
void subscription_callback(int type, char * topic, char * msg, int length) {

. . .

    } else if (msg[0] == 'T') {

        GX_EVENT gxe;

        int target_temp;

        sscanf(&msg[1], "%d", &target_temp);

        gxe.gx_event_type = GX_EVENT_CLOUD;

        /** Send event to GUI */

        gxe.gx_event_sender         = GX_ID_NONE;

        gxe.gx_event_target         = 0;  /* the event to be routed to the widget that has input focus */

        gxe.gx_event_display_handle = 0;

        gxe.gx_event_payload.gx_event_intdata[0] = target_temp;

        gx_system_event_send(&gxe);

    } else {

        ssp_err_t err;

        char * newBuf;

        err = tx_block_allocate(&g_cloud_message_pool, &newBuf, 20);

        if (err == TX_SUCCESS) {

            memcpy(newBuf, msg, length);

            err = tx_queue_send(&g_cloud_driver_command_queue, &newBuf, 20);

            if (err) {

                tx_block_release(newBuf);

        }

    }

}
  1. Modify void hmi_thread_main(void) to reflect the following:
void hmi_thread_main(void)

{

    ssp_err_t err;

    UINT      status = TX_SUCCESS;

    sf_message_header_t * p_message = NULL;

    char provisionConfigBuffer[200];

    char m1_apikey[100] = {0};

    char m1_mqtt_user_id[32] = {0};

    char m1_mqtt_project_id[32] = {0};

    char m1_password[100] = {0};

    tx_block_pool_create(&g_cloud_message_pool,

            "cloud message pool",

            CLOUD_MSG_BLOCK_SIZE,

            &_cloud_message_pool,

            sizeof(_cloud_message_pool));

    /* Initializes GUIX. */

 

 

16. Build

build

CHECKPOINT:

You have successfully updated the ConnectedWeatherPanel workflow, compiled and built the project.

Now, you are ready to flash the board with your new build, attach the AMS sensor, connect to Renesas IoT Sandbox and visualize your data.

 

17. Program the Board, Connect AMS Sensor, and Leave it running

At this point, make sure your board has power by plugging Micro USB to J19 (DEBUG_USB) and your ETHERNET (J11) is connected to your network.  Now, you need to update the board’s image with the previously generated build.

To flash the board, right click on ‘ConnectedWeatherPanel’, then select:

Debug As -> Renesas GDB Hardware Debugging

connweather

If any errors occur, resolve them and try to reprogram the board again.

Note: You can find the new image ConnectedWeatherPanel.srec in the Debug folder of your project.

Connect the AMS sensor to J14 (PMODB) connector as shown in the picture:

boardpic

If you haven’t yet activated the SK-S7 template project in Renesas IoT Sandbox, then click here.

NOTE: We will use this same activation link because it has all the necessary tags and streams automatically generated.  This is faster than starting from scratch with a blank project.

NOTE: You can use the same email address that you used in prior activations.  Specify a unique project name for your Connected Weather Panel project.

Once activation is completed, you will receive an email with your account credentials needed to provision the kit and access the cloud portal.  This email will include your:

  • API Key
  • Device username and password
  • Credentials for your mobile app (optional)

Login to Renesas IoT Sandbox with your web credentials.  Select your newly created project in the top right drop down.

CHECKPOINT:

By now, you should have flashed your board with your build, connected sensors, provisioned the kit, and logged into the Renesas IoT Sandbox.

Now, you are ready to update your workflows and visualize the collected data.

 

18. Initialize Board Display

In this step, you will update some of the current workflows as well as create your first workflows in order to print AMS sensor generated “Connected Weather Panel” data on the board screen when it connects.

When you provisioned the kit, three workflows were already generated for you:workflow

You will need to modify these workflows to represent changes done in e2 studio.  Additionally, you will create a new workflow to visualize the data generated by AMS sensor – air quality, temperature and humidity, color and proximity.

 

19. Modify Get Weather and Location Workflow

Click on Workflow Studio on the left side of the Renesas IoT Sandbox and then click on Get Weather and Location workflow. Double click on the Base Python module.

Change Base Python line 1386 from:

MQTT.publish_event_to_client(IONode.get_input('in2')['event_data']['value'], "60")

to:

MQTT.publish_event_to_client(IONode.get_input('in2')['event_data']['value'], "T60")

Click Save and Activate.

 

20. Modify Set Board Temperature Workflow

Similarly, modify the Set Board Temperature workflow with the following three changes (lines 6, 8, and 10):

A.  Change Base Python line 6 from:

    MQTT.publish_event_to_client(IONode.get_input('in2')['event_data']['value'],str(IONode.get_input('in1')['event_data']['value']))

to:

    MQTT.publish_event_to_client(IONode.get_input('in2')['event_data']['value'], 'T{}'.format(str(IONode.get_input('in1')['event_data']['value'])))

B.  Change Base Python line 8 from:

MQTT.publish_event_to_client(IONode.get_input('in2')['event_data']['value'], "60")

to:

MQTT.publish_event_to_client(IONode.get_input('in2')['event_data']['value'], "T60")

C.  Change Base Python line 10 from:

MQTT.publish_event_to_client(IONode.get_input('in2')['event_data']['value'], "85")

to:

MQTT.publish_event_to_client(IONode.get_input('in2')['event_data']['value'], "T85")

Now, you will generate workflows for the data generated by AMS sensor.

 

21. Create Air Quality Sampling Workflow

This workflow will send commands over MQTT to the device to read several registers from the air quality sensor on the AMS module.  The command is interpreted by the M1 Cloud Driver that was included in the project earlier in this tutorial.  The M1 Cloud Driver then transmits the register data as an array of raw bytes to the Renesas IoT Sandbox under the tag air_quality.  This workflow will run once a minute.

Click on Workflow Studio on the left side of the Renesas IoT Sandbox and click the “Create +” button.

First, name the workflow “Air Quality Sampling” by typing this in the textbox at the top left of the workflow then click anywhere on the empty canvas to save it.

airqual

Next, select the “Tags & Triggers” icon from the right toolbar.

tags_trig

From the Tags & Triggers menu, select “scheduler” and click and drag “Custom” from the menu onto the empty workflow space.

custom

Similarly, From the Tags & Triggers menu, select “raw” and click and drag “device_id” from the menu onto the empty workflow space.

raw_device

From the Modules menu, select “Foundation” and click and drag “Base Python” from the menu onto the workflow space.

basepython

Drag the “in1” circle on the Base Python module to the circle on the bottom of the device_id tag. This will give the Python code access to the information in the device_id tag.

connector

In Custom tag, set user to ‘device’; then click Save and Activate

customtag

In device_id tag, uncheck the trigger option; then click Save and Activate

deviceid

 

In Base Python, replace the original code with following code; then click Save and Activate.

Base Python code:

'''

This workflow requests the air quality data from the sensors on the board

Last Updated: Sept 15, 2016

Author: Medium One

'''

import MQTT

device_id = IONode.get_input('in1')['event_data']['value']

def get_data():

write_data = [0x5A]

send_mqtt_msg(u'3;2;7;{};air_quality;'.format(len(write_data)) + u''.join(map(unichr, write_data)));

def send_mqtt_msg(msg):

mqtt_msg = msg

if not isinstance(msg, basestring):

mqtt_msg = ''.join(map(unichr, msg))

MQTT.publish_event_to_client(device_id, mqtt_msg, 'latin1')

get_data()

 

22.  Create Temperature and Humidity Sampling Workflow

This workflow will send commands over MQTT to the device to write and read several registers from the temperature and humidity sensor on the AMS module. The command is interpreted by the M1 Cloud Driver that was included into the project earlier in this tutorial.  The M1 Cloud Driver then transmits the register data as an array of raw bytes to the Renesas IoT Sandbox, under the tag temp_and_humidity.  This workflow will run once a minute.

Follow the same step of Air Quality Sampling Code workflow to create Temperature and Humidity Sampling workflow.

Ensure you enable changes in following settings:

  • In Custom tag, set user to ‘device’; then click Save and Activate
  • In device_id tag, uncheck the trigger option; then click Save and Activate
  • In Base Python, replace the original code with following code; then click Save and Activate

temp

Base Python code:

'''

This workflow requests the temperature and humidity from the board.

Last Updated: Sept 15, 2016

Author: Medium One

'''

import MQTT

ENS210_ADDR = 0x43

mqtt_buffer = u''

device_id = IONode.get_input('in1')['event_data']['value']

def write_register(reg, data):

global mqtt_buffer

mqtt_buffer += u'3;2;0;3;unused;' + u''.join(map(unichr, [ENS210_ADDR, reg, data]))

def read_register(reg, num, tag_name):

global mqtt_buffer

mqtt_buffer += u'3;2;{};2;{};'.format(num, tag_name) + u''.join(map(unichr, [ENS210_ADDR, reg]))

#read_register(0x00, 2, 'tahcid')

#print mqtt_buffer

#MQTT.publish_event_to_client(device_id, mqtt_buffer, 'latin1')

#mqtt_buffer = u''

write_register(0x21, 0x03)

MQTT.publish_event_to_client(device_id, mqtt_buffer, 'latin1')

mqtt_buffer = u''

write_register(0x22, 0x03)

MQTT.publish_event_to_client(device_id, mqtt_buffer, 'latin1')

mqtt_buffer = u''

read_register(0x30, 6, 'temp_and_humidity')

MQTT.publish_event_to_client(device_id, mqtt_buffer, 'latin1')

 

23.  Create Color and Proximity Sampling Workflow

This workflow will send commands over MQTT to the device to write and read several registers from the color and proximity sensor on the AMS module.  The command is interpreted by the M1 Cloud Driver that was included into the project earlier in this tutorial.  The M1 Cloud Driver then transmits the register data as an array of raw bytes to the Renesas IoT Sandbox, under the tags color and proximity.  This workflow will run once a minute.

Follow the same steps of the Air Quality Sampling Code workflow to create the Color and Proximity Sampling workflow.

Ensure you enable changes in following settings:

  • In Custom tag, set user to ‘device’; then click Save and Activate
  • In device_id tag, uncheck the trigger option; then click Save and Activate
  • In Base Python, replace the original code with following code; then click Save and Activate

color

Base Python code:

'''

This workflow decodes the color and proximity data from the sensors.

Last Updated: Sept 15, 2016

Author: Medium One

'''

import MQTT

TMD3782_ADDR = 0x39

mqtt_buffer = u''

device_id = IONode.get_input('in1')['event_data']['value']

def write_register(reg, data):

global mqtt_buffer

cmd_reg = 0xA0 | reg

mqtt_buffer += u'3;2;0;3;unused;' + u''.join(map(unichr, [TMD3782_ADDR, cmd_reg, data]))

def read_register(reg, num, tag_name):

global mqtt_buffer

cmd_reg = 0xA0 | reg

mqtt_buffer += u'3;2;{};2;{};'.format(num, tag_name) + u''.join(map(unichr, [TMD3782_ADDR, cmd_reg]))

write_register(0x00, 0x0f)  # enable prox, color

MQTT.publish_event_to_client(device_id, mqtt_buffer, 'latin1')

mqtt_buffer = u''

write_register(0x01, 0x00)  #

MQTT.publish_event_to_client(device_id, mqtt_buffer, 'latin1')

mqtt_buffer = u''

write_register(0x0E, 0x10)

MQTT.publish_event_to_client(device_id, mqtt_buffer, 'latin1')

mqtt_buffer = u''

read_register(0x14, 8, 'color')

MQTT.publish_event_to_client(device_id, mqtt_buffer, 'latin1')

mqtt_buffer = u''

read_register(0x1c, 2, 'proximity')

MQTT.publish_event_to_client(device_id, mqtt_buffer, 'latin1')

 

Wait 2 Minutes

The 2 minute wait time is necessary to ensure that sensor data has been transmitted.  The generated workflows send commands to the board to sample the sensors once a minute.  The board then sends the sample values to the cloud.

 

24. Select New raw Tags

Now you can build your workflows to process the raw byte arrays and produce the desired sensor data.  To do so, you need to select the new raw tags; in this tutorial, we will use the following four tags:

  • air_quality
  • color
  • proximity
  • temp_and_humidity

Go to Config -> Data Streams, and click Edit for raw Data Streams:

raw

 

Activate the new tags – air_quality, color, proximity, temp_and_humidity:

timeseries

 

Once all tags have been selected, click Save Data Stream:

savedatastream

 

25.  Create Air Quality Processing Workflow

This workflow will process the raw array of bytes containing the register values read from the air quality sensor, into the intended data.  The air quality sensor reports:

  • the effective air quality (number, ppm)
  • a status indicator of the sensor’s operation (string)
  • and an effective resistance of the sensor membrane (number)

This data will be output from this processing workflow and saved to the processed data stream under the following tags:

  • air_quality
  • status
  • resistance

This workflow is triggered when data for the raw tag air_quality is received.

Create Air Quality Processing workflow as depicted below:

airquality

 

In Base Python, replace the original code with following code; then click Save and Activate.

Base Python Code:

'''

This workflow decodes the air quality data from the sensors.

Last Updated: Sept 15, 2016

Author: Medium One

'''

buf = IONode.get_input('in1')['event_data']['value']

status_val = buf[2]

status = "FATAL" if buf[3] else "OK" if status_val == 0x00 else "RUNNING" if status_val == 0x10 else "BUSY" if status_val == 0x01 else "ERROR" if status_val == 0x80 else "FATAL"

IONode.set_output('out1', {

"value": (buf[0] << 8) | buf[1],

"resistance": (buf[4] << 16) | (buf[5] << 8) | buf[6],

"status": status

})

 

In the Processed Stream – Single tag, set Tag Name to ‘air_quality’; then click Save and Activate:

procstream

 

 

26.  Create Temperature and Humidity Processing Workflow

This workflow will process the raw array of bytes containing the register values read from the temperature and humidity sensor into the intended data. The temperature and humidity sensor reports:

  • temperature (number, Kelvin)
  • humidity (number, %)

This data will be output from this processing workflow and saved to the processed data stream under the following tags:

  • temperature (degrees C)
  • humidity

This workflow is triggered when data for the raw tag temp_and_humidity is received.

Create Temperature and Humidity Processing workflow as depicted below:

temphum

 

In Base Python, replace the original code with following code; then click Save and Activate:

Base Python Code:

'''

This workflow decodes the temperature and humidity from the sensor.

Last Updated: Sept 15, 2016

Author: Medium One

'''

CRC7WIDTH = 7

CRC7POLY = 0x89

CRC7IVEC = 0x7F

DATA7WIDTH = 17

DATA7MASK = ((1<<DATA7WIDTH)-1)

DATA7MSB = (1<<(DATA7WIDTH-1))




# The crc7(val) function returns the CRC-7 of a 17 bits value val.

# Compute the CRC-7 of 'val' (should only have 17 bits)

def crc7(val):

# Setup polynomial

pol = CRC7POLY

# Align polynomial with data

pol = pol << (DATA7WIDTH-CRC7WIDTH-1)

# Loop variable (indicates which bit to test, start with highest)

bit = DATA7MSB;

# Make room for CRC value

val = val << CRC7WIDTH

bit = bit << CRC7WIDTH

pol = pol << CRC7WIDTH

# Insert initial vector

val |= CRC7IVEC

# Apply division until all bits done

while( bit & (DATA7MASK<<CRC7WIDTH) ):

if( bit & val ):

val ^= pol

bit >>= 1

pol >>= 1

return val




handt = IONode.get_input('in1')['event_data']['value']

out = {}

t_val = handt[0] | (handt[1] << 8) | (handt[2] << 16)

h_val = handt[3] | (handt[4] << 8) | (handt[5] << 16)

t_data = t_val & 0xffff;

t_valid = (t_val >> 16) & 0x1;

t_crc = (t_val >> 17) & 0x7f;

h_data = h_val & 0xffff;

h_valid = (h_val >> 16) & 0x1;

h_crc = (h_val >> 17) & 0x7f;

print "t_data: {}, t_valid: {}, t_crc: {}, h_data: {}, h_valid: {}, h_crc: {}".format(t_data, t_valid, t_crc, h_data, h_valid, h_crc)

if t_valid:

t_payl = t_val & 0x1ffff;

calc_t_crc = crc7(t_payl)

if calc_t_crc == t_crc:

out['temperature'] = round(float(t_data) / 64 - 273.15,2)

else:

log("Invalid temperature CRC, expected: {}, actual: {}".format(calc_t_crc, t_crc))

if h_valid:

h_payl = h_val & 0x1ffff;

calc_h_crc = crc7(h_payl)

if calc_h_crc == h_crc:

out['humidity'] = round(float(h_data) / 512,2)

else:

log("Invalid humidity CRC, expected: {}, actual: {}".format(calc_h_crc, h_crc))

# TinK = float(t_data) / 64  # Temperature in Kelvin

# TinC = TinK - 273.15  # Temperature in Celsius

# TinF = TinC * 1.8 + 32.0  # Temperature in Fahrenheit

# H = float(h_data)/512

# print("Kelvin: {}, Celsius: {}, Farenheit: {}, Humidity: {}".format(TinK, TinC, TinF, H))




# set output to input

if out:

IONode.set_output('out1', out)

 

27.  Create Color Processing Workflow

This workflow will process the raw array of bytes containing the register values read from the color sensor into the intended data. The color sensor reports:

  • alpha (number)
  • red (number)
  • green (number)
  • blue (number)

This data will be output from this processing workflow and saved to the processed data stream under the following tags:

  • alpha
  • red
  • green
  • blue

This workflow is triggered when data for the raw tag color is received.

Create Color Processing workflow as depicted below:

colorproc

 

In Base Python, replace the original code with following code; then click Save and Activate:

Base Python Code:

'''

This workflow decodes the color data from the sensors.

Last Updated: Sept 15, 2016

Author: Medium One

'''

def little_endian_parse(byte_pair):

return byte_pair[0] | (byte_pair[1] << 8)

color_rgb = IONode.get_input('in1')['event_data']['value']

print color_rgb

out = {}

a = little_endian_parse(color_rgb[0:2])

r = little_endian_parse(color_rgb[2:4])

g = little_endian_parse(color_rgb[4:6])

b = little_endian_parse(color_rgb[6:])

out['alpha'] = a

out['red'] = r

out['green'] = g

out['blue'] = b

IONode.set_output('out1', out)

 

28.  Create Proximity Processing Workflow

This workflow will process the raw array of bytes containing the register values read from the proximity sensor into the intended data. The proximity sensor reports:

  • proximity (number)

This data will be output from this processing workflow and saved to the processed data stream under the following tags:

  • proximity

This workflow is triggered when data for the raw tag proximity is received.

Create Proximity Processing workflow as depicted below:

prox

 

In Base Python, replace the original code with following code; then click Save and Activate:

Base Python Code:

'''

This workflow decodes the proximity data from the sensors.

Last Updated: Sept 15, 2016

Author: Medium One

'''

def little_endian_parse(byte_pair):

return byte_pair[0] | (byte_pair[1] << 8)

proximity = little_endian_parse(IONode.get_input('in1')['event_data']['value'])

out = {'value': proximity}

IONode.set_output('out1', out)

 

In Processed Stream – Single tag, set Tag Name to ‘proximity’; then click Save and Activate.

 

CHECKPOINT:

Your workflow studio should have a total of 10 workflows.

workstudio

 

Wait 2 Minutes

The 2 minute wait time is again necessary to ensure that sensor data has been transmitted.  After all the sensors transmit their data, raw data will now trigger the processing workflows that were just created above to produce the processed data that can be analyzed.

 

29. Now AMS SENSOR DATA IS AVAILABLE in the Processed Stream

Go to Config -> Data Streams, and click Edit for processed Data Streams:

configdata

 

Confirm that the new processed data tags are present and selected, and click Save Data Stream:

schema1

schema2

schema3

schema4

schema5

schema6

 

 

30. Visualize the Sensor Data

Now, it is the time to visualize data.  As you can see, the AMS module detects air quality, humidity and proximity.  The changes can be seen in the real time gauge widgets or line charts showing data changes over time.

You can build many more workflows around the sensor data you wish to process.

dashboard

 

Summary:

In this tutorial, you have successfully attached sensors to your board, built a project detecting sensor data, created a new image mirroring the new features, built the appropriate workflow and visualized the data.

 

What’s Next?

Congrats, you’ve just easily used a new sensor to collect the required data and created meaningful workflows to visualize the desired data. This is just scratching the surface of what is possible between Renesas e2 studio environment in conjunction with the Renesas IoT Sandbox capabilities.  Please check out the other tutorials and documentation.  Happy building!