Sunday, 6 December 2015

Christmas project time!

In the run up to Christmas I fancy making something Christmassy!

My first thought was visualising Christmas related tweets through IFTTT. After linking my photon to IFTTT and playing around with a few recipes it was clear that the triggers were just not reliable enough and the correct tweets were not coming through.

So let's create something from scratch.

First we need a mechanism for a notification to be sent to the photon to trigger the visualisation. This is done by exporting a function to the particle cloud that will give us a REST API endpoint to poke.

Create xmas.cpp

  
   #include "application.h"  
   
   #define ledPin D7  
   
   int handleTweet(String message);  
   
   void setup()  
   {  
    Particle.function("tweet", handleTweet);  
    pinMode(ledPin, OUTPUT);  
   }  
   
   void loop()  
   {  
    delay(1000);  
    digitalWrite(ledPin, LOW);  
    delay(1000);  
   }  
   
   int handleTweet(String message)  
   {  
    digitalWrite(ledPin, HIGH);  
    Serial.print("Received tweet: ");  
    Serial.print(message);  
    Serial.println();  
   
    return 0;  
   }  

This program will export a function called 'tweet' which takes in a String (max length 63 characters) and pull the D7 pin high when it is called. This is the pin with the blue LED next to it on the board so we can easily see it is working without constructing a circuit. The function also writes a log line to the serial output so we can see what the message is.

   $ particle compile p  
   $ sudo particle flash --usb photon_firmware_xxx.bin  
   $ sudo particle serial monitor  

Now we are connected to the photon and listening for log messages.

When you export a cloud function a REST endpoint is created in the format:

   https://api.particle.io/v1/devices/<device ID>/<function name>

So to poke the function exported for my particular photon you can use curl:

   $ curl https://api.particle.io/v1/devices/12341234/tweet -d access_token=12341234 -d "args=hello world"  

You can find your device ID and access tokens with the following commands:

 $ particle list  
 $ particle token list  

The 'user' access token is the one you want to use here. You can also find this token on the particle cloud IDE under 'Settings'.

Once you submit the curl command you instantly see "Received tweet: hello world" written to the serial log. Pretty cool!



Next post we'll hook up a circuit to visualise the data received by the photon.

No comments:

Post a Comment