The social media hamster

(la muerte peluda is back)


Every hackathon we host at Mikamai usually means a lot of leftovers. From pizza crusts to burned LEDs, you can find a lot of useful and useless stuff even in the deepest and darkest corners of our huge open space.

And in one of these dark corners I found a scared little friend, which I suddenly decided to adopt.

image

We became BFFs, and we do everything together, coding, drinking, pranking the teammates and cycling, but he wanted to be useful to me, so I went into my cove and start thinking… what an ex cartoon eating plush hamster can do for me?

The answer was quite obvious! He can warn me whenever someone tweets me or cites me in a tweet! Genius!

So, here are the ingredients

  • Twitter streaming APIs
  • Electric IMP (I decided to use an Electric Imp just because I had a spare one, you can even use a spark core or an Arduino Yún)
  • A servo
  • Chopsticks
  • Some screws
  • Cable ties
  • Something heavy
  • Obviously, absulutely essential, a plush hamster
  • An USB power adapter or a USB battery pack if you want your project to be portable

image

I also used an LED for visual debugging, I tried to put a pair of LEDs instead of my hamster’s eyes, but it was too scary, and it remembered a lot my creepy doll, so I decided not to use them

Then I had to make the hamster move with the servo. It’s just a prototype, so I decided to keep it very very simple, and I secured the hamster to the servo with a chopstick, some copper wire and some screws to keep the hamster from doing a barrel roll. The surgery was not so traumatic, so my hamster is still happy. Then I fixed the servo to an heavy metal plate with a cable tie, just to provide a solid base.

I drilled some holes to the chopstick

image

Then put some screws in it and i secured the chopstick to the servo

image

And I used a bit of copper wire to secure the hamster to the screws

image

image

And a cable tie to fix the servo to the metal plate

image

Now everything’s in place!

image

The circuit is dead simple. Just connect the power pins of the servo to the GND-VIN pins of the Electric Imp, and the third pin to the Imp’s pin number 7

image

The Electric Imp is one of the easiest platforms to configure, thanks to the Blink app, so you can have it online in a couple of minutes. You can even use your phone as hotspot, it works perfectly and it makes your social hamster fully portable.

image

Now, the code. The Electric imp platform gives you all the instruments to interact with the whole world of APIs and webservices. Basically, the code is splitted in two: An agent, that runs on the Electric Imp Cloud servers, and a device, which is your electric Imp

[Copy & Paste from the official Electric Imp documentation]

The agent object represents the imp’s agent: the server-side Squirrel, running in the Electric Imp’s cloud servers, that deals with Internet requests and responses on behalf of the imp. The agent object is used to mediate communication between the imp and its agent.

The device object represents the server-based agent’s view of the imp and is used to mediate communication between the agent and the imp.

[End of copy&paste]

So here we go with our agent code. It’s based on the useful twitter library included in the Electric Imp webservices reference. I also added this piece of code to generate the tweet event manually

// test function for manual hamster shaking
function requestHandler(request, response) {
  try {
    // check if the user sent led as a query parameter
    if ("tweet" in request.query) {
        device.send("tweet", null); 
    }
    // send a response back saying everything was OK.
    response.send(200, "tweet test ok");
  } catch (ex) {
    response.send(500, "Internal Server Error: " + ex);
  }
}

// register the HTTP handler
http.onrequest(requestHandler);

To enable the twitter stream real time parsing, I just needed to configure these twitter constants

// Twitter Keys
const API_KEY = "";
const API_SECRET = "";
const AUTH_TOKEN = "";
const TOKEN_SECRET = "";

and this line

twitter.stream("@jeko", onTweet);

which basically tells to the stream object to catch all the tweets containing the string “@jeko”

So, here’s the complete agent code

// Copyright (c) 2013 Electric Imp
// This file is licensed under the MIT License
// http://opensource.org/licenses/MIT

// Twitter Keys
const API_KEY = "";
const API_SECRET = "";
const AUTH_TOKEN = "";
const TOKEN_SECRET = "";

class Twitter {
    // OAuth
    _consumerKey = null;
    _consumerSecret = null;
    _accessToken = null;
    _accessSecret = null;

    // URLs
    streamUrl = "https://stream.twitter.com/1.1/";
    tweetUrl = "https://api.twitter.com/1.1/statuses/update.json";

    // Streaming
    streamingRequest = null;
    _reconnectTimeout = null;
    _buffer = null;


    constructor (consumerKey, consumerSecret, accessToken, accessSecret) {
        this._consumerKey = consumerKey;
        this._consumerSecret = consumerSecret;
        this._accessToken = accessToken;
        this._accessSecret = accessSecret;

        this._reconnectTimeout = 60;
        this._buffer = "";
    }

    /***************************************************************************
     * function: Tweet
     *   Posts a tweet to the user's timeline
     * 
     * Params:
     *   status - the tweet
     *   cb - an optional callback
     * 
     * Return:
     *   bool indicating whether the tweet was successful(if no cb was supplied)
     *   nothing(if a callback was supplied)
     **************************************************************************/
    function tweet(status, cb = null) {
        local headers = { };

        local request = _oAuth1Request(tweetUrl, headers, { "status": status} );
        if (cb == null) {
            local response = request.sendsync();
            if (response && response.statuscode != 200) {
                server.log(format("Error updating_status tweet. HTTP Status Code %i:rn%s", response.statuscode, response.body));
                return false;
            } else {
                return true;
            }
        } else {
            request.sendasync(cb);
        }
    }

    /***************************************************************************
     * function: Stream
     *   Opens a connection to twitter's streaming API
     * 
     * Params:
     *   searchTerms - what we're searching for
     *   onTweet - callback function that executes whenever there is data
     *   onError - callback function that executes whenever there is an error
     **************************************************************************/
    function stream(searchTerms, onTweet, onError = null) {
        server.log("Opening stream for: " + searchTerms);
        // Set default error handler
        if (onError == null) onError = _defaultErrorHandler.bindenv(this);

        local method = "statuses/filter.json"
        local headers = { };
        local post = { track = searchTerms };
        local request = _oAuth1Request(streamUrl + method, headers, post);


        this.streamingRequest = request.sendasync(

            function(resp) {
                // connection timeout
                server.log("Stream Closed (" + resp.statuscode + ": " + resp.body +")");
                // if we have autoreconnect set
                if (resp.statuscode == 28) {
                    stream(searchTerms, onTweet, onError);
                } else if (resp.statuscode == 420) {
                    imp.wakeup(_reconnectTimeout, function() { stream(searchTerms, onTweet, onError); }.bindenv(this));
                    _reconnectTimeout *= 2;
                }
            }.bindenv(this),

            function(body) {
                 try {
                    if (body.len() == 2) {
                        _reconnectTimeout = 60;
                        _buffer = "";
                        return;
                    }

                    local data = null;
                    try {
                        data = http.jsondecode(body);
                    } catch(ex) {
                        _buffer += body;
                        try {
                            data = http.jsondecode(_buffer);
                        } catch (ex) {
                            return;
                        }
                    }
                    if (data == null) return;

                    // if it's an error
                    if ("errors" in data) {
                        server.log("Got an error");
                        onError(data.errors);
                        return;
                    } 
                    else {
                        if (_looksLikeATweet(data)) {
                            onTweet(data);
                            return;
                        }
                    }
                } catch(ex) {
                    // if an error occured, invoke error handler
                    onError([{ message = "Squirrel Error - " + ex, code = -1 }]);
                }
            }.bindenv(this)

        );
    }

    /***** Private Function - Do Not Call *****/
    function _encode(str) {
        return http.urlencode({ s = str }).slice(2);
    }

    function _oAuth1Request(postUrl, headers, data) {
        local time = time();
        local nonce = time;

        local parm_string = http.urlencode({ oauth_consumer_key = _consumerKey });
        parm_string += "&" + http.urlencode({ oauth_nonce = nonce });
        parm_string += "&" + http.urlencode({ oauth_signature_method = "HMAC-SHA1" });
        parm_string += "&" + http.urlencode({ oauth_timestamp = time });
        parm_string += "&" + http.urlencode({ oauth_token = _accessToken });
        parm_string += "&" + http.urlencode({ oauth_version = "1.0" });
        parm_string += "&" + http.urlencode(data);

        local signature_string = "POST&" + _encode(postUrl) + "&" + _encode(parm_string);

        local key = format("%s&%s", _encode(_consumerSecret), _encode(_accessSecret));
        local sha1 = _encode(http.base64encode(http.hash.hmacsha1(signature_string, key)));

        local auth_header = "oauth_consumer_key=""+_consumerKey+"", ";
        auth_header += "oauth_nonce=""+nonce+"", ";
        auth_header += "oauth_signature=""+sha1+"", ";
        auth_header += "oauth_signature_method=""+"HMAC-SHA1"+"", ";
        auth_header += "oauth_timestamp=""+time+"", ";
        auth_header += "oauth_token=""+_accessToken+"", ";
        auth_header += "oauth_version="1.0"";

        local headers = { 
            "Authorization": "OAuth " + auth_header
        };

        local url = postUrl + "?" + http.urlencode(data);
        local request = http.post(url, headers, "");
        return request;
    }

    function _looksLikeATweet(data) {
        return (
            "created_at" in data &&
            "id" in data &&
            "text" in data &&
            "user" in data
        );
    }

    function _defaultErrorHandler(errors) {
        foreach(error in errors) {
            server.log("ERROR " + error.code + ": " + error.message);
        }
    }

}

twitter <- Twitter(API_KEY, API_SECRET, AUTH_TOKEN, TOKEN_SECRET);

function onTweet(tweetData) {
    // log the tweet, and who tweeted it (there is a LOT more info in tweetData)
    server.log(format("%s - %s", tweetData.text, tweetData.user.screen_name));
    device.send("tweet", null); 
}


// test function for manual hamster shaking
function requestHandler(request, response) {
  try {
    // check if the user sent led as a query parameter
    if ("tweet" in request.query) {
        device.send("tweet", null); 
    }
    // send a response back saying everything was OK.
    response.send(200, "tweet test ok");
  } catch (ex) {
    response.send(500, "Internal Server Error: " + ex);
  }
}

twitter.stream("yoursearchstring", onTweet);

// register the HTTP handler
http.onrequest(requestHandler);

Then, here’s the device code, based on the electric Imp PWM Servo example

// These values may be different for your servo
const SERVO_MIN = 0.03;
const SERVO_MAX = 0.1;

// create global variable for servo and configure
servo <- hardware.pin7;
servo.configure(PWM_OUT, 0.02, SERVO_MIN);

// assign pin9 to a global variable
led <- hardware.pin9;
// configure LED pin for DIGITAL_OUTPUT
led.configure(DIGITAL_OUT);

// global variable to track current state of LED pin
state <- 0;
// set LED pin to initial value (0 = off, 1 = on)
led.write(state);



// expects a value between 0.0 and 1.0
function SetServo(value) {
  local scaledValue = value * (SERVO_MAX-SERVO_MIN) + SERVO_MIN;
  servo.write(scaledValue);
}

// expects a value between -80.0 and 80.0
function SetServoDegrees(value) {
  local scaledValue = (value + 81) / 161.0 * (SERVO_MAX-SERVO_MIN) + SERVO_MIN;
  servo.write(scaledValue);
}

// current position (we'll flip between 0 and 1)
position <- 0;

function HamsterDance() {
  SetServoDegrees(-10);
  imp.sleep(0.5);
  SetServoDegrees(0);
  imp.sleep(0.2);
  SetServoDegrees(-15);
  imp.sleep(0.2);
  SetServoDegrees(5);  
  imp.sleep(0.2);
  SetServoDegrees(-20);
  imp.sleep(0.2);
  SetServoDegrees(0);
  imp.sleep(0.2);
  SetServoDegrees(-78);
} 


function ShakeRattleAndRoll(ledState){
    server.log("Let's shake the hamster!");  
    // turn on the led for visual debugging
    led.write(1);
    // 
    HamsterDance();
    imp.sleep(2);
    // turn off the led
    led.write(0);

} 

// initialize the servo to the start position
SetServoDegrees(-78);

//shake the hamster when got a tweet message from the Agent
agent.on("tweet", ShakeRattleAndRoll);

And… that’s it! Just connect the Electric Imp to a power source, configure the wifi via the Electric Imp mobile App, and start tweeting! Your hamster will be soo happy to warn you whenever a tweet is coming!!

Ciao and happy hacking!

Stefano

AtTiny85 based capacitive sensor LED switch

Not so much time ago, I met a girl, and she designs ceramic lamps.

viondesign.com

I mean, the lamps are really, really gorgeous, and they are illuminated by a 12V LED module.

As soon as I saw one of these lamps, I decided to make some experiments with them, because they are so beautiful that the classic ON/OFF switch did not do justice to them.

Recently, I studied the Arduino capsense library for other purposes, and I thought that a capacitive sensor would have been a very nice way to turn the lamp on and off without the use of a regular switch.

The basic idea was to paint the inside of the lamp with some conductive paint and use the lamp itself as a switch.

So, here’s what I did.

First of all, the prototyping. The best thing about AtTinys is that you can use Arduino for prototyping, and then, with very small code adjustments, burn the code into the AtTiny, make the circuit supersmall, and go to production.

I started from the basic Capacitive Sensor library example.

It worked nice, but the reading was not very stable, and since I linked the LED intensity directly to the sensor reading, the LED was flickering a lot (as you can see in this video)

So I followed the instructions, and put a very small capacitor (20pF) between the sensor (an aluminium foil for prototyping) and ground. That helped a lot, but it wasn’t enough.

Then I decided to add some smoothing code to my sketch.. Open source code is soooo cool 🙂 You always find someone that can really help you 🙂

The original code takes the average reading between 100 readings, but since the AtTiny is much slower than the Arduino (1Mhz vs 16 Mhz) I decided to make an average reading between 10 values, and it worked great for me.

Ok, now the LED turns on and off when my hand is close to the sensor. But I wanted it to stay on or off, like a regular switch does. So I put this code, that works in this way: if the sensor reaches the maximum value (when I touch it), then I switch the lamp on/off and I stop the reading for a second.

So this is the final code for Arduino.

#include <CapacitiveSensor.h>

int cap_pin_out = 4;
int cap_pin_in = 2;
int lowcap = 300;  // just above reading when noting is near
int highcap = 1800; // cap reading when almost touching
CapacitiveSensor   capsense = CapacitiveSensor(cap_pin_out, cap_pin_in);  // 10M resistor between pins 1 & 2, pin 2 is sensor pin, add a wire and or foil if desired
int ledPin = 13;
int dur = 10; //duration is 10 loops
int brightness;
bool isOn = 0;

/* smoothing */
const int numReadings = 10;
int readings[numReadings];      // the readings from the analog input
int index = 0;                  // the index of the current reading
long total = 0;                  // the running total
int average = 0;                // the average

void setup()
{
  pinMode(ledPin, OUTPUT); // output pin
  pinMode(cap_pin_in, INPUT); // output pin
  pinMode(cap_pin_out, OUTPUT); // output pin

  // initialize all the readings to 0:
  for (int thisReading = 0; thisReading = numReadings)
    // ...wrap around to the beginning:
    index = 0;

  // calculate the average:
  average = total / numReadings;
  // send it to the computer as ASCII digits

  long start = millis();

  brightness = map(average, lowcap, highcap, 0, 255);
  brightness = constrain(brightness, 0, 255);

  if (isOn == true && brightness == 255) {
    isOn = false;
    delay(500);
  } else if (isOn == false && brightness == 255) {
    isOn = true;
    delay(500);
  }

  if (isOn == true) {
    analogWrite(ledPin, 255);
  } else {
    analogWrite(ledPin, brightness);
  }

  delay(10);

}

At this point I had a couple of things left to do: first of all, to control an hi-power 12V led, instead of a 5V one, and, second, try to power the circuit with the 12V LED power supply.

To control an 12V LED, I used a TIP102, that is a really heavy duty affordable NPN darlington transistor. It’s perfect to control LED strips, hi power LEDs and LED modules. The connection is really easy, it just needs an 1K resistor and this simple scheme

Since the ATTiny can be powered at 5V, and I did not want to use two power supplies, I decided to use this 12v to 5v voltage converter. It’s very simple to use: just connect the IN Pins to the 12V and you get 5V from the output pins (yes, I know, I should have used a capacitor for stability, but the AtTiny is very forgiving and works perfectly even without it)

Ok now that everything was perfect, I burned the code to the AtTiny. If you need some instructions on how to do that, here’s a step by step tutorial I wrote some time ago.

I had to make some minor adjustments to the code: I changed the sensor pins form 4,2 to 1,2 and the LED pin from 13 to 0… and boom! we’re ready to change platform! 🙂

So here’s the schematics for the AtTiny85

The circuit is pretty simple and can be easily assembled on a protoboard.

I painted the inside of the lamp with this paint, so now the inside of the skull is conductive and can be used as a capacitive sensor.

To connect the sensor wire to this paint, I used some BareConductive electric paint

The assembled circuit was so tiny that fitted perfectly inside the skull

A little hint: when using capacitive sensor, is very important to ground the circuit, so be sure to have a ground connection between the circuit, the power supply, and the mains ground.

Here is the final result… isn’t it nice? 🙂

Ciao!

Jeko

Another important thing with capacitive sensors is grounding.

The Creepy Doll

Here at Mikamai, we often organise events and hackathons. After the last hackathon, someone left an old doll, and it was kinda creepy… so why not make it even creepier?

I decided to put two red LEDs instead of the eyes, and a vibration sensor to turn on the LEDs when you shake the doll. Everything is powered by an AtTiny85 and a single CR2032 battery.

Materials and tools

image

Materials:

image

Tools:

  • A sharp cutter
  • Hot glue gun
  • A soldering iron and solder
  • Needle and thread, to sew it back
  • optional – a Dremel to drill the eyes

Prototyping and testing the circuit

image

Using the AtTiny 85 is a great choice for those who are familiar with Arduino, because you have the possibility to use the Arduino IDE to program it. This means that you can prototype the circuit with Arduino before deploying it to the AtTiny.

So I wrote this code, and I built a simple testing circuit with Arduino.

#import <Arduino.h>


int led = 0; // LEDs pin
int button = 2; // Tilt sensor pin
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by
int storedVal = 0;     // used to save the tilt sensor state

void setup() {
  pinMode(button, INPUT_PULLUP); // initialize the button pin a pullup input, so I don't have to use an external pullup resistor.
  pinMode(led, OUTPUT); // initialize the digital pin as an output.
}


void loop() {

  int sensorVal = digitalRead(2); // Read the sensor state

  if (sensorVal != storedVal) { //if the sensor value has changed, blink the eyes
    storedVal = sensorVal; // store the sensor state
    fadeEyes(); // call the eyes led fade function
  } else {
    digitalWrite(led, LOW); // otherwise, turn the led off
  }

  delay(10); // a small delay for debouncing the sensor
}

void fadeEyes() {

  for (int i = 0; i < 768; i++) { //cycle 3 times

    analogWrite(led, brightness); // set the brightness of led pin:
    if (brightness == 255) { // at maximum brightness, wait 5 seconds
      delay(5000); 
    }
    // change the brightness for next time through the loop:
    brightness = brightness + fadeAmount;

    // reverse the direction of the fading at the ends of the fade:
    if (brightness == 0 || brightness == 255) {
      fadeAmount = -fadeAmount;
    }

    // wait for 30 milliseconds to see the dimming effect
    delay(100);

  }

  digitalWrite(led, LOW);
}   

The code is pretty simple: it waits for a changement in the tilt sensor state, and when it happens, it starts a little loop fading the leds brightness

When the code works on Arduino, you are ready to deploy it on your AtTiny85

Moving to AtTiny85

Programming an AtTiny with an Arduno can be tricky, but fear not! I made a very simple tutorial on how to do that with the latest Arduino IDE and Arduino Uno/diecimila or Arduino Leonardo/Yun. Just follow these steps, and you can easily use this sketch on the AtTiny85

Testing the AtTiny85 based circuit

image

image

Now we can move the programmed AtTiny on a new breadboard, following this scheme

There is no resistor on the LED because I’m using a 3.3V coin battery. The circuit should start working as soon as you plug the battry: when the tilt sensor is shook, the LED fades 🙂

Making the circuit

image

Now that everything is tested, we can make the circuit. I decided to use a stripboard because even if it’s a little big, the result will be more stable and short circuit proof. Start placing the components on the stripboard and soldering them, the circuit is supersimple so this should be a very easy task.

I’ve put the LEDs in parallel, I know that I should have used a small resistor, but I was more focused on the simplicity of the project than on its life expectation, plus, it will be powered by a 3.3V battery, so I didn’t really care about it 🙂

The only precaution was to put some tape on the led wires to avoid short circuits.

Now you can test the circuit alone. If everything is fine, you can move to the next step

The doll surgery

image

With the cutter, remove some stitches from the doll and remove the head’s stuffing. Than drill the holes on the eyes. I used a Dremel for this task, but you can even use the cutter. Now insert the circuit, starting from the eyes. When the led pupils are in the holes, pour a lot of hot glue from the inside of the head, so you will be sure that the LEDs will stay at their place. Then put some more stuffing, the circuit, some more stuffing, the tilt sensor and the rest of the stuffing. In this way you are sure that everything won’t accidentally move and you will reduce the risk of short circuits to the minimum.

I suggest to use some velcro or a couple of buttons to close back the doll, so you can change the battery whanever you want

You’re done!

image

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

Intel Galileo: Getting Started with Mac OS X

A step-by-step tutorial by jeko

IMPORTANT: Connect your intel Galileo to the 5V power supply before any other connection or you will damage the board.

During the Rome Maker Faire, I was lucky to get an Intel Galileo. But when I had to use it, it was suddenly clear that it’s not as straightforward as Arduino. I had to resort to desperate measures and do something that really only a very restricted class of noble people do, I had to read the manual.

image

The getting started guide by Intel really helped, but the problem is that it’s clearly written by engineers, while the Galileo board wants to attract makers, designers, artists and many people that are used to the “tutorial” or “step by step” approach and are not really into manual reading.

I used to be an RTFM fanatic, but I’m getting old, and I have learned to appreciate when people help me, so I’m very happy to contribute and give some help to those in need.

So. You have an Intel Galileo board, a Mac (I assume you have Mac OS X Mavericks installed), and you want to run the very first basic example: the “Blink” sketch from the Arduino examples. Right?

image

This is what you have to do, straight and easy.

So, let’s start:

  1. Download the Galileo software from the Intel website. If you already have the Arduino IDE, don’t overwrite it. Even if the Intel software is based on the Arduino IDE, it is not 100% identical, and it will only manage the Galileo board, so if you want to use them both, simply unzip the Intel software, rename it into “Galileo”, and move it into your Application folder. Don’t rename it into something with spaces, and do not put it into folders with a space in their name, because it won’t work.
  2. Plug the 5V adapter, wait 10 seconds and then connect the USB client (the little usb port next to the ethernet plug) to your Mac’s USB port
  3. You have to wait a minute: it takes a little while for the USB stack to start on the Galileo board, then you can start the Galileo IDE
  4. Go to Tools > Port menu and select the /dev/cuXXX serial port. If you don’t see the port, close the IDE, wait a minute, and open it again.
  5. Now, you have to update the Galileo’s firmware, so, go on Help > Firmware Upgrade. If everything is ok, you should see a message asking for confirmation if the 5V power cable is plugged in. Since you have followed these instructions, it should be, so click yes, do the same on the next dialog and the process should begin. It will take 5-6 minutes. During the process, avoid touching the cables or the board or the IDE. Just sit down and relax.
  6. When the process is complete, the “Target Firmware upgraded successfully.” message is displayed. Click OK to close the message.
  7. Now choose the blink example from File > Examples > 01.Basics > Blink

Upload the blink sketch and you’re done! It’s time to celebrate! 🙂

Jeko

P.S. The Quark processor can become very hot, don’t worry it’s normal.

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