Chapter 4
Flash an LED in Response to a Twitter Event

You’ve created your Twitter bot with Node. If you’ve set it up on your Raspberry Pi, you can hook up an LED and make it flash when an event happens on Twitter.

In this chapter, you’ll wire up an LED on a breadboard hooked in to your Pi. Next, you’ll write a short program that will make the LED blink twice. Finally, you’ll add this code to your Twitter bot program so that each time your bot’s Twitter handle is mentioned, the LED will alert you by blinking (Figure 4-1).

c04f001.tif

Figure 4-1: Blinking LED

Set Up the LED on Your Raspberry Pi

The setup, shown in Figure 4-2, is fairly simple.

Here’s what you’ll need:

  • Raspberry Pi with 5V power supply
  • Breadboard
  • 2 male-to-female jumper cables (the example uses black and green)
  • An LED

Step 1. Locate the GPIO pins on your Pi (Figure 4-3).

c04f002.tif

Figure 4-2: Complete LED setup on Raspberry Pi

c04f003.tif

Figure 4-3: Close-up of GPIO pins

Step 2. Connect the female end of the green jumper cable to pin 4 of the GPIO on the Pi, as shown in both Figures 4-1 and 4-2.

Step 3. Connect the female end of the black jumper cable to pin 3 of the GPIO.

Step 4. Take a look at your LED. One leg is longer than the other. The longer leg is the plus side, and the shorter leg is the minus terminal. This is important to keep track of.

Step 5. Insert your LED into the breadboard as shown in Figure 4-2. Make sure the plus side of the LED is on the right.

Step 6. Connect the male end of the black cable to the breadboard adjacent to the minus terminal of the LED. If any of this is confusing, just take a close look at Figure 4-2.

Step 7. Connect the male end of the green cable to the breadboard adjacent to the plus terminal of the LED.

Your Pi will now be able to blink the LED in response to the code you’re about to write!

Create the Blink Program

Open your terminal and connect to your Pi. Navigate to the directory where you created your Twitter bot files.

pi@raspberrypi:~ $ cd newtwitbot
pi@raspberrypi:~/newtwitbot $

Remember using npm to install the Twitter code library called twit? We’re going to use npm again, this time to import another library called onoff that lets us control the LED.

To install this library, use this command:

pi@raspberrypi:~/newtwitbot $ npm install --save onoff

After onoff has finished installing, create and open a new file, helloBlink.js.

pi@raspberrypi:~/newtwitbot $ nano helloBlink.js

This opens the editor with a new blank file. Here’s the code to enter:

//helloBlink.js
var Gpio = require('onoff').Gpio, 
  led = new Gpio(4, 'out');
var iv = setInterval(function () { 
  led.writeSync(led.readSync() === 0 ? 1 : 0)
}, 500);
// Toggle state of the LED every half second
setTimeout(function () {
  clearInterval(iv); 
  led.writeSync(0); 
  // Turn LED off 
  led.unexport();
}, 2000); 
// End blinking after 2 seconds

Save this file.

Now give it a try with the node command:

pi@raspberrypi:~/newtwitbot $ node helloBlink.js

Make Your Bot Detect Your Twitter Handle

Before your bot can blink in response to your Twitter handle being tweeted, it needs to be able to detect when that happens. In this section, we’ll add some code that will tweet a greeting back to anyone who tweets your handle.

In the last chapter, you created a Twitter bot in a program called index.js. Open index.js (or whatever you named your file) in an editor. We’ll add this new code to the end of the current file. Make sure you change @doggothebotto to whatever you named your bot!

//Respond when someone mentions me, @doggothebotto
var stream = Twitter.stream('statuses/filter', 
{ track: ['@doggothebotto'] }); 
//Look for my @name 
stream.on('tweet', tweetEvent);
function tweetEvent(tweet) {
  // Get Twitter handle of who tweeted me
  var name = tweet.user.screen_name; 
  // Now send a reply back to the sender
  var reply='You mentioned me! @' + name + ' ' + 'Bork bork!';
  var params = {
    status: reply, in_reply_to_status_id: nameID
  };
  Twitter.post('statuses/update', params, 
  function(err, data,response) {
    if (err !== undefined) {
      //Report error if response tweet fails
      console.log(err); 
    } else {
      //Report success
      console.log('Tweeted: ' + params.status); 
    }
  })
};

Basically, this code listens for your bot’s Twitter handle. When it detects your handle, it grabs the handle of the sender. Then it creates a reply that includes the sender’s handle, and tweets it. In our example, if someone—let’s call her @lynnbeighley—were to tweet anything containing my bot’s name, @doggothebotto, the bot will respond with You mentioned me! @lynnbeighley Bork bork!.

Make Your Bot Blink the LED When Mentioned

The last step is to add in the code you used in the helloBlink.js program at the correct point in your bot program. You can copy and paste it immediately after this line:

console.log('Tweeted: ' + params.status);

The complete block of code we added to the end of your bot code in this chapter is

//Respond when someone mentions me, @doggothebotto
var stream = Twitter.stream('statuses/filter', 
{ track: ['@doggothebotto'] }); 
//Look for my @name 
stream.on('tweet', tweetEvent);
function tweetEvent(tweet) {
  // Get Twitter handle of who tweeted me
  var name = tweet.user.screen_name; 
  // Now send a reply back to the sender
  var reply='You mentioned me! @' + name + ' ' + 'Bork bork!';
  var params = {
    status: reply, in_reply_to_status_id: nameID
  };
  Twitter.post('statuses/update', params, 
  function(err, data,response) {
    if (err !== undefined) {
      //Report error if response tweet fails
      console.log(err); 
    } else {
      //Report success
      console.log('Tweeted: ' + params.status); 
var Gpio = require('onoff').Gpio, 
  led = new Gpio(4, 'out');
var iv = setInterval(function () { 
  led.writeSync(led.readSync() === 0 ? 1 : 0)
}, 500);
// Toggle state of the LED every half second
setTimeout(function () {
  clearInterval(iv); 
  led.writeSync(0); 
  // Turn LED off 
  led.unexport();
}, 2000); 
// End blinking after 2 seconds
    }
  })
};

You’ve now got a bot that not only responds when someone tweets at it, but also blinks an LED to let you know! Using similar techniques, you could monitor Twitter for more practical search terms—for example, the words tsunami and earthquake.

Node, Pi, and the Internet of Things

You’ve now had a jumpstart into JavaScript with Node and Raspberry Pi. You can control real-world devices and interact with the Internet. Blinking an LED is just a small taste of what you can directly control with your Raspberry Pi. Now that you can do that, you can connect and control other, more interesting electronic devices.

For example, you could attach a temperature sensor and periodically post environmental readings to a web page. Or you could use a motion sensor and set up an alert to catch your cat jumping up on your counter at night.

Now it’s up to you to dream up and build your own JavaScript/Node/Pi projects!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset