Tutorial

Using the Arduino library

This guide will show you how to get started using the Cosm Arduino library, and hopefully demonstrate how much easier it is to use this library than to construct HTTP requests manually as you used to have to do.

This guide assumes you’ve already signed up to Cosm, and will walk you through creating a feed and publishing data to it from your Arduino.

Prerequisites

Before starting, you’ll need to make sure you have an up to date version of the Arduino software. At time of writing the current version is Arduino 1.0.3, but the latest version should always be available from the Arduino downloads page.

NOTE: The following tutorial will not work if the version of your Arduino software is less than 1.0 as this was the first version to include the version of the Ethernet library capable of using DHCP and DNS rather than hard coded IP addresses, so if you have an old version of the Arduino software, go ahead and upgrade it before we begin.

Importantly, you’ll also need either an Arduino (or compatible) board with an Arduino Ethernet Shield, or an Arduino Ethernet (i.e. the model with onboard Ethernet).

You should also note that the Cosm library will not work with boards that don’t use the Wiznet W5100 Ethernet chipset, so for example ENC28J60 based boards will not work. This is because it depends on the stock Ethernet library under the hood, which doesn’t work with other Ethernet controllers.

Installing the Library

We hope at some point to bundle the Cosm library with the main Arduino distribution, which will mean you’ll be able to get started using it without jumping through any extra hoops, but until that point you need to manually install the library.

Installing a library is a fairly straightforward process however, and you’ll only need to do this once.

Installing a 3rd party library

The main Arduino site has a guide to installing 3rd party Arduino libraries, which it’s worth having a read through especially if this is the first library you’ve installed.

The basic idea is you just need to download the library (which is typically distributed as a .ZIP file), and copy the unpacked contents into the libraries folder within your Arduino installation folder. For more details on this you should read the Arduino documentation.

Alternatively if you are familiar with Git version control software, then both of the libraries you need are available on Github, so can be installed by simply cloning the repositories into your libraries folder.

Finding your libraries folder

In general your libraries folder will live inside the DocumentsArduinolibraries folder in both Windows and OSX (allowing for the obvious differences between the platforms). The location on Linux may vary depending on how you installed the platform. If the location is not obvious however, you will always be able to locate it by opening the File > Preferences menu item, and viewing the directory location listed as the Sketchbook location. Your libraries folder will be within this folder.

Installing the HttpClient library

As I stated previously, the Cosm library depends on the core Ethernet library that is packaged with the main Arduino download, however it also depends on the HttpClient library which provides a higher level interface for interacting with web services. So to make the Cosm library work, you first need to download and install this library.

The latest version of HttpClient is available for download here : https://github.com/amcewen/HttpClient/archive/master.zip, so that should be downloaded and unpacked into your libraries directory.

Alternatively to install the library via Git, you should open a terminal, change into your libraries directory, and run something like :

$ git clone git://github.com/amcewen/HttpClient.git HttpClient

Installing the Cosm library

Once you’ve installed the HttpClient library, then you should go ahead and install the Cosm library. This is available to download here : https://github.com/cosm/cosm-arduino/archive/master.zip, so again this should also be downloaded and unpacked into your libraries directory.

Alternatively you can use Git again by running :

$ git clone git://github.com/cosm/cosm-arduino.git CosmArduino

from within your libraries folder.

The end result of these two processes should be that your libraries folder should contain both an HttpClient folder and a CosmArduino one, and inside each of those folders should be the Arduino header/source files. If the unpacked folders have different names, it doesn’t really matter, but feel free to rename them.

Verifying your install

Once both libraries are installed you should quit the Arduino software if it is already running, or start it if not; then open up the File > Examples menu and you should see both HttpClient and CosmArduino included in the examples list.

If the examples aren’t visible anywhere, then it means you haven’t installed the libraries correctly. In this case make sure that the code hasn’t been unpacked in an extra child directory.

Getting your first example working

There are some examples bundled with the Cosm library, which you should look at, as the following code is just a barely modified version of one of those examples, which demonstrates how to send data to Cosm. But before we get to the Arduino code we need to first create a feed and API key on Cosm to which we will be pushing data.

1. First of all you need to create a new feed, to which we’ll be publishing data, so login to Cosm, and then click the +Device/Feed button (or the big plus if you’ve never created a feed before).

2. Choose Arduino

3. Give your test feed a title

4. Then click through, without adding tags, and press Create.

5. This should bring up a success message which contains the sample sketch given below. This sample sketch should also have been pre-populated with your new feed ID and an API key that will allow your Arduino to both update and read from the feed.

6. Copy the sample code given into a new Arduino sketch, and then press Finish to close the modal, which should take you back to your console, and you should see that a new blank feed has been created.

If you didn’t copy the sample code before pressing Finish, don’t panic. The exact same code is given below, so you can just copy it from here. However you will need to manually add your feed ID and API key into the sketch.

Your feed ID can be found by clicking into the feed page (either in the URL, or there will be a Feed ID listed on the page. To find your API key you’ll need to visit : https://cosm.com/v2/users/YOUR_USERNAME/keys, and you should see a key labelled with the feed ID you just noted down.

Sample Cosm Arduino Sketch

/** * Cosm Arduino sensor client example.
*
* This sketch demonstrates connecting an Arduino to Cosm (https://cosm.com),
* using the new Arduino library to send and receive data.
*
* Requirements
* * Arduino with Ethernet shield or Arduino Ethernet (board must use the
* Wiznet Ethernet chipset)
* * Arduino software with version >= 1.0
* * An account at Cosm (https://cosm.com)
*
* Optional
* * An analog sensor connected to pin 2 (note we can still read a value from
* the pin without this)
*
* Created 8th January, 2013 using code written by Adrian McEwen with
* modifications by Sam Mulube
*
* Full tutorial available here: https://cosm.com/docs/quickstart/arduino.html
*
* This code is in the public domain.
**/

#include
#include
#include
#include

#define API_KEY “YOUR_API_KEY” // your Cosm API key #define FEED_ID YOUR_FEED_ID // your Cosm feed ID // MAC address for your Ethernet shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

// Analog pin which we’re monitoring (0 and 1 are used by the Ethernet shield)
int sensorPin = 2;

unsigned long lastConnectionTime = 0;      // last time we connected to Cosm
const unsigned long connectionInterval = 15000;      // delay between connecting to Cosm in milliseconds
// Initialize the Cosm library

// Define the string for our datastream ID
char sensorId[] = “sensor_reading”;

CosmDatastream datastreams[] = {
CosmDatastream(sensorId, strlen(sensorId), DATASTREAM_FLOAT), };

// Wrap the datastream into a feed
CosmFeed feed(FEED_ID, datastreams, 1 /* number of datastreams */);

EthernetClient client;
CosmClient cosmclient(client);

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);

Serial.println(“Cosm Sensor Client Example”);
Serial.println(“==========================”);

Serial.println(“Initializing network”);
while (Ethernet.begin(mac) != 1) {
Serial.println(“Error getting IP address via DHCP, trying again…”); delay(15000); }

Serial.println(“Network initialized”);
Serial.println(); }

void loop() {
// main program loop
if (millis() – lastConnectionTime > connectionInterval) {
// read a value from the pin
int sensorValue = analogRead(sensorPin);
// send it to Cosm
sendData(sensorValue);
// read the datastream back from Cosm
getData();
// update connection time so we wait before connecting again
lastConnectionTime = millis(); }
}

// send the supplied value to Cosm, printing some debug information as we go
void sendData(int sensorValue) {
datastreams[0].setFloat(sensorValue);

Serial.print(“Read sensor value “);
Serial.println(datastreams[0].getFloat());

Serial.println(“Uploading to Cosm”);
int ret = cosmclient.put(feed, API_KEY);
Serial.print(“PUT return code: “);
Serial.println(ret);
Serial.println(); }

// get the value of the datastream from Cosm, printing out the value we received
void getData() {
Serial.println(“Reading data from Cosm”);

int ret = cosmclient.get(feed, API_KEY);
Serial.print(“GET return code: “);
Serial.println(ret);

if (ret > 0) {
Serial.print(“Datastream is: “);
Serial.println(feed[0]);

Serial.print(“Sensor value is: “);
Serial.println(feed[0].getFloat()); }

Serial.println(); }


This example combines the DatastreamUpload and DatastreamDownload examples included with the Cosm library to both send and receive data from Cosm.

Don’t worry about the fact that you don’t have a sensor attached to the pin we are trying to read from in this sketch – with nothing attached we’ll end up reading a randomish value, which will then be sent up to Cosm.

If required, change YOUR_FEED_ID and YOUR_API_KEY to the values created for you, and then hit Upload to compile your code, and load it to your Arduino.

If the upload fails, make sure the Arduino is correctly connected to the USB port, and that you have selected the correct board type from the Tools > Board menu. However if all goes smoothly, your code should have been uploaded to the board, and the Arduino should be running, publishing data to Cosm.

Viewing your debug page

To verify that the data is reaching Cosm, you should just try refreshing your feed page, which should show that it’s started to receive updates. However if you’d like greater visibility into what it’s sending, or if the upload doesn’t seem to be working, you should next have a look at your debug page.

This page is available here : https://cosm.com/users/YOUR_USERNAME/debug

This page attempts to show realtime updates of data hitting our system, which can sometimes give a clue to why something isn’t working as expected. Here’s a capture of my debug page having received a successful update :

If everything has worked, then you should see continuously updating stream of successful updates being received by our systems. If there’s been any issues, then you should see some error updates coming in, with the important caveat that if the error is in the API key, then we don’t have any way of correlating the incoming requests with your account, so those requests won’t show on the debug page.

Next Steps

This example demonstrates the most basic way we can push data to Cosm from an Arduino using the new library, but doesn’t do anything else, i.e. consume any data and do something with it locally. For examples of this, or for more complicated examples that get/send data for multiple datastreams, please have a play with the other examples packaged with the Cosm library.

If you have any difficulties with any of this, please drop us a line at support@cosm.com.