All Collections
Connect your Devices
Connect your RevPi Core 3 + RevPi DIO to Ubidots over HTTP
Connect your RevPi Core 3 + RevPi DIO to Ubidots over HTTP

Integrate Industrial grade controls (I/O) and monitoring with the RevPi DIO module and Ubidots; including setup for a Unit Counting App.

Isabel Lopez avatar
Written by Isabel Lopez
Updated over a week ago

Revolution Pi is an open, modular, and durable industrial PC based on the established Raspberry Pi while meeting the EN61131-2 standard. Equipped with the Raspberry Pi Compute Module, the RevPi Core base can be expanded seamlessly using appropriate I/O modules and fieldbus gateways for energy management, process monitoring, machine health and more.

The Rev Pi Core is the foundation to any application and depending on your I/O requirements expansion modules such as RevPi DIO, RevPi AIO, RevPi Gates can be attached as digital, analog, or gateway modules. 

In this tutorial, we will detail the integration of a the RevPI DIO to visualize and control output signals to your machines or applications with Ubidots. The RevPi DIO digital I/O module comes with 14 digital inputs and 14 outputs, PWM (pulse width modulation), and counter inputs. For a more detailed list of functionalities of the RevPI DIO, check out the Revolution Pi product brochure

Requirements 

Step-by-Step

  1. Hardware Setup

  2. System Setup

  3. PiCtory Setup 

  4. Sending (POST) data to Ubidots

  5. Unit Counter Application Development

  6. Receiving (GET) data from Ubidots

  7. Summary

1. Hardware Setup

As per any new device setup, we recommend becoming familiar with the RevPi Core + RevPi DIO official quick start guide by Revolution Pi. Then be sure your able to assemble the RevPi Core + DIO correctly referencing the below articles for additional details, as needed.

Once your RevPi Core + RevPi DIO are assembled together, powered correctly, and connected to the Internet, we can continue with Firmware required to communicate with Ubidots.

2. System setup 

1. First we must have access to the inputs and outputs of the Revolution Pi. The "python3-revpimodio” module provides all the access to the IOs of the Revolution Pis, and can be programmed very easy with Python3.

Based on the image installed in your RevPi Core reference this guide to make the installation properly. If you have the Jessie Image on your core, simply install the module from the Kunbus repository by running the commands below in the RevPi Terminal:

NOTE: To be able to run the commands below, you must access the RevPi. If you do not yet know how to access the RevPi's terminal, please refer to this guide.  

  • Update system packages: 

sudo apt-get update
  • Install:

sudo apt-get install python3-revpimodio2
  • Update Distribution (all): 

sudo apt-get dist-upgrade

2. Next, install the requests module for python3 by running the command below in the RevPi Core terminal:

sudo apt-get install python3-requests 

3. Once each of the commands above have finished, verify everything as accurate by opening Python3 into your RevPi Core terminal and importing the module previously installed.

Open the Python3 by running the command below into the RevPi Core terminal:

python3

Once you have access to Python3, import the modules ''revpimodio2" and "requests" as is shown below:

import revpimodio2 
import requests

If receive and error messages after importing the module, verify the issue shown and try again.
​ 

3. PiCtory Setup 

PiCtory lets you link up several RevPi modules, alongside the PiBridge that physically links the modules with one another, creating a configuration file. The file has to inform your RevPi Core which modules are to be found in which position and what are the basic settings of the modules. To get a better idea how this works, check out the video below: 

1. Open your web browser and enter the IP address of your RevPi Cores in the address bar of your browser. Then, you will see the login windows, to enter, assign the username and password where is indicated. The login credentials can be found on the side of your RevPi.

  • username: admin

  • password: You will find it on the sticker on the side of your RevPi Core. 

Enter to the "APPS" section:

2. To start with the PiCtory settings, press the green button called "START". 

3. From the device catalog select the version of your RevPi Core and assign it to the configuration boards. Then, assign the RevPi DIO at the right of the RevPi Core. Remember connect the RevPi Core to the right of your RevPi Core using the PiBridge. 

IMPORTANT NOTE: The position of the modules assigned in the PiCtory configuration has to be the same as assigned in the physical world to be able to generate the configuration file properly. 

 3. Now that you have the modules needed assigned into the configuration boards, lets verify the name of the pins that we are going to use below. You will find two sample codes provided, one is for send a value from a reading input of the RevPi DIO, and the other one for controlling an output of the RevPi DIO. 

  • The input that we are going to use is the Input 1, see below for pin-out diagram:

From the Value Editor section, verify if the name assigned for the Input 1 is "I_1"  as is shown on the image below, if not please adjust the INP name to be "l_1." IMPORTANT NOTE: If you skip this step the firmware code will miss reading this pin. 

  • The output that we are going to use is the Output 1, see below for pin-out diagram:

From the Value Editor section, verify the name assigned to Output 1 is "O_1"  as is shown on the image below, if not please adjust the INP name to be "O_1." IMPORTANT NOTE: If you skip this step the firmware code will miss reading this pin. 

4. Sending (POST) data to Ubidots

1. To begin writing your firmware, create a Python script in the RevPi Core terminal. We are going to use nano editor, in order to create the new script. To do this run the command below in the RevPi terminal. 

nano ubidots_revpi.py

As you will see, the nano editor terminal will automatically populate and you can begin your code. 

2. Copy and Paste the sample code below into the nano editor. Once pasted, assign your Ubidots Token where indicated in the script. Reference here for help locating your Ubidots token, if needed.

In this sample code we are going to read the Input 1 (I_1) of the RevPi DIO module to send its status to Ubidots.

NOTE: To save the script into the nano editor - press Ctrl+O, confirm the file name to write (ubidots_revpi_di.py), and press enter. To close the nano editor press Ctrl+X.

################################################################################
# This script send the Digital Input(DI) status of a pin from the Revpi DIO
# expansion module to the Ubidots Cloud (https://ubidots.com/)
#
# Authors: M. Hernandez
################################################################################

import requests
import time
import revpimodio2
from uuid import getnode as get_mac

TOKEN = "A1E-dfBFE58BECK3YgAia1Sss2H9WTvW4I" # Assign your Ubidots TOKEN
VARIABLE = "motion-detector" # Assign the Ubidots Variable label
DELAY = 2 # Set the delay desired to post the data

revpi = revpimodio2.RevPiModIO(autorefresh=True) # Instance to access to the IOs of the RevPi

s = requests.Session()
s.headers.update({'x-test': 'true'})

'''
This method build the JSON to be sent to the Ubidots Cloud
'''
def build_json(variable, value):
    try:
        # This structure send one value to the Ubidots Cloud. Please reference to the
        # Ubidots REST API Reference (https://ubidots.com/docs/api/) to learn how to
        # send more thant one value
        data = {variable: value}
        return data
    except:
        return None

'''
This method make the HTTP Request to the Ubidots Cloud
'''
def post_variable(device, variable, value):
    try:
        # Reference to the Ubidots REST API Reference (https://ubidots.com/docs/api/)
        # to learn how to build the HTTP Request to the Ubidors Server
        url = "https://industrial.api.ubidots.com/api/v1.6/devices/" + device
        headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"}
        data = build_json(variable, value)
        response = s.post(url=url, headers=headers, json=data)
        return response.json()
    except:
        pass

if __name__ == "__main__":
    while True:
        mac = get_mac() # get the mac address of your device
        device_mac = ':'.join(("%012X" % mac)[i:i+2] for i in range(0, 12, 2))
        # Read the status of the Input called 'I_1'
        sensor_status = float(revpi.io.I_1.value)
        # Send the POST Request to the Ubidots Server
        print("Posting values to Ubidots")
        request = post_variable(device_mac, VARIABLE, sensor_status)
        print(request)
        time.sleep(DELAY)

3. Now let's test the script. Run the script previously created in the RevPi terminal by executing the below code: 

python3 ubidots_revpi_di.py

Once the script begins to run, you will see the successful status response from the Ubidots Server 201 :

4. Go to your Ubidots account and verify the data has been received. You will see a new device automatically created in the Device section with the device name being the MAC address of your RevPi Core.

Don't like the MAC address as your device's name in your Ubidots display? Don't worry; you can change the name to a more friendly one, but the device label will be stay as the MAC address to never get confused which device is which. Reference to Ubidots Help Center for more on Device Labels and Device Name changes in Ubidots.
​ 
Click on any device in your Device section to visualize the variable being recorded and sent to Ubidots from our sample firmware. As you can see, our sample code has provided a motion-detector variable:

5. Unit Counter Application Development

Now that the status of your Input is updating in your Ubidots account. Let's start playing with the Ubidots features to design and deploy your application. In this tutorial we will deploy a Unit Counter for boxes moving across a supply line.

At first, we are going to create a Synthetic Variable a complex mathematical computation tool. Thanks to this Ubidots Analytics Engine you will be able to compute the average, maximum, minimum, sum, and count of other variable; in this case the variable previously created (motion-detector). For this guide, we are going to compute a sum of the variable motion-detector every minute to know how many boxes were detected as they passes along the supply line. 

To create the variable, press "Add Variable". Then, select "Synthetic":

In the following window, you should assign the following expression: 

sum(x, data_range)

Where:

  • x  is the variable desired to be compute

  • data_range is the interval time desired to compute the values of the variable assigned as x

For a detailed explanation of Synthetics Variables, refer to this guide.  

After assigning the expression, you should have something similar to:

To save the changes, press "Accept". Then, assign the name of the new variable, in this case, we named ours "boxes".  

Result after calculating the sum:

Now that we know how many boxes our sensor is detecting, we can create an event based on the "boxes" variable to keep pace with production and be alerted if production falls behind. 

Our production goal is 10 "boxes" a minute. In order to maintain this goal, the RevPi will need to detect 10 boxes minimum per minute. To be alerted to falling production we will simply create an alert letting us know when less than 10 boxes were detected.

Go to the Event section of your Ubidots account by pressing Device Management > Events > Add Event (plus blue icon).

Then, assign the following configurations to the event and press the right blue icon to continue:

  • First field: Synthetics Variable created - Boxes  

  • Second field: Value

  • Third field: Less than

  • Fourth field: 10

  • Fifth field: 0  

After assign the parameters you should have something like:  

Now you need to assign the action desired for this event. To continue, press the plus orange icon and choose the action desired:

I configured the event with an e-mail action. And as you can see below, when the event is triggered I receive the message below:

IMPORTANT NOTE: The code provided above is only reading the input 1 without establishing any sensor configuration. Based on the sensors used, add the configuration of the sensor into the code as needed.

6. Receiving (GET) data from Ubidots

In this sample application we are going to control an output of the RevPi DIO module to be able to turn ON/OFF a light from the Ubidots cloud.

1. To be able to control an output form an Ubidots variable you have to create it first the variable. Enter your RevPi device and create a new variable by selecting "Add Variable" and press "Raw":

Then, assign it the name "light". Once the device is properly created, your device display will look something like this:

2. Go to your main Ubidots Dashboard and create a control widget. Click the yellow plus(+) icon and follow the on screen options to deploy new dashboard widgets. Select Control –> Switch –> RevPICore(MACAddress) –> light (variable just created) > Finish. 

After constructing your new widget, the Dashboard will reload and be populated with your new light control widget. 

This "control" widget will send its status to the RevPi DIO output to control the status of a light or any other device connected to Output 1.  

To implement this control capability, we'll go ahead and update our firmware. 

3. Create a new python script using nano editor. To do this run the command below in the RevPi terminal:

nano ubidots_revpi_do.py

As you will see, the nano editor terminal will automatically populate and you can begin your code. 

4. Please copy and paste the sample code below into the nano editor. Once pasted, assign your Ubidots Token where indicated in the script. Reference here for help locating your Ubidots token.

In this sample code we are going to control an output of the RevPi DIO module to be able to turn ON/OFF a light from the Ubidots dashbaord.

NOTE: To save the script into the nano editor - press Ctrl+O, confirm the file name to write (ubidots_revpi_di.py), and press enter. To close the nano editor press Ctrl+X.

################################################################################
# This script control an Output(DO) status of a pin from the Revpi DIO
# expansion module from the Ubidots Cloud (https://ubidots.com/)
#
# Authors: M. Hernandez
################################################################################

import requests
import time
import revpimodio2
from uuid import getnode as get_mac

TOKEN = "A1E-dfBFE58BECK3YgAia1Sss2H9WTvW4I" # Assign your Ubidots TOKEN
VARIABLE = "light" # Assign the Ubidots Variable label to be controlled
DELAY = 5 # Set the delay desired to post the data

revpi = revpimodio2.RevPiModIO(autorefresh=True) # Instance to access to the IOs of the RevPi

s = requests.Session()
s.headers.update({'x-test': 'true'})

'''
This method make the HTTP Request to the Ubidots Cloud
'''

def get_lastvalue(device_label, variable_label):
    try:
        # Reference to the Ubidots REST API Reference (https://ubidots.com/docs/api/)
        # to learn how to build the HTTP Request to the Ubidors Server
        url = "https://industrial.api.ubidots.com/api/v1.6/devices/" + device_label + "/" + variable_label + "/lv"
        headers = {"X-Auth-Token": TOKEN}
        response = s.get(url=url, headers=headers)
        return response.json()
    except:
        pass

if __name__ == "__main__":
    while True:
        mac = get_mac() # get the mac address of your device
        device_mac = ':'.join(("%012X" % mac)[i:i+2] for i in range(0, 12, 2))
        # Send the GET Request to the Ubidots Server
        print("Getting values from Ubidots")
        light_status = get_lastvalue(device_mac, VARIABLE)
        if light_status == 1.00:
            revpi.io.O_1.value = True
            print("Light TURNED ON")
        else:
            revpi.io.O_1.value = False
            print("Light TURNED OFF")
        time.sleep(DELAY)

5. Now let's test the script. Run the script previously created in the RevPi terminal: 

python3 ubidots_revpi_do.py

Once the script begins to run, you will see the light status message:

6. Now change the status of the "Control" widget from your Ubidots Dashboard and visualize the status of the RevPI DIO output.

7. Summary 

In just a few minutes you've integrated the RevPi Core + RevPi DIO with Ubidots, received data from your supply line for unit count, built an application to track and alert you to production requirements, and control the lights of your factory floor - all by using the RevPi Core + DIO with Ubidots. To learn more or deploy new Industrial solutions for monitoring or management, check out the full lineup of RevPi expansion modules.

Now its time to create Ubidots Dashboards to visualize and understand your data to make the best decisions, simply and coherently. 

Other readers have also found useful...

Did this answer your question?