MaKey MaKey Guitar Hero

Deze week dus een MaKey MaKey gekocht! In een opwelling. En als excuus dat het ook wel leuk voor de kinderen zou zijn. Het is Tof Speelgoed, maar ik was er na twee dagen al achter dat ik me zelf toch liever met het écht programmeren van een "standaard" Arduino bezig houd. En mijn kinderen vonden het, bij het geluid van een bongo wanneer ik op hun neus drukte, na de derde keer al saai. Jammer, want juist ik had daarbij de grootste lol.

Vandaag heb me dus maar op een wat uitgebreider knutselprojectje gestort: het maken van een Guitar Hero controller. Hier volgt een stap voor stap fotoverslag.

Lees verder MaKey MaKey Guitar Hero

Share Button

Twitmaslights: gebruik een Arduino Yún om de kleur een led strip via Twitter te veranderen

English version

Nadat het me gelukt was om een led strip met een Arduino Uno en een Wifi schield via Twitter te besturen, wilde ik ook een webcam toevoegen, zodat de Arduino met een foto van de lampjes met de nieuwe kleur terug kan tweeten. Voor dat doel heb ik een  Arduino Yún gekocht.  Net als de andere Arduino's heeft deze ook een ATmega processor. Maar het speciale van de  Yún is that deze ook over een Atheros AR9331 processor beschikt. En daar draait Linux op! Dit bord heeft onder andere wifi, een USB-A poort, een micro-SD kaart slot, digitale input/output pins en een micro USB aansluitiing, die ik allemaal voor dit project nodig heb.

Wat het doet

Elke 30 seconden wordt op Twitter gezocht naar de meest recente openbare tweet met de hashtag #twitmaslights, gevolgd door een dubbele punt en een kleur. Deze kleur kan in hexadecimale notatie zijn gegeven of als een van de 140 officiële html kleurnamen. Wanneer er een tweet wordt gevonden, wordt de tekst na "#twitmaslights:" geparsed en gecontroleerd op een geldige kleurcode of kleurnaam. Als dat lukt, veranderen de kleuren van de led strip en neemt de camera een foto. Die foto wordt aan een reply toegevoegd van @twitmaslights, aan degene die de #twitmaslights tweet verstuurde. Op die manier ben ik tenminste niet de enige die van de kerstverlichting in mijn woonkamer kan genieten. 🙂

Twitmaslights gear

Hoe het werkt - of eigenlijk: hoe het dat niet doet

Het heeft een tijdje geduurd voordat ik doorhad hoe de twee "kanten" - de ATmega (Arduino) en de Atheros (Linux) - moesten worden gebruikt om met elkaar te communiceren. Met de Bridge library kun je dat op verschillende manieren doen, maar hoe, wat, waar, wanneer en waarom was me in het begin niet zo duidelijk.

In eerste instantie gebruikte ik de ATmega om al het zware werk te verrichten, inclusief het zoeken naar tweets, parsen, controleren op geldige kleurcodes en het tweeten van updates. Omdat er hierbij veel bewerkingen met strings (tekst) nodig zijn, bleek de kleine hoeveelheid RAM geheugen (slechts 2,5 KB!) van de Arduino microcontroller al snel niet toereikend te zijn. En ik had op dat moment de camera nog niet eens aangesloten!

Ik maakte ook gebruik van Temboo, een erg slimme en gemakkelijke manier om een Yún te verbinden met verschillende online services (Twitter, Facebook, Google+, Paypal, Instagram, FourSquare... noem maar op!) Hier was ik erg van onder de indruk, totdat ik er achter kwam dat een gebruiker maar een beperkte hoeveelheid (1000 per maand) api verzoeken krijgt. Als je meer wilt, moet je betalen voor een uitgebreid plan. Een ander nadeel van Temboo is het geheugengebruik: in mijn geval snoept het nog eens minstens 10% van het programmeerbaar geheugen af en vertoont onvoorspelbaar gedrag als er nog maar weinig RAM aan de Arduino kant overblijft. Aan de andere kant verdient Temboo wel een groot compliment voor hun support: ze namen zelf het initiatief om contact met me op te nemen toen ze merkten dat ik problemen had met het versturen van tweets vanaf de Yún.

Twitmaslights: purple

Hoe het uiteindelijk wel werkt

Ik bedacht me toen (waarom had ik dat niet eerder gedaan?!) dat ik de Linux kant van de Yún moest gebruiken om al het zware werk te verrichten. Je kunt je eigen Python scripts schrijven, ze op een micro SD kaart opslaan en ze uitvoeren vanaf de Arduino kant. Ook is het eenvoudig om gegevens van de ene naar de andere kant te sturen. Als je eenmaal doorhebt hoe dat werkt, snapt hoe je extra Python modules op de juiste manier kunt installeren, deze methode gebruikt om Twython te installeren en deze aanwijzingen gebruikt om een webcam aan de praat te krijgen, wordt het tweeten van een foto zelfs eenvoudiger en krachtiger dan wanneer je dat met Temboo had gedaan!

 

Share Button

Twitmaslights: use an Arduino Yún to control colored led lights with Twitter

Nederlandstalige versie

After I successfully managed to control a LED strip via Twitter with an Arduino Uno and a Wifi Shield, I wanted to add a webcam, so the Arduino could reply with a picture of the newly colored lights. For this purpose, I bought an Arduino Yún. Like other Arduino devices it has an ATmega processor. But the the thing that is special about the Yún is that it also has an Atheros AR9331 processor, which supports Linux! And among other features, the board has wifi, a USB-A port, a micro-SD card slot, digital input/output pins and a micro USB connection, all of which I need for this project.

What it does

Every 30 seconds, Twitter is searched for the latest public tweet which contains the hashtag "#twitmaslights:", followed by a color. This color can be given in hexadecimal notation, or as one of the 140 official html color names. When a new tweet is encountered, the text after "#twitmaslights:" is parsed and checked for a valid color code or name. When this succeeds, the colors of the LED strip change and the webcam takes a picture. This picture is added to a reply from @twitmaslights to whoever posted the #twitmaslights tweet, so at least I'm not the only one who gets some satisfaction from the Christmas lights in my living room 🙂

Twitmaslights gear

How it works - or rather: how it doesn't

It took me some time to understand the way the two "sides" - the ATmega (Arduino) and the Atheros (Linux) - had to be used to communicate. The Bridge library offers various methods to do this, but what, where, how, when and why wasn't very clear to me in the beginning.

At first, I used the ATmega to do all the heavy work, including searching for tweets, parsing, checking for valid color codes and tweeting updates. Because there are many string (text) operations involved with this, the little RAM memory (only 2.5 KB!) of the Arduino microcontroller soon turned out not to be enough. And that was at the point I didn't even connect the camera yet!

I also used Temboo, which offers a very inventive and easy way to connect a Yún to many different online services (Twitter, Facebook, Google+, Paypal, Instagram, FourSquare... you name it!) I was very impressed with this, until I found out that a user has only a limited amount (1000 a month) of api requests. If you want more, you'll have to pay for an extended plan. Another drawback of Temboo is its memory usage. In my case it ate up at least another 10% of program memory and showed unpredictive behaviour when I ran out of RAM on the Arduino side. On the other hand, a big pro for Temboo is their support: they actively took the initiative to contact me when they noticed I was having trouble sending tweets from the Yún.

Twitmaslights: purple

How to really get it to work

I figured out (why hadn't I done that before?!) that I had to use Linux side of the Yún to do all the heavy work. You can write your own Python scripts, save them on a micro SD card and call them from the Arduino side. It's also easy to send data from one side to another. If you know how this works, know how to install additional Python modules the right way, use that method to install Twython and use this guide to succesfully connect a webcam, tweeting an image even becomes easier and more powerful than using Temboo!


 

Share Button

How to control a LED strip with Twitter

Several months after my Twitterdoorbell adventures I decided it was time for a new (not so) useful Arduino project. After I bought 5 meters of RGB LED strip ("IClite Digital RGB-LED Flex Band") at the Aldi in Germany and successfully connected this to an Arduino Uno, I knew it's destiny was to hang in my christmas tree in December to act as Twitter controlled christmas lights.

Usage

To change the color of the LED strip, a twitter user has to send a tweet with hashtag #twitmaslights, followed by a colon (:) and a six digit hexadecimal number (red-green-blue). For example: #twitmaslights:ff0000 would make the LEDs turn red.

Connecting the RGB strip to an Arduino Uno

(Source: http://www.tns-labs.org/iclite-digital-rgb-led-flex-band-aldi-arduino/ [German])

Because the Aldi LED strip doesn't work with the AdaFruit Neopixel library out of the box, I needed to use this modified library.

The Aldi LED strip comes with a 12V power supply which connects to a controller. This is a little white box which has 4 outputs: V (VCC), G (ground), another G (ground) and D (data), which all connect to the four corresponding inputs (called VCC, GND, GND and DI) on the LED strip.

To use the Arduino instead of the supplied one as a controller, you have to connect it in the folowing way:

  • The DI connection on the LED strip goes to pin 6 on the Arduino.
  • The GND connection next to DI on the LED strip goes to GND on the Arduino.
  • Because the Arduino Uno can only supply 5V, you have to leave the VCC and the GND next to it connected to the original controller.

Hopefully the following picture makes this a bit clearer. (Notice that this is an Arduino Uno with a WiFi shield on top of it.)

IMG_20131028_213604

To test the LED strip, just use the "Strandtest" example that comes with the Neopixel library.

Checking Twitter for a specific hastag

Been there, done that! But to ensure that you stay on the current page, I will explain it again 🙂

Using the Twitter API to search for specific tweets used to be a simple matter of an http GET request which you could paste in the url field of your browser. But nowadays you must use 0auth to connect to the API and use something called Apllication-only authentication. The drawback of this method is that you have to connect to the Twitter servers through SSL. Unfortunately, an Arduino Uno is too slow and does not have enough resources to be capable of this task.

I came up with the following solution: I created a PHP script on my own web server which makes the request to search for a specific tweet. Then the PHP script parses the JSON response from Twitter and outputs the search result on a web page: twitmaslights.crutzen.eu. The only thing the Arduino does is connecting to this page and read the output: the tweet which was searched for.

This is the PHP script:

 "",
    'oauth_access_token_secret' => "",
    'consumer_key' => "",
    'consumer_secret' => ""
);

/** Perform a GET request and echo the response **/
/** Note: Set the GET field BEFORE calling buildOauth(); **/
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = '?q=%23twitmaslights&count=1&include_entities=false';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$json = $twitter->setGetfield($getfield)
             ->buildOauth($url, $requestMethod)
             ->performRequest();
//echo $json;
$obj = json_decode($json, true);
$tweet = $obj["statuses"][0]["text"];
echo "Tweet: $tweet
"; $user = $obj["statuses"][0]["user"]["screen_name"]; echo "User: @$user"; ?>

This script outputs the most recent tweet with hashtag #twitmaslights betweet <tweet> tags and the user who sent the tweet between <user> tags. It uses the TwitterApiExchange class, which you can find here.

So, for example, the page on my web server outputs the following

Change color to red! #twitmaslights:FF0000
@RalpCrutzen

Now it's the Arduino's task to connect to twitmaslights.crutzen.eu, look for the text between the <tweet> and <user> tags, filter the hex color code from the tweet and change the color of the LED lights accordingly.

The Arduino part

As mentioned before, I use an Arduino Uno with a WiFi shield. I had issues connecting to a server with version 1.0.5 of the Arduino IDE. But using IDE 1.0.3 instead solved this problem.

I'm going to explain the sketch piece by piece. If you want to download the sketch as a whole, you can do this here.

/*
 Twitmaslights
 
 Control an Adafruit NeoPixel strip via Twitter.
 
 created 27 October 2013
 by Ralph Crutzen for the @twitmaslights project
*/

#include 
#include 
#include 
#include 

First, we include the necessary libraries. TextFinder is used to search for a specific string in a stream. You can download it here. The AdaFruit NeoPixel library can be found here. If you, just like me, use the German Aldi LED strips, you have to use this library. Put the downloaded folders in the sketchbook/libraries folder.

#define PIN 6

// Parameter 1 = number of pixels in strip
// Parameter 2 = pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(49, PIN, NEO_GRB + NEO_KHZ800);

The last line is the declaration of the strip object. The first parameter of the constructor is the number of LEDs in the strip. (Because I messed up my own strip a little, I had to cut out a piece and now I only have 49 lights left.) The second parameter is the pin number (6) to which the strip's DI input is connected to.

char ssid[] = ""; //  your network SSID (name)
char pass[] = "";    // your network password (use for WPA, or use as key for WEP)

int status = WL_IDLE_STATUS;
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "twitmaslights.crutzen.eu";

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
WiFiClient client;

These variable declarations are used to make a connection with the WiFi shield. I copied the most of the code that handles the WiFi part from the WifiWebClient example on the official Arduino website.

char tweet[141] = "", oldTweet[141] = "";
char user[141];
String hashtag = "#twitmaslights:";
char color[7];

I think that most of the above variables are self-explanatory. oldTweet is used to check if the detected tweet is a new one.

void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
 
  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue:
    while(true);
  }
 
  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:    
    status = WiFi.begin(ssid, pass);
 
    // wait 10 seconds for connection:
    delay(10000);
  }
  Serial.println("Connected to wifi");
  printWifiStatus();
}

The setup() routine initializes the LED strip, the serial window (used for some debugging info) and connects to the Wifi network. The WiFi part is from the WifiWebClient example again. The printWifiStatus function puts some info about the connection in the serial window.

void loop() {
  int i;
  TextFinder finder(client);
  
  Serial.println("\nStarting connection to server...");
  
  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected to server");
    // Make a HTTP request:
    client.println("GET /index.php HTTP/1.1");
    client.print("Host: ");
    client.println(server);
    client.println("User-Agent: Arduino/1.0");
    client.println("Connection: close");
    client.println();
  }  

The loop() routine starts with connecting to the webserver and then makes a http request for index.php: the file that returns the tweet and user.

  // if there are incoming bytes available
  // from the server, look for the right tags:
  while (client.connected()) {
    if (client.available()) {
      if ( (finder.getString("", "", tweet, 141) != 0) &&
           (finder.getString("", "",   user,  141) != 0) ) {
        for (i = 0; i < 141; i++)
          if (oldTweet[i] != tweet[i])
            break;
        if (i != 141) {
          //Serial.println(tweet);
          foundTweet(tweet, user);
          for (i = 0; i < 141; i++)
            oldTweet[i] = tweet[i];
          break;
        }
        else {
          Serial.println("No new tweets :-(");
        }
      }
    }
  }

After that comes one the fun parts: look for text between <tweet> and <user> tags. If found, check if the tweet is not the same as the previous one (oldTweet). If it's a new tweet, call the function foundTweet, which handles the color code parsing.

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println("Disconnecting from server.");
    client.flush();
    client.stop();
  }
  
  // wait to reconnect
  Serial.println("Wait...");
  delay (30000); // Max. 30000
}

The loop() routine ends with disconnecting from the server and waiting for 30 seconds to make a new request. These 30 seconds matter, because Twitter won't be amused when you make too much requests and word goes around you even can get banned for connecting too often...

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

This function is used by the setup() routine to give you some info about the established WiFi connection. Again, this code is from WifiWebClient example.

void foundTweet(char* tweet, char* user) {
  int i;

  Serial.println("New tweet!");
  Serial.print("Tweet: ");
  Serial.println(tweet);
  Serial.print("From: ");
  Serial.println(user);

  String sTweet(tweet);
  int iBeginHashtag = sTweet.indexOf(hashtag);
  if (iBeginHashtag == -1) {
    Serial.println("Hashtag not found or without colon");
  }
  else {
    // Get color code from tweet
    sTweet.substring(iBeginHashtag + hashtag.length()).toCharArray(color,7);
    Serial.println(color);
    for (i=0; i<6; i++)
      if (((color[i] < 'A') || (color[i] > 'F')) &&
          ((color[i] < 'a') || (color[i] > 'f')) &&
          ((color[i] < '0') || (color[i] > '9')))
        break;
    if (i == 6) {
      char red[] = {color[0],color[1]};
      char green[] = {color[2],color[3]};
      char blue[] = {color[4],color[5]};
      byte r = hexToByte(red);
      byte g = hexToByte(green);
      byte b = hexToByte(blue);
      if (b == 255) b = 254; // Fixes bug in (modified for Aldi) AdaFruit_Neopixel library
      for(uint16_t i=0; i

The foundTweet() function is my favorite part of the sketch! It checks for the hashtag #twitmaslights, followed by a colon (:) and six hexadecimal digits. These digits are then stored in a character array and each of the three pairs (which represent red, green and blue) are converted to a numeric values with the hexToByte() function - see below. These numeric values are used as parameters in the strip.SetPixelColor() function, which turns the lights on.

byte hexToByte(char hexString[]) {
  
  // https://github.com/benrugg/Arduino-Hex-Decimal-Conversion
  
  byte decValue = 0;
  char nextChar;
  
  for (int i = 0; i < 2; i++) {
    
    nextChar = char(hexString[i]);
    if (nextChar >= 48 && nextChar <= 57) nextChar = map(nextChar, 48, 57, 0, 9);
    if (nextChar >= 65 && nextChar <= 70) nextChar = map(nextChar, 65, 70, 10, 15);
    if (nextChar >= 97 && nextChar <= 102) nextChar = map(nextChar, 97, 102, 10, 15);
    nextChar = constrain(nextChar, 0, 15);
    
    decValue = (decValue * 16) + nextChar
  }
  
  return decValue;
}

So what's next?

First of all, I could think of some improvements:

  • Not everyone knows what hexadecimal numbers and html color codes are, so I could also make the Arduino search for #twitmaslights followed by the official names of some of the most used html colors.
  • By polling my server only once in 30 seconds and only using the color in the most recent tweet, it could happen that some tweets don't get handled. Polling Twitter more often than once in 30 seconds could result in a ban. So I have to change the sketch so that every tweet is put in a queue. But because I don't expect that my Twitmaslights will be that popular, this doesn't really have a high priority.
  • How cool would it be to connect a photo camera to the Arduino and tweet a picture of the lights back to the person who requested a new color? The Arduino Uno can't handle processing the camera image, so I ordered an Arduino Yún. I expect the final result with the camera to be really cool, so stay tuned to my blog and twitter account if you want to know how I'm going to make that work!

Final words

I really hope that you found my explanation clear and useful. Feel free to ask anything, but please be patient when you wait for an answer...

Share Button

How to hack a doorbell and connect it to Twitter - Part 7: Adding it all together

After combining the sender, receiver and both Twitter sketches (and making some adjustments), I now present to you... the final result.

IMG_20130718_142140

The following sketch

  • checks for tweets with a specific hashtag every 40 seconds. When it finds one, it makes the doorbell ring and posts the screen name of the tweep as a new tweet;
  • posts a tweet when someone pushes the doorbell button.

To avoid posting a duplicate tweet (which isn't allowed by Twitter), the program appends a timestamp to each tweet.

Lees verder How to hack a doorbell and connect it to Twitter - Part 7: Adding it all together

Share Button