Raspberry Pi has become a widely used device, not only for prototyping and educational purposes, but also for production projects within companies.

Besides its small size, low cost and fully operational Linux OS, the greatest difference from your Destkop PC lies in its ability to interact with other peripherals through GPIO pins (General Purpose Input/Ourput Pins).

This allows you to code pretty robust hardware applications without having to be an expert in embedded electronics.

At the end of this guide you’ll be able to read and send data values from your Pi to Ubidots.

Requirements

To complete this tutorial, you’ll need:

  • A Raspberry Pi connected to the Internet

Setup

This guide assumes your Raspberry Pi has been configured and is already connected to the Internet. To learn how to do this, we suggest following this quick start guide from Raspberry Pi Foundation.

If you’re using a WiFi dongle, we suggest using Wicd to manage your WiFi connection.

Updating Repositories and Installing Libraries 

Update apt-get repositories:

$ sudo apt-get update
$ sudo apt-get upgrade

Requests: HTTP for Humans

Requests is a popular Python library that simplifies making HTTP requests from any python script which can be run in your computer's terminal or any embedded Linux device such is the Raspberry Pi.

To install the library run the command below in the Raspberry Pi Terminal: 

$ pip install requests

Send one value to Ubidots

Let’s create a python script using your favorite text-editor. We’ll use “nano” in this case. This script sends a random value to Ubidots but it can be easily adapted to send values from digital inputs in your Raspberry Pi, or even analog readings when using special shields.

Create Python script

$ nano ubi_test.py

Copy and paste the below code in your terminal; assigning your Ubidots TOKEN where indicated in the code. For more information, please see the Ubidots REST API Reference

import time
import requests
import math
import random

TOKEN = "..."  # Put your TOKEN here
DEVICE_LABEL = "machine"  # Put your device label here
VARIABLE_LABEL_1 = "temperature"  # Put your first variable label here
VARIABLE_LABEL_2 = "humidity"  # Put your second variable label here
VARIABLE_LABEL_3 = "position"  # Put your second variable label here


def build_payload(variable_1, variable_2, variable_3):
    # Creates two random values for sending data
    value_1 = random.randint(-10, 50)
    value_2 = random.randint(0, 85)

    # Creates a random gps coordinates
    lat = random.randrange(34, 36, 1) + \
        random.randrange(1, 1000, 1) / 1000.0
    lng = random.randrange(-83, -87, -1) + \
        random.randrange(1, 1000, 1) / 1000.0
    payload = {variable_1: value_1,
               variable_2: value_2,
               variable_3: {"value": 1, "context": {"lat": lat, "lng": lng}}}

    return payload


def post_request(payload):
    # Creates the headers for the HTTP requests
    url = "http://things.ubidots.com"
    url = "{}/api/v1.6/devices/{}".format(url, DEVICE_LABEL)
    headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"}

    # Makes the HTTP requests
    status = 400
    attempts = 0
    while status >= 400 and attempts <= 5:
        req = requests.post(url=url, headers=headers, json=payload)
        status = req.status_code
        attempts += 1
        time.sleep(1)

    # Processes results
    if status >= 400:
        print("[ERROR] Could not send data after 5 attempts, please check \
            your token credentials and internet connection")
        return False

    print("[INFO] request made properly, your device is updated")
    return True


def main():
    payload = build_payload(
        VARIABLE_LABEL_1, VARIABLE_LABEL_2, VARIABLE_LABEL_3)

    print("[INFO] Attemping to send data")
    post_request(payload)
    print("[INFO] finished")


if __name__ == '__main__':
    while (True):
        main()
        time.sleep(1)

Once the code has been compiled with your Ubidots TOKEN, press CONTROL + O and ENTER to save the file - assigning a file name as you save (be sure to remember the ".py" in your file name). Once the script is saved, exit the Python editor by pressing CONTROL + X and return to the computer's terminal. 

Run the script

$ python ubi_test.py

Get one value from Ubidots

Create a python script using your favorite text-editor. We’ll use “nano” in this case.

Create Python script

$ nano ubi-test-get.py

Copy and paste the below code in your terminal; assigning your Ubidots TOKEN where indicated in the code. Also, you have to assign the device label and variable label desired to obtain the information desired.

 For more information, please see the Ubidots REST API Reference

import requests
import random
import time

TOKEN = "xxxxxxxx" # Assign your Ubidots Token
DEVICE = "xxxxxxxx" # Assign the device label to obtain the variable
VARIABLE = "xxxxxxxx" # Assign the variable label to obtain the variable value
DELAY = 1  # Delay in seconds

def get_var(device, variable):
    try:
        url = "http://things.ubidots.com/"
        url = url + \
            "api/v1.6/devices/{0}/{1}/".format(device, variable)
        headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"}
        req = requests.get(url=url, headers=headers)
        return req.json()['last_value']['value']
    except:
        pass


if __name__ == "__main__":
    while True:
        print(get_var(DEVICE, VARIABLE))
        time.sleep(DELAY)

Run the script

$ python ubi-test-get.py


Did this answer your question?