Arduino Yún + Twitter Streaming API blink example

This is a simple example on how to run some code on the Arduino side of the Arduino Yún on specific events fired through the Twitter Streaming API

i.e. when a tweet containing a specific #hashtag is twitted, Arduino blinks an LED

I love this experiment because it’s near real time and it gives a lot of possibilities, and it’s very easy to set up

Requirements

  • An Arduino Yún (obviously) with an external SD card (required for hosting the Python libraries you’ll need)
  • A twitter app you own
  • The Tweepy library for Python
  • And, finally… this code
  • 🙂

Instructions

“I love instructions, they give me confidence.”
me

  1. In case you haven’t done it yet, upgrade your Arduino Yún to the latest version and expand it’s disk space using the SD card
  2. Log to your Arduino using ssh
  3. Install a bunch of useful stuff
     $ opkg update
     $ opkg install git
     $ opkg install python-expat
     $ opkg install python-openssl
     $ opkg install python-bzip2
    

    easy_install

     $ opkg install distribute
    

    pip

     $ easy_install pip
    

    tweepy

     $ pip install tweepy
    

    or install it manually cloning it from github

      $ git clone https://github.com/tweepy/tweepy.git
      $ cd tweepy
      $ python setup.py install
    
  4. If you don’t have one, create your twitter app
    and get your consumer key and consumer secret. Then, generate an access token and get your access token and access token secret

  5. Create a working folder for all the scripts (i.e. /root/python)

     $ mkdir /root/python
     $ cd /root/python
    

    and, while in the python folder, clone the Twitter Blink example

      $ git clone git@github.com:amicojeko/TwitterBlink.git
    

    don’t forget to make the kill_processes.sh script executable!

      $ chmod +x kill_processes.sh
    
  6. Then use vi or nano (I personally installed vim) to put your twitter app configuration data into the streaming.py script, and to configure the string to be searched inside the Twitter Stream Maelstrom
     $ nano streaming.py
    

    now everything should be ready.

  7. Open the Arduino IDE and load the TwitterBlink.ino script that is in the Arduino folder (you can download it from GitHub )

  8. Configure the script folder (in case you created a folder different from root/python/ in the previuos steps)

    You can customize the script for your needings, in it’s initial configuration it will blink the LED attached to pin 13 (and the built in LED as well) so it’s perfect for testing

  9. Upload the script to Arduino, it should start working as soon as it’s uploaded

  10. Have fun!!

cheers!

Jeko

Arduino Yún Extra WiFi Reset Button

One of the biggest problems with Arduino Yún is that the WiFi reset button is embedded on the board, and it’s very difficult to reach. Once you have packed you project in an enclosure, there’s no way to reset the wifi settings, unless the wifi reset button is reachable through a pinhole.

But how does the integrated wifi reset button work? When it’s pressed for more than 5 seconds, Arduino calls a little script: /usr/bin/wifi-reset-and-reboot

So I’ve made a very simple sketch that does exactly the same: it waits for our extra reset button to be pressed for more than 5 seconds, and when it happens it calls the same exact script using the Yún’s Bridge library.

So you can add your extra wifi reset button, and put it where you want!

Here’s the code

#include <Process.h>

const int  buttonPin = 7;  // the pin that the pushbutton is attached to
const int ledPin = 13;     // the pin that the LED is attached to

int buttonPushTimer = 0;   // timer for the reset button
int buttonState = 0;       // current state of the button
int lastButtonState = 0;   // previous state of the button

void setup() {
  Bridge.begin();
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);
  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, start the timer
    if (buttonState == LOW) {
      buttonPushTimer = millis();
    }
  }
  else {
    // if the state has changed, and the button is still pressed, check the timer
    if (buttonState == LOW) {
      if (millis() > buttonPushTimer + 5000) {
        // if the button has been pressed for 5 seconds, reset arduino wifi
        wifi_reset();
      }
    }
    // Delay a little bit to avoid bouncing
    delay(50);
  }
  lastButtonState = buttonState;
}



void wifi_reset() {
  //blink led 10 times
  for (int i = 0; i < 10; i++) {
    digitalWrite(ledPin, HIGH);
    delay(50);
    digitalWrite(ledPin, LOW);
    delay(50);
  }
  // call the wifi reset script
  Process p;
  p.runShellCommand("wifi-reset-and-reboot");
}

I Hope it was useful!

Happy resetting!

Jeko

Arduino Yún social photo camera

After making an USB Audio card work with Arduino Yún, the logical second step was try to use an USB camera instead, and it worked! I was so amazed by this new huge set of possibilitities to create, that I started a little weekend project: to build an Arduino based Facebook photo camera

I was so into this project that I didn’t realize that, even if the single steps are very simple, they’re quite a lot! So I decided to write this step-by-step tutorial and to split it into … articles.

Just to be clear:

The goal

To build photocamera that shoots pictures and publishes them directly to a specific Facebook Album.

Ingredients

The Steps

  1. Install the USB Camera on Arduino Yún
  2. Take your first picture
  3. Create the Facebook Application
  4. Post your first picture with the Temboo API
  5. Install the Temboo SDK on Arduino Yún
  6. Make the python script and publish your first photo to Facebook from Arduino
  7. Create the Arduino sketch
  8. Put everything together

1. Install the USB Camera on Arduino Yún

I assume that your Arduino Yún is already configured for wi-fi (or connected via the Ethernet port), and that you have SSH access to it, if not, follow this link to configure the wifi network and this link to connect via SSH.

The UVC package is already available fot Linino via opkg, so installing the Camera is a very easy step, just connect to your Yún via ssh and type

$ opkg update
$ opkg install kmod-video-uvc

We also need a software for taking pictures, I used fswebcam that is supersmall and very easy to use

$ opkg install fswebcam

Now we can test it!

2. Take your first picture

First of all, be sure to use and SD card for storage or you will quickly fill the Arduino internal storage, and you don’t want to do that. If you are using an SD card, you should see it mounted in /mnt/sda1. If it’s not, put a FAT32 formatted micro SD card into the SD Card Slot, and reboot your Arduino

Now plug the camera to the USB host port, and type

$ cd /mnt/sda1
$ fswebcam test.png

If everything is ok, you took your first picture!

This means that now we can take pictures from our Arduino sketch, via the Yún’s Bridge library, in this way

Process.runShellCommand("fswebcam /mnt/sda1/test.png");

Now we will learn how to share them on Facebook using Temboo.

3. Create the Facebook Application

This is easy, but you must be a Facebook developer to do that. That simply means that you have to accomplish these easy steps before starting. Done? ok! So now let’s create a blank Facebook Application

image creation

and configure it in this way:

configuration

 Create a Temboo Application

First of all, register on Temboo. When you’re in, create a new application, then go to https://temboo.com/library/Library/Facebook/Publishing/UploadPhoto/

add new credentials for the new Facebook app.

temboo config

Choose oAuth wizard, go directly to the third step and copy and paste the app id & app secret from your Facebook application.

Go to the next step, click on launch authorisation and grant the authorisation to the Facebook application.

Now you have the access token

Click on use these values and save, copy and paste the access token in the access token form field if needed.

Now you need the target album id. to get an album id, just go on Facebook, open an album (not a single photo) and the URL will look like this.

albumid

The album id is the highlighted part. copy and paste it into the AlbumID field on Temboo

I also choose to open the Optional Input section and to put a custom message 🙂

message

If you take a look to the sample code, Temboo has made pretty much all the job for you, but we need to make some changes, we will make them later. Now we need some gratification, so let’s post our first picture!

4. Post your first picture with the Temboo API

You already put your Access Token and the desired AlbumID. The only thing that’s missing is the Base64 Encoded image. So go to http://www.freeformatter.com/base64-encoder.html and paste the URI of the image you want to encode, then copy the encoded string and paste it into the Temboo interface.

https://i0.wp.com/i.imgur.com/DT1Ij8U.png?w=640

Click TRY IT OUT and voilà, the image it’s magically posted on your album!

5. Install the Temboo SDK on Arduino Yún

We will use the Temboo API from a Python script, so we need to download the SDK. The download page is here https://temboo.com/download, all we have to do is download the Python SDK and unzip it into the root folder of your Micro SD card (it will unzip into a /temboo folder).

A very important step is installing OpenSSL support for Python, as the Temboo libraries will try to use SSL to publish the photos.

$ opkg update
$ opkg install python-openssl

6. Make the python script and publish your first photo to Facebook from Arduino

As I wrote before, the generated code from Temboo is a good starting point, but we need to make some modifications in order to make it work.

# Instantiate the Choreo, using a previously instantiated TembooSession object, eg:
# session = TembooSession('jeko', 'APP_KEY_NAME', 'APP_KEY_VALUE')
uploadPhotoChoreo = UploadPhoto(session)

# Get an InputSet object for the choreo
uploadPhotoInputs = uploadPhotoChoreo.new_input_set()

# Set credential to use for execution
uploadPhotoInputs.set_credential('ArduinoCamera')

# Set inputs
uploadPhotoInputs.set_Message("This photo has been shot and published with an Arduino Yún")
uploadPhotoInputs.set_AlbumID("")

# Execute choreo
uploadPhotoResults = uploadPhotoChoreo.execute_with_results(uploadPhotoInputs)

Download my version of the script and copy it into the root folder of the SD card. Here’s what I did.

Step number one, the encoding. I’m italian and we use a lot of accented characters, so I’ll use UTF-8 as the default script encoding, so I added

# coding=utf-8

at the top of my script. Now we need to read the photo from the disk, and to base64 encode it, so we will need the base64 and the sys libraries.

import base64
import sys

The Temboo libraries are not included in the generated script by Temboo, so we will have to add them

from temboo.core.session import TembooSession
from temboo.Library.Facebook.Publishing import UploadPhoto

The script will read the first argument, and use it as the name of the image file to encode

with open(str(sys.argv[1]), "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

In this line you have to put your Temboo’s account name, and the app name and key (from this page)

session = TembooSession('ACCOUNT_NAME', 'APP_KEY_NAME', 'APP_KEY_VALUE')

You’ll also need to put yout access token, message (if you want one) and Album ID into the script

uploadPhotoInputs.set_AccessToken("ACCESS_TOKEN")
uploadPhotoInputs.set_Message("MESSAGE")
uploadPhotoInputs.set_AlbumID("ALBUM_ID")   

The rest of the script is basically identical to the Temboo’s example.

We can now try to publish our first photo with the script!

$fswebcam testpic.jpg
$python sendphoto.py testpic.jpg 

At this point I strongly hope that it’s working for you as it’s working for me (otherwise contact me and we will try to solve the problem together) because you have just published your first picture to Facebook with Arduino! The only missing step is to make an Arduino sketch to take and send the picture without using SSH

7. Create the Arduino sketch

I started from the basic “Button” example, as I wanted the camera to be triggered by a simple Pushbutton. The circuit is the same of the button example. Just download this arduino sketch

you can customise the LED and Button pin if you want

const int buttonPin = 2; // pin for the pushbutton 
const int ledPin =  13; // pin for the status led

as well as the path for the photos and the Python script (important! this folder must contain the Temboo SDK)

String path = "/mnt/sda1/"; // path of the images and script file 

The setup is pretty simple, we will use the Bridge library to invoke the Python script, and the Serial library for a very basic debugging

void setup() {
    Bridge.begin(); // The bridge library is used to run processes on the linux side
    pinMode(ledPin, OUTPUT);      
    pinMode(buttonPin, INPUT); 
    Serial.begin(57600); // Serial port for debugging
    filename = "test";
}

Then, when the pushbutton is pressed, the script generates a new timestamp based filename running the “date +%s” command

if (buttonState == LOW) {
    filename = "";
    p.runShellCommand("date +%s"); //generate a timestamp
    while(p.running()); // wait until the command has finished running

    while (p.available()>0) {
        char c = p.read(); //reads the first available character
        filename += c; //and adds it to the filename string
    } 

    filename.trim(); //used to avoid trailing spaces or newline characters
    filename += ".png"; //finally I add the png extension

This part of the code will take the picture and send it to Facebook using the Bridge library

p.runShellCommand("fswebcam " + path + filename); //let's take the picture
while(p.running());  //waits till the picture is saved
Serial.println("picture taken"); 

p.runShellCommand("python " + path + "sendphoto.py " + path + filename); //sends the picture to facebook 
while(p.running()); 
Serial.println("picture sent"); //last debug message    

8. Put everything together

Ok! Everything is ready! Just upload the code to Arduino, push the button and… Smile!! You’re on Facebook! 🙂

I really hope that you enjoyed this tutorial, it opens a lot of possibilities! Trap cameras, cameras triggered by doors, by sounds or any kind of sensor… I’d really like to see your projects and share them!

Cheers and happy hacking!

Stefano

Arduino Yún with SOUND the supereasy way

At the Codemotion in Milano, I had a chat with Federico Vanzati from Officine Arduino, and he gave me the fantastic idea to try to use a supercheap USB Audio card with Arduino Yún to give to it full audio capabilities with zero effort.

And suddenly I was like…

image

I mean, it’s awesome! It could give me (and hopefully to you) infinite new possibilities! Sound with Arduino with no external libraries or crappy MP3 shields? How great could it be? Now that we have a great Wi-Fi support thanks to the Yún, this was the real missing feature!

I started with buying this sound card (http://www.manhattan-products.com/hi-speed-usb-3-d-sound-adapter)

Then, all I had to do was plug the sound card in, open an ssh session to the yun, and type:

opkg update
opkg install kmod-usb-audio
opkg install madplay

End of the story. Now you have sound support on the Arduino Yún. I only tried MP3 playback, I didn’t try to record some audio yet, but I’ll try soon!

To test it just copy an mp3 audio file (I named it ItCouldWork.mp3) in the root folder, or, even better, in the SD card, then upload this sketch

#include <Process.h>

const int buttonPin = 2;
const int ledPin =  13;

int buttonState = 0;
Process p;

void setup() {
  Bridge.begin();
  pinMode(ledPin, OUTPUT);      
  pinMode(buttonPin, INPUT);     
  Serial.begin(57600);
}

void loop(){
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {     
    digitalWrite(ledPin, HIGH);  
    p.runShellCommand("madplay /root/ItCouldWork.mp3");
    while(p.running());  
    Serial.println("it works!");
  } 
  else {
    digitalWrite(ledPin, LOW); 
  }
}

It’s based on the button example, so you have to connect a pushbutton to the digital Pin 2.

image

Now, connect the sound card to the speakers and… push the button!

Magic, isn’t it?

It doesn’t sound too bad, actually the sound quality is good! And the delay is very short! I mean, it’s just the first experiment, we can work on it!

I really hope this will amaze you as it amazed me… I’m superhappy!

Many thanks to my friend and coworker Massimo, that knows Linux better than I know myself.

Bye!

Jeko

How to install an SFTP Server on Arduino Yùn

By default, Arduino Yùn’s Linino has Dropbear, an SSH server that procides basic SCP but has no SFTP capabilities, so you cannot connect to the Yún with client software such as Cyberduck.

You can solve this basic issue by installing OpenSSH’s SFTP Server running this command in the Arduino’s SSH console.

opkg update
    opkg install openssh-sftp-server

The server will be installed in /usr/libexec/sftp-server, exactly where Dropbear will look for it.

Arduino Yún Gmail Lamp – Part one

Finally!!! Finally I put my hands on a brand new Arduino Yún. I’ve been waiting for this a long, loooong time. I’ve been playing with Arduino since the “diecimila” model came out and I, as a lot of people, always suffered the lack of connectivity and of real computing power. I tried to solve some of these problems using RaspberryPi and/or Electric Imp, but I always missed the Arduino approach… easy, lots of shields and Arduino ready parts, a lot of documentation, a strong community and the freedom of Open Source.

image

Now one of my dreams came true, and every time I go deeper into the discovery of the Yún’s capabilities, I find something amazing, very smart and very well done.

I won’t describe the platform itself, as many articles talking about that are already published and there will be many more to come. I’ll start directly with a real life example, in just a few hours I finally built something really, really useful to me, something I already built several times in various ways but none of which really satisfied me.

The task is pretty simple, and I believe it will be very useful to many people: I need to be alerted in real time when I receive some important emails. Not all the emails: we provide customer care for many clients, with different SLAs, and I need to be alerted only for the most important ones. Moreover, sometimes I look forward to receiving a precise email… a shipment confirmation, a mail from a special someone… I need something flexible, eye catching, that doesn’t depend on my computer or my cellphone (that always has only 1% battery)

So I decided to build a GMail Lamp and Arduino Yún was the perfect choice (and now that I built it, I can confirm that. It is perfect)

The working principle is very straightforward: On GMail, I defined a new label, so I can quickly change the rules for the messages that will go under it, then I tell to Arduino Yún which label to watch for (via REST APIs… amazing) and that’s it! The lamp (actually only just a led, the lamp will come in the future) turns on every time I get new messages under that label. It’s the bat-signal principle! 🙂

image

Okay, now let’s get a bit more technical… how did I do it?

The hardware:

  • An Arduino Yún, and it must be connected to the internet.
    – A LED (or a relay if you want to turn on a real lamp, as I will do in the future)
    – Optional: a MAX7219 based 7 segment LED Display, if you also want to know how many unread messages you got. I used this one,http://dx.com/p/8-segment-led-display-board-module-for-arduino-147814 that’s supercheap and works perfectly.

This is the connection scheme (supersimple)

The LED goes on Digital Pin 13
The LED Display uses pins 10,11,12 and, obviously, GND and +5V

image

Ok, the hardware is ready. When you will program the Yún for the first time, even if you can program it over the wifi network, I suggest you use the serial port via USB because it’s faster and I still use the serial port to debug (even if you have a brand new Console object :). But it’s just a personal choice.

Now, the Code.

Even if it’s short, I think it’s very interesting because I used many new features of the Yún. I’m not going to describe all the code, that you can freely download or fork from GitHub (https://github.com/amicojeko/Arduino-Yun-Gmail-Check). I’ll try to describe only the parts that involve brand new code and that are peculiar of the Yún

Let’s start from the beginning

#include <Process.h>

With the Process library, you can run some code on the Linux side of the Yún and catch the stdout on Arduino. It’s amazing because you can delegate to Linux all the dirty jobs and the heavy computing. In this case, I use the Linux “curl” command to get the ATOM feed of my label from GMail.

The Process library also includes the Bridge library, that allows you to pass information between the two sides of the Yún (Linux and Arduino) using a key/value pairing. And it gives you the power of REST APIs, I use it to configure the label to observe.

#include <FileIO.h>

With this library, you can use the inernal memory or a micro SD card/USB key for storage. All these features are native on the Yún!

#include "LedControl.h" /* Downloaded From http://playground.arduino.cc/Main/LedControl */

I use this library to control the 7 segment LED Display

const int ledPin = 13;

I’ve used the pin 13 for the led. As I told you before, you can replace the LED with a relay in order to turn on and off a real lamp!

const char* settings_file = "/root/gmail_settings"; /* This is the settings file */

I’m saving under “/root” cause /tmp and /var will be erased at every reboot.

Bridge.get("label", labelbuffer, 256);

This is a supercool line of code that uses an übercool Yún’s feature. I’m telling Arduino to listen for a REST call on the URL http://arduino.local/data/put/label/LABEL

When I get some data, it will put the value of LABEL in the localbuffer. The localbuffer was initialized like that

char labelbuffer[256];

That means that you can actually talk with your Arduino while it runs projects! You can get or put variables, you can finally make dynamic projects! I used it to tell Arduino which label to observe, but I can, and I will go further, I promise.

label = String(labelbuffer);
File settings = FileSystem.open(settings_file, FILE_WRITE);
settings.print(label);
settings.close();

This is cool too. Using the FileIO object, I save the label in a local file on the Linux side of Arduino, so when I will turn it off and on again, It will remember my settings.

File settings = FileSystem.open(settings_file, FILE_READ);
while (settings.available() > 0){
  char c = settings.read();
  label += c;
}
settings.close();

This is how I read a file from the filesystem.

Process p;

p.runShellCommand("curl -u " + username + ":" + password + " "https://mail.google.com/mail/feed/atom/" + label + "" -k --silent |grep -o "<fullcount>[0-9]*</fullcount>" |grep -o "[0-9]*"");

while(p.running()); // do nothing until the process finishes, so you get the whole output
int result = p.parseInt();

This is another bit of Yún’s magic. I run the curl command to get the ATOM feed of a specific label, and then I parse it with the grep command, and finally I get the number of unread messages for that label. Even if on the Yún’s Linux stack there are both Python and Lua, I thought that this solution was the most simple and stupid, and I love to KISS.

That’s it, now i just have to turn the LED on and to display the number of unread messages on the LED Display…

In a single day I learned how to use the Bridge library to get data from REST webservices, how to save and load data from the Linux filesystem, and how to run processes on the Linux side and get the STDOUT results. I already knew how to use the LED Display but I hope that someone learned something new even about that 🙂

Now I will build the actual lamp, improving both the Hardware and the Software sides, I will make it gorgeous and fully configurable, and I will keep you informed about that!

Cheers to everybody and happy hacking!

Jeko