Filter results by

Your first IoT device

Let's build an IoT device that sends flame sensor data to ARTIK Cloud using ARTIK Cloud's WebSockets. The IoT device consists of an off-the-shelf sensor, Arduino UNO and Raspberry Pi.

In this implementation, a Simple Manifest is used to create a new device type quickly. Then you can easily connect the IoT device to ARTIK Cloud, and start to send sensor data from the device to ARTIK Cloud.

For this tutorial you should be familiar with the basic ARTIK Cloud APIs.

Architecture

The diagram below shows the high-level architecture:

Architecture

We use the following hardware components:

  • Raspberry Pi with a network connection
  • Arduino UNO with a breadboard
  • IR flame sensor
  • USB and power cables, plus wiring for the breadboard

We will write the following software:

  • A Sketch program running on the Arduino
  • A Node.js script running on the Raspberry Pi

Download the software at GitHub now.

If you do not have a Raspberry Pi, you may still work through this tutorial. Connect your Arduino UNO to your computer that has an Internet connection and run the Node.js script on the computer instead of the Raspberry Pi.

Step 1: Create and connect a new device type

Go to the Developer Dashboard to create a private device type.

  1. First, sign into the ARTIK Cloud Developer Dashboard. If you don't have a Samsung account, you can create one at this step.
  2. Click "+ New Device Type".
  3. Name this device type "Flame Sensor" and give it a unique name such as "com.example.iot.flame". Note the characters <,>,&,'," are not allowed.
  4. Click "Create Device Type". This creates the device type and takes you to the device types page.

Now let's create a Manifest for our "Flame Sensor" device type.

  1. Click "Flame Sensor" in the left column.
  2. Click "Manifest" and then "+ New Version".
  3. Enter "onFire" as the Field Name and "Boolean" for Data Type. Flame Sensor
  4. Click "Save" and then "Next: Actions".
  5. Bypass Actions for this tutorial and click "Save New Manifest".

A Simple Manifest is automatically approved.

Do not publish this device type, since it is for tutorial purposes only.

Finally go to My ARTIK Cloud to connect a new Flame Sensor device:

  1. Sign into My ARTIK Cloud.
  2. On the dashboard, click to connect a new device. Choose the "Flame Sensor" device type you just created. Connect ARTIK Cloud device
  3. Click "Connect Device…". You're taken back to the dashboard.
  4. Click the Settings icon of the device you just added. In the pop-up, click "GENERATE DEVICE TOKEN…".
  5. Copy the device ID and device token on this screen. You will use these in the code. Generate ARTIK Cloud device token

Step 2: Set up the Arduino

Now let's wire the sensors to the Arduino.

Arduino and sensors

The two sensors are wired as follows:

Fritzing

Next, upload the Sketch program (read_flame_sensor.ino) to the Arduino UNO using the Arduino IDE. This code reads one digital value from the IR flame sensor, and then sends it to the serial port every 5 seconds (you can change this parameter in the code later, since ARTIK Cloud has rate limits for the number of messages per day). For the digital readings, "0" means that a fire is detected and "1" means no fire.

Here is read_flame_sensor.ino. The code is straightforward.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Delay between reads
const int delayBetweenReads = 5000;//5s

// For flame detector senso
const int flameDigitalPinIn = 2; 

void setup() {
  // initialize serial communication @ 9600 baud:
  Serial.begin(9600);
  pinMode(flameDigitalPinIn, INPUT);
}

void loop() {
  // HIGH(1) means no fire is detected
  // LOW (0) means fire is detected
  int flameDigitalReading = digitalRead(flameDigitalPinIn);
  
  Serial.println(String(flameDigitalReading));

  delay(delayBetweenReads);
}

Step 3: Set up the Raspberry Pi

Connect your Raspberry Pi to a monitor, mouse and keyboard. Ensure that an Ethernet or WiFi connection is working, and make sure the OS is up-to-date:

1
2
$ sudo apt-get update
$ sudo apt-get upgrade

If not already installed, install Node.js for ARM, then add the packages serialport and ws via npm:

1
2
$ npm install serialport
$ npm install ws

Now connect the serial port from the Arduino to the USB on the Raspberry Pi.

Arduino and Raspberry Pi

Finally, download the Node.js program send_data_to_artik_cloud.js to the Raspberry Pi. Replace the placeholders in the code with the device token and device ID you collected from My ARTIK Cloud.

The Node.js code is also given below. It establishes a device channel WebSocket connection between the Raspberry Pi and ARTIK Cloud. After the WebSocket connection is open, register() method registers the device with the WebSocket. Each time, the code reads one data point from the serial port, and then wraps it in a message and sends the message to ARTIK Cloud via WebSocket.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
var webSocketUrl = "wss://api.artik.cloud/v1.1/websocket?ack=true";
var device_id = "<YOUR DEVICE ID>";
var device_token = "<YOUR DEVICE TOKEN>";

var isWebSocketReady = false;
var ws = null;

var serialport = require("serialport")
var SerialPort = serialport.SerialPort;
var sp = new SerialPort("/dev/ttyACM0", {
    baudrate: 9600,
    parser: serialport.parsers.readline("\n")
});

var WebSocket = require('ws');

/**
 * Gets the current time in millis
 */
function getTimeMillis(){
    return parseInt(Date.now().toString());
}

/**
 * Create a /websocket device channel connection 
 */
function start() {
    //Create the websocket connection
    isWebSocketReady = false;
    ws = new WebSocket(webSocketUrl);
    ws.on('open', function() {
        console.log("Websocket connection is open ....");
        register();
    });
    ws.on('message', function(data, flags) {
        console.log("Received message: " + data + '\n');
    });
    ws.on('close', function() {
        console.log("Websocket connection is closed ....");
    });
}

/**
 * Sends a register message to the websocket and starts the message flooder
 */
function register(){
    console.log("Registering device on the websocket connection");
    try{
        var registerMessage = '{"type":"register", "sdid":"'+device_id+'", "Authorization":"bearer '+device_token+'", "cid":"'+getTimeMillis()+'"}';
        console.log('Sending register message ' + registerMessage + '\n');
        ws.send(registerMessage, {mask: true});
        isWebSocketReady = true;
    }
    catch (e) {
        console.error('Failed to register messages. Error in registering message: ' + e.toString());
    }   
}

/**
 * Send one message to ARTIK Cloud
 */
function sendData(onFire){
    try{
        ts = ', "ts": '+getTimeMillis();
        var data = {
            "onFire": onFire
        };
        var payload = '{"sdid":"'+device_id+'"'+ts+', "data": '+JSON.stringify(data)+', "cid":"'+getTimeMillis()+'"}';
        console.log('Sending payload ' + payload);
        ws.send(payload, {mask: true});
    } catch (e) {
        console.error('Error in sending a message: ' + e.toString());
    }   
}

/**
 * All start here
 */
start(); // create websocket connection

sp.on("open", function () {
    sp.on('data', function(data) {
            if (!isWebSocketReady){
                console.log("Websocket is not ready. Skip sending data to ARTIK Cloud (data:" + data +")");
                return;
            }
            console.log("Serial port received data:" + data);
            var flameDigitalValue = parseInt(data);

            // flameDigitalValue = 1 ==> no fire is detected
            // flameDigitalValue = 0 ==> fire is detected
            var onFire = false;
            if (flameDigitalValue == 0) {
               onFire = true;
            }
            sendData(onFire);
    });
});

Step 4: Fire it up and view the data!

Let's start the Node.js program on the Raspberry Pi from the terminal:

1
$ node send_data_to_artik_cloud.js

In the terminal, you should see the payload of the message sent to ARTIK Cloud and the corresponding response from ARTIK Cloud as follows:

1
2
3
Serial port received data:84,1003,1
Sending payload {"sdid":"45176de99e424d98b1a3c42558bfccf4", "ts": 1438722871167, "data": {"onFire":false}, "cid":"1438722871167"}
Received message: {"data":{"mid":"77b89ba8d8fb41a296403044698de3ac","cid":"1438722871167"}}

Log into My ARTIK Cloud once again.

View your device data as it's generated by clicking the device name in the device box. This takes you to Data Visualization. From there, click the "+/- CHARTS" button and check "onFire" to visualize a chart for each field. (Read this post for more information on Data Visualization.) Now light up a lighter, and observe the chart of "onFire" changes like the following:

data visualization