Make it tweet

193
http://www.instructables.com/id/Make-it-Tweet/ Introduction "Make it Tweet" gives you the complete step-by-step instructions for 13 different projects that will have you Twittering from your favorite appliance in no time. Build a Twittering coffee pot, a Tweet-a-Watt, a twittering garden bed and much more! All projects come from Instructables.com, are written by our creative community, and contain pictures for each step so you can easily make these yourself. Instructables is the most popular project-sharing community on the Internet. We provide easy publishing tools to enable passionate, creative people like you to share their most innovative projects, recipes, skills, and ideas. Instructables has over 40,000 projects covering all subjects, including crafts, art, electronics, kids, home improvement, pets, outdoors, reuse, bikes, cars, robotics, food, decorating, woodworking, costuming, games, and more. Check it out today! Laura Khalil Editor, Instructables.com

Transcript of Make it tweet

Page 1: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Introduction"Make it Tweet" gives you the complete step-by-step instructions for 13 different projects that will have you Twittering from your favorite appliance in no time. Build aTwittering coffee pot, a Tweet-a-Watt, a twittering garden bed and much more! All projects come from Instructables.com, are written by our creative community, andcontain pictures for each step so you can easily make these yourself.

Instructables is the most popular project-sharing community on the Internet. We provide easy publishing tools to enable passionate, creative people like you to sharetheir most innovative projects, recipes, skills, and ideas. Instructables has over 40,000 projects covering all subjects, including crafts, art, electronics, kids, homeimprovement, pets, outdoors, reuse, bikes, cars, robotics, food, decorating, woodworking, costuming, games, and more. Check it out today!

Laura KhalilEditor, Instructables.com 

Page 2: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Table of Contents

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Author and Copyright Notices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

Tweet-a-watt - How to make a twittering power meter... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

Intro:   Tweet-a-watt - How to make a twittering power meter... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

Step 1:   Make it! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

Step 2:   Prep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

Step 3:   Make the Receiver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

Step 4:   Configure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

Step 5:   Solder the Transmitter - parts list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

Step 6:   Transmitter Schematic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

Step 7:   Assemble and create the transmitter - 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

Step 8:   Assemble and create the transmitter - 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

Step 9:   Assemble and create the transmitter - 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

Step 10:   Assemble and create the transmitter - 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

Step 11:   Assemble and create the transmitter - 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

Step 12:   Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

Step 13:   Expand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

Step 14:   Design - overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

Step 15:   Design - listen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

Step 16:   Design - store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

Step 17:   Design - graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

Step 18:   Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

Step 19:   Download . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

Related Instructables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

Tweet-a-Pot: Twitter Enabled Coffee Pot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

Intro:   Tweet-a-Pot: Twitter Enabled Coffee Pot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

Step 1:   Supplies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

Step 2:   Setting Up Your Computer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

Step 3:   Setting up Twitter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

Step 4:   The Code: Python Side . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

File Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

Step 5:   The Code: Arduino Side . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

File Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

Step 6:   Hardware Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

Step 7:   Make Some Coffee . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

Step 8:   Final Thoughts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

Related Instructables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

The Twittering Office Chair . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

Intro:   The Twittering Office Chair . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

Step 1:   Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

Page 3: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 2:   Go get stuff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

Step 3:   Make a sensor mount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

File Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

Step 4:   Attach the sensor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

Step 5:   Plug it in . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

Step 6:   Program the Squidbee . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

File Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

Step 7:   Connect to the computer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

Step 8:   Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

Step 9:   Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

Step 10:   Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

File Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

Step 11:   Disassemble the chair . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

Step 12:   Undo the upholstery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

Step 13:   Modify the cushion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

Step 14:   Insert the sensor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

Step 15:   Reassemble . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

Step 16:   Bottoms up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

Step 17:   Turn it on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

Step 18:   Run the code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

File Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

Step 19:   Tweet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

Related Instructables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

Arduino sprinkler valves + wifi + twitter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

Intro:   Arduino sprinkler valves + wifi + twitter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

Step 1:   The water part. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

Step 2:   Arduino + Ethernet shield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

Step 3:   Schematics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

Step 4:   Relay board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

Step 5:   Manual control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

Step 6:   Connectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

Step 7:   Arduino sketch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

File Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

Step 8:   Web interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

Step 9:   Wireless + scripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

Step 10:   Voila. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

Step 11:   Twitter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87

File Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87

Related Instructables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87

Garduino Upgrade, Now with more Twitter! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

Intro:   Garduino Upgrade, Now with more Twitter! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

Page 4: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 1:   Gather your materials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

Step 2:   Build your Garduino . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89

Step 3:   Upgrade #1: Remote Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89

File Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

Step 4:   Update #2: Relay Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

Step 5:   Upgrade #3: New Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

File Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93

Step 6:   Upgrade #4: Wireless Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93

Step 7:   Update #5: Twitter your Garden . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

Step 8:   Useful project notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

Related Instructables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96

The Smuggie: Tweet straight from your Snuggie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97

Intro:   The Smuggie: Tweet straight from your Snuggie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97

Step 1:   Writing the Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98

File Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98

Step 2:   Twitter Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98

Step 3:   Cut the Fabric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

Step 4:   Cut the Foam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100

Step 5:   Cut some holes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100

Step 6:   Prepare the wire . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101

Step 7:   Tape the leads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101

Step 8:   Tape the switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101

Step 9:   Sew the switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

Step 10:   Attach the switch to the Snuggie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

Step 11:   Hook the Smuggie up to our Arduino. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

Step 12:   Prepare to Smuggie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103

Related Instructables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104

Twitter Mood Light - The World's Mood in a Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105

Intro:   Twitter Mood Light - The World's Mood in a Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105

Step 1:   How it works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106

Step 2:   All you need is... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

Step 3:   Connect the Arduino and WiFly to a computer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

Step 4:   Connecting the LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

Step 5:   Choosing good search terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

Step 6:   Download the code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113

File Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

Step 7:   Programming step 1: SPI UART . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116

Step 8:   Programming step 2: Connecting to a Wireless Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

Step 9:   Programming step 3: Searching Twitter with TCP/IP port 80 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

Step 10:   Programming step 4: RGB LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

Step 11:   Programming 5: Computing the World Mood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122

Step 12:   Building the Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

Page 5: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 13:   Enjoy! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

Related Instructables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127

Twitter Controlled Light-Bot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128

Intro:   Twitter Controlled Light-Bot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128

Step 1:   Make the circuit! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129

Step 2:   Setup the Arduino Software! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129

File Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129

Step 3:   Setup the Twitterrific Software! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

Step 4:   Setup the AppleScript Editor Software! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

File Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131

Step 5:   GO! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131

Step 6:   UPDATE!!! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132

File Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132

Related Instructables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132

@tweet_tree: Twitter controlled Christmas tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133

Intro:   @tweet_tree: Twitter controlled Christmas tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133

Step 1:   Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133

Step 2:   Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134

Step 3:   Firmware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135

Step 4:   Get one . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135

Related Instructables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136

Twittering Laser Tripwire with Webcam Capture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137

Intro:   Twittering Laser Tripwire with Webcam Capture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137

File Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

Step 1:   Connecting The LDR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

Step 2:   Connecting the Laser Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141

Step 3:   Everything in place . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142

Step 4:   Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143

Step 5:   Using open() in processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144

Step 6:   Now run it. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145

Related Instructables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146

Twitter Watcher, the #twatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

Intro:   Twitter Watcher, the #twatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

Step 1:   Using it . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149

Step 2:   Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149

Step 3:   PCB and partlist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152

Step 4:   Firmware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152

Step 5:   Bootloader for network firmware upgrades . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154

Step 6:   Taking it further, get your own . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155

Related Instructables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156

Twitter scrolling picture frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157

Intro:   Twitter scrolling picture frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157

Page 6: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 1:   Cut a holder to fit the frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158

Step 2:   Move the stand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159

Step 3:   Scroll Twitter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159

Related Instructables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159

Give Your Cat Twitter Powers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160

Intro:   Give Your Cat Twitter Powers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160

Step 1:   Theory / Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161

Step 2:   Build a cat sensor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162

Step 3:   Connect your cat sensor to Arduino, and Arduino to your PC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162

Step 4:   Set up Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163

Step 5:   Detect switch state in Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164

Step 6:   Send a Twitter update . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164

Step 7:   Capture an image when the cat gets into bed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164

Step 8:   Upload the image via FTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164

Step 9:   Putting it all together. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165

File Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165

Related Instructables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165

Enormous led Mood light . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166

Intro:   Enormous led Mood light . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166

Step 1:   Gather Your Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167

Step 2:   Gather Your Materials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168

Step 3:   Make the led lanterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170

Step 4:   Constructing the Cube . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173

Step 5:   Time for the wiring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174

Step 6:   Building the Circuit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175

Step 7:   Wiring the Arduino . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176

Step 8:   Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177

Related Instructables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181

LED wind indicator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182

Intro:   LED wind indicator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182

Step 1:   What do you need . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183

Step 2:   The circuit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183

Step 3:   Programming the microcontroller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185

File Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185

Step 4:   Getting the required data to the device. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186

File Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187

Related Instructables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187

Simple LED flowers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188

Intro:   Simple LED flowers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188

Step 1:   Prep packaging peanut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189

Step 2:   Hollow out peanut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189

Page 7: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 3:   Insert LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189

Step 4:   Poke holes for lace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190

Step 5:   Cut desired lace "petals" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190

Step 6:   Weave Lace in place . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190

Step 7:   Hot glue petals and pistils . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191

Step 8:   Insert battery and magnet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192

Related Instructables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192

Page 8: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Author and Copyright NoticesInstructable: Tweet-a-watt - How to make a twittering power meter...Author: adafruitLicense: Attribution-NonCommercial-ShareAlike (by-nc-sa)

Instructable: Tweet-a-Pot: Twitter Enabled Coffee PotAuthor: frenzyLicense: Attribution-NonCommercial-ShareAlike (by-nc-sa)

Instructable: The Twittering Office ChairAuthor: randofoLicense: Attribution-NonCommercial-ShareAlike (by-nc-sa)

Instructable: Arduino sprinkler valves + wifi + twitterAuthor: nicooLicense: Attribution-NonCommercial-ShareAlike (by-nc-sa)

Instructable: Garduino Upgrade, Now with more Twitter!Author: natantusLicense: Attribution-ShareAlike (by-sa)

Instructable: The Smuggie: Tweet straight from your SnuggieAuthor: jblinderLicense: Attribution-NonCommercial-ShareAlike (by-nc-sa)

Instructable: Twitter Mood Light - The World's Mood in a BoxAuthor: RandomMatrixLicense: None (All Rights Reserved) (c)

Instructable: Twitter Controlled Light-BotAuthor: anonymouse197License: Attribution-NonCommercial-ShareAlike (by-nc-sa)

Instructable: @tweet_tree: Twitter controlled Christmas treeAuthor: ianLicense: Attribution-NonCommercial-ShareAlike (by-nc-sa)

Instructable: Twittering Laser Tripwire with Webcam CaptureAuthor: action_owlLicense: Attribution-NonCommercial-ShareAlike (by-nc-sa)

Instructable: Twitter Watcher, the #twatchAuthor: ianLicense: Attribution-NonCommercial-ShareAlike (by-nc-sa)

Instructable: Twitter scrolling picture frameAuthor: ianLicense: Attribution-NonCommercial-ShareAlike (by-nc-sa)

Instructable: Give Your Cat Twitter PowersAuthor: bpunktLicense: Attribution-NonCommercial-ShareAlike (by-nc-sa)

Instructable: Enormous led Mood lightAuthor: Tesla-incLicense: Attribution-NonCommercial-ShareAlike (by-nc-sa)

Instructable: LED wind indicatorAuthor: janwLicense: Attribution-NonCommercial-ShareAlike (by-nc-sa)

Instructable: Simple LED flowersAuthor: chiefchaceLicense: Attribution-NonCommercial-ShareAlike (by-nc-sa)

Page 9: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

DisclaimerAll do-it-yourself activities involve risk, and your safety is your own responsibility, including proper use of equipment and safety gear, and determining whether you haveadequate skill and experience. Some of the resources used for these projects are dangerous unless used properly and with adequate precautions, including safety gear.Some illustrative photos do not depict safety precautions or equipment, in order to show the project steps more clearly. The projects are not intended for use by children.

Many projects on Instructables are user-submitted, and appearance of a project in this format does not indicate it has been checked for safety or functionality. Use of theinstructions and suggestions is at your own risk. Instructables, Inc. disclaims all responsibility for any resulting damage, injury, or expense. It is your responsibility to makesure that your activities comply with all applicable laws.

Page 10: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Tweet-a-watt - How to make a twittering power meter...by adafruit on March 29, 2009

Author:adafruit    Adafruit IndustriesAll-original DIY electronics kits - Adafruit Industries is a New York City based company that sells kits and parts for original, open source hardware electronicsprojects featured on www.adafruit.com as well as other cool open source tronix' that we think are interesting and well-made.

Intro:  Tweet-a-watt - How to make a twittering power meter...Tweet-a-watt - How to make a twittering power meter...

This project documents my adventures in learning how to wire up my home for wireless power monitoring. I live in a rented apartment so I don't have hacking-access to ameter or breaker panel. Since I'm still very interested in measuring my power usage on a long term basis, I built wireless outlet reporters. Building your own powermonitor isn't too tough and can save money but I'm not a fan of sticking my fingers into 120V power. Instead, I'll used the existing Kill-a-watt power monitor, which worksgreat and is available at my local hardware store.

My plan is to have each room connected to a 6-outlet power strip which powers all the devices in that room (each kill-a-watt can measure up to 15A, or about 1800W,which is plenty!). That way I can track room-by-room usage, for example "kitchen", "bedroom", "workbench", and "office".

Each wireless outlet/receiver can be built for ~$55 with a few easily-available electronic parts and light soldering, no microcontroller programming or high voltageengineering is necessary!

You can see my setup including graphs and reports at http://twitter.com/tweetawatt

If you'd like to build one for yourself

1. Buy a kit: get all the parts you need, there's a starter kit at the adafruit webshop2. Make: turn each Kill-a-Watt into a wireless power level transmitter3. Software: Download & run it on your computer to get data and save it to a file and/or publish it

If you want to know how it was made, check out:

1. Listen: write simple software for my computer (or Arduino, etc) to listen for signal and compute the current power usage2. Store: Create a database backend that will store the power usage for long-term analysis at http://wattcher.appspot.com3. View: Graph and understand trends in power usage

Check out the latest readings at http://wattcher.appspot.com

Image Notes1. Wireless transmission indicator2. Uses a Kill-a-Watt, available at many hardware or electronic stores3. Measures up to 15A (1800 Watts!)

Page 11: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Image Notes1. XBee listens to data coming from the Kill-a-Watt measurement sensors2. XBee wireless module in an adapter and a few passive components to keepthings running smooth

Step 1: Make it!Before you start...

You should only attempt this project if you are comfortable and competent working with high voltage electricity, electronics and computers. Once the project is complete itis enclosed and there are no exposed high voltages. However, you must only work on the project when its not plugged in and never ever attempt to test, measure,open, or probe the circuitboards while they are attached to a wall socket. If something isn't working: stop, remove it from the wall power, then open it up andexamine. Yes it takes a few more minutes but it's a lot safer!

Your safety is your own responsibility, including proper use of equipment and safety gear, and determining whether you have adequate skill and experience. Power tools,electricity, and other resources used for this projects are dangerous, unless used properly and with adequate precautions, including safety gear. Some illustrative photosdo not depict safety precautions or equipment, in order to show the project steps more clearly. This projects is not intended for use by children.

Use of the instructions and suggestions is at your own risk. Adafruit Industries LLC, disclaims all responsibility for any resulting damage, injury, or expense. It is yourresponsibility to make sure that your activities comply with applicable laws.

OK, if you agree we can move on!

Make a tweet-a-watt

To make the tweet-a-watt setup, we will have to go through a few steps

1. Prepare by making sure we have everything we need and know the skills necessary to build the project2. Build the receiver setup by soldering up one of the adapter kits3. Configure the XBee wireless modems4. Build the transmitter setup by modifying a Kill-a-Watt to transmit via the XBee5. Run the software, which will retrieve data and save it to a file, upload it to a database and/or twitter

Step 2: PrepTutorials

Learn how to solder with tons of tutorials!Don't forget to learn how to use your multimeter too!

Tools

There are a few tools that are required for assembly. None of these tools are included. If you don't have them, now would be a good time to borrow or purchase them.They are very very handy whenever assembling/fixing/modifying electronic devices! I provide links to buy them, but of course, you should get them wherever is mostconvenient/inexpensive. Many of these parts are available in a place like Radio Shack or other (higher quality) DIY electronics stores.

I recommend a "basic" electronics tool set for this kit, which I describe here.

Soldering iron. One with temperature control and a stand is best. A conical or small 'screwdriver' tip is good, almost all irons come with one of these.

A low quality (ahem, $10 model from radioshack) iron may cause more problems than its worth!

Do not use a "ColdHeat" soldering iron, they are not suitable for delicate electronics work and can damage the kit (see here)

Solder. Rosin core, 60/40. Good solder is a good thing. Bad solder leads to bridging and cold solder joints which can be tough to find. Dont buy a tiny amount, you'll runout when you least expect it. A half pound spool is a minimum.

Multimeter/Oscilloscope. A meter is helpful to check voltages and continuity.

Flush/diagonal cutters. Essential for cutting leads close to the PCB.

Desoldering tool. If you are prone to incorrectly soldering parts.

'Handy Hands' with Magnifying Glass. Not absolutely necessary but will make things go much much faster.

Check out my recommended tools and where to buy.

Page 12: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Good light. More important than you think.

Page 13: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 3: Make the ReceiverOverview

We'll start with the receiver hardware, that's the thing that plugs into the computer and receives data from the wireless power plug. The receiver hardware does 'doubleduty', it also is used to update the XBee's modems' firmware (which, unfortunately, is necessary because they come from the factory with really old firmware) andconfigure the modems.

What you'll need

The receiver is essentially, an XBee, with a USB connection to allow a computer to talk to it the XBee.

Name FTDI cableDescription A USB-to-serial converter. Plugs in neatly into the Adafruit XBee adapter to allow a computer to talk to the XBee.Datasheet TTL-232R 3.3V or 5.0VDistributor MouserQty 1

Name Adafruit XBee Adapter kitDescription I'll be using my own design for the XBee breakout/carrier board but you can use nearly any kind as long as you replicate any missing parts such as the3.3Vsupply and LEDsYou will have 2 adapter kits but you should only assemble one for this part! The other one needs different instructions so just hold off!Datasheet WebpageDistributor AdafruitQty 1

Name XBee moduleDescription We'll be using the XBee "series 1" point-to-multipoint 802.15.4 modules with a chip antenna part # XB24-ACI-001. They're inexpensive and work great. Thisproject most likely won't work with any other version of the XBee, and certainly not any of the 'high power' Pro types!DatasheetDistributor AdafruitQty 1

Solder the adapter together!

This step is pretty easy, just go over to the XBee adapter webpage and solder it together according to the instructions!

Remember: You will have 2 adapter kits but you should only solder one of them at this point! The other one needs different instructions so just hold off!

Connect to the XBee

Now its time to connect to the XBees

Find your FTDI cable - use either 3.3V or 5V. These cables have a USB to serial converter chip molded into them and are supported by every OS. Thus configuring orupgrading or connecting is really trivial. Simply plug the cable into the end of the module so that the black wire lines up with GND. There is a white outline showing wherethe cable connects.

You'll need to figure out which serial port (COM) you are using. Plug in the FTDI cable, USB adapter, Arduino, etc. Under Windows, check the device manager, look for"USB Serial Port"

Digi/Maxstream wrote a little program to help configure XBees, its also the only way I know of to upgrade them to the latest firmware. Unfortunately it only runs onWindows. Download X-CTU from Digi and install it on your computer

After installing and starting the program, select the COM port (COM4 here) and baud rate (9600 is default). No flow control, 8N1. Make sure the connection box looks justlike the image (other than the com port which may be different)

To verify, click Test / Query

Hopefully the test will succeed. If you are having problems: check that the XBee is powered, the green LED on the adapter board should be blinking, the right COM port &baud rate is selected, etc.

Now unplug the adapter from the FTDI cable, carefully replace the first XBee with the other one and make sure that one is talking fine too. Once you know both XBeesare working with the adapter, its time to upgrade and configure them, the next step!

Page 14: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 15: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 4: ConfigureOverview

OK so far you have assembled one of the XBee adapter boards and connected it to your computer using the FTDI cable. (The other adapter is for later so don't doanything with it yet!) The XBees respond to the X-CTU software and are blinking just fine. Next we will update the firmware

Upgrading the firmware

There's a good chance your XBees are not running the latest firmware & there's a lot of features added, some of which we need to get this project running. So next up isupgrading!

Go to the Modem Configuration tab. This is where the modem is configured and updated

Click Download new versions... and select to download the latest firmwares from the Web

Once you have downloaded the newest firmware, its time to upgrade!

Click on Modem Parameters -> "Read" to read in the current version and settings

Now you will know for sure what function set, version and settings are stored in the modem

Select from the Version dropdown the latest version available

Check the Always update firmware checkbox

And click Write to initialize and program the new firmware in!

Page 16: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

That's it, now you have the most recent firmware for your modem. You should now uncheck the Always update firmware checkbox. If you have problems, like forexample timing out or not being able to communicate, make sure the RTS pin is wired up correctly as this pin is necessary for upgrading. FTDI cables are already set upfor this so you shouldn't have a problem

Rinse & Repeat

Upgrade the firmware on both of the XBees so they are both up to date

At this point it might be wise to label the two XBees in a way that lets you tell them apart. You can use a sharpie, a sticker or similar to indicate which one is the receiverand which is the transmitter

Configure the transmitter XBee

Both XBee's need to be upgraded with the latest firmware but only the transmitter (which is going to be put inside a Kill-a-Watt) needs to be configured. The configureprocess tells the XBee what pins we want to read the sensor data off of. It also tells the XBee how often to send us data, and how much.

Plug the transmitter XBee into the USB connection (put the receiver XBee away) and start up X-CTU or a Terminal program. Connect at 9600 baud, 8N1 parity.Thenconfigure each one as follows:

1. Set the MY address (the identifier for the XBee) to 1 (increment this for each transmitter so you can tell them apart, we'll assume you only have one for now)2. Set the Sleep Mode SM to 4 (Cyclic sleep)3. Set the Sleep Time ST to 3 (3 milliseconds after wakeup to go back to sleep)4. Set the Sleep Period SP to C8 (0xC8 hexadecimal = 200 x 10 milliseconds = 2 seconds between transmits)5. Set ADC 4 D4 to 2 (analog/digital sensor enable pin AD4)6. Set ADC 0 D0 to 2 (analog/digital sensor enable pin AD0)7. Set Samples to TX IT to 13 (0x13 = 19 A/D samples per packet)8. Set Sample Rate IR to 1 (1 ms between A/D samples)

if you think there will be more XBee's in the area that could conflict with your setup you may also want to

1. Set the PAN ID to a 4-digit hex number (its 3332 by default)

You can do this with X-CTU or with a terminal program such as hyperterm, minicom, zterm, etc. with the command stringATMY=1,SM=4,ST=3,SP=C8,D4=2,D0=2,IT=13,IR=1You'll need to start by getting the modem's attention by waiting 10 seconds, then typing in +++ quickly, then pausing for another 5 seconds. Then use AT to make sure itspaying ATtention to your commands

Basically what this means is that we'll have all the XBees on a single PAN network, each XBee will have a unique identifier, they'll stay in sleep mode most of the time,then wake up every 2 seconds to take 19 samples from ADC 0 and 4, 1ms apart. If you're having difficulty, make sure you upgraded the firmware!

Make sure to WRITE the configuration to the XBee's permanent storage once you've done it. If you're using X-CTU click the "Write" button in the top left. If you're using aterminal, use the command ATWR !

Note that once the XBee is told to go into sleep mode, you'll have to reset it to talk to it because otherwise it will not respond and X-CTU will complain. You can simplyunplug the adapter from the FTDI cable to reset or touch a wire between the RST and GND pins on the bottom edge of the adapter.

Now that the transmitters are all setup with unique MY number ID's, make sure that while they are powered from USB the green LED blinks once every 2 seconds(indicating wakeup and data transmit)

Configure the receiver XBee

Plug the receiver XBee into the USB connection (put the receiver XBee away) and start up X-CTU. If you set the PAN ID in the previous step, you will have to do thesame here

Set the PAN ID to the same hex number as above

If you didn't change the PAN above, then there's nothing for you to do here, just skip this step

Next!

Now that the XBees are configured and ready, its time to go to the next step where we make the Kill-a-Watt hardware

Page 17: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 18: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 19: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 5: Solder the Transmitter - parts listBefore you start...

You should only attempt this project if you are comfortable and competent working with high voltage electricity, electronics and computers. Once the project is complete itis enclosed and there are no exposed high voltages. However, you must only work on the project when its not plugged in and never ever attempt to test, measure,open, or probe the circuitboards while they are attached to a wall socket. If something isn't working: stop, remove it from the wall power, then open it up andexamine. Yes it takes a few more minutes but it's a lot safer!

Your safety is your own responsibility, including proper use of equipment and safety gear, and determining whether you have adequate skill and experience. Power tools,electricity, and other resources used for this projects are dangerous, unless used properly and with adequate precautions, including safety gear. Some illustrative photosdo not depict safety precautions or equipment, in order to show the project steps more clearly. This projects is not intended for use by children.

Use of the instructions and suggestions is at your own risk. Adafruit Industries LLC, disclaims all responsibility for any resulting damage, injury, or expense. It is yourresponsibility to make sure that your activities comply with applicable laws.

OK, if you agree we can move on!

Transmitter partslist

For each outlet you want to monitor, you'll need:

Name: Kill-a-WattDescription: "Off the shelf" model P4400 power monitorDatasheet: P3 Kill-a-wattDistributor: Lots! Also check hardware/electronics storesQty: 1

Name: Adafruit XBee AdapterDescription: I'll be using my own design for the XBee breakout/carrier board but you can use nearly any kind as long as you replicate any missing parts such as the3.3V

Page 20: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

supply and LEDsDatasheet: WebpageDistributor: AdafruitQty: 1

Name: XBee moduleDescription: We'll be using the XBee "series 1" point-to-multipoint 802.15.4 modules with a chip antenna part # XB24-ACI-001. They're inexpensive and work great. Thisproject most likely won't work with any other version of the XBee, and certainly not any of the 'high power' Pro types!Distributor: AdafruitQty: 1

Name: D3Description: 1N4001 diode. Any power diode should work fine. Heck, even a 1n4148 or 1n914 should be OK. But 1N4001 is suggested and is in the kit.Datasheet: Generic 1N4001Distributor: Digikey MouserQty: 1

Name: D2Description: Large diffused LED, for easy viewing. The kit comes with green.Qty: 1

Name: C3Description: 220uF, 4V or higher (photo shows 100uF)Datasheet: GenericDistributor: Digikey MouserQty: 1

Name: C4Description: 10,000uF capacitor (wow!) / 6.3V (photo shows a mere 2200uF) Try to get 16mm diameter, 25mm longDatasheet: GenericDistributor: Digikey [Mouser]Qty: 1

Name: R4 R6Description: 10K 1/4W 1% resistor (brown black black red gold) or 10K 1/4W 5% resistor (brown black orange gold). 1% is preferred but 5% is OKDatasheet: GenericDistributor: Mouser DigikeyQty: 2

Name: R3 R5Description: 4.7K 1/4W 1% resistor (yellow violet black brown gold) or 4.7K 1/4W 5% resistor (yellow violet red gold). 1% is preferred but 5% is OK.Datasheet: GenericDistributor: Mouser DigikeyQty: 2

Name: Ribbon cableDescription: Ribbon cable, or other flexible wire, at least 6 conductors, about 6" longDatasheet: Generic RibbonDistributor: DigikeyQty: 6"

Name: Heat shrinkDescription: Heat shrink! A couple inches of 1/8" and 1/16" eachDatasheet: Generic

It will run you about $50-$60 for each outlet

Page 21: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 22: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 6: Transmitter SchematicThe XBee radio does all of the hard work, it listens on two analog input ports (AD0 and AD4) for voltage and current data. Then it transmits that information wirelessly tothe host computer receiver XBee. There are a few we have to engineer around to make it Work:

1. We want to run the XBee off the Kill-a-Watt's internal power supply. However its current limited and wont provide 50mA in a burst when the XBee transmits. We solvethis by adding a simple 'rechargeable battery' in the form of a really large capacitor C4.

2. The Kill-a-Watt runs at 5V but XBees can only run at 3.3V so we have a voltage regulator IC1 and two capacitors two stabilize the 3.3V supply, C1 and C2.

3. The XBee will transmit every few seconds, even while the capacitor is charging. This means that it will keep draining the capacitor, resetting, and trying again, basicallyfreaking out while the power supply is still building. We prevent this by adding another fairly big capacitor C3 on the reset line. This slows down the XBee, delaying thestartup by a few seconds & keeps the XBee from starting up till we have solid power.

4. The XBee analog sensors run at 3.3V but the Kill-a-Watt sensors run at 5V. We use simple voltage dividers R3/R4 and R5/R6 to reduce the analog signal down to areasonable level

Step 7: Assemble and create the transmitter - 1Open up your kit and get out the parts for the transmitter. Remember that we'll be using most of but not all of an XBee adapter kit. The two small LEDs, the 74HC125Nchip, a 10K and 1K resistor are not used and you should put them aside for a future project so you don't accidentally use them here.

Check to make sure you've got everything you need. The only thing not shown here is the XBee radio and Kill-a-Watt.

Place the PCB of adapter kit and get ready to solder by heating up your soldering iron, and preparing your hand tools

We'll start by soldering in the 3.3V regulator, which is identical to the standard XBee Adapter kit you made in the receiver instructions. Don't forget to check the polarity ofC2 and that IC1 is in the right way. Then solder and clip the three components.

Now we will veer from the standard XBee adapter instructions and add a much larger LED on the ASC line so that we can easily see it blinking when its in the Kill-a-Watt.Make sure to watch for the LED polarity, because a backwards LED will make debugging very difficult. The longer lead goes in the + marked solder hole.

Give the LED about half an inch of space beyond the end of the PCB as shown. Also solder in the matching 1K resistor R2

Page 23: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Solder in the two 2mm 10pin female headers in the adapter kit. Be careful with the solder so that you don't accidentally fill the female header. Use a sparing amount tomake sure there's a connection but its not overflowing

Page 24: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 8: Assemble and create the transmitter - 2Now its time to prepare the wires we need for the next few stops. Use your diagonal cutters to notch off the brown, red, orange and yellow wires from the end of therainbow ribbon cable in the kit.

Then tear off the four wires from the rest of the cable.

Do the same for the black and white wires and the single green wire. Then cut the green wire so its only about 1.5" long. You should now have 3 strips of wire, one 6"with 4 conductors, one 6" with 2 conductors and one 1.5" with 1 conductor

Use wirestrippers to strip the ends of the green wire, 1/4" from the ends

Then tin the green wire by heating the ends of the wire and applying a little solder to bind together the stranded wire.

Use the green wire to create a jumper between the VREF pin, 7th from the top on the right and the VCC pin on the top left.

Double check to make sure you get this right! Then solder it in place. This will set the reference point of the analog converter to 3.3V

Go back to the 4-piece ribbon cable. Split the ends with the diagonal cutter, then strip and tin all 8 ends.

Put a 4.7K resistor in a vise or holder, then clip one end off and tin it just like the wires.

Cut a 1/2" piece of 1/16" heat shrink and slip it onto the yellow wire, making sure there's clearance between the heatshrink and the end of the wire. Then solder the yellowwire to the 4.7k resistor.

Do the same for the orange wire and the other 4.7K resistor. Use a heat source (a heat gun or hair drier is perfect) to shrink the heatshrink over the soldered wire/resistorjoint.Then bend the resistor 90degrees and clip the other end of the 4.7k resistors

Page 25: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 26: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 9: Assemble and create the transmitter - 3Now we will build the voltage divider. Take the two 10K resistors and connect them as shown. One goes from AD0 and one from AD4. Both then connect to ground.Conveniently, the chip we are not using had grounded pins so we can 'reuse' those pins.

Now comes the tricky part. We want to connect the other end of the 4.7K resistor to the AD0 pin but the 10K resistor is already there. Use your soldering iron to melt ablob of solder onto the top of the 10K resistor and then piggyback the 4.7K resistor by soldering to the top of the 10K resistor.

Solder the orange wire to the AD0 pin, the yellow to the AD4

The other two wires are for carrying power. The red wire should be soldered to the +5V pin on the bottom of the adapter PCB. The brown wire to the GND pin.

We're nearly done with the adapter soldering. Lastly is the 220uF reset capacitor. We'll connect this to the RST pin, 5th from the top on the left. Make sure the long leadis connected to the RST pin and the shorter lead goes to the 4th pin of where the chip would go. Check the photo on the left to make sure you've got it in right.

The capacitor wont fit underneath the XBee module so give it some lead length so that the cylindrical bulk is next to the 3.3V regulator.

For reference, the images below show what the back should look like.

... and what it should look like with the XBee modem installed. Make sure the pins on the XBee line up with the header.

Page 27: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 28: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 10: Assemble and create the transmitter - 4Now replace the PCB with the huge capacitor.

Clip the long leads down. You'll need to use the "-" stripe to keep track of which pin is negative and which is positive.

Tin both leads with solder.

Solder the other end of the red ribbon wire (that goes to +5V on the XBee adapter) to the positive pin of the capacitor.

Then solder the brown wire (that goes to GND on the XBee adapter) to the negative pin.

Clip the cathode lead down of the 1N4001 diode, that's the end with the white stripe. on it. Solder the diode so that the white-stripe side is connected to the positive pin ofthe big capacitor.

Take the black and white ribbon from earlier. Split, strip and tin the four ends. Cut a 1" piece of 1/8" heatshrink and slip it onto the white wire. Slip a 1/2" piece of 1/16"heat shrink onto the black wire.

Clip the other end of the diode (the side without a white stripe) and solder the white wire to it. Solder the black wire to the negative pin of the big capacitor.

Now shrink the heatshrink so that the capacitor leads and diode are covered.

All right, here is what you should have, an adapter with two sensor lines (orange and yellow) hanging off and two power lines (red and brown) that are connected to thebig capacitor. Then there are two black&white wires connected to the capacitor, the white one through a diode.

Page 29: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 30: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 11: Assemble and create the transmitter - 5Now its time to open the Kill-a-Watt! There are only 3 screws that hold it together, and they are found on the back.

Now its time to open the Kill-a-Watt! There are only 3 screws that hold it together, and they are found on the back.

Use a 3/8 drill bit to make a hole near the right corner of the case back. This is what the LED will stick out of. (Ignore the white tape and #4, this is a recycled kill-a-watt :)

Now find the LM2902N chip. This is a quad op-amp that senses the power line usage. We're going to piggy-back right on top of it, and borrow the ground, 5V power and2 sensor outputs!

With your soldering iron, melt a bit of solder on pin 1, 4, 11 and 14 of the chip. Make sure you have the chip oriented correctly, the notch indicates where pins 1 and 14are

Solder the white wire (5V to the XBee) to pin 4. Solder the black wire (ground) to pin 11 directly across.

Now solder the yellow wire to pin 1 and the orange wire to pin 14.

Use two small pieces of sticky foam and stick them onto the back of the case.

Then place the XBee adapter and capacitor on the tape so that the LED sticks out of the hole drilled earlier

Tuck the excess ribbon cable out of the way so that they are not near the 120V connections which could make them go poof.

Close it up and plug it in.

You'll notice its a bit finicky for a few seconds as the big capacitor charges up. The display may not come up for 15-30 seconds, and it may fade in and out at first. Thenumbers may also be wrong for a bit as it powers up. Within about 30 seconds, you should see the display stabilize and the indicator LED blinking every 2 seconds!

Go back to your computer, plug the receiver XBee into the USB adapter and make sure it has the latest firmware uploaded and set it to the same PAN ID as thetransmitters. You will see the RSSI LED (red LED) light up. That means you have a good link!

Open up the Terminal in X-CTU (or another terminal program) and connect at 9600 baud 8N1 parity and you'll see a lot of nonsense. Whats important is that a new chunkof nonsense gets printed out once every 2 seconds, indicating a packet of data has been received.

The hardware is done. Good work!

Page 31: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 32: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 33: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 34: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 12: SoftwareIntroduction

Now that the hardware is complete, we come to the exciting part: running the software that retrieves the data from our receiver XBee and saves it to our computer oruploads it to a database or updates our twitter feed or....whatever you'd like!

Here is how it works, the XBee inside the Kill-a-Watt is hooked up to two analog signals. One is the voltage signal which indicates the AC voltage read. In general this is asine wave that is 120VAC. One tricky thing to remember is that 120V is the 'RMS' voltage, and the 'true voltage' is +-170VDC. ( You can read more about RMS voltage atwikipedia basically its a way to indicate how much 'average' voltage there is.) The second reading is the AC current read. This is how much current is being drawnthrough the Kill-a-Watt. If you multiply the current by the voltage, you'll get the power (in Watts) used!

The XBee's Analog/Digital converter is set up to take a 'snapshot' of one sine-cycle at a time. Each double-sample (voltage and current) is taken 1ms apart and it takes17 of them. That translates to a 17ms long train of samples. One cycle of power-usage is 1/60Hz long which is 16.6ms. So it works pretty well!

Lets look at some examples of voltage and current waveforms as the XBee sees them.

For example this first graph is of a laptop plugged in. You'll see that its a switching supply, and only pulls power during the peak of the voltage curve.

Now lets try plugging in a 40W incandescent light bulb. You'll notice that unlike the switching supply, the current follows the voltage almost perfectly. That's because alightbulb is just a resistor!

Finally, lets try sticking the meter on a dimmable switch. You'll see that the voltage is 'chopped' up, no longer sinusoidal. And although the current follows the voltage, itsstill matching pretty well.

The XBee sends the raw data to the computer which, in a python script, figures out what the (calibrated) voltage and amperage is at each sample and multiplies eachpoint together to get the Watts used in that cycle. Since there's almost no device that changes the power-usages from cycle-to-cycle, the snapshot is a good indicator ofthe overall power usage that second. Then once every 2 seconds, a single snapshot is sent to the receiver XBee

Install python & friends

The software that talks to the XBee is written in python. I used python because its quick to develop in, has multi-OS support and is pretty popular with software andhardware hackers. The XBees talk over the serial port so literally any programming language can/could be used here. If you're a software geek and want to use perl, C,C#, tcl/tk, processing, java, etc. go for it! You'll have to read the serial data and parse out the packet but its not particularly hard.

However, most people just want to get on with it and so for you we'll go through the process of installing python and the libraries we need.

1. Download and install python 2.5 from http://www.python.org/download/ I suggest 2.5 because that seems to be stable and well supported at this time. If you useanother version there may be issues2. Download and install pyserial from the package repository (this will let us talk to the XBee thru the serial port)3. If you're running windows download and install win32file for python 2.5 (this will add file support)4. Download and install the simplejson python library (this is how the twitter api likes to be spoken to)

Now you can finally download the Wattcher script we will demonstrate here! We're going to download it into the C:\wattcher directory, for other OS's you can of coursechange this directory

Basic configure

We'll have to do a little bit of setup to start, open up the wattcher.py script with a text editor and find the line

SERIALPORT = "COM4" # the com/serial port the XBee is connected to

change COM4 into whatever the serial port you will be connecting to the XBee with is called. Under windows its some COMx port, under linux and mac its something like/dev/cu.usbserial-xxxx check the /dev/ directory and/or dmesg

Save the script with the new serial port name

Test it out

Once you have installed python and extracted the scripts to your working directory, start up a terminal (under linux this is just rxvt or xterm, under mac its Terminal,under windows, its a cmd window)

I'm going to assume you're running windows from now on, it shouldn't be tough to adapt the instructions to linux/mac once the terminal window is open.

Run the command cd C:\wattcher to get to the place where you uncompressed the files. By running the dir command you can see that you have the files in the directory

Make sure your transmitter (Kill-a-Watt + Xbee) is plugged in, and blinking once every 2 seconds. Remember it takes a while for the transmitter to charge up power andstart transmitting. The LCD display should be clear, not fuzzy. Make sure that there's nothing plugged into the Kill-a-Watt, too. The RSSI (red) LED on the receiverconnected to the computer should be lit indicating data is being received. Don't continue until that is all good to go.

Now run python by running the command C:\python25\python.exe wattcher.py

You should get a steady print out of data. The first number is the XBee address from which it received data, following is the estimated current draw, wattage used and theWatt-hours consumed since the last data came in. Hooray! We have wireless data!

Calibrating

Now that we have good data being received, its time to tweak it. For example, its very likely that even without an appliance or light plugged into the Kill-a-Watt, the scriptthinks that there is power being used. We need to calibrate the sensor so that we know where 'zero' is. In the Kill-a-Watt there is an autocalibration system butunfortunately the XBee is not smart enough to do it on its own. So, we do it in the python script. Quit the script by typing in Control-C and run it again this time asC:\python25\python.exe wattcher.py -d note the -d which tells the script to print out debugging information

Now you can see the script printing out a whole mess of data. The first chunk with lots of -1's in it is the raw packet. While its interesting we want to look at the line thatstarts with ampdata:

ampdata: [498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 497, 498, 498, 498]

Now you'll notice that the numbers are pretty much all the same. That's because there's nothing plugged into the tweetawatt and so each 1/60 Hz cycle has a flat line at

Page 35: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

'zero'. The A/D in the XBee is 10 bits, and will return values between 0 and 1023. So, in theory, if the system is perfect the value at 'zero' should be 512. However, thereare a bunch of little things that make the system imperfect and so zero is only close to 512. In this case the 'zero' calibration point is really 498. When its off there is a 'DCoffset' to the Amp readings, as this graph shows:

See how the Amp line (green) is steady but its not at zero, its at 0.4 amps? There is a 'DC offset' of 0.4 amps

OK, open up the wattcher.py script in a text editor.

vrefcalibration = [492, # Calibration for sensor #0]492, # Calibration for sensor #1489, # Calibration for sensor #2492, # Calibration for sensor #3501, # Calibration for sensor #4493] # etc... approx ((2.4v * (10Ko/14.7Ko)) / 3

See the line that says # Calibration for sensor #1? Change that to 498

vrefcalibration = [492, # Calibration for sensor #0]498, # Calibration for sensor #1489, # Calibration for sensor #2492, # Calibration for sensor #3501, # Calibration for sensor #4493] # etc... approx ((2.4v * (10Ko/14.7Ko)) / 3

Save the file and start up the script again, this time without the -d

Now you'll see that the Watt draw is 2W or less, instead of 40W (which was way off!) The reason its not 0W is that, first off, there's a little noise that we're reading in theA/D lines, secondly there's power draw by the Kill-a-Watt itself and finally, the XBee doesn't have a lot of samples to work with. However <2W is pretty good consideringthat the full sensing range is 0-1500W

Note the graph with the calibrated sensor:

See how the Amps line is now at 0 steady, there is no DC offset

Logging data

Its nice to have this data but it would be even nicer if we could store it for use. Well, thats automatically done for you! You can set the name of the log file in thewattcher.py script. By default it's powerdatalog.csv. The script collects data and every 5 minutes writes a single line in the format Year Month Day, Time, Sensor#,Watts for each sensor.As you can see, this is an example of a 40W incandescent lightbulb plugged in for a few hours. Because of the low sample rate, you'll see someminor variations in the Watts recorded. This data can be easily imported directly into any spreadsheet program

Tweeting

Finally we get to the tweeting part of the tweet-a-watt. First open up the wattcher.py script and set

# Twitter username & passwordtwitterusername = "username"twitterpassword = "password"

to your username and password on twitter. You can make an account on twitter.com if you don't have one.

Then run the script as usual. Every 8 hours (midnight, 8am and 4pm) the script will sent a twitter using the Twitter API

Then check it out at your account:

Image Notes1. A laptop plugged in, switching power supply

Image Notes1. 40W lightbulb

Page 36: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Image Notes1. Light bulb on dimmer switch

Page 37: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 38: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 13: ExpandOverview

Once you've got your base system up and running here are some ideas for how to extend, improve or expand it!

Add more outlets

So you can track more rooms, of course

Graphing

If you'd like to play some more with the script, there's some extras built in. For example, you can graph the data as it comes in from the XBee, both Watts used and theactual 'power line' waveform. Simply set GRAPHIT = True you'll need to install a mess of python libraries though, including wxpython, numpy and pylab

Remove the computer

It took a few hours, but I hacked my Asus wifi router to also log data for me. There'll be more documentation soon but here's some hints:

Do basically everything in [Do basically everything in MightyOhm's tutorial. You can use the FTDI cable to reprogram the router, just move the pins around. Then add a16mb USB key (I was given one as schwag so look in your drawers) and install python and the openssl library as well as the other libraries needed like pyserial. The codeshould pretty much just run! (I'll put up more detailed notes later)]

The router still works as my wifi gateway to the cablemodem, and only uses 5W MightyOhm's tutorial]. You can use the FTDI cable to reprogram the router, just move thepins around. Then add a 16mb USB key (I was given one as schwag so look in your drawers) and install python and the openssl library as well as the other librariesneeded like pyserial. The code should pretty much just run! (I'll put up more detailed notes later)

The router still works as my wifi gateway to the cablemodem, and only uses 5W

Step 14: Design - overviewDesign overview

For those interested in how to build a sensor node system with a Google Appengine backend, here is the process by which I created it. Of course, you should have thehardware part done first!

1. Listen - designing the parser for the computer that grabs XBee packets, and extracts the useful data2. Store - how to use GAE to store the data in 'the cloud'3. Graph - using Google Visualizations to make pretty graphs

Page 39: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 15: Design - listenData listening & parsing

In this section we will work on the receiver software, that will talk to a receiver XBee and figure out what the sensor data means. I'll be writing the code in python which isa fairly-easy to use scripting language. It runs on all OS's and has tons of tutorials online. Also, Google AppEngine uses it so its a good time to learn!

This whole section assumes that you only have 1 transmitter and 1 receiver, mostly to make graphing easier to cope with. In the next section we'll tie in more sensorswhen we get to the datalogging part!

Raw analog input

We'll start by just getting raw data from the XBee and checking it out. The packet format for XBees is published but instead of rooting around in it, I'll just use the handyXBee library written for python. With it, I can focus on the data instead of counting bytes and calculating checksums.

To use the library, first use the pyserial module to open up a serial port (ie COM4 under windows, /dev/ttyUSB0 under mac/linux/etc) You can look at the XBee projectpage for information on how to figure out which COM port you're looking for. We connect at the standard default baudrate for XBees, which is 9600 and look for packets

from xbee import xbeeimport serial

SERIALPORT = "COM4" # the com/serial port the XBee is connected toBAUDRATE = 9600 # the baud rate we talk to the xbee

# open up the FTDI serial port to get data transmitted to xbeeser = serial.Serial(SERIALPORT, BAUDRATE)ser.open()

while True:# grab one packet from the xbee, or timeoutpacket = xbee.find_packet(ser)if packet:xb = xbee(packet)

print xb

Running this code, you'll get the following output:

<xbee {app_id: 0x83, address_16: 1, rssi: 85, address_broadcast: False, pan_broadcast: False, total_samples: 19, digital: [[-1, -1, -1, -1, -1, -1, -1, -1, -1], [-1, -1,-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1, -1, -1], [-1 , -1, -1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1, -1, -1], [-1, -1 , -1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1, -1, -1], [-1, -1, -1 , -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1 , -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1 , -1, -1, -1, -1], [-1,-1, -1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1 , -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1 , -1, -1], [-1, -1, -1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1, -1 , -1], [-1, -1, -1, -1, -1, -1, -1, -1, -1]], analog: [[190, -1, -1, -1, 489, -1], [109, -1, -1, -1, 484, -1], [150, -1, -1, -1, 492, -1], [262, -1, -1, -1, 492 , -1], [423, -1, -1, -1,492, -1], [589, -1, -1, -1, 492, -1], [740, -1, -1, -1, 492, -1], [843, -1, -1, -1, 492, -1], [870, -1, -1, -1, 496, -1], [805, -1, -1, -1, 491, -1], [680, -1, -1, -1, 492, -1], [518, -1, -1,-1, 492, -1], [349, -1, -1, -1, 491, -1], [199, -1, -1, -1, 491, -1], [116, -1, -1, -1, 468, -1], [108, -1, -1, -1, 492, -1], [198, -1, -1, -1, 492, -1], [335, -1, -1, -1, 492, -1], [523, -1,-1, -1, 492, -1]]}>

which we will reformat to make a little more legible

<xbee {app_id: 0x83,address_16: 1,rssi: 85,address_broadcast: False,pan_broadcast: False,total_samples: 19,digital: [[-1, -1, -1, -1, -1, -1, -1, -1, -1],[-1, -1, -1, -1, -1, -1, -1, -1, -1],[-1, -1, -1, -1, -1, -1, -1, -1, -1],[-1, -1, -1, -1, -1, -1, -1, -1, -1],[-1, -1, -1, -1, -1, -1, -1, -1, -1],[-1, -1, -1, -1, -1, -1, -1, -1, -1],[-1, -1, -1, -1, -1, -1, -1, -1, -1],[-1, -1, -1, -1, -1, -1, -1, -1, -1],[-1, -1, -1, -1, -1, -1, -1, -1, -1],[-1, -1, -1, -1, -1, -1, -1, -1, -1],[-1, -1, -1, -1, -1, -1, -1, -1, -1],[-1, -1, -1, -1, -1, -1, -1, -1, -1],[-1, -1, -1, -1, -1, -1, -1, -1, -1],[-1, -1, -1, -1, -1, -1, -1, -1, -1],[-1, -1, -1, -1, -1, -1, -1, -1, -1],[-1, -1, -1, -1, -1, -1, -1, -1, -1],[-1, -1, -1, -1, -1, -1, -1, -1, -1],[-1, -1, -1, -1, -1, -1, -1, -1, -1],[-1, -1, -1, -1, -1, -1, -1, -1, -1]],analog: [[190, -1, -1, -1, 489, -1],[109, -1, -1, -1, 484, -1],[150, -1, -1, -1, 492, -1],[262, -1, -1, -1, 492, -1],[423, -1, -1, -1, 492, -1],[589, -1, -1, -1, 492, -1],[740, -1, -1, -1, 492, -1],[843, -1, -1, -1, 492, -1],[870, -1, -1, -1, 496, -1],[805, -1, -1, -1, 491, -1],[680, -1, -1, -1, 492, -1],

Page 40: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

[518, -1, -1, -1, 492, -1],[349, -1, -1, -1, 491, -1],[199, -1, -1, -1, 491, -1],[116, -1, -1, -1, 468, -1],[108, -1, -1, -1, 492, -1],[198, -1, -1, -1, 492, -1],[335, -1, -1, -1, 492, -1],[523, -1, -1, -1, 492, -1]]

}>

OK now its clear whats going on here. First off, we get some data like the transmitter ID (address_16) and signal strength (RSSI). The packet also tells us how manysample are available (19). Now, the digital samples are all -1 because we didn't request any to be sent. The library still fills them in tho so thats why the non-data is there.The second chunk is 19 sets of analog data, ranging from 0 to 1023. As you can see, the first sample (#0) and fifth sample (#4) contain real data, the rest are -1. Thatcorresponds to the hardware section where we setup AD0 and AD4 to be our voltage and current sensors.

We'll tweak our code so that we can extract this data only and ignore the rest of the packet.

This code creates two arrays, voltagedata and ampdata where we will stick the data. We throw out the first sample because usually ADCs are a bit wonky on the firstsample and then are good to go after that. It may not be necessary tho

#!/usr/bin/env pythonimport serialfrom xbee import xbee

SERIALPORT = "COM4" # the com/serial port the XBee is connected toBAUDRATE = 9600 # the baud rate we talk to the xbeeCURRENTSENSE = 4 # which XBee ADC has current draw dataVOLTSENSE = 0 # which XBee ADC has mains voltage data

# open up the FTDI serial port to get data transmitted to xbeeser = serial.Serial(SERIALPORT, BAUDRATE)ser.open()

while True:# grab one packet from the xbee, or timeoutpacket = xbee.find_packet(ser)if packet:xb = xbee(packet)

#print xb# we'll only store n-1 samples since the first one is usually messed upvoltagedata = [-1] * (len(xb.analog_samples) - 1)ampdata = [-1] * (len(xb.analog_samples ) -1)# grab 1 thru n of the ADC readings, referencing the ADC constants# and store them in nice little arraysfor i in range(len(voltagedata)):voltagedata[i] = xb.analog_samples[i+1][VOLTSENSE]ampdata[i] = xb.analog_samples[i+1][CURRENTSENSE]print voltagedataprint ampdata

Now our data is easier to see:

Voltage: [672, 801, 864, 860, 755, 607, 419, 242, 143, 108, 143, 253, 433, 623, 760, 848, 871, 811]Current: [492, 492, 510, 491, 492, 491, 491, 491, 492, 480, 492, 492, 492, 492, 492, 492, 497, 492]

Note that the voltage swings from about 100 to 900, sinusoidally.

Normalizing the data

Next up we will 'normalize' the data. The voltage should go from -170 to +170 which is the actual voltage on the line, instead of 100 to 900 which is just what the ADCreads. To do that we will get the average value of the largest and smallest reading and subtract it from all the samples. After that, we'll normalize the Currentmeasurements as well, to get the numbers to equal the current draw in Amperes.

#!/usr/bin/env pythonimport serialfrom xbee import xbee

SERIALPORT = "COM4" # the com/serial port the XBee is connected toBAUDRATE = 9600 # the baud rate we talk to the xbeeCURRENTSENSE = 4 # which XBee ADC has current draw dataVOLTSENSE = 0 # which XBee ADC has mains voltage data

# open up the FTDI serial port to get data transmitted to xbeeser = serial.Serial(SERIALPORT, BAUDRATE)ser.open()

while True:# grab one packet from the xbee, or timeoutpacket = xbee.find_packet(ser)if packet:xb = xbee(packet)

Page 41: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

#print xb# we'll only store n-1 samples since the first one is usually messed upvoltagedata = [-1] * (len(xb.analog_samples) - 1)ampdata = [-1] * (len(xb.analog_samples ) -1)# grab 1 thru n of the ADC readings, referencing the ADC constants# and store them in nice little arraysfor i in range(len(voltagedata)):voltagedata[i] = xb.analog_samples[i+1][VOLTSENSE]ampdata[i] = xb.analog_samples[i+1][CURRENTSENSE]

# get max and min voltage and normalize the curve to '0'# to make the graph 'AC coupled' / signedmin_v = 1024 # XBee ADC is 10 bits, so max value is 1023max_v = 0for i in range(len(voltagedata)):if (min_v > voltagedata[i]):min_v = voltagedata[i]if (max_v < voltagedata[i]):max_v = voltagedata[i]

# figure out the 'average' of the max and min readingsavgv = (max_v + min_v) / 2# also calculate the peak to peak measurementsvpp = max_v-min_v

for i in range(len(voltagedata)):#remove 'dc bias', which we call the average readvoltagedata[i] -= avgv# We know that the mains voltage is 120Vrms = +-170Vppvoltagedata[i] = (voltagedata[i] * MAINSVPP) / vpp

# normalize current readings to amperesfor i in range(len(ampdata)):# VREF is the hardcoded 'DC bias' value, its# about 492 but would be nice if we could somehow# get this data once in a while maybe using xbeeAPIampdata[i] -= VREF# the CURRENTNORM is our normalizing constant# that converts the ADC reading to Amperesampdata[i] /= CURRENTNORM

print "Voltage, in volts: ", voltagedataprint "Current, in amps: ", ampdata

We'll run this now to get this data, which looks pretty good, there's the sinusoidal voltage we are expecting and the current is mostly at 0 and then peaks up and downonce in a while. Note that the current is sometimes negative but that's OK because we multiply it by the voltage and if both are negative it still comes out as a positivepower draw

Voltage, in volts: [-125, -164, -170, -128, -64, 11, 93, 148, 170, 161, 114, 46, -39, -115, -157, -170, -150, -99]

Current, in amps: [0.064516129032258063, -1.096774193548387, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.096774193548387,]0.0, 0.0, 0.0, -0.064516129032258063, 0.0, 0.0, -0.70967741935483875, 0.0, 0.0]

Basic data graphing

Finally, I'm going to add a whole bunch more code that will use the numpy graphing modules to make a nice graph of our data. Note that you'll need to install wxpythonas well as numpy, and matplotlib!

At this point, the code is getting waaay to big to paste here so grab "wattcher.py Mains graph" from the download page!

Run it and you should see a graph window pop up with a nice sinusoidal voltage graph and various amperage data. For example this first graph is of a laptop plugged in.You'll see that its a switching supply, and only pulls power during the peak of the voltage curve.

Now lets try plugging in a 40W incandescent light bulb. You'll notice that unlike the switching supply, the current follows the voltage almost perfectly. Thats because alightbulb is just a resistor!

Finally, lets try sticking the meter on a dimmable switch. You'll see that the voltage is 'chopped' up, no longer sinusoidal. And although the current follows the voltage, itsstill matching pretty well.

Graphing wattage!

OK neat, its all fun to watch waveforms but what we -really want- is the Watts used. Remember, P = VI otherwise known as Watts = Voltage * Current. We can calculatetotal Watts used by multiplying the voltages and currents at each sample point, then summing them up over a cycle & averaging to get the power used per cycle. Oncewe have Watts, its easy to just multiply that by 'time' to get Watt-hours!

Download and run the wattcher.py - watt grapher script from the download page

Now you can watch the last hour's worth of watt history (3600 seconds divided by 2 seconds per sample = 1800 samples) In the image above you can see as I dim a 40-watt lightbulb. The data is very 'scattered' looking because we have not done any low-pass filtering. If we had a better analog sampling rate, this may not be as big a dealbut with only 17 samples to work with, precision is a little difficult

Done!

OK great! We have managed to read data, parse out the analog sensor payload and process it in a way that gives us meaningful graphs. Of course, this is great for

Page 42: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

instantaneous knowledge but it -would- be nice if we could have longer term storage, and also keep track of multiple sensors. In the next step we will do that by takingadvantage of some free 'cloud computing' services!

Image Notes1. A laptop plugged in, switching power supply

Image Notes1. 40W lightbulb

Image Notes1. Light bulb on dimmer switch

Step 16: Design - storeIntroduction

OK we are getting good data from our sensors, lets corral it into more useful chunks and store it in a database. We could make a database on the computer, but sincewe'd like to share this data, it makes more sense to put it online. There are custom services that are specifically designed to do this sort of thing like Pachube but I'mgoing to reinvent the wheel and design my own web-app that stores and displays energy data. (Mostly I want to play around with Google App Engine!)

You have 5 minutes!

We get data every few seconds from the XBee modem inside the kill-a-watt. We could, in theory, put data into our database every 2 seconds but that would quicklyballoon the amount of storage necessary. It would also make sorting through the data difficult. So instead lets add up all the sensor data for 5 minutes and then take theaverage.

We'll do this by keeping two timers and one tally. One timer will track how long its been since the last sensor signal was sent, and the other will track if its been 5 minutes.The tally will store up all the Watt-hours (Watt measurements * time since last sensor data). Then at the end we can average by the 5 minutes

This chunk of code goes near the beginning, it creates the timers and tally and initializes them

...fiveminutetimer = lasttime = time.time() # get the current timecumulativewatthr = 0...

Then later on, after we get our data we can put in this chunk of code:

Page 43: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

# add up the delta-watthr used since last reading# Figure out how many watt hours were used since last readingelapsedseconds = time.time() - lasttimedwatthr = (avgwatt * elapsedseconds) / (60.0 * 60.0) # 60 seconds in 60 minutes = 1 hrlasttime = time.time()print "\t\tWh used in last ",elapsedseconds," seconds: ",dwatthrcumulativewatthr += dwatthr

# Determine the minute of the hour (ie 6:42 -> '42')currminute = (int(time.time())/60) % 10# Figure out if its been five minutes since our last saveif (((time.time() - fiveminutetimer) >= 60.0) and (currminute % 5 == 0)):# Print out debug data, Wh used in last 5 minutesavgwattsused = cumulativewatthr * (60.0*60.0 / (time.time() - fiveminutetimer))print time.strftime("%Y %m %d, %H:%M"),", ",cumulativewatthr,"Wh = ",avgwattsused," W average")

# Reset our 5 minute timerfiveminutetimer = time.time()cumulativewatthr = 0

Note that we calculate delta-watthours, the small amount of power used every few seconds. Then we can get the average watts used by dividing the watthours by thenumber of hours that have passed (about 1/12th). Instead of going by exact 5 minutes, I decided to only report on the 5's of the hour (:05, :10, etc) so that its easier tosend all the data at once if theres multiple sensors that started up at different times.

Download wattcher-5minreporter.py from the Download page. If you run this, you'll get a steady stream

Near the end you can see the timestamp, the Watthrs used in the last few minutes and the average Wattage

Multisensor!

We have good data but so far it only works with one sensor. Multiple sensors will mess it up! Time to add support for more than one XBee so that I can track a few rooms.I'll do that by creating an object class in python, and using the XBee address (remember that from part 1?) to track. I'll replace the code we just wrote with the following:

At the top, instead of the timer variables, I'll have a full class declaration, and create an array to store them:

####### store sensor data and array of histories per sensorclass Fiveminutehistory:def init(self, sensornum):self.sensornum = sensornumself.fiveminutetimer = time.time() # track data over 5 minutesself.lasttime = time.time()self.cumulativewatthr = 0

def addwatthr(self, deltawatthr):self.cumulativewatthr += float(deltawatthr)

def reset5mintimer(self):self.cumulativewatthr = 0self.fiveminutetimer = time.time()

def avgwattover5min(self):return self.cumulativewatthr * (60.0*60.0 / (time.time() - self.fiveminutetimer))

def str(self):return "[id#: %d, 5mintimer: %f, lasttime; %f, cumulativewatthr: %f]" % (self.sensornum, self.fiveminutetimer, self.lasttime, self.cumulativewatthr)

######### an array of historiessensorhistories = []

When the object is initialized with the sensor ID number, it also sets up the two timers and cumulative Watthrs tracked. I also created a few helper functions that will makethe code cleaner

Right below that I'll create a little function to help me create and retrieve these objects. Given an XBee ID number it either makes a new one or gets the reference to it

####### retrieverdef findsensorhistory(sensornum):for history in sensorhistories:if history.sensornum == sensornum:return history# none found, create it!history = Fiveminutehistory(sensornum)sensorhistories.append(history)return history

Finally, instead of the average Watt calculation code written up above, we'll replace it with the following chunk, which retreives the object and tracks power usage with theobject timers

# retreive the history for this sensorsensorhistory = findsensorhistory(xb.address_16)#print sensorhistory

# add up the delta-watthr used since last reading# Figure out how many watt hours were used since last readingelapsedseconds = time.time() - sensorhistory.lasttimedwatthr = (avgwatt * elapsedseconds) / (60.0 * 60.0) # 60 seconds in 60 minutes = 1 hrsensorhistory.lasttime = time.time()

Page 44: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

print "\t\tWh used in last ",elapsedseconds," seconds: ",dwatthrsensorhistory.addwatthr(dwatthr)

# Determine the minute of the hour (ie 6:42 -> '42')currminute = (int(time.time())/60) % 10# Figure out if its been five minutes since our last saveif (((time.time() - sensorhistory.fiveminutetimer) >= 60.0) and (currminute % 5 == 0)):# Print out debug data, Wh used in last 5 minutesavgwattsused = sensorhistory.avgwattover5min()print time.strftime("%Y %m %d, %H:%M"),", ",sensorhistory.cumulativewatthr,"Wh = ",avgwattsused," W average"

# Reset our 5 minute timersensorhistory.reset5mintimer()

The code basically acts the same except now it wont choke on multiple sensor data! Below, my two Kill-a-Watts, one with a computer attached (100W) and another with alamp (40W)

Onto the database!

The App Engine

So we want to have an networked computer to store this data so we can share the data, but we really don't want to have to run a server from home! What to do? Well asmentioned before, you can use Pachube or similar, but I will show how to roll-your-own with Google App Engine (GAE). GAE is basically a free mini-webserver hosted byGoogle, that will run basic webapps without the hassle of administrating a database server. Each webapp has storage, some frameworks and can use Google accountsfor authentication. To get started I suggest checking out the GAE website, documentation, etc. I'll assume you've gone through the tutorials and jump right into designingmy power data storage app called Wattcher (a little confusing I know)

First, the app.yaml file which defines my app looks like this:

application: wattcherversion: 1runtime: pythonapi_version: 1

handlers:- url: /.*script: wattcherapp.py

Pretty simple, just says that the app uses wattcherapp.py as the source file

Next, we'll dive into the python code for our webapp. First, the includes and database index. To create a database, we actually define it -in the python file-, GAE thenfigures out what kind of database to create for you by following those directions (very different than MySQL where you'd create the DB separately)

import cgi, datetime

from google.appengine.api import usersfrom google.appengine.ext import webappfrom google.appengine.ext.webapp.util import run_wsgi_appfrom google.appengine.ext import db

class Powerusage(db.Model):author = db.UserProperty() # the usersensornum = db.IntegerProperty() # can have multiple sensorswatt = db.FloatProperty() # each sending us latest Watt measurementdate = db.DateTimeProperty(auto_now_add=True) # timestamp

We use the default includes. We have a single database table called Powerusage, and it has 4 entries: one for the user, one for the sensor number, one for the lastreported Watts used and one for a datestamp

Each 'page' or function of our webapp needs its own class. Lets start with the function that allows us to store data in the DB. I'll call it PowerUpdate.

class PowerUpdate(webapp.RequestHandler):def get(self):

# make the user log inif not users.get_current_user():self.redirect(users.create_login_url(self.request.uri))

powerusage = Powerusage()

if users.get_current_user():powerusage.author = users.get_current_user()#print self.requestif self.request.get('watt'):powerusage.watt = float(self.request.get('watt'))else:self.response.out.write('Couldnt find \'watt\' GET property!')returnif self.request.get('sensornum'):powerusage.sensornum = int(self.request.get('sensornum'))else:powerusage.sensornum = 0 # assume theres just one or something

powerusage.put()self.response.out.write('OK!')

Page 45: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

When we send a request to do that with a GET call (ie requesting the webpage), we'll first make sure the user is authenticated and logged in so we know their name.Then we'll create a new database entry by initializing a new instantiation of Powerusage. Then we'll look the GET request for the watt data, which would be in the formatwatt=39.2 or similar. That's parsed for us, thankfully and we can also get the sensor number which is passed in the format sensornum=3. Finally we can store the datainto the permanent database

Next is a useful debugging function, it will simply print out all the data it has received for your account!

class DumpData(webapp.RequestHandler):def get(self):

# make the user log inif not users.get_current_user():self.redirect(users.create_login_url(self.request.uri))

self.response.out.write('<html><body>Here is all the data you have sent us:<p>')

powerusages = db.GqlQuery("SELECT * FROM Powerusage WHERE author = :1 ORDER BY date", users.get_current_user())

for powerused in powerusages:if powerused.sensornum:self.response.out.write('<b>%s</b>\'s sensor #%d' %(powerused.author.nickname(), powerused.sensornum))else:self.response.out.write(<b>%s</b>' % powerused.author.nickname())

self.response.out.write(' used: %f Watts at %s<p>' % (powerused.watt, powerused.date))self.response.out.write("</body></html>")

This function simply SELECT's (retrieves) all the entries, sorts them by date and prints out each one at a time

Finally we'll make a basic 'front page' that will show the last couple of datapoints sent

class MainPage(webapp.RequestHandler):def get(self):

self.response.out.write('<html><body>Welcome to Wattcher!<p>Here are the last 10 datapoints:<p>')

powerusages = db.GqlQuery("SELECT * FROM Powerusage ORDER BY date DESC LIMIT 10")

for powerused in powerusages:if powerused.sensornum:self.response.out.write('<b>%s</b>\'s sensor #%d' %(powerused.author.nickname(), powerused.sensornum))else:self.response.out.write('<b>%s</b>' % powerused.author.nickname())

self.response.out.write(' used: %f Watts at %s<p>' % (powerused.watt, powerused.date))self.response.out.write("</body></html>")

Its very similar to the DataDump function but its only 10 points of data and from all users, nice to use when you just want to 'check it out' but don't want to log in

Finally, we have a little initializer structure that tells GAE what pages link to what functions

application = webapp.WSGIApplication([('/', MainPage),]('/report', PowerUpdate),('/dump', DumpData)],debug=True)

def main():run_wsgi_app(application)

if name == "main":main()

Test!

OK lets try it out, first lets visit http://wattcher.appspot.com/report

Remember we made it a requirement to supply -some- data. Lets try again http://wattcher.appspot.com/report?watt=19.22&sensornum=1

Yay we got an OK! Lets check out the data stored by visiting http://wattcher.appspot.com/dump

There's two entries because I did a little testing beforehand but you can see that there are 2 entries. Nice!

We can also visit the GAE control panel and browse the data 'by hand'

Anyways, now that that's working, lets go back and add the reporting technology to our sensor-reader script

Getting the report out

Only a little more hacking on the computer script and we're done. We want to add support for sending data to GAE. Unfortunately right now our authentication is donethrough Google accounts so its not easy to run on an Arduino. To adapt it you'd have to send the username in the Report GET and hope nobody else uses the same one(unless you also add a basic password system)

Anyhow, I totally ripped off how to do this from some nice people on the Internet

Download appengineauth.py from the download page, and change the first few lines if necessary. We hardcode the URL we're going to and the account/password as

Page 46: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

well as the GAE app name

users_email_address = "[email protected]"users_password = "mypassword"my_app_name = "wattcher"target_authenticated_google_app_engine_uri = 'http://wattcher.appspot.com/report'

The real work happens at this function sendreport where it connects and sends the Watt data to the GAE site

def sendreport(sensornum, watt):# this is where I actually want to go toserv_uri = target_authenticated_google_app_engine_uri + "?watt="+str(watt)+"&sensornum="+str(sensornum)

serv_args = {}serv_args['continue'] = serv_uriserv_args['auth'] = authtoken

full_serv_uri = "http://wattcher.appspot.com/_ah/login?%s" % (urllib.urlencode(serv_args))

serv_req = urllib2.Request(full_serv_uri)serv_resp = urllib2.urlopen(serv_req)serv_resp_body = serv_resp.read()

# serv_resp_body should contain the contents of the# target_authenticated_google_app_engine_uri page - as we will have been# redirected to that page automatically## to prove this, I'm just gonna print it outprint serv_resp_body

Finally, we wrap up by adding the following lines to our computer script, which will send the data nicely over to GAE!

# Also, send it to the app engineappengineauth.sendreport(xb.address_16, avgwattsused)

You can download the final script wattcher.py - final from the download page!

Don't forget to visit wattcher.appspot.com to check out the lastest readings

Page 47: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 17: Design - graphMaking pretty pictures

Data is great, but visualizations are better. In this step we'll manipulate our stored history so that we can make really nice graphs!

First we'll start by making our sensors named, so that its easier for us to keep track of which is what. Then we'll look at our graph options and data formats. Finally we'llreformat our data to make it ready for graphing

Configuring the sensor names

Its no fun to have data marked as "sensor #1" so I added a 'config' page where the app engine code looks at what sensor numbers have sent data to the database andthen allows you to name them. Of course, you need to have the sensor on and sending data -first- before this will work

The configure screen looks something like the image below.

This code uses GET when it should really use POST. I'm kinda old and dont like debugging with POST so...yeah.

class Configure(webapp.RequestHandler):def get(self):# make the user log in if no user name is suppliedif self.request.get('user'):account = users.User(self.request.get('user'))else:if not users.get_current_user():self.redirect(users.create_login_url(self.request.uri))account = users.get_current_user()

self.response.out.write('<html><body>Set up your sensornode names here:<p>')

# find all the sensors up to #10sensorset = []for i in range(10):c = db.GqlQuery("SELECT * FROM Powerusage WHERE author = :1 and sensornum = :2", users.get_current_user(), i)if c.get():sensorset.append(i)

Page 48: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

self.response.out.write('<form action="/config" method="get">')for sensor in sensorset:name = ""currnamequery = db.GqlQuery("SELECT * FROM Sensorname WHERE author = :1 AND sensornum = :2", users.get_current_user(), sensor)currname = currnamequery.get()

# first see if we're setting it!if self.request.get('sensornum'+str(sensor)):name = self.request.get('sensornum'+str(sensor))if not currname:currname = Sensorname() # create a new entrycurrname.sensornum = sensorcurrname.author = users.get_current_user()currname.sensorname = namecurrname.put()else:# we're not setting it so fetch current entryif currname:name = currname.sensorname

self.response.out.write('Sensor #'+str(sensor)+': <input type="text" name="sensornum'+str(sensor)+'" value="'+name+'"></text><p>')

self.response.out.write("""<div><input type="submit" value="Change names"></div></form></body></html>""")

Now we can have more useful data in the history dump

Now we can see that Phil is mostly to blame for our power bill!

Google Visualizer

So we have data and we'd like to see our power usage history. Graphing data is a lot of work, and I'm lazy. So I look online and find that Google -also- has a visualizationAPI! This means I don't have to write a bunch of graphical code, and can just plug into their system. Sweet!

OK checking out the gallery of available visualizations, I'm fond of this one, the Annotated Time Line

Note how you can easily see the graphs, scroll around, zoom in and out and each plot is labeled. Perfect for plotting power data!

Data formatting

Theres a few restrictions to how we get the data to the visualization api and our best option is JSon data. As far as I can tell, JSON is what happened when everyone said"wow, XML is really bulky and wasteful". Anyhow, theres like 4 layers of framework and interpretive data structions and in the end there was a pretty easy to use librarywritten by the Google Visualizations team that let me 'just do it' with a single call by putting the data into a python 'dictionary' in a certain format.

Lets go through the code in sections, since the function is quite long

class JSONout(webapp.RequestHandler):def get(self):

# make the user log in if no user name is suppliedif self.request.get('user'):account = users.User(self.request.get('user'))else:if not users.get_current_user():self.redirect(users.create_login_url(self.request.uri))account = users.get_current_user()

# assume we want 24 hours of datahistorytimebegin = 24if self.request.get('bhours'):historytimebegin = int(self.request.get('bhours'))

# assume we want data starting from 0 hours agohistorytimeend = 0if self.request.get('ehours'):historytimeend = int(self.request.get('ehours'))

# data format for JSON happinessdatastore = []columnnames = ["date"]columnset = set(columnnames)description ={"date": ("datetime", "Date")}

# the names of each sensor, if configuredsensornames = [None] * 10

First up we get the user we're going to be looking up the data for. Then we have two variables for defining the amount of data to grab. One is "ehours" (end hours) andthe other is "bhours". So if you wanted the last 5 hours, bhours would be 5 and ehours would be 0. If you wanted 5 hours from one day ago, bhours would be 29 andehours would be 24. datastore is where we will corall all the data. columnnames and description are the 'names' of each column. We always have a date column, thenanother column for each sensor stream. We also have a seperate array to cache the special sensor names.

onto the next section! Here is where we actually grab data from the database. Now app engine has this annoying restriction, you can only get 1000 points of data at onceso what I do is go through it 12 hours at a time. The final datastore has all the points but its easier on the database, I guess. One thing that's confusing perhaps is eachcolumn has a name and a description. The name is short, say "watts3" for sensor #3, but the description might be "Limor's workbench". I don't even remember writing this

Page 49: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

code so maybe you can figure it out on your own?

# we cant grab more than 1000 datapoints, thanks to free-app-engine restriction# thats about 3 sensors's worth in one day# so we will restrict to only grabbing 12 hours of data at a time, about 7 sensors worth

while (historytimebegin > historytimeend):if (historytimebegin - historytimeend) > 12:timebegin = datetime.timedelta(hours = -historytimebegin)timeend = datetime.timedelta(hours = -(historytimebegin-12))historytimebegin -= 12else:timebegin = datetime.timedelta(hours = -historytimebegin)historytimebegin = 0timeend = datetime.timedelta(hours = -historytimeend)

# grab all the sensor data for that time chunkpowerusages = db.GqlQuery("SELECT * FROM Powerusage WHERE date > :1 AND date < :2 AND author = :3 ORDER BY date", datetime.datetime.now()+timebegin,datetime.datetime.now()+timeend, account)

# sort them into the proper format and add sensor names from that DB if not done yetfor powerused in powerusages:coln = "watts" + str(powerused.sensornum)entry = {"date": powerused.date.replace(tzinfo=utc).astimezone(est), coln: powerused.watt}if not (coln in columnset):columnnames.append(coln)columnset = set(columnnames)# find the sensor name, if we canif (len(sensornames) < powerused.sensornum) or (not sensornames[powerused.sensornum]):currnamequery = db.GqlQuery("SELECT * FROM Sensorname WHERE author = :1 AND sensornum = :2", account, powerused.sensornum)name = currnamequery.get()

if not name:sensornames[powerused.sensornum] = "sensor #"+str(powerused.sensornum)else:sensornames[powerused.sensornum] = name.sensorname

description[coln] = ("number", sensornames[powerused.sensornum])#self.response.out.write(sensornames)

# add one entry at a timedatastore.append(entry)

Finally at the end of all the looping, we call the magic function that turns the dictionary into JSON, wrap it in the proper Google Visualization package, then spit it out!

# OK all the data is ready to go, print it out in JSON format!data_table = gviz_api.DataTable(description)data_table.LoadData(datastore)self.response.headers['Content-Type'] = 'text/plain'self.response.out.write(data_table.ToJSonResponse(columns_order=(columnnames),order_by="date"))

If you were to visit http://wattcher.appspot.com/[email protected]&bhours=1 it would output something like this:

google.visualization.Query.setResponse({'version':'0.5', 'reqId':'0', 'status':'OK', 'table': {cols:[{id:'date',label:'Date',type:'datetime'},{id:'watts1',label:'Limor',type:'number'},{id:'watts5',label:'Workbench',type:'number'},{id:'watts2',label:'Adafruit',type:'number'},{id:'watts4',label:'Phil2',type:'number'}],rows:[{c:[{v:new Date(2009,1,25,21,20,2)},{v:64.8332291619},,,{v:null}]},{c:[{v:new Date(2009,1,25,21,20,3)},,{v:230.122099757},,{v:null}]},{c:[{v:newDate(2009,1,25,21,20,3)},,,{v:65.4923925044},{v:null}]},{c:[{v:new Date(2009,1,25,21,20,4)},,,,{v:48.6947643311}]},{c:[{v:newDate(2009,1,25,21,25,3)},,{v:228.409810208},,{v:null}]},{c:[{v:new Date(2009,1,25,21,25,3)},{v:67.3574917331},,,{v:null}]},{c:[{v:newDate(2009,1,25,21,25,3)},,,{v:66.0046383897},{v:null}]},{c:[{v:new Date(2009,1,25,21,25,4)},,,,{v:47.3892235642}]},{c:[{v:newDate(2009,1,25,21,30,2)},{v:84.9379517795},,,{v:null}]},{c:[{v:new Date(2009,1,25,21,30,3)},,,,{v:99.7553490071}]},{c:[{v:newDate(2009,1,25,21,30,5)},,{v:229.73642288},,{v:null}]},{c:[{v:new Date(2009,1,25,21,30,6)},,,{v:66.6556291818},{v:null}]},{c:[{v:newDate(2009,1,25,21,35,2)},,,{v:67.3146052998},{v:null}]},{c:[{v:new Date(2009,1,25,21,35,3)},{v:96.2322216676},,,{v:null}]},{c:[{v:newDate(2009,1,25,21,35,3)},,{v:226.678267688},,{v:null}]},{c:[{v:new Date(2009,1,25,21,35,4)},,,,{v:158.428422765}]},{c:[{v:newDate(2009,1,25,21,40,3)},,{v:232.644574879},,{v:null}]},{c:[{v:new Date(2009,1,25,21,40,4)},,,,{v:153.666193493}]},{c:[{v:newDate(2009,1,25,21,40,6)},,,{v:66.7874343225},{v:null}]},{c:[{v:new Date(2009,1,25,21,40,12)},{v:95.0019590395},,,{v:null}]},{c:[{v:newDate(2009,1,25,21,40,21)},{v:95.0144043571},,,{v:null}]},{c:[{v:new Date(2009,1,25,21,40,23)},,,{v:66.8060307611},{v:null}]},{c:[{v:newDate(2009,1,25,21,45,2)},,,{v:66.9814723201},{v:null}]},{c:[{v:new Date(2009,1,25,21,45,3)},,{v:226.036818816},,{v:null}]},{c:[{v:newDate(2009,1,25,21,45,3)},{v:99.2775581827},,,{v:null}]},{c:[{v:new Date(2009,1,25,21,45,4)},,,,{v:154.261889366}]},{c:[{v:newDate(2009,1,25,21,50,4)},{v:102.104642018},,,{v:null}]},{c:[{v:new Date(2009,1,25,21,50,4)},,,,{v:155.441084531}]},{c:[{v:newDate(2009,1,25,21,50,5)},,,{v:67.0087146687},{v:null}]},{c:[{v:new Date(2009,1,25,21,50,5)},,{v:230.678636915},,{v:null}]},{c:[{v:newDate(2009,1,25,21,55,3)},{v:103.493297176},,,{v:null}]},{c:[{v:new Date(2009,1,25,21,55,3)},,,,{v:151.309223916}]},{c:[{v:newDate(2009,1,25,21,55,4)},,,{v:66.9174858741},{v:null}]},{c:[{v:new Date(2009,1,25,21,55,4)},,{v:227.765325835},,{v:null}]},{c:[{v:newDate(2009,1,25,22,0,3)},,,{v:67.0004310254},{v:null}]},{c:[{v:new Date(2009,1,25,22,0,3)},,,,{v:150.389989112}]},{c:[{v:newDate(2009,1,25,22,0,3)},,{v:230.892049553},,{v:null}]},{c:[{v:new Date(2009,1,25,22,0,4)},{v:92.2432771363},,,{v:null}]},{c:[{v:newDate(2009,1,25,22,15,3)},{v:97.5910440774},,,{v:null}]},{c:[{v:new Date(2009,1,25,22,15,3)},,,,{v:143.722595861}]},{c:[{v:newDate(2009,1,25,22,15,4)},,,{v:64.4898008851},{v:null}]},{c:[{v:new Date(2009,1,25,22,15,4)},,{v:222.357617868},,{v:null}]}]}});

Anyways, you can kinda see the data, also note its actually a function call, this stuff is really kinky!

Now go to the Google Visualizations Playground and enter in that URL into the sandbox

And you can see the visualization itself pop out! (this is just a screen shot so go do it yerself if you want to mess around)

OK go mess around, adding and changing bhours and ehours

Page 50: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Wrapping up the visualization

OK we're nearly done. Now we just need to basically grab the code from the sandbox and make it a subpage in our app engine...like so:

class Visualize(webapp.RequestHandler):def get(self):

# make the user log in if no user name is suppliedif self.request.get('user'):account = users.User(self.request.get('user'))else:if not users.get_current_user():self.redirect(users.create_login_url(self.request.uri))account = users.get_current_user()

historytimebegin = 24 # assume 24 hoursif self.request.get('bhours'):historytimebegin = int(self.request.get('bhours'))

historytimeend = 0 # assume 0 hours agoif self.request.get('ehours'):historytimeend = int(self.request.get('ehours'))

# get the first part, headers, outself.response.out.write(<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="content-type" content="text/html; charset=utf-8" /><title>Google Visualization API Sample</title><script type="text/javascript" src="http://www.google.com/jsapi"></script><script type="text/javascript">google.load("visualization", "1", {packages: ["annotatedtimeline"]});

function drawVisualizations() {)

# create our visualizationself.response.out.write(new google.visualization.Query("http://wattcher.appspot.com/visquery.json?user=+account.email()+&bhours=+str(historytimebegin)+").send(function(response) {new google.visualization.AnnotatedTimeLine(document.getElementById("visualization")).draw(response.getDataTable(), {"displayAnnotations": true});});)

self.response.out.write(}

google.setOnLoadCallback(drawVisualizations);</script></head><body style="font-family: Arial;border: 0 none;"><div id="visualization" style="width: 800px; height: 250px;"></div></body></html>)

The first part is pretty straight forward, get the user name or login. Then we will assume the user wants 1 last day of data, so set bhours and ehours. Then we literallyjust print out the code we copied from Google's Visualization sandbox, done!

Viz Viz Viz

The only thing I couldn't figure out is how to get 3 visualizations going on at once (last hour, day and week) with the above code. It just kinda broke. So for the triple view Ihad to use iframes :(

class VisualizeAll(webapp.RequestHandler):def get(self):

# make the user log in if no user name is suppliedif self.request.get('user'):account = users.User(self.request.get('user'))else:if not users.get_current_user():self.redirect(users.create_login_url(self.request.uri))account = users.get_current_user()

self.response.out.write(<h2>Power usage over the last hour:</h2><iframe src ="[email protected]&bhours=1" frameborder="0" width="100%" height="300px"><p>Your browser does not support iframes.</p></iframe>

<h2>Power usage over the last day:</h2><iframe src ="[email protected]&bhours=24" frameborder="0" width="100%" height="300px"><p>Your browser does not support iframes.</p></iframe>

Page 51: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

<h2>Power usage over the last week:</h2><iframe src ="[email protected]&bhours=168" frameborder="0" width="300%" height="500px"><p>Your browser does not support iframes.</p></iframe>

)

Anyhow, it works just fine.

Timecodes!

The final thing that wont be reviewed here is how I got the date and times to be EST instead of UTC. As far as I can tell, its kind of broken and mysterious. Check thecode if you want to figure it out.

Step 18: ResourcesOther power monitoring projects!

Get some good ideas here!

"Carbon Penance" a power monitor by Annina Rust that punishes the userJason Winter's Real-Time power monitorMazzini's project pushes data onto PachubePachube has lots of other projects!Furnace monitoring, using a DAQ board and phototransistor

Power monitoring productsWanna just buy it?

Black & Decker home electric meter watcherDIY KYOTO's power-clip Wattson is prettyCurrentCost

Websites & Software

Myenergyusage.org (one fellow upgrading his Wattson's software by hand)Wattzon.org (social energy information)

Page 52: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 19: DownloadSoftware

Zip file of the most recent python scripts this is what you want if you've built a tweet-a-watt and you want to get your project running

X-CTU profiles

Receiver, connected to computerTransmitter, embedded in the Kill-a-Watt. Change the unique ID if you have more than one!

Design files

All this stuff (other than the XBee library and the AppEngineAuth library, which are not written by me) is for you in the Public Domain! These are for debugging and designpurpose and show how the project is put together. If you just want to "run the code" see the "software" above

XBee libraryAppEngineAuth library for pythonWattcher.py - graph just the mains dataWattcher.py - graph mains and wattage dataWattcher.py - Reports averages every 5 minutesWattcher.py - Sends data to Wattcher Google App

For the latest code, please check the google code repository where you'll find any new code. And hey, are you good at this sort of code? I could really use some help. Itworks OK but it could look and run much better so please commit patches and hang out on the forum!

Related Instructables

Getting startedwith theMaxbotix sonarsensor - quickstart guide byadafruit

Proto Shield byadafruit

Musical MIDIShoes bythobson

Make your petdishes tweet! bythoughtfix

The BestArduino bymsuzuki777

Tilt SensorTutorial byadafruit

TemperatureSensor Tutorial!by adafruit

Quiz-O-Tron3000: Arduinoquiz contestantlockout systemby RoysterBot

Page 53: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Tweet-a-Pot: Twitter Enabled Coffee Potby frenzy on January 3, 2011

Author:frenzyI'm the QA engineer here at instructables. This is just a test

Intro:  Tweet-a-Pot: Twitter Enabled Coffee PotLike the idea of making coffee on the fly? from your bed? While you're on the bus coming home? Then the Tweet-a-pot is for you!

Tweet-a-pot is the next in fancy twitter enabled devices. This coffee pot enables its owner to make a pot of coffee from anywhere they have cell phone reception, usingtwitter and an arduino board.

The tweet-a-pot is the easy implementation for remote device control! with a bit of code and some hardware, you can have your very own twitter enabled coffee pot.

Take a look at this quick video, Special thanks to Sam:

Step 1: SuppliesTo make your very own tweet-a-pot you will need the following

1 Power Switch Tail, this is basically a relay that is used to interface with the AC voltage1 Arduino Board (any will do)1 Computer running the arduino IDE and Python1 Drip Coffee Pot

Page 54: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 2: Setting Up Your ComputerFirst you need to set up your receiving computer.

To interface between the arduino and twitter, we are going to use python. There is a library that is already put together that enables us to use the twitter API. It's calledpython-twitter.

After you have installed python, install the python-twitter library and all its dependencies. If you run into trouble just consult the documentation over on the python-twitterwebsite.

Next, install the Arduino IDE so you can program your arduino and talk to it via serial port.

Once those are set up and working, time to go grab your credentials from twitter.com

Step 3: Setting up TwitterInterfacing with twitter used to be easy, all you had to do was put your name and password into your code and it would work. Now twitter has taken user info moreseriously using oAuth, and as a result now you must register your app with twitter and get an API key.

First, make a twitter account for this project that is separate from your main twitter account. I chose, driptwit. 

Then, go to dev.twitter.com and register your app, this will enable you to grab 4 important pieces of information

-Access Token-Access Token Secret-Consumer Key-Consumer Secret

These keys will be needed in the python code later to interface with the twitter API. After you have those 4 codes, you should be able to continue.

Page 55: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 4: The Code: Python SideFirst lets go over our python code. The python code basically uses the python-twitter library to ask twitter for the statuses of user "x", it then takes the last status andsearches for the term "#driptwit".if found sends the ascii value of 1 to the serial port (and to the arduino), if #driptwitstop is found, it sends an ascii value of 0.Lastly it loops and checks the twitter account every 15 seconds looking for changes.

As you can see, below is where you enter the keys you got from twitter in the last step.

Here is the actual code:

#******************************************## Tweet-a-Pot by Gregg Horton 2011 ## Please email changes or ## updates to [email protected] ## *****************************************#

##Import Libraries

import twitterimport serialimport time

##authenticate yourself with twitterapi = twitter.Api(consumer_key='consumerkeyhere', consumer_secret='consumersecrethere', access_token_key='accesskey', access_token_secret='accesssecret')

##set to your serial portser = serial.Serial('/dev/ttyUSB0', 19200)

## check serial portdef checkokay():ser.flushInput()time.sleep(3)line=ser.readline()time.sleep(3)

if line == ' ':line=ser.readline()print 'here'## Welcome messageprint 'Welcome To Drip Twit!'print 'Making Coffee..'def driptwit():status = [ ]x = 0

status = api.GetUserTimeline('X') ##grab latest statuses

checkIt = [s.text for s in status] ##put status in an array

drip = checkIt[0].split() ##split first tweet into words

## check for match and write to serial if matchif drip[0] == '#driptwit':print 'Tweet Recieved, Making Coffee'ser.write('1')elif drip[0] == '#driptwitstop': ##break if doneser.write('0')print 'stopped, awaiting instructions.'else:ser.write('0')print 'Awaiting Tweet'

while 1:driptwit() ## call driptwit functiontime.sleep(15) ## sleep for 15 seconds to avoid rate limiting

File Downloads

Page 56: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

driptwitsample.py (1 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'driptwitsample.py']

Step 5: The Code: Arduino SideThe only connection between the python code and arduino is a single serial value. Python sends this as an ascii value, so arduino interprets this as a bit number, in ourcase 1= 49.

I didn't know how to make python spit out serial bytes, so after seeing what the python code was sending, i just modified the arduino code to react to the right value.

Here is the code:

/*Tweet-a-pot Gregg Horton 2011Please email changes to [email protected] so ican improve this code!

Enables blinking/relay control over twitter, using python codeBased off of Blink and Serial demo code

*/

int relayPin = 13; // LED connected to digital pin 13int incomingByte = 0; //declare incoming byte// The setup() method runs once, when the sketch starts

void setup() {// initialize the digital pin as an output:pinMode(relayPin, OUTPUT);Serial.begin(19200); // set up Serial library at 19200 bps

Serial.println("Arduino is ready!");}

// the loop() method runs over and over again,// as long as the Arduino has power

void loop(){if (Serial.available() > 0) {// read the incoming byte:incomingByte = Serial.read();Serial.println(incomingByte);if (incomingByte == 49){digitalWrite(relayPin, HIGH);} else {digitalWrite(relayPin, LOW);}

// say what you got:Serial.print("I received: ");Serial.println(incomingByte, DEC);}}

File Downloads

driptwit.pde (1 KB)

Page 57: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

[NOTE: When saving, if you see .tmp as the file ext, rename it to 'driptwit.pde']

Step 6: Hardware SetupThe hardware set up is pretty simple, as the AC voltage control is being handled by the power switch tail

The power switch tail allows you to hook up 2 wires, one to ground and one to the control pin, to turn on and off the relay. As seen in the code, all you need is a simplehigh/low statement.

Connect the arduino to your computer and make sure your serial port is set, then plug the power switch tail leads into pin 13 and ground

Next connect the coffee pot to the relay and plug the relay into a regular outlet. Its that easy!

The coffee maker has to have coffee and water in it as well before you begin.

Step 7: Make Some CoffeeI did a lot of testing before hooking this up to an actual coffee pot (and even then found some bugs), but once you get it working, its time to make coffee!

Fill the pot with water and coffee grounds, and tweet to the account the code is following.

If the message contains the word #driptwit the coffee will start, if it receives #driptwitstop, or you tweet something else it will stop.

Once the pot of coffee is done, tweet again to turn it off. Its that easy!

Then enjoy your hot piping cup of tweet coffee.

Image Notes1. Yum!

Image Notes1. Coffee Time!

Page 58: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Image Notes1. After Tweet Is Recieved the Pot Turns On

Page 59: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 8: Final ThoughtsThis project can be extended to any AC device that you want to control remotely. You could turn on lights or open garage doors with the same concepts

The code is not perfect, any improvements that people give me i will gladly include and test out. A large improvement on this project would be to integrate an ethernetshield so you wouldn't have to have a dedicated computer.

I want to give special thanks to the team the developed the python-twitter library, without them this project would be much harder.

Related Instructables

Ironic MustacheTwitter Interfaceby frenzy

simpleTweet_01python bypdxnat

Twitter MentionMood Light bypdxnat

simpleTweet_00processing bypdxnat

Back home bypaasselin

Make your petdishes tweet! bythoughtfix

Use twitter andweather to postnotes andtemperature tooffice door(Photos) bybogdanzalmoxis

The TwitteringOffice Chair byrandofo

Page 60: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

The Twittering Office Chairby randofo on January 25, 2009

Author:randofo    Randy Sarafan loves you!I am the author of the book '62 Projects to Make with a Dead Computer' and Community Manager here at Instructables. I'm always sharing tons of awesomeprojects. Subscribing to me = fun and excitement!

Intro:  The Twittering Office ChairThe Twittering office chair "tweets" (posts a Twitter update) upon the detection of natural gas such as that produced by human flatulence. This is part of my commitmentto accurately document and share my life as it happens.

For more in depth theory, please see the next step entitled Theory.

See the results of the toots of your on labor on Twitter.

Step 1: TheoryAccording to my coworker, Twitter is supposed to happen in that space between Flickr posts and Facebook updates, in the space when life actually happens. Well, in thespace of time "when life actually happens," life actually happens. It is neither pretty nor ugly. It is just life. If Twitter is supposed to be a document of life as it happens,then it should really document life, indiscriminately, as it happens without interference. If it fails to do this, then life then becomes the space between "tweets" (Twitterposts).

Therefore, it is of the utmost importance, to be able to update Twitter with life events without actually interfering with the event themselves. The documentation of life,henceforth, needs to be automated.

That said, I decided the first part of life that needed to be documented was my daily flatulence at work. I am not going to lie, I am a gassy individual. Since my flatulence isa part of life, it would be fraudulent of me to document life as it happens without documenting these occurrences.

In keeping with the process of non-interference in daily activity, I have created an office chair to both detect and Twitter my flatulence without having to bother me toupdate it myself.

Page 61: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 2: Go get stuffYou will need:

- Office chair- Squidbee TX/RX pair- 1/8" piece of acrylic- 50K trimpot- Natural gas sensor- Solid hookup wire- Soldering setup- Laser cutter (or saw and drill)- Razor blade- Screwdriver set- Drill- Nuts and bolts (or screws)- Pliers- A staple gun- Python- A Twitter account

Page 62: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 3: Make a sensor mountMake a sensor mount by downloading the attached Corel file and laser cutting your 1/8 piece of acrylic using your awesome Epilog laser cutter.

Did I mention how awesome Epilog laser cutters are?

Anyhow... If, unlike us at Instructables, you do not have a laser cutter, you can download the file and print it to paper. Cut out the circular outline from the sheet of paperand tape this to your acrylic as a guide. Where necessary, drill holes through the acrylic using a power drill and cut around the outline with a jigsaw (or similar).

Page 63: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

File Downloads

naturalGasTemplate.cdr (13 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'naturalGasTemplate.cdr']

Step 4: Attach the sensorAttach the sensor to the mounting bracket by follow the wiring in the schematic pictured. If you don't have a trimpot, you can insert a resistor value between 22K and 47K(a trimpot is recommended).

When the components are inserted, solder them in place. You may want to first cut off any extra leads that may confuse you.

See the datasheet here.

Page 64: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 65: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 5: Plug it inOpen your Squidbee (assuming you didn't make one yourself) and detach all of the useless sensors. Plug in your natural gas detecting sensor such that the power goesto the power socket and the data line goes to pin 2 (as shown).

Page 66: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 67: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 68: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 6: Program the SquidbeeNow is the time to program your Squidbee with the code to read the analog sensor.

First things first, unplug the Xbee shield from the Arduino (the part of the Squidbee the sensor is plugged into). Also, change the power jumper from battery to USBpower.

Next, plug the Arduino into your USB port.

Open the Arduino programmer.

Set the Serial port (usually looks like /dev/tty.usbserial-A70048pF). Write down the serial port address for future reference.

Download, open and hit the "play" button to compile the code (download below). Upload the code to your Arduino.

Unplug the Arduino from your computer. Switch the jumper back to battery power and put the Xbee shield back on.

Page 69: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

File Downloads

TwitChairCode.zip (635 bytes)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'TwitChairCode.zip']

Step 7: Connect to the computerWhen you are ready to start taking sensor readings, plug your 9V battery into the Squidbee transmitter and connect the receiver to the computer.

You can see the incoming stream of data by watching the serial monitor in the Arduino interface on your computer.

Page 70: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 8: PythonBefore you can go any farther, you need Python.

If you are using a Mac with a recent version of OS X, you should have Python already.

Open the Terminal, type into the command prompt "python" and hit "enter."

This should open up Python.

To see Python do its thing type:print 'hello world' (and hit Enter)

This will return "Hello World" in the prompt.

To quit Python hit "control-D".

If you don't have Python, you can go download it here and install it by following the instructions listed.

Step 9: DependenciesThere are a number of hoops you have to jump through before you can run the Python code in the next step.

The first thing you need is the setuptools shell script. Open terminal and change your working directory to the directory setuptools is in. You can change directories bytyping "cd nameofdirectory" and hitting "enter". and you can look at what directories are in your current location by typing in "ls" and hitting "enter".

Once you are in the correct directory, install the shell script by typing chmod setuptools.egg (or whatever the exact name of the file is. Do not rename the file). This mayrequire entering your administrator password. Do so when prompted and hit "enter".

You should now be able to use Easy Install, which, happens to be one of the greatest pieces of code ever written. Once you have Easy Install you just need to type intothe command prompt "easy_install" followed by the name of the package you are trying to download and hit "enter." For example, "easy_install greatcode" (not a realexample). Next thing you know, you have downloaded and installed the whole "greatcode" package for use in your own code.

Open your prompt and type each line below and hit enter. This will install the Simple Json, Twitter, Time and advanced Math (numpy) packages.

easy_install simplejsoneasy_install pyserialeasy_instally numpyeasy_instally time

Download and install Python Twitter by following the directions on the page (you might even just try "easy_install twitter").

Page 71: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 10: CodeThis project was a great excuse for me to start to learn Python. As a novice, this code is not perfect, but it gets the job done. If you any have suggestions as to how thismay be improved, please let me know.

That said, some helpful things I learned about Python include:One of Python's greatest features (or possibly the worst?) is its lack of syntax. You rarely need to remember a closing or opening tag. You can just keep typing out linesof code and Python will try its best to process it.

Python processes blocks of code based on their indentation. Improper indentation can result in catastrophe. For instance, the only way the code knows that something ispart of a for loop is because it is indented the same as everything else that is also part of that loop. This can start to get tricky with nested loops (loops inside of loops)and lead to confusion and bad code.

Python's function system is confusing on a number of levels (for instance some variables are mutable and some not). I don't fully understand the complexities offunctions, but if you are interested, you should definitely look it up.

The code we are going to use includes a number of packages, a collection of functions that can be invoked at will (see last step for more information about installingpackages).

We are importing the following packages:- Python Twitter- PySerial- Numpy- Time- Random

The code is as follows:

#!/usr/bin/python #Filename: TwitterChair.pyimport twitterimport serialimport numpyimport timeimport random## Your username and password here#api = twitter.Api(username='yourusername', password='yourpassword')## Change this to match your serial port#ser = serial.Serial('/dev/tty.usbserial-A70063pF', 19200)serialArray = []global gassygassy = 0def checkokay(): ser.flushInput() time.sleep(3) line=ser.readline() time.sleep(3) if line == ' ': line=ser.readline() print 'here'def startvalues(i): while i <= 50: #time.sleep(.25) line=ser.readline() serialArray.append(int(line)) ser.flushInput() i=i+1 print serialArraycheckokay()startvalues(0)def main(i, i1): ArrayTransfer = numpy.array(i) ComparatorValue = int(numpy.mean(ArrayTransfer)) print ComparatorValue lastReading = ComparatorValue print lastReading loopy = i1 print loopy y = 0 x = 0 while y < 10: while x < 5: line=ser.readline() currentReading = int(line) if currentReading > lastReading: lastReading = currentReading print lastReading print currentReading time.sleep(6) ser.flushInput() x=x+1 print 'half minute' x=0 y=y+1 if lastReading > (ComparatorValue + 50): i1 = 1 if i1 == 1: sayings = ["He farted again with success and vigor. Woest me.", "Pfffffffffft", "Ugh. That was a gross one", "Someone please disassemble me", "If I could puke my foam stuffing, I would", "I wish I were some other chair", "He farted right on me again", "Didn't hear that coming", "allow me to repeat... ppppfffffffffftttttttttttt", "It wasn't always like this."] pickSaying = random.randint(0,9) print pickSaying status = api.PostUpdate(sayings[pickSaying]) loopy = 0 print 'done' if __name__ == "__main__": main(serialArray, loopy)main(serialArray, gassy)

File Downloads

TwitterChair.py (1 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'TwitterChair.py']

Step 11: Disassemble the chairMark on the seat of the chair the space between your bottom and the bottom of the backer. This is the space in which you want to install the sensor.

Remove the seat from the chair assembly and undo the upholstery until you can access the foam in the area in which you marked.

Page 72: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 73: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 12: Undo the upholsteryThe fabric on your chair is probably held on with staple.

Remove the staples from the back side of the seat such that you can pull up a little of the fabric.

Page 74: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 13: Modify the cushionRip up the foam so that there is a pocket in which the sensor can be inserted into the chair. I found using a razor blade to get the hole started, made it slightly easier.

Page 75: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 14: Insert the sensorInsert the sensor into the hole you just made in the cushion of the chair's seat. If possible, angle the sensor slightly towards where your rear will be.

Step 15: ReassemblePut the chair back together. This means reupholstering it with a staple gun and refastening any nuts and bolts.

Page 76: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 77: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 16: Bottoms upSomehow, fasten the transmitter box to the bottom of the chair's seat in a manner that you can still open and close the case.

I chose to attach mine using hot glue. You can also use things like nuts and bolts.

This may require first emptying the case.

Page 78: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 17: Turn it onPlug the battery into the transmitter attached to the chair and close the case.

Plug the receiver into the computer.

Image Notes1. When strange men tell me to label all of my work with strange stickers that Idon't understand, I listen!

Step 18: Run the codeRun the code by opening the terminal, navigating to the directory the file is located in and typing in python TwitterChair.py

If you didn't download the python file yet from the "code" step, download it from this step!

File Downloads

Page 79: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

TwitterChair.py (1 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'TwitterChair.py']

Step 19: TweetTweet when you toot. Happily let people know that you are engaging in life as it happens.

Related Instructables

simpleTweet_00processing bypdxnat

TweetingAttendant(Photos) bynaturallyresistant

ImageCapturing BirdFeeder byquasiben

Tweet-a-watt -How to make atwittering powermeter... byadafruit

simpleTweet_01python bypdxnat

Use twitter andweather to postnotes andtemperature tooffice door(Photos) bybogdanzalmoxis

Do notEnter(Twitter-updates)(WithoutEthernet Sheild)(Photos) byvishalapar

TwittercontrolledArduinoOutputs - no PC- LCD Display +Sensor data toTwitter byXenonJohn

Page 80: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Arduino sprinkler valves + wifi + twitterby nicoo on May 19, 2011

Intro:  Arduino sprinkler valves + wifi + twitterThis is my first post so... be brutal !

I have a small yard with a very odd shape, well... L-shaped really and not enough pressure at the tap to be able to water it in one go. So I had to create 3 sprinkler subsystems that can only be turned on one at a time.

I sourced 3 Gardena valves but refused to cough up the extra cash for their dull 'computer' (not sure why they call it a computer btw). Besides, controlling the valves froma browser was the bear minimum I would expect and Gardena does not offer this functionality. (My friend) dd-wrt even allowed me to re-use an old router of mine andmade the whole thing wireless...

Arduino time, I say...

As a bonus, I inserted at the end of this instructable my scripts that automagically turn the sprinklers on and off, check the weather forecast (so I don't water the lawn if itis going to rain soon) and log their activity on twitter.

Enjoy !

Here are the parts I used for this project:

- various pipes / hose adapters (from Gardena)- 3 x 24v Irrigation Valve (from Gardena)- 1 x arduino board- 1 x ethernet shield (www.nuelectoronics.com )- 1 x relay board (which I had lying around, a smaller board / a relay shield - with at least 3 relays - would have been sufficient)- 1 x 220v -> 24vAC transformer (from ebay)- 1 x 10vDC adaptor (a recycled phone charger)- 1 x router (Buffalo WHR-G125) with dd-wrt (http://www.dd-wrt.com )- 2 x momentary push button- 1 x power switch- a couple of meters of ethernet cable.

Image Notes1. valves2. relay board3. arduino ethernet shield4. 220v AC to 24v AC5. manual controls6. dd-wrt wifi client. Can connect to an existing wifi network.7. 10v DC8. water from the tap.9. to the garden

Page 81: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 1: The water part.The valves are very simple to use. They are closed by default and get magically opened by powering their solenoids with 24v AC.

I found this transformer on ebay for not very much. 230v AC -> 24v AC (did I mention I am in Europe ?), that will do.

Image Notes1. main water arrives here.2. arduino can turn sub systems on or off.3. a 24v AC valve.

Image Notes1. 220v 50-60hz2. 24V AC 2.5 amp, that's plenty !

Step 2: Arduino + Ethernet shieldI used an arduino (atmega328) with an ethernet shield from www.nuelectronics.com.3 digital pins are controlling 3 relays that let the 24v AC through.A 4th digital pin is used for the ground for convenience sake, really (the connector that came with the relay board conveniently had 3 relays + ground on 4 adjacent pins...if that makes sense...).

An old cell phone charger gives me 10v DC which I get to the arduino through the Vin + GND pins.

Finally, I added a couple of push buttons for manual control. I use the Analog input trick (different resistor values give different analog reads for each button). In the end Ionly used one of them.

Page 82: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 3: Schematics- arduino ethernet shield.- 3 relays on the digital pins (the actual connection to the relays is not as simple-minded as this diagram as I use a whole relay board).- 2 push buttons.

Page 83: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 4: Relay boardThe relay board needed a little bit of juice and could not be powered by a 9v battery.The power adapter I found delivers 10v 05.A and that's plenty. As a bonus it also powers the arduino.

I used an ethernet cable to link the relay board to the valves.

Due to popular demand here is a little bit more on "relay boards":

A relay is a mechanical switch that can let through a voltage that is not compatible with your typical microcontroller voltage. In my case I needed my arduino to open andclose a switch on my 24V AC circuit (the one that controls the valves).

The "controlling side" of a relay is driven by a transistor connected to the microcontroller pins. I connected my arduino pins (ground + 3 pins) to the input connector of theboard which in turn connects me to said transistors.

It turned out that the Arduino pins were not powerful enough to drive the relay coils so I also connected an external power supply to the board. The arduino pins controlthe transistors bases and the power going through the transistors and the coils comes from the optional external power supply (otherwise it comes from the arduino pinsthemselves).

This is a very standard setup and relay boards (also known as relay modules), whether they propose one, two or more relays, will always offer the following:- control pins (ground + 1 pin per relay) to connect to your arduino.- external power supply pins (ground + Vcc) to be used if necessary.- 3 connectors per relay : you use the middle one (Common) and one of the other two whether you want the controlled circuit to be normally open (NO) or normally closed(NC) when the relay is not powered.

I sourced the 8 relay board on ebay (search for 'arduino relay module', sort by price, get the cheapest one that fits your needs, i.e. that can let through enough Volts &Amps - usually they have different V&A combinations for AC and DC -).

Image Notes1. the 3 relays used for this project2. 10v DC from the phone charger.3. 4 pins from the arduino4. 24v AC5. to the valves

Step 5: Manual controlA *very* cheap control box.

Basic On/Off switch and a couple of push buttons connected to an analog pin of the arduino.

Voila.

I now realize that the white and black wires are both Ground. Could have done the same with 3 wires, oh well...

Page 84: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Image Notes1. black-red : 10v DC2. green-white: analog pin / ground3. 2.2k resistor

Image Notes1. 3 power outlets ! - phone charger - 24v AC transformer - router power adapter

Step 6: ConnectorsThe ethernet cable is connected to the valves.

Image Notes1. common wire2. valve 13. valve 24. valve 3

Image Notes1. main water arrives here.2. arduino can turn sub systems on or off.3. a 24v AC valve.

Image Notes1. ethernet cable.

Page 85: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 7: Arduino sketchI hacked an example sketch that came with the shield.

I used arduino 0017 (pretty dated, I know...) so this code should be compatible with anyone using revision 17 and above (should be a lot of people !).

Quick comments:

- The following code turns on the pull-up resistor of the analog input. A good thing to know.

pinMode(analogInPin, INPUT);digitalWrite(analogInPin, HIGH); // turn on pull-up resistor

- I added a check on the size of the buffer that holds the page, so you have an indication that bad things happened if the buffer was too small.

- The manual button cycles through the valves.

- The web interface can turn on/off any combination of valves.

- The valves are turned off automagically after 20 minutes (can be modified, time in seconds, 0 disables the functionality).

File Downloads

garden_sketch.txt (10 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'garden_sketch.txt']

Step 8: Web interfaceI gave the IP 192.168.74.6 to my arduino.

Pointing a browser at it should get you something like the picture above.

Note the fancy coloring. ;-)

Step 9: Wireless + scripting

Now, for the cherry on the cake.

1.  Wireless

As you probably already know, dd-wrt is an open-source firmware for routers. It installed nicely on my old buffalo and I could turn said buffalo into a wifi client thatconnects to my wifi network and serves as a bridge for any device physically plugged into the (former) router.

Arduino + ethershield is no exception and it can now be accessed to wirelessly...

Google is your friend and the keywords are 'dd-wrt wireless bridge'.

2. Script interface

This should not come as a big surprise, but I'll mention it anyway. The valves can be controlled from the command line using wget.

This allows for scripting, cron jobs etc...

For example, to turn on valve #1, use the following command:

wget '192.168.74.6/?cmd=2'

Page 86: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Image Notes1. Plug into a port of the client bridge instead of your usual switch.

Step 10: Voila.

Image Notes1. 3 power outlets ! - phone charger - 24v AC transformer - router power adapter

Page 87: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 11: TwitterMy watering system is now installed. It is crontrolled by a cron job on my home server (linux box running Ubuntu).

The sprinklers are turned on one after the other, 3 times a week unless rain is announced for the next day.

Every action is logged and sent to a twitter thread.

Here is the magic (in bash):

- crontab.txt: insert these lines into the crontab of your favorite server.

- weather.sh: connects to www.weather.com. Change your location ('where' in the script).

- twit.sh: sends a twit. Change your username + password

- sprinkler.sh: turns sprinklers on anf off, check the weather forecast and sends twits.

File Downloads

crontab.txt (383 bytes)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'crontab.txt']

twit.txt (1 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'twit.txt']

weather.txt (489 bytes)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'weather.txt']

sprinkler.txt (2 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'sprinkler.txt']

Related Instructables

Tweeting WiFiRadio ControlPanel (Photos)by schazamp

DisplayingTwitter feedwithout a PC! byfabrizio.granelli

TerrariumTwitterMonitoring byMarioBoehmer

Tweet'n'knock -Tweeting theknock (Photos)byfabrizio.granelli

TwittercontrolledArduinoOutputs - no PC- LCD Display +Sensor data toTwitter byXenonJohn

Web-controlledTwitteringRoomba bymatchlighter

Twitter SensingThermoelectricComponent byEngidan

Do notEnter(Twitter-updates)(WithoutEthernet Sheild)(Photos) byvishalapar

Page 88: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Garduino Upgrade, Now with more Twitter!by natantus on November 14, 2009

Author:natantus    Chris Gilmer ProjectI'm a software and aerospace engineer. When I've got free time I like to work on robot projects. I want to stay involved with education and the open hardwarecommunity.

Intro:  Garduino Upgrade, Now with more Twitter!A couple months ago I came across two great instructables.  The first was the Garduino, an arduino controlled garden to help you grow plants at home.  The second wasthe Tweet-a-Watt, a project that teaches you how to monitor your home power usage using Xbees and Twitter.  I read about both these projects here at Instructables andin Make Magazine, Vol 18. 

I thought it would be great to combine both these projects and build myself an indoor garden that I could monitor from work via Twitter.  Thus began an adventure ingardening and electronics that taught me a lot and took me much longer than perhaps it should have.  Fortunately for you I'm going to write down all the steps so you canget started right away.  Maybe you'll follow up with this project and upgrade your garden or use this as a guide to start on a similar project.  Either way, I hope you'll letme know what you get up to.

If you're ready then head to the next step and begin the process!

Edit: Please see the code now posted on GitHub - https://github.com/chrisgilmerproj/garduino-upgrade

Image Notes1. Basil plant good for soups2. Mint good for ... what isn't it good for?3. Water bucket with pump4. Foil keeps the light inside5. Planter with lots of yummy soil6. SEnsor board7. Pump relay box8. Light relay box9. Arduino running it all10. Power to all the good stuff here11. Light for the plant from the "Hydroponics Store"12. Starter kit for garden drip system

Image Notes1. Hadn't thought of the foil idea yet2. Plants! They grow!3. All the good upgrades for this project4. Water ... note that it's not on my kitchen floor yet5. Box of goodies

Step 1: Gather your materialsThis project is really two projects in one.  It is both a gardening project and a wireless project.  But, as is true with any project, getting your materials will probably be thehardest part.  This is because building can move along pretty fast once you have everything, but it's finding out you're missing the one crucial piece that always holdsthings up.  Below is a list of web pages from my wiki with a list of all the parts you'll need.  Go ahead and take a look, I've listed them with as much detail as I could and ifI've left something out just let me know so I can add it to the list.

Various Parts Lists:

Garduino Parts ListRelay Box Parts ListArduino Xbee Adapter Parts List

I highly recommend you buy a couple extra parts here and there.  You'll find, as I did, that they come in handy when you make a mistake.  For the majority of the partsnothing is particularly expensive so buying a few extra things won't hurt.

Page 89: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 2: Build your GarduinoThe Garduino Instructable is probably your best resource for starting this project.  It has tons of great insights that will help you get started with your own arduinocontrolled garden.  He has also put together a website with more pictures and a kit that you can get, but I chose to build this project with my own parts.

When you get started you'll want to get some plants and a place to plant them.  I recommend a local gardening store where possible.  You'll pick up some healthy plantsthere and probably a few good tips on how to care for them.  I picked up basil and mint, a couple plants I'd find useful to have for cooking.  I also got an 8" x 18" planterwith a matching dish to catch water.  You can certainly go out and use tubs or custom pots, just choose what's right for you and your plants.  Also, pick something that willlook nice around your house if that's important to you.

The first thing that is different about my project is that I was building an indoor garden.  My apartment doesn't have a lot of light from any of the windows, nor does anygood light fall on the patio.  This changed a lot of the parameters for my garden.  For one, I didn't need a light or temperature sensor, something I discovered after thefact, as my light will be constant from the fluorescent bulb and my temperature inside the apartment is pretty stable. 

I also learned that whether you choose to keep your plants inside or outside you should be aware of bugs.  My first plants died because of spider mites, somethingI hadn't even thought of when starting this project.  I found the solution was actually pretty easy, involving a spray bottle, a tiny bit of soap and water.  It's a much cleanersolution, especially if you plan to eat your plants, and doesn't hurt the environment either.

Image Notes1. Basil plant good for soups2. Mint good for ... what isn't it good for?3. Water bucket with pump4. Foil keeps the light inside5. Planter with lots of yummy soil6. SEnsor board7. Pump relay box8. Light relay box9. Arduino running it all10. Power to all the good stuff here11. Light for the plant from the "Hydroponics Store"12. Starter kit for garden drip system

Image Notes1. Defense against spider mites!

Step 3: Upgrade #1: Remote SensorsOne of my early upgrades to this project was to take the sensors off the arduino and put them closer to the plants.  I wanted to do this primarily to keep the arduino as faraway from the water and water pump as possible.  The nice thing about this is that you can put your arduino somewhere accessible and safe and keep the sensors youwant closer to the plants, where they are needed.  Is this a good idea?  Maybe, but I was happy to do it.

My sensor was designed to have the temperature, light and moisture sensors onboard.  Also, I included 2 red LEDs so that I could indicate if the plants were beingwatered or if the temperature went out of an acceptable range.  Of course this was before I had decided to keep the plants indoors, so in retrospect I'd probably ditch thetemp and light sensor and leave the LED on the arduino.  Better yet I could have just used the onboard LED connected to pin 13 on the arduino.  Then all I'd have is twowires leaving the arduino to act as the moisture sensor for the plant.  Regardless, this was a fun part of the project and I learned a lot.

You can download the schematic and board layout files I created.  I decided to build the board by hand instead of having it manufactured for me primarily due to cost.

Page 90: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Image Notes1. All the sesors and lights that tell my arduino what the plant is up to2. Down here are the nails that act as the moisture sensor3. Nails act as the moisture sensors for the plant4. The light was thankfully turned off for this photo

Image Notes1. A ton of resistors2. LEDs tell me about the temperature and the pump3. Temperature sensor4. light sensor, pretty useless right here5. Moisture Sensor wires

File Downloads

garden_sensor.brd (10 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'garden_sensor.brd']

Page 91: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

garden_sensor.sch (69 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'garden_sensor.sch']

Step 4: Update #2: Relay BoxesThe most important upgrade I think I made was to build real relay boxes to control my power to the light and the water pump.  With water so close to the electricity Ifigured a safer approach was needed than the one used in the original Garduino instructable.  Fortunately the author pointed out a great resource at SparkFun that I usedto do the project. 

Finding the whole thing incredibly useful I wrote up another instructable on how I built my relay boxes and made it more generic for other projects where you might wantan arduino to control power.  Check out the Arduino Controlled Relay Box Instructable when you get a chance.

At this point I decided to add on an arduino protoboard to my project so that I could have access to more power lines without having to solder together a newbreadboard.  You may choose to do something different, but this made things significantly easier, especially if I decide to do more modification later.

If you don't do anything else with your Garduino definitely do this upgrade.  It's definitely the most important.

Image Notes1. Test and Reset buttons2. Extension cord wires3. Nail mount housing hides in the shadows!4. Control wires

Image Notes1. Nail mount housing2. GFCI Outlet3. Relay circuit completed4. Hot wire disconnected from the extension cord5. Extension cord

Image Notes1. Relay - 240/120V, 30A2. Load connectors3. Control connectors to Arduino4. LED tells you its on or off5. Diode to protect microcontroller6. Transistor does all the hard work for no pay!

Page 92: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Image Notes1. Breadboard for circuit2. Beefy Relay3. Load connector4. Control connector5. Bright red LED6. Transistor7. Diode8. Resistor9. Resistors, same type

Step 5: Upgrade #3: New SoftwareNow it's time for the software upgrade.  With an indoor garden I no longer had the need to have the entire project be automated within the arduino.  The original arduinokept an internal clock and counted the amount of daylight from the light sensor against the number of seconds in the day.  I found this to be more frustrating than it wasworth once I moved inside and stopped using the light sensor.  This was primarily because I found that the light cycle revolved around when I power cycled the arduino,having no way to set the internal clock myself.

In fact I thought I could do a better job regulating the time from my laptop.  Not only would the light only be on at night and in the morning when I wouldn't care, but I couldreset the arduino power at any time and it wouldn't change this schedule.  The added advantage to this method would be that I'd also be able to record the sensorreadings from the garden to look at them later. 

To get started you have to know that the arduino can talk over a serial connection to your laptop.  You probably already knew this, but what you may not know is that youcan use the Python programming language to read and talk to the arduino.  This is great because it opens up all sorts of tools for you to use when interacting with yourarduino.

For this you'll need to download and install the following:

Arduino IDE (0017 or later)Python (preferably 2.6.X or later)PySerial Library

At this point I also want to direct you to the Arduino Controlled Servo Robot project by Oomlout.  My methods roughly follow what I learned there.  The basic premise isthat you'll be sending a command from the laptop to the arduino every 15 seconds.  The arduino will decode this message, check that it is a correct message, and thenthe arduino will use the commands to manage the garden.  If no message is received then no new actions will be applied to the garden. 

I choose to send a command that looks like this: "+++lw".  The arduino can tell if the message is correct by reading that I have included the "+++".  Then I pass the letters'l' and 'w'.  If the 'l' is lower case then it tells the arduino to turn off the light.  If the 'l' is an uppercase 'L' then the light will come on.  Easy, right?  

The 'w' is trickier.  I have included some safety protocols in my software.  The arduino will only turn on the pump for a maximum of 5 times for 5 seconds each time.  Youmay wonder how a plant will live on only 25 seconds of watering.  Well I reset the counter every 4 hours.  This way the plant will continue to get water and my kitchen willnot continue to get flooded.  The 'w' as a lower case tells the arduino nothing useful, but if I change the 'w' to an uppercase 'W' then the pump counter will reset to zeroand the arduino can again water my plant if it's necessary.  Make sense?  You may want to something slightly different, but this worked for me.

Page 93: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Instead of including the code in the text here I've decided to include files.  You should be able to open these with your Arduino IDE for the arduino code and with IDLE ora text editor for the Python code.

File Downloads

garduino_twitter.py (7 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'garduino_twitter.py']

garduino.pde (4 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'garduino.pde']

twitter.py (45 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'twitter.py']

Step 6: Upgrade #4: Wireless ControlNow comes the exciting part!  It's probably not likely that you can leave your computer connected via USB to your arduino all day long in your kitchen.  If you can that'sgreat, but I need my laptop in my office where I find it useful.  This is where my experience with the Tweet-a-Watt came in handy.

Early on I decided to use Xbee wireless devices to talk between my computer and the computer.  Now I apparently did things the hard way because I thought you'd needto send the data through the Xbee controller from the arduino and then decode it on the other end with the Xbee Python library.  This turns out to be completely untrue. You certainly can do it this way, but it's way harder than simply using the Xbee modules as a direct serial link to your computer.

It may have taken me hours, but this step shouldn't take you very long once you've set up your Xbees.  Essentially you remove the USB cable between your computerand the arduino, hook up your Xbee modules (one to the computer via an FTDI cable and one to the arduino via tx/rx lines), and then continue as though you were stillusing the USB cable.  Don't believe me? Try it.  Maybe this was obvious to other people but it was pretty exciting when I figured it out.

Now I should tell you there are several steps to doing this whole wireless step.  You need to first purchase and assemble the Xbee modules.  Then you'll want to programeach of the Xbee chips and finally connect them up.  The best resource I found for setting up my modules was actually a tutorial about Wirelessly Programming yourArduino.

I decided to set up my arduino to be wirelessly programmed so that I could easily update the code from my laptop when I needed to upgrade my arduino.  This was anadded bonus to being able to wirelessly talk to my arduino via serial and it just seemed to sweeten the whole project.  I also found this made some of the debuggingeasier since I needed to do a lot of writing and rewriting to the arduino.

Page 94: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Image Notes1. Xbee module for computer2. FTDI cable to computer3. Arduino Duemilanove4. 9V power from wall5. TX/RX lines to Xbee module6. Xbee module for arduino7. Electronics to program arduino remotely and hit the reset8. Power!

Step 7: Update #5: Twitter your GardenNow you've got your garden all hooked up to your computer and talking wirelessly to the computer.  You may even be recording your data to a file to look at it later.  Whatyou may not be able to do yet is monitor your plants while you're at work.  To do this I employed Twitter, much like the Tweet-a-Watt did.  I signed up for an account that Icould use for testing, @chrisgilmertest.  Then I hooked my code into the Python Twitter API, entered my user name and password, and voila!  I was done.

I set up my twitter to send back the readings for the different sensors and the current time.  I know you can track the time you posted, but I wanted the time from mycomputer.  I also decided to have it tweet every half hour.  When I originally was programming this I had it tweet every 5 minutes, which was good when I wanted toensure it was actually working, but got annoying to follow pretty quick.  I may actually have it tweet every hour or couple hours in the future.  You get to decide what youwant for yourself and go from there.

I have asked friends to help me come up with some silly messages for my garden to tweet, based on the sensor readings, so maybe I'll get some snarky comments upthere soon.

You may have noticed that this code was already provided to you earlier in this Instructable.  My hope was that you got excited and already started to play with it.  If not,what are you waiting for?

Image Notes1. Arduino and protoshield2. Sensor board3. Xbee module set up temporarily on a protoboard4. Pump outlet5. Light outlet6. Too many wires!

Image Notes1. I like to time tag all of these2. I think my garden has not put out more tweets than me3. People are already following my garden!

Page 95: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 8: Useful project notesI learned a bunch of useful things while doing this project and I wanted to make sure I captured them here for you.  Hopefully I've written them all down because they aremighty handy:

Plants:When it comes to plants remember that they are indeed alive.  They are also tasty, not just to you but often to other things as well.  My first plants were eaten by cats andthen destroyed by spider mites.  I never would have thought about this during the planning stage of the project and it definitely cost me a few extra bucks to replace them. 

Lighting:Plants need light and it can be tough finding the right set of lights.  There is plenty of information out there about lights for growing plants but it turns out to be incrediblydifficult to find these lights at a local hardware store.  It took me a while but after asking around I was directed to a Hydroponics Store.  You know the kind (wink, wink),and they hooked me up in no time at all.  Pun partially intended.  The people were great at the store and definitely reminded me of why I like to buy local when possible.

Water:You've got to be really careful when you get started with automatically watering your plants.  The soil resistivity will change dramatically as you first start to water it,meaning your calibration of the sensors will be difficult.  I found this out the hard way when my pump decided to water not only my plant but my entire kitchen.  It's betterto program in some safety catches in the software to prevent this.  My plants will only water for up to 30 seconds at four different times in the day and no more.  It may bedifferent for you, but be warned.

Wireless Programming:You may have set up your arduino to be wirelessly programmed.  I did and I found the only annoying thing is that I'd reset my arduino when I reset my computer.  Turnsout I was flipping the reset line on the arduino via the Xbee.  The easiest solution to fix this was to disconnect the reset line whenever I didn't want to reprogram.  I couldstill leave the other electronics in place, but removing the reset line fixed the problem without having to disassemble anything else.

Final Comments:I had a lot of fun building this project.  I learned a lot along the way and I hope to have some delicious plants for eating after all this work.  I hope you found this projectinteresting and useful for upgrading your own Garduino.  If you do follow any of the upgrades in this project let me know and tell me how they worked out for you.

You can always ask for more information or check out my website for more information.  I keep a blog, a project wiki, and an svn repository with the latest code.  I alsohave a set of photos you can look at.  Hopefully it's all up to date and full of resources to help you out.  Good luck with your project!

PS - If you like this project please vote for it in the "Arduino Contest" and help me win!

Image Notes1. Basil plant good for soups2. Mint good for ... what isn't it good for?3. Water bucket with pump4. Foil keeps the light inside5. Planter with lots of yummy soil6. SEnsor board7. Pump relay box8. Light relay box9. Arduino running it all10. Power to all the good stuff here11. Light for the plant from the "Hydroponics Store"12. Starter kit for garden drip system

Page 96: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Related Instructables

Tweeting PetBowl byswimray5 Image

Capturing BirdFeeder byquasiben

The TwitteringOffice Chair byrandofo

Wireless AltoidsDisplay byAlexdlp

Twitter MentionMood Light bypdxnat

Tweet-a-watt -How to make atwittering powermeter... byadafruit

simpleTweet_01python bypdxnat

ConfiguringXBees for APIMode byquasiben

Page 97: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

The Smuggie: Tweet straight from your Snuggieby jblinder on October 12, 2010

Author:jblinder    Justin Blinderhacker / maker

Intro:  The Smuggie: Tweet straight from your SnuggieWant to tweet how satisfied you are cuddled up in your Snuggie? The Smuggie is a modified Snuggie, designed specifically for those who feel the need to express theirsmug satisfaction with a Snuggie to their friends on Twitter.Here's a list of everything you'll need:

- Processing IDE (http://processing.org/)Arduino IDE (http://arduino.cc/)- A Twitter account (https://twitter.com/)- At least one Snuggie"- 1 Arduino Main Board (http://www.sparkfun.com/commerce/product_info.php?products_id=666)- 1 Solderless Breadboard (any size, the smaller the better)- About 5-10 feet of 22AWG Solid Core Wire- A needle and thread- About a foot of foam core- About a foot of Conductive Tape

By: Justin Blinderhttp://blog.justinblinder.com

Page 98: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 1: Writing the CodeCode1) Download and Install Arduino/Processing (there are tutorials on each website on how to get setup).

2) Open up Arduino. The code below is basically going to program our Arduino to wait for a button press, and send a message to Processing every time the button ispressed. Copy the code into the Arduino window and plug your Arduino into your computer. Click the upload button at the top of the window. You'll see a message on thebottom of the window that says "Done" once everything's finished. Now our Arduino is all ready for coding.

Arduino Code2) Now let's pen up Processing. The following code is going to handle the following:- Connect to a remote Twitter client (so you can tweet from your very own Twitteraccount)- Listen for a button press from our Arduino- If it sees that a button is pressed, send Twitter our status update

3) Copy and paste the code below into the Processing window. On the line that says:String myStatus = "enter your status update here";replace the text "enter your status update here" with the message you'd like to tweet (leaving the quotes intact). Make sure your message is a maximum of 140charecters, otherwise your Smuggie's won't tweet!

Processing Code

File Downloads

code.zip (1 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'code.zip']

Step 2: Twitter SetupTwitter Setup

Now let’s register our Twitter account with the Smuggie Twitter Client.  This will allow us to tweet from our processing application, using our desired Twitter name.

1) Go to the Twitter website and log into your account. Once your at the homepage, open the following link:

http://magichive.com/projects/smuggie/register.php

2) You’ll be asked to click a link will then be redirected to a page with a 7-digit number. Copy the number and insert it at the end of the following link, then load the link inyour browser:

http://magichive.com/projects/smuggie/validate.php?pin=

Now we’re ready to start making our Smuggie.

Page 99: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 3: Cut the FabricAlright, now we’re going to make a “soft switch”, which in this case is essentially two strips of wire wrapped in conductive material, that will be housed in fabric. Whenwe press down on the fabric, the switch will close, which is what our arduino will be listening for in order to send a tweet.

1) First, get about a 12?x6? piece of fabric (I used some at the base of my original Snuggie).

Page 100: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 4: Cut the Foam2) Cut a piece of foam that’s roughly a little less than half the width of our fabric, and a little shorter than the height of the fabric (about 5?x5?). We’ll want the foam to beabout a quarter of an inch thick, so if it’s thinner you can double up pieces as shown in the picture.

Step 5: Cut some holes3) Cut a hole in the center of the foam that’s about 1.5 – 2? in diameter.

Page 101: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 6: Prepare the wire4) Take out your wire, and cut two pieces, each about 4 feet long (it’ll be easier in the long run if they’re 2 different colors). Strip about 1? of insulation off of the end foreach wire. Then, take roughly 6? of conductive tape and wrap it around the end of one of the exposed wires. Fold the conductive tape around so that it is flat, and about3? wide (like in the picture).

Step 7: Tape the leads5) Tape each wire onto the end of a piece of foam, tight enough so that it goes through the hole only if pressure is applied.

Step 8: Tape the switch6) Tape both pieces of foam together, so that the conductive tape is on the outer side of each foam section.

Page 102: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 9: Sew the switch7) Now we can sew the switch into our fabric, so that it fits snugly around the foam.

Step 10: Attach the switch to the Snuggie8) Finally, sew the switch onto your Snuggie, whereever you so please.

Step 11: Hook the Smuggie up to our Arduino.Simply connect one lead of the soft switch to the power port on the Arduino, and the other lead to Pin 12 with a 10k resistor in between.

Here is what our Smuggie circuit will look like.

Page 103: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 12: Prepare to SmuggieNow, all we need to do is fire up our Processing app, and you’re ready to tweet! 

Thanks to my friend Julie Pinzur (http://zipperteeth.blogspot.com/), for the Smuggie modeling help. 

Page 104: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Related Instructables

Arduino LCDTwitter displayby PKM

Tweet-a-Pot:Twitter EnabledCoffee Pot byfrenzy

simpleTweet_00processing bypdxnat

TwittercontrolledArduinoOutputs - no PC- LCD Display +Sensor data toTwitter byXenonJohn

simpleTweet_01python bypdxnat

Make an EasyButton Tweetthe Hard Way byLayout

Tweety Buttonby Great_Skot

ThermalTweeternetworkedTwitter printerby ian

Page 105: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Twitter Mood Light - The World's Mood in a Boxby RandomMatrix on April 22, 2010

Intro:  Twitter Mood Light - The World's Mood in a Box

How's the world feeling right now? This box tells you.

Powered by: an Arduino, a WiFly wireless module, an RGB LED, Twitter.com and a 9v battery.

I’m a news junkie. I want to know everything that is going on in the world as soon as it happens. I want to wake up and know immediately if something big has happenedovernight.

However, I’m an extraordinarily busy man; I don’t have time to read news feeds; reading that headline that I already knew about or don’t care about is time that I’mnever getting back!

No. What I need is some way to be constantly in touch with the world's events as they unfold, alerted when something big happens, and to be made aware of it all fasterthan awareness itself!

...A way to get a glimpse of the collective human consciousness as an extension of my own.  Something that I don't have to continually check or poll, but instead, like apart of my body, it will tell me when it's feeling pain or generally in need of my attention ...leaving me time to get on with other things.

And so, I present: The World Mood in a Box!

The Arduino connects directly to any wireless network via the WiFly module, continually searches Twitter for tweets with emotional content, collates the tweets for eachemotion, does some math, and then fades the color of the LED to reflect the current World Mood; Red for Anger, Yellow for Happy, Pink for Love, White for Fear,Green for Envy, Orange for Surprise, and Blue for Sadness.

If an unexpectedly high number of tweets of a particular emotion are found, then the LED will flash to alert us to the possibility of a world event that has caused thisunusually strong emotional reaction.

For example, a world disaster and it may flash Blue or Red (sadness or anger), if the strong favourite loses a big football game it may fade to Orange (surprise), …and If itflashes White, the collective human mind is feeling extreme fear, and it's probably best to go hide in a cupboard and sit it out, waiting for sunnier skies and a return toYellow or Pink.  ...OK, I'm not that busy.

Image Notes1. The world is happy!

Image Notes1. uhhoh! the world is full of envy. ...back to bed!

Page 106: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Image Notes1. World, why so sad?

Step 1: How it worksAn Arduino connects directly (no computer required!) to any wireless network via the WiFly module, repeatedly searches Twitter for tweets with emotional content (akasentiment extraction or tapping into the moodosphere), collates the tweets for each emotion, analyzes the data, and fades the color of an LED to reflect the current WorldMood:

Red for AngerYellow for HappyPink for LoveWhite for FearGreen for EnvyOrange for SurpriseBlue for Sadness

Example search terms to find tweets that may express surprise:

"wow""can't believe""unbelievable""O_o"

If an unexpectedly high number of tweets of a particular emotion are found, then the LED will flash to alert anyone nearby to the possibility of a big world event that hascaused this unusually strong emotional reaction.

Example signals:

A world disaster and it may flash Blue or Red indicating it best to check a news site to see why everyone is so sad and/or angry.If the strong favourite loses a big football game, it may flash Orange to express the surprise at this unlikely event.If there is a heat wave in London it might turn Yellow to reflect how much happier people now are.If it flashes White, the collective human consciousness is feeling extreme fear and something terrifyingly bad is probably about to happen. Time to hide and/orpanic.

Uses

You could put it on your desk to get an early warning of something big happening somewhere in the worldA literal 'mood light' at a party or a game whereby you guess what colour it will change to next and for what reasonA world mood barometer perhaps next to your bed to decide if it is best to hit snooze until it's less angry outsideA gauge of public sentiment to help you decide when to sell all your stocks and shares, and head to the hills.In a foyer or waiting area or other public space for people to look at and contemplate.Set it to connect to any wireless network and carry it around in the streets, stopping strangers to explain to them that you have managed to capture the world'smood and have it locked in this here box.

Page 107: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 2: All you need is...I ordered most of the electronics from Sparkfun, and picked up the rest from the local Radioshack. The acrylic I got from a local plastic shop(!) - they cut it and drilled ahole free of charge.

Materials

Arduino DuemilanoveWifly Shield www.sparkfun.com/commerce/product_info.phpBreakaway headers  www.sparkfun.com/commerce/product_info.php9v battery9v to Barrel Jack Adapter5mm RGB LED3x resistors (2x100 ohm,1x180 ohm)WireSmall printed circuit boardUSB Cable A to B to connect Arduino to computerRosin-core solderSource code

The Acrylic Box

1 x (5" x 5" x 0.25") - the top4 * (4.75" x 4.75" x 0.25") - the 4 walls1 x (4.5" x 4.5" x 0.25") - the base1 x (4.5" x 4.5" x 0.125") - the mirror with a 6mm hole drilled in the middle4 x (4.25 x 1" x 0.25") - the 4 inside wallsAcrylic solvent cementSand paper (to help diffuse the light)

Tools

Soldering ironA computerArduino development environmentA wireless network (802.11b/g)PliersWire stripper

Useful links

The Arduino development tools can be downloaded from here:www.arduino.cc/en/Main/Software

and Arduino tutorials start here:http://arduino.cc/en/Guide/HomePage

Arduino / WiFly:arduino.cc/en/Reference/HomePagehttp://www.arduino.cc/en/Tutorial/SPIEEPROMhttp://www.lammertbies.nl/comm/info/serial-uart.htmlhttp://www.tinyclr.com/downloads/Shield/FEZ_Shields_WiFly.cshttp://www.sparkfun.com/commerce/tutorial_info.php?tutorials_id=158

Page 108: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

http://www.sparkfun.com/datasheets/Components/SMD/sc16is750.pdfhttp://www.sparkfun.com/datasheets/Wireless/WiFi/WiFlyGSX-um.pdfhttp://www.sparkfun.com/datasheets/Wireless/WiFi/rn-131G-ds.pdfhttp://www.societyofrobots.com/microcontroller_uart.shtml

Related:nlp.stanford.edu/courses/cs224n/2009/fp/22.pdfwww.webservius.com/corp/docs/tweetfeel_sentiment.htmi8news.uterm.org/mood/twitter-mood-reader/community.openamplify.com/content/docs.aspx/www.instructables.com/id/The-Twittering-Office-Chair/http://www.tweetfeel.com

Image Notes1. wire2. Wifly Shield3. Arduino Duemilanove4. RGB LED5. Breakaway headers6. 3x resistors (2x100 ohm,1x180 ohm)7. 9v battery and Barrel Jack Adapter8. Pliers9. Wire cutters10. USB Cable A to B11. small printed circuit board

Image Notes1. 1 x (5" x 5" x 0.25") - the top2. 4 * (4.75" x 4.75" x 0.25") - the 4 walls3. sandpaper4. Acrylic solvent cement5. 4 x (4.25 x 1" x 0.25") - the 4 inside walls6. 1 x (4.5" x 4.5" x 0.25") - the base7. 1 x (4.5" x 4.5" x 0.125") - the mirror with a 6mm hole drilled in the middle

Image Notes1. solder2. soldering iron3. laptop

Page 109: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 3: Connect the Arduino and WiFly to a computerSparkfun have a decent tutorial on how to do this:

www.sparkfun.com/commerce/tutorial_info.php

Firstly, the Wifly breakout board needs to be stacked on top of the arduino and the RX, TX, Vin, Gnd, pin 10, pin 11, pin 12 and pin 13 needed to be connected. I usedbreakaway headers and soldered the required pins.

Connect to a computer using an A to B USB cable.

Download the Arduino software from here:arduino.cc/en/Main/Software

Check that you can compile and upload a sample program by following the instructions here:(remember to set the board and COM ports correctly)arduino.cc/en/Guide/HomePage

Image Notes1. soldered RX, TX2. Soldered 10,11,12,133. Soldered Vin, Gnd

Page 110: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 4: Connecting the LEDOnly some pins provide 8-bit PWM (Pulse-width modulation)This gives 256 steps of control from full off (0) to full on (255) for each of the Red, Green and Blue channels of the LED.

PWM pins on the Arduino are 3,5,6,9,10,11. (see www.arduino.cc/en/Main/ArduinoBoardDuemilanove)

I used 3, 5 and 6.I used the pliers to bend the legs of the LED, and mounted it on the circuit board. Each resistor is then mounted next to each of the RGB legs, and the wires are twistedtogether. Then I added the 4 connecting wires and twisted them. Finally, I soldered all the connections. 

Note: The pictures illustrate using the same resistor for each colour channel, but I should have used the resistance levels in the data sheet:

180 Ohm for Red100 Ohm for Green100 Ohm for Blue

Also note, I covered the back with insulating tape to stop any shorts when putting it all into the box.Also, from the datasheet, "the Sensor inputs SENS0-7 are extremely sensitive to over voltage. Under no conditions should these pins be driven above 1.2VDC. Placingany voltage abovethis will permanently damage the radio module and render it useless."

wiring.org.co/learning/basics/rgbled.htmlwww.sparkfun.com/datasheets/Components/YSL-R596CR3G4B5C-C10.pdf

Page 111: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Image Notes1. PWM pins 3,5,6

Step 5: Choosing good search terms

Twitter allows you to search for recent tweets that contain particular words or phrases.

You can search for tweets that contain any of a list of phrases by using the "+OR+" conjunction.

For example, here is a search request that might find tweets that express Fear:

GET /search.json?q="i'm+so+scared"+OR+"i'm+really+scared"+OR+"i'm+terrified"+OR+"i'm+really+afraid"+OR+"so+scared+i"&rpp=30&result_type=recent

I spent a long time finding good search phrases.

The search phrases needed to produce tweets that:

very often express the desired emotion.1.

Page 112: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

very rarely express the opposite emotion or no emotion.2.

Many search phrases that I thought would work, turned out to not work that well when I searched with them.

Smileys have been used with some success to extract whether the sentence is positive or negative, but I didn't find them useful for extracting anything more.

The trouble with smileys is that a smile can mean so many things ;D

It is often used, it seems, as a kind of qualifier for the whole sentence; since people have to compress their thoughts into 140 characters, the meaning can becomeambiguous.

The smiley often then acts as a qualifier that:

'this is a friendly comment''don't take this the wrong  way''i am saying hello/goodbye with a smile''this is almost a joke''I know I'm being cheeky''I don't really mean this'

Phrases using adverbs seemed to produce better results."so scared" or "really scared" is better than just "scared" which returns bad results: for example, "not scared".

Phrases in the first person seemed to produce better results.Some search phrases give tweets that suggest the author feels the emotion: for example, "i really hate...", often sounds like they really are full of hate or angry, whereasother phrases containing the word "hate" give tweets that do not seem to express much emotion, like "why do you hate..."

Hyperbole is your best friend, ever:Using phrases with hyperbole produced good results. Tweets with "I'm terrified" or "I'm petrified" in them were generally more fearful sounding than "I'm scared"

Regardless, the approach is still naive, but statistically, from my tests, it does seem to work well.

While testing the code, I did at one point get the horribly ominous "Flashing White" that signifies the world is feeling intense fear, but since I was still testing it all, I did nothide under the table straight away, but instead, threw caution to the winds, and went on to Twitter to see what people were suddenly so fearful about.

The recent tweets containing the Fear search string (see top of page) were largely relating to a large thunderstorm that had just started somewhere near Florida.

If you're interested, here are some of those tweets: 

"Ahhh Thunder I'm so scared of Thunder !!!!! Help some 1""I'm so scared of lightning now. Like I just ran home praying ""On our way to Narcosses at @Disney world's Grand Floridian hotel and there's a tropical storm right now. I'm terrified! ...""I'm in my bathroom til the rain stops. I'm terrified of lightning and thunder...""I'm terrified of thunder storms *hides in corner*""I'm terrified of Thunder :(""If only I was wit my becky during this thunderstorm cause I'm really scared cause of a bad experience"

So... it works! ...Well, it needs the numbers tweaking to ignore the world's "tantrums", the short-lived fits of emotional outburst, and be more concerned with largerchanges that signify bigger news.

Image Notes1. Scary!! http://www.flickr.com/photos/thru_the_night/3807826324/

Page 113: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 6: Download the codeThe attached WorldMood.zip contains 4 subdirectories (or "libraries") and the Arduino sketch WorldMood.pde

The four libraries need to be copied into the Arduino library directory and then they can be imported as shown.

WorldMood/WorldMood.pde (see below) should be opened in the Arduino development environment.

You then need to correct the "[your network]" and "[your network password]" fields. eg.

#define network ("mynetwork")#define password ("mypassword")

Then the sketch (and libraries) should be compiled and uploaded to the Arduino board.

see arduino.cc/en/Hacking/LibraryTutorial

The next 5 programming steps just give an overview of each of the components and include the most noteworthy parts of the source code...

**** Update ****

If you have a newer board then you may need to change this

struct SPI_UART_cfg SPI_Uart_config = {0x50,0x00,0x03,0x10};

to this:struct SPI_UART_cfg SPI_Uart_config = {0x60,0x00,0x03,0x10};

See here for more info:http://forum.sparkfun.com/viewtopic.php?f=13&t=21846&sid=24282242d4256db0c7b7e814d7ca6952&start=15

http://www.sparkfun.com/commerce/product_info.php?products_id=9367

***** End Update ****

  // LED setup - only some pins provide 8-bit PWM (Pulse-width modulation)// output with the analogWrite() function.// http://www.arduino.cc/en/Main/ArduinoBoardDuemilanove// PWM: 3,5,6,9,10,11#define redPin    (3)#define greenPin (5)#define bluePin   (6) // delay in ms between fade updates// max fade time = 255 * 15 = 3.825s#define fadeDelay (15) // Wifi setup#define network ([your network])#define password ([your network password])#define remoteServer ("twitter.com") const char* moodNames[NUM_MOOD_TYPES] = { "love", "joy", "surprise", "anger", "envy", "sadness", "fear",}; const char* moodIntensityNames[NUM_MOOD_INTENSITY] = { "mild", "considerable", "extreme",}; // the long term ratios between tweets with emotional content// as discovered by using the below search terms over a period of time.float tempramentRatios[NUM_MOOD_TYPES] = { 0.13f, 0.15f, 0.20f, 0.14f, 0.16f, 0.12f, 0.10f,}; // these numbers can be tweaked to get the system to be more or less reactive// to be more or less susceptible to noise or short term emotional blips, like sport results// or bigger events, like world disasters#define emotionSmoothingFactor (0.1f)

Page 114: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

#define moodSmoothingFactor (0.05f)#define moderateMoodThreshold (2.0f)#define extremeMoodThreshold (4.0f) // save battery, put the wifly to sleep for this long between searches (in ms)#define SLEEP_TIME_BETWEEN_SEARCHES (1000 * 5) // Store search strings in flash (program) memory instead of SRAM.// http://www.arduino.cc/en/Reference/PROGMEM// edit TWEETS_PER_PAGE if changing the rpp valueprog_char string_0[] PROGMEM = "GET/search.json?q=\"i+love+you\"+OR+\"i+love+her\"+OR+\"i+love+him\"+OR+\"all+my+love\"+OR+\"i'm+in+love\"+OR+\"i+really+love\"&rpp=30&result_type=recent";prog_char string_1[] PROGMEM = "GET/search.json?q=\"happiest\"+OR+\"so+happy\"+OR+\"so+excited\"+OR+\"i'm+happy\"+OR+\"woot\"+OR+\"w00t\"&rpp=30&result_type=recent";prog_char string_2[] PROGMEM = "GET/search.json?q=\"wow\"+OR+\"O_o\"+OR+\"can't+believe\"+OR+\"wtf\"+OR+\"unbelievable\"&rpp=30&result_type=recent";prog_char string_3[] PROGMEM = "GET/search.json?q=\"i+hate\"+OR+\"really+angry\"+OR+\"i+am+mad\"+OR+\"really+hate\"+OR+\"so+angry\"&rpp=30&result_type=recent";prog_char string_4[] PROGMEM = "GET /search.json?q=\"i+wish+i\"+OR+\"i'm+envious\"+OR+\"i'm+jealous\"+OR+\"i+want+to+be\"+OR+\"why+can't+i\"+&rpp=30&result_type=recent";prog_char string_5[] PROGMEM = "GET/search.json?q=\"i'm+so+sad\"+OR+\"i'm+heartbroken\"+OR+\"i'm+so+upset\"+OR+\"i'm+depressed\"+OR+\"i+can't+stop+crying\"&rpp=30&result_type=recent" ;prog_char string_6[] PROGMEM = "GET/search.json?q=\"i'm+so+scared\"+OR+\"i'm+really+scared\"+OR+\"i'm+terrified\"+OR+\"i'm+really+afraid\"+OR+\"so+scared+i\"&rpp=30&result_type=recent" ; // be sure to change this if you edit the rpp value above#define TWEETS_PER_PAGE (30) PROGMEM const char *searchStrings[] =        {   string_0, string_1, string_2, string_3, string_4, string_5, string_6,}; void setup(){ Serial.begin(9600); delay(100);} void loop(){ // create and initialise the subsystems  WiFly wifly(network, password, SLEEP_TIME_BETWEEN_SEARCHES, Serial); WorldMood worldMood(Serial, emotionSmoothingFactor, moodSmoothingFactor, moderateMoodThreshold, extremeMoodThreshold,tempramentRatios); LED led(Serial, redPin, greenPin, bluePin, fadeDelay); TwitterParser twitterSearchParser(Serial, TWEETS_PER_PAGE);  wifly.Reset();  char searchString[160];  while (true) {    for (int i = 0; i < NUM_MOOD_TYPES; i++)    {      twitterSearchParser.Reset();       // read in new search string to SRAM from flash memory      strcpy_P(searchString, (char*)pgm_read_word(&(searchStrings[i])));       bool ok = false;      int retries = 0;       // some recovery code if the web request fails      while (!ok)      {        ok = wifly.HttpWebRequest(remoteServer, searchString, &twitterSearchParser);         if (!ok)        {          Serial.println("HttpWebRequest failed");           retries++;          if (retries > 3)          {            wifly.Reset();            retries = 0;          }

Page 115: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

        }      }       float tweetsPerMinute = twitterSearchParser.GetTweetsPerMinute();       // debug code      Serial.println("");      Serial.print(moodNames[i]);      Serial.print(": tweets per min = ");      Serial.println(tweetsPerMinute);       worldMood.RegisterTweets(i, tweetsPerMinute);    }     MOOD_TYPE newMood = worldMood.ComputeCurrentMood();    MOOD_INTENSITY newMoodIntensity = worldMood.ComputeCurrentMoodIntensity();     Serial.print("The Mood of the World is ... ");    Serial.print(moodIntensityNames[(int)newMoodIntensity]);    Serial.print(" ");    Serial.println(moodNames[(int)newMood]);     led.SetColor((int)newMood, (int)newMoodIntensity);     // save the battery    wifly.Sleep();     // wait until it is time for the next update    delay(SLEEP_TIME_BETWEEN_SEARCHES);     Serial.println(""); }} 

File Downloads

WorldMood.zip (18 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'WorldMood.zip']

Page 116: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 7: Programming step 1: SPI UARTThe WiFly Shield equips your Arduino with the ability to connect to 802.11b/g wireless networks.The featured components of the shield are:

a Roving Network's RN-131G wireless moduleSC16IS750 SPI-to-UART chip. 

Serial Peripheral Interface Bus (or SPI) is a "four wire" serial bus capable of high rates of data transmission. A serial bus allows data to be sent serially (synchronously),i.e. one bit at a time, rather than in parallel (asynchronous)

The Universal asynchronous receiver/transmitter (or UART) is a type of asynchronous receiver/transmitter, a piece of computer hardware that translates data betweenparallel and serial forms.

The PC communicates over UART with the Arduino through pins RX and TX1.The Arduino communicates over SPI with the SPI-UART chip on the WiFly shield (SC16IS750 SPI-to-UART chip) though pins 10-13 (CS, MOSI, MISO, SCLK2.respectively)The RN-131G wireless module accesses network and send/receive serial data over UART.3.

The SPI-to-UART bridge is used to allow for faster transmission speed and to free up the Arduino's UART.

The code below is based on a number of sources, but primarily from this tutorial over at sparkfun:www.sparkfun.com/commerce/tutorial_info.php WiFly Wireless Talking SpeakJet Server

/* Test if the SPI<->UART bridge has been set up correctly by writing a test   character via SPI and reading it back.   returns true if success*/bool WiFly::TestSPI_UART_Bridge(){ // Perform read/write test to check if SPI<->UART bridge is working  // write a character to the scratchpad register. WriteByteToRegister(SPR, 0x55);  char data = ReadCharFromWiFly(SPR);  if(data == 0x55) {    return true; } else {    m_printer->println("Failed to init SPI<->UART chip");    return false; }} /* A series of register writes to initialize the SC16IS750 SPI-UART bridge chip   see http://www.tinyclr.com/downloads/Shield/FEZ_Shields_WiFly.cs*/void WiFly::SPI_UART_Init(void){ WriteByteToRegister(LCR,0x80); // 0x80 to program baudrate WriteByteToRegister(DLL,SPI_Uart_config.DivL); //0x50 = 9600 with Xtal = 12.288MHz WriteByteToRegister(DLM,SPI_Uart_config.DivM);  WriteByteToRegister(LCR, 0xBF); // access EFR register WriteByteToRegister(EFR, SPI_Uart_config.Flow); // enable enhanced registers WriteByteToRegister(LCR, SPI_Uart_config.DataFormat); // 8 data bit, 1 stop bit, no parity WriteByteToRegister(FCR, 0x06); // reset TXFIFO, reset RXFIFO, non FIFO mode WriteByteToRegister(FCR, 0x01); // enable FIFO mode}

Page 117: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Image Notes1. the SC16IS750 SPI-to-UART chip!

Step 8: Programming step 2: Connecting to a Wireless NetworkAgain, this is largely based on the sparkfun tutorial, but I've removed the delays with "waits for response". This speeds things up and is easier to error check.

www.sparkfun.com/commerce/tutorial_info.php

/* Send the correct commands to connect to a wireless network using the parameters used on construction*/void WiFly::AutoConnect(){ delay(DEFAULT_TIME_TO_READY);  FlushRX();  // Enter command mode EnterCommandMode();  // Reboot to get device into known state WriteToWiFlyCR("reboot"); WaitUntilReceived("*Reboot*"); WaitUntilReceived("*READY*");  FlushRX();  // Enter command mode EnterCommandMode();  // turn off auto joining WriteToWiFlyCR("set wlan join 0"); WaitUntilReceived(AOK, ERR);  // Set authentication level to WriteToWiFly("set w a "); WriteToWiFlyCR(auth_level); WaitUntilReceived(AOK, ERR);  // Set authentication phrase to WriteToWiFly("set w p "); WriteToWiFlyCR(m_password); WaitUntilReceived(AOK, ERR);  // Set localport to WriteToWiFly("set i l "); WriteToWiFlyCR(port_listen); WaitUntilReceived(AOK, ERR);  // Deactivate remote connection automatic message WriteToWiFlyCR("set comm remote 0"); WaitUntilReceived(AOK, ERR);  // Join wireless network WriteToWiFly("join "); WriteToWiFlyCR(m_network);  delay(DEFAULT_TIME_TO_JOIN);  bool ok = WaitUntilReceived("IP=");

Page 118: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

 delay(DEFAULT_TIME_TO_WAIT);  FlushRX();  if(ok == false) {    m_printer->print("Failed to associate with '");    m_printer->print(m_network);    m_printer->println("'\n\rRetrying...");    FlushRX();    AutoConnect(); } else {    m_printer->println("Associated!");    ExitCommandMode(); }  // TODO save this configuration}  /* Enter command mode by sending: $$$ Characters are passed until this exact sequence is seen. If any bytes are seen before these chars, or after these chars, in a 1 second window, command mode will not be entered and these bytes will be passed on to other side.*/void WiFly::EnterCommandMode(){ FlushRX(); delay(1000); // wait 1s as instructed above m_printer->println("Entering command mode."); WriteToWiFly("$$$"); WaitUntilReceived("CMD");}  /* exit command mode send the "exit" command and await the confirmation result "EXIT"*/void WiFly::ExitCommandMode(){ WriteToWiFlyCR("exit"); WaitUntilReceived("EXIT");}

Page 119: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 9: Programming step 3: Searching Twitter with TCP/IP port 80Http is just TCP/IP on port 80

for example:

"Open www.google.com 80"

will open a Http connection to www.google.com.

Twitter actually requires more of the Http protocol than google.

For example, the "Host" field is often required in case there's more than onedomain name mapped to the server's IP address so it can tell whichwebsite you actually want.

Twitter also requires a final linefeed and carriage return ("\r\n")

"GET /\n""Host: server\r\n""\r\n"

I use search.json rather than search.atom to give results in non-html format, and more easily parsed. (see apiwiki.twitter.com/Twitter-API-Documentation)

  /* Parameters: The server to telnet into, the get command that needs to be sent, a custom HtmlParser that is called every time a character is received. The parser is responsible for processing the HTML that is returned.*/bool WiFly::HttpWebRequest(const char* server, const char* getCommand, HtmlParser* parser){ m_printer->println(getCommand); FlushRX(); FlushRX();  // Enter command mode EnterCommandMode(); FlushRX();  // open a TCP connection, port 80 for HTTP WriteToWiFly("open "); WriteToWiFly(server); WriteToWiFlyCR(" 80");  bool openOK = WaitUntilReceived(COMM_OPEN);  if (openOK == false) {    m_printer->println("open port failed!");    delay(1000);    WriteToWiFlyCR("close");    WaitUntilReceived(COMM_CLOSE);     ExitCommandMode();    return false; }  // eg. "GET /search.json?q=foo HTTP/1.1\r\n" WriteToWiFlyCRLF(getCommand);  // eg. "Host: search.twitter.com\r\n" WriteToWiFly("Host: "); WriteToWiFlyCRLF(server);  // "\r\n" WriteToWiFlyCRLF("");  // now wait for the response  int timeOut = 0; bool ok = false;  while(timeOut < 5000)// timeout after 5 seconds  {    if((ReadCharFromWiFly(LSR) & 0x01))    {      char incoming_data = ReadCharFromWiFly(RHR);      m_printer->print(incoming_data,BYTE);       bool done = parser->Parse(incoming_data);      if (done)      {        ok = true;        break;      }

Page 120: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

       timeOut = 0; //reset the timeout    }    else    {      delay(1);      timeOut++;    } }  FlushRX();  // disconnect TCP connection. WriteToWiFlyCR("close"); WaitUntilReceived(COMM_CLOSE);  ExitCommandMode();  return ok;}

Image Notes1. perfect

Image Notes1. too many tweets...

Page 121: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 10: Programming step 4: RGB LEDA simple library for setting the colour of an RGB LED. The library will fade between the colours as the world mood changes, and will flash if it is a significant change inmood.

*** update ***

If you find the colours look wrong, try removing the "255 -" from the analogWrite calls.Thanks to shobley for finding this.More info at http://www.stephenhobley.com/blog/2010/06/11/arduino-world-mood-light-using-twitter-and-wishield/

*** end update ***

/* The led is initially set to be currentColorID and over time will fade to desiredColorID with a time delay, fadeDelay, measured in ms, between each step. No effort is made to scale the step size for each rgb channel so each may not complete at the same time.*/void LED::FadeTo(int desiredColorID){      // check for valid colorID if (desiredColorID >= NUM_COLORS ||      desiredColorID < 0)    {      //logger.log("invalid Color id")      return;    }    // get a local copy of the colors Color currentColor; currentColor.r = Colors[m_currentColorID].r; currentColor.g = Colors[m_currentColorID].g; currentColor.b = Colors[m_currentColorID].b;  Color desiredColor; desiredColor.r = Colors[desiredColorID].r; desiredColor.g = Colors[desiredColorID].g; desiredColor.b = Colors[desiredColorID].b;  bool done = false;  while (!done) {    // move each of r,g,b a step closer to the desiredColor value       if (currentColor.r < desiredColor.r)    {      currentColor.r++;    }    else if (currentColor.r > desiredColor.r)    {      currentColor.r--;    }       if (currentColor.g < desiredColor.g)    {      currentColor.g++;    }    else if (currentColor.g > desiredColor.g)    {      currentColor.g--;    }       if (currentColor.b < desiredColor.b)    {      currentColor.b++;    }    else if (currentColor.b > desiredColor.b)    {      currentColor.b--;    }     // write the new rgb values to the correct pins    analogWrite(m_redPin, 255 - currentColor.r);      analogWrite(m_greenPin, 255 - currentColor.g);    analogWrite(m_bluePin, 255 - currentColor.b);         // hold at this color for this many ms    delay(m_fadeDelay);       // done when we have reach desiredColor 

Page 122: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

    done = (currentColor.r == desiredColor.r &&            currentColor.g == desiredColor.g &&            currentColor.b == desiredColor.b);            } // while (!done)  m_currentColorID = desiredColorID;}  

Step 11: Programming 5: Computing the World MoodThe mood light should be responsive enough to reflect what has just happened in the world, but it must not be so overly sensitive as to be susceptible to noise, and alsonot be too sluggish to be late in informing you of a big world event.  

The important thing is to carefully normalize and smooth the data, and to adjust the thresholds to give the right level of responsiveness and alarm. (i.e. it should flashwhen a headline news story happens and not when a TV show starts, GMT) Emotion, mood, and temperament

Firstly, the "world's emotion" is calculated by searching twitter for tweets with each of the 7 mood types (love, joy, surprise, anger, fear, envy, sad) .

A measure of "tweets per minute" is used to calculate the current emotion. A higher number of tweets per minute suggests more people are currently feeling that emotion.

Emotions are volatile, so these short-lived emotional states are smoothed over time by using a "fast exponential moving average"(see en.wikipedia.org/wiki/Moving_average#Exponential_moving_average)

This gives us ratios for the different moods.

Each mood ratio is then compared to a base line, a "slow exponential moving average", that I call the "world temperament".

The mood that has deviated furthest from its baseline temperament value is considered to be the current world mood.

The deviation is measured as a percentage, so, for example, if fear changes from accounting for 5% of tweets to 10% then this is more significant than joy changing from40% to 45% (They are both a +5% in additive terms, but fear increased by 100% in multiplicative terms.)

Finally, the world temperament values are tweaked slightly in light of this new result. This gives the system a self adjusting property so that the world temperament canvery slowly change over time.

These values in WorldMood.pde are used to adjust how sensitive the system is to information.

Do you want it to pick up when people are happy about a sport result or scared about the weather?Or would you prefer to only track big events like natural disasters or terrorist attacks?

adjust accordingly...

#define emotionSmoothingFactor (0.1f)#define moodSmoothingFactor (0.05f)#define moderateMoodThreshold (2.0f)#define extremeMoodThreshold (4.0f)

 MOOD_TYPE WorldMood::ComputeCurrentMood(){ // find the current ratios

Page 123: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

 float sum = 0; for (int i = 0; i < NUM_MOOD_TYPES; i++) {    sum += m_worldMoodCounts[i]; }  if (sum < 1e-4f) {#ifdef DEBUG    m_printer->print("unexpected total m_worldMoodCounts");#endif // ifdef DEBUG     return m_worldMood; }  for (int i = 0; i < NUM_MOOD_TYPES; i++) {    m_worldMoodRatios[i] = m_worldMoodCounts[i] / sum; }  // find the ratio that has increased by the most, as a proportion of its moving average. // So that, for example, an increase from 5% to 10% is more significant than an increase from 50% to 55%.  float maxIncrease = -1.0f;  for (int i = 0; i < NUM_MOOD_TYPES; i++) {    float difference = m_worldMoodRatios[i] - m_worldTemperamentRatios[i];     if (m_worldTemperamentRatios[i] < 1e-4f)    {#ifdef DEBUG      m_printer->print("unexpected m_worldTemperamentRatios");#endif // ifdef DEBUG      continue;    }     difference /= m_worldTemperamentRatios[i];     if (difference > maxIncrease)    {      maxIncrease = difference;      m_worldMood = (MOOD_TYPE)i; // this is now the most dominant mood of the world!    } }  // update the world temperament, as an exponential moving average of the mood. // this allows the baseline ratios, i.e. world temperament, to change slowly over time. // this means, in affect, that the 2nd derivative of the world mood wrt time is part of the current mood calcuation. // and so, after a major anger-inducing event, we can see when people start to become less angry. sum = 0; for (int i = 0; i < NUM_MOOD_TYPES; i++) {    if (m_worldTemperamentRatios[i] <= 0)    {#ifdef DEBUG      m_printer->print("m_worldTemperamentRatios should be initialised at construction");#endif // #ifdef DEBUG       m_worldTemperamentRatios[i] = m_worldMoodRatios[i];    }    else    {      const float a = m_moodSmoothingFactor;      m_worldTemperamentRatios[i] = (m_worldTemperamentRatios[i] * (1.0f - a)) + (m_worldMoodRatios[i] * a);    }     sum += m_worldTemperamentRatios[i]; }  if (sum < 1e-4f) {#ifdef DEBUG    m_printer->print("unexpected total m_worldTemperamentRatios total");#endif // #ifdef DEBUG    return m_worldMood; }  // and finally, renormalise, to keep the sum of the moving average ratios as 1.0f for (int i = 0; i < NUM_MOOD_TYPES; i++) {    m_worldTemperamentRatios[i] *= 1.0f / sum; #ifdef DEBUG    m_printer->print("temperament ratio: ");

Page 124: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

    m_printer->println(m_worldTemperamentRatios[i]);#endif    } #ifdef DEBUG // debug code - check sum is 1. sum = 0; for (int i = 0; i < NUM_MOOD_TYPES; i++) {    sum += m_worldTemperamentRatios[i]; }  if (sum > 1.0f + 1e-4f || sum < 1.0f - 1e-4f) {    m_printer->println("unexpected renormalise result"); }#endif // #ifdef DEBUG  return m_worldMood;}  

Image Notes1. World, why so sad?

Image Notes1. too many tweets...

Image Notes1. ...and so the LED turns green.

Step 12: Building the BoxBuild an acrylic box ala this Instructable:

www.instructables.com/id/LED-Cube-Night-Light/

Page 125: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Image Notes1. I do have a thumb2. and pinkie

Image Notes1. put a big book on it and leave it to dry

Page 126: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Image Notes1. the tape helps prevent shorts

Image Notes1. sanded to help diffuse the LED

Step 13: Enjoy!Some possible extensions include:

Making it multilingual and not just English speaking places. Perhaps just associating with a keyword, for example every tweet must contain the word "Obama", then you could gauge public opinion on just that subject.Location specific. Perhaps you just care about your town or country. Twitter allows you to use the geocoding to do this.Make it tweet what the world mood is so as to complete the circleAbility to connect to it from a computer to see what keywords people are so emotive about.

I am very interested to hear any comments, corrections or questions. Please do contact me, if you so wish.

Page 127: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Related Instructables

RotaryEmotiphone byzvizvi

Twitter MentionMood Light bypdxnat

Arduino moodlighting by sapc

Web-controlledTwitteringRoomba bymatchlighter

TerrariumTwitterMonitoring byMarioBoehmer

Arduino LilypadInteractivePassionSensing Scarfby ArduinoFun

Easy Mood lightby rickharris

Twitter SensingThermoelectricComponent byEngidan

Page 128: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Twitter Controlled Light-Botby anonymouse197 on July 29, 2010

Author:anonymouse197I didn't realise that I didn't have anything about me...

Intro:  Twitter Controlled Light-BotHave you ever wanted to actually make that Arduino Twitter Mood Lamp that looks so cool but don't want to use a complex Wifi-ish thing. Well this is the basic principlebehind that fantastic instructable. Unfortunately I have no knowledge of any form of windows programming so I use applescript (but I would love any windowscontributions!) You will also be pleased to note that the arduino is not soldered directly onto so to restore your arduino to its previous state you simply need to un-plug allof the pins.

This instructable uses:

An Arduino (I used a new Duemilanove)A USB cordThe Arduino softwarean Applescript Editorthe Twitterrific ApplicationSome LED's (I used 4)Some wire (or just some paperclips)and a Breadboard (not necessary but makes life easier)

(I will be adding images as soon as it is light enough to do so)Note: if you struggle to understand the instructions please read the sentences again as I sometimes use illogical sentence structures. If you continue to struggle just posta comment!

Also Note: This is not a smooth or streamlined application. I have cut corners for simplicity and because it is the learning curve that I am on. For example you should notbe able to use the computer when the script (step 3) is running, and the only way to stop the script is to cancel it by pressing cmd-. or clicking stop. Therefore I take noresponsibility for any damage done, problems caused, or anything negative of the like.

Please have a go on thisTwitter account!Also why not check out how it works?

Image Notes1. pin 13 connects to A3 on the board but this was an old build2. should be E63. GND connects to A14. LED "legs" straddle ground and a pin5. USB connection needs to be connected throughout the process6. bits of bent paperclip :)

Image Notes1. my laptop controlling the process.

Page 129: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 1: Make the circuit!The circuit is very simply, and as any hardcore arduinoer will know, very lazy. Simply use a wire (or paperclip) to connect the ground pin on the arduino to the first point inthe top left of your protoboard. This should be labeled A1 on the protoboard. Then continue downwards wiring pin 13 on the arduino to C1 on the protoboard (NOT B1 oryou may end up running out of ground pins), wiring pin 12 on the arduino to D1 and so on until you have the same number of pins wired up on the arduino (excludingground) as you have LEDs..

Now you need to put the LEDs in. You can either solder wires to your LED's and have them set up in a nice neat fashion or simply plug the LEDs into the protoboard. Thefirst LED we will plug the leg on the flat side (negative) into the first free ground pin (A2) and the second leg into the pin 13 connections on the protoboard below (C2).With the second LED we plug the connecter on the flat side of the LED (negative) into the next free ground pin (A3) and the second leg into the pin 12 connections on theprotoboard below (C3). Continue to do this until you have used all of your LEDs.

The setup should look a little like this: (Photos coming soon)

Image Notes1. pin 13 connects to A3 on the board but this was an old build2. should be E63. GND connects to A14. LED "legs" straddle ground and a pin5. USB connection needs to be connected throughout the process6. bits of bent paperclip :)

Step 2: Setup the Arduino Software!You will need the Arduino package, so follow the instructions on this  page, skipping steps 6 and 9. You will also need an applescript editor. (Note: I will be using thenative 'AppleScript Editor' that comes with Mac OS X and I have not tested any other editors or operating systems other than snow leopard.)

Download the 'TweetLED.pde' file, unzip it, rename it with .pde rather than the odd instructables thing and double click it. it will open in the arduino software so save it toa place of your choice. Now, upload it to the arduino and test it out by opening the serial monitor and typing one followed by enter. This should turn on the first LED. Nowminimise the Arduino window but KEEP OPEN THE SERIAL MONITOR! Also please make sure that whenever you change applications that the curser always is in thetop box.

Image Notes1. keep this window open and make sure that the curser always stays in the top box!2. this one should be minimized. It WILL cause problems with the script (I think) if it is not.3. Arduino Software

File Downloads

Page 130: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

TweetLED.pde (956 bytes)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'TweetLED.pde']

Step 3: Setup the Twitterrific Software!This is as simple as downloading Twitterrific , and logging in with your twitter account. You will also want to change some of the settings (see screen shot). Now you candrag the box to the corner of your screen to keep it out of the way but it does need to be open when the script is running.

Image Notes1. Shame that you cannot choose 'Direct Messages only'2. This is very important3. and this is the most important4. this is not used as all refreshing is built into the applescript

Image Notes1. i like this one2. i like this one too

Step 4: Setup the AppleScript Editor Software!This is easy. Simply dowload the 'Twitter Script.scpt' file below (if instructables does anything weird simply change the ending to .scpt). Look for AppleScript in spotlightand open the application. In the application navigate the the file, and open it. You can save it to the same place as the other file if you like.

Note: this is probably not the most efficient way of doing this but I am not great at scripting...

Page 131: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Image Notes1. this is the big red go button2. you might want to compile it first if you mistrust my coding ability :P3. this will always be here as putting in a way to stop the script is surprisingly complicated.

File Downloads

Twitter Script.scpt (10 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'Twitter Script.scpt']

Step 5: GO!simply make sure the correct windows are open and that the cursor is in the top box of the serial monitor and click 'Run' on the applescript editor. Now just let it do itsthing. If something goes horribly wrong just click 'Stop' on the applescript editor, press cmd-. , or at a last resort press and hold the off/on button on the computer. I cannotbelieve that it has been this simple! With all of the coding done from scratch it took me ages!

May I take this opportunity to thank RandomMatrix and the rest of the Instructables community for the inspiration and assitance... 

Image Notes1. cursor was in this box. other arduino window is minimized2. Twitterrific is open and ready3. the big red button

Page 132: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

4. the emergency stop button :S

Step 6: UPDATE!!!If you want the update for swirls and six LED's, check out my webpage on it at http://aricooperdavis.cz.cc/Ari/Instructable.html . I will also be adding the files here!!

File Downloads

Twitter Script.scpt (17 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'Twitter Script.scpt']

TwoLED_Control.pde (1 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'TwoLED_Control.pde']

Related Instructables

RunAppleScriptswith the wave ofa hand byphotoelectric

Developing forPICs using aMac : FriendlyUI by BarnabyWalters

TwittercontrolledArduinoOutputs - no PC- LCD Display +Sensor data toTwitter byXenonJohn

MacOS Foot Switchfrom a GuitarAmp Pedal. byaymans

Twitter MentionMood Light bypdxnat

Create anApplescript/ArduinoAlert flag. byaarone

Tweet'n'knock -Tweeting theknock (Photos)byfabrizio.granelli

SimpleApplescriptTutorial by101lenny101

Page 133: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

@tweet_tree: Twitter controlled Christmas treeby ian on December 21, 2009

Intro:  @tweet_tree: Twitter controlled Christmas tree@tweet_tree is a Christmas tree that everyone can control from Twitter. Just tweet a color to @tweet_tree. A small embedded server reads your tweets, and fades ourfiber optic tree to the colors you send. New tweets are grabbed every few seconds.

Live streaming video of @tweet_tree is on USTREAM (The broadcast has ended, thanks to everyone who gave us a light show with Twitter!). See this article with theoriginal formatting at DangerousPrototypes.com

@tweet_tree is a stand-alone network appliance based on our open source, business card size web platform. The web platform is available as a kit for $35, includingworldwide shipping. Seeed Studio can assemble yours for $5 more.

Using itTo choose the color of our tree, just send a color to @tweet_tree on Twitter.

@tweet_tree red, green, purple, green, p, g, r, b

@tweet_tree understands red, orange, yellow, green, blue, and purple. Send one color, or combination of colors to morph through. Separate multiple colors with acomma. Only the first letter of the color matters, r,o,y,g,b, & p, are acceptable color commands.

@tweet_tree red, *ff0000, green, *00ff00, blue, *0000ff

You can also blend custom colors using 24bit hexadecimal color codes. Here's a color picking tool to help you choose values. Send the value as *rrggbb, where rr=red,gg=green, and bb=blue. We used the * designator because the more common # is already used for Twitter hash tags. 

Step 1: OverviewTweet a color to @tweet_tree on Twitter. A business card size server connects to Twitter once every few seconds and grabs new tweets. A multicolor LED in our fiberoptic Christmas tree fades to the new color.If there's are more than one color in a tweet, or multiple tweets, the tree fades between them until it reaches the most recently sent tweet.

Page 134: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 2: HardwareThe tweet_tree has three primary components.

Web platform

Our open source web platform does the heavy lifting. It has all the hardware we need to connect to Twitter, parse tweets, and convert them to colors. The color(s) arestored in memory and sent to the ShiftBrite LED over a simple 3-wire interface.

The web platform is available as a kit for $35, including worldwide shipping. For an extra $5 Seeed Studio will assemble it for you.

ShiftBrite LED

A ShiftBrite high-power LED blasts the colors sent in the tweets.

IO2->LATCHIO3->CLOCKIO4->DATAGND->GND

It only takes three pins to control the ShiftBrite, we used IO2-4 on the web platform IO header. The EI pin should be permanently enabled by connecting it to ground. Themodule requires a 5volt+ power supply, we tapped the same supply we used for the web platform.

Fiber optic tree

Our tweet_tree is a small fiber optic Christmas tree, but you could use more ShiftBrites to light a full-size tree or yard display.

We removed the original guts from the base of the fiber optic tree and replaced them with the ShiftBrite. A major concern was that the LED wouldn't be bright enough toreplace the original mini-halogen lamp, but the ShiftBrite works perfectly.

Page 135: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 3: FirmwareFirmware

The latest firmware downloads are on the project Google Code page. The code is written in C, and compiled with the free Microchip C30 demonstration compiler.

The firmware uses an adapted version of the #twatch source code to connect to Twitter over the internet. It opens a TCP connection and sends a search query for'@tweet_tree', the response is a JSON formatted data file like this.

A JSON parsing state machine searches through the data for the 'text' and the 'id' tags. The text tag value is processed for color commands. The value of the first id tagis stored too. We'll use it to limit results to new tweets in the next search query. Hint: try JSONView to work with JSON in Firefox.

If a new color command is found, the LED fades into the new color. If multiple commands or tweets are found, the colors morph from oldest to newest, with a 5 secondpause between each. The tree always ends on the most recently tweeted color.

Every minute, or after completing a stored sequence, whichever takes longest, the web platform queries Twitter for fresh tweets. It appends the saved id tag value to thesearch query so the feed only returns new tweets. Twitter limits the number of queries you can make in an hour, but 60 is well below the limit.

The ShiftBrite is controlled with bitbang routines from our RGB remote control pumpkin project.

Compiling

This firmware uses the free Microchip TCPIP stack. If you want to compile the firmware yourself, download the TCPIP stack and follow the instructions in main.c.

Step 4: Get oneTaking it further

Twitter-controlled holiday possibilities are endless. The web platform can Twitter-enable a Halloween or Christmas yard display. Multiple Shiftbrite modules could be tiedtogether to light a large Christmas tree, or substitute a TLC5940 16channel LED driver to control individual LEDs.

Other web platform demos

Open source web platformSD card server demo

Get one

The web platform is available as a kit for $35, including worldwide shipping. For an extra $5 Seeed Studio will assemble it for you.

Page 136: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Related Instructables

ThermalTweeternetworkedTwitter printerby ian

Give Your CatTwitter Powersby bpunkt

simpleTweet_00processing bypdxnat

TwittercontrolledArduinoOutputs - no PC- LCD Display +Sensor data toTwitter byXenonJohn

Twitter MentionMood Light bypdxnat

Cloudphone(wip) (Photos) bythemoep

Display PDFfiles with a linuxserver. byComputothought

Twitter enabledcandy machine(Photos) by_macke_

Page 137: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Twittering Laser Tripwire with Webcam Captureby action_owl on January 1, 2010

Intro:  Twittering Laser Tripwire with Webcam Capture

This instructable will show you how to construct a laser tripwire that can twitter and grab an image from a webcam, as well as execute any command you can put in abash script.This instructable is actually quite simple and is even suitable as a beginner arduino project. It requires a GNU/linux (or possibly Mac) operating system with the arduinoIDE and Processing IDE working properly. This project could also be implemented in Windows if you created a more complex processing application.

Hardware RequirementsArduino BoardLaser pointer/penLight Dependant Resistor100Kohm Resistor

Optional:  Webcam  Breadboard

Software RequirementsArduino IDEProcessing IDELinux OS (I'm using Arch Linux for this project)CurlWebcam (part of xawtv)

Other Stuff:MirrorSolder and Soldering IronWireHot Glue GunHacksaw/KnifeStraw or Ballpoint Pen

Image Notes1. Laser Pointer

Page 138: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

2. Arduino3. Some Wire4. LDR (Light Dependant Resistor)5. 100Kohm Resistor

File Downloads

arduino.pde (359 bytes)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'arduino.pde']

processing.pde (688 bytes)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'processing.pde']

twitter.trip (270 bytes)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'twitter.trip']

Step 1: Connecting The LDR I needed the LDR and the laser to be in a position where they would not move around so I connected my LDR and resistor directly to the Arduino without a breadboard,but you can do it however you like, below are the photos for soldering and bending them into shape I also included a simple diagram.

I cut the end off of a ballpoint pen so that I could slip it over the LDR to prevent ambient light from affecting the reading, you could also use a straw.

Page 139: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 140: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 141: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 2: Connecting the Laser Pointer

You can find these really cheap at some retail stores, I know that mine was under $3.

Unscrew the end and remove the batteries.

Use a hacksaw or sharp seraded knife to cut off 1 to 1/2 inch of the laser pointer, so that you can access the spring. You may not need to do this depending of what kindof laser pointer you found.

Connect and solder a wire to the spring ( I bent mine out to make it easier ) then rough up a small part of the outside of the laserpointer with a knife/sandpaper/pliers ectso that you can solder it to the outer casing. Then tape the button that activates the laser.

On my laser pointer the spring is + and the casing is - yours might be reversed. The best way to check is to take note of what position the batteries go in, the coin cellswill have + marked on one side, if that side touches the spring then the spring is +.

Connect your + wire (Casing) to digital pin 13 on your arduino and you - wire (spring) to GND. 

Now upload the arduino sketch and ensure that you are getting readings from the LDR and that the laser is on.

To accomplish this you must uncomment this line://Serial.println(ldrVal);

and comment out this one:Serial.print("1");

If all is well you can position your Laser and LDR in a  fixed position, bounce the laser to the LDR with a mirror to see that its registering. When the laser is detected itshould print a "1".  You may need to adjust the threshold values depending on your LDR.

Image Notes1. Goes to GND2. Goes to +5V

Page 142: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Image Notes1. Tape to hold the button in the ON position2. It's really a pain to solder onto this casing

Step 3: Everything in place

Now you are going to need to make sure that your LDR and laser are not going to be moving around while you're testing the rest of the software.

I used a hot glue gun and used a small amount of hot glue on each edge of my arduino board to secure it to a plastic cassette case, (a piece of wood and some screwswould be ideal but I didn't have any) The hot glue should be removed easy and if it doesn't it's in an unimportant location.

I then hot glued my laserpointer onto the platic cassette case and rested it against the arduino's digital headers. The LDR doesn't move around so I didn't have to worryabout it moving. Your set up may vary but you get the idea.

You'll then want to make sure the whole thing won't move around, I used sticky tack on the bottom of the cassette case and put a jar of change on top of the USB cableso that it would not move around while testing.

You'll also want to affix your mirror to something, it's up to you to figure this one out I used sticky tack to adhere the mirror to an old and heavy Kodak brownie cameraand set it on a stool with a few books on top while testing everything out. Later I just affixed the mirror to my camera tripod.

Image Notes1. Mirror2. Protip: I scrapped this for a camera tripod, much better.

Image Notes1. My black cover fell of at some point and I couldn't find it.2. Plastic Cassette case

Page 143: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 4: Processing

Load the Processing sketch and leave this line commented out://open("/home/your_usename/twitter.trip");

Make sure that your laser is pointed at the LDR and run the sketch. The screen area should be green and when you block the laser it should turn red, then after 10seconds it should turn back to green.

The 10 second hold is to ensure that you're not twittering the same message multiple times, you can change this value by modifying the "int threshold=10000" variable.

Now that everything is working it's time to get your scripts in place

put twitter.trip into:/home/your_username/

Change these to your twitter username and passworduser="name"pass="password"

open up a terminal and type:chmod a+x /home/your_username/twitter.trip

then run it./twitter.trip

go to your twitter page and you should see "laser tripped on..." as your last tweet.

Now time to get the webcam working, you can skip this step if you don't want to use a webcam or if you know how to grab a frame from a webcam in linux via script.

First you want to make sure that the program called "webcam" is installed, it's a part of xawtv.

Arch Linux: pacman -S xawtvFedora: yum install xawtvDebian/Ubuntu: apt-get install xawtv

Then configure .webcamrc however you need, mine is below.The best part about webcam is that it has ftp support so that the image can be uploaded to a webserver, if you don;t want FTP comment that part out.

.webcamrc in /home/your_username/

[grab]device = /dev/video0text="%Y-%m-%d %H:%M:%S"#infofile = filenamefg_red = 0fg_green = 0fg_blue = 0fg_red = 255fg_green = 255fg_blue = 255width = 320height = 240delay = 0wait = 0input = pac207#norm = palrotate = 0top = 0left = 0bottom = -1right = -1quality = 75trigger = 0once = 1archive = /home/action-owl/webcam/%Y-%m-%d--%H:%M:%S.jpg

[ftp]host = ftp.yourwebsite.comuser = usernamepass = passworddir  = public_html/img/webcamfile = webcam.jpgtmp  = uploading.jpgpassive = 1debug = 1auto = 0local = 0ssh = 0

Page 144: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 5: Using open() in processing

The "open()" function works a little differently depending on your environment so you may need to find out what works for you, the method below should work.

Uncomment://open("/home/your_username/twitter.trip");

If you are using Nautilus or Thunar File Managers(XFCE and Gnome):Navigate to twitter.trip and right-click it.Select "Open with other application"select "Use a custom command"and type in "bash"

Processing is supposed to send executables to the shell to be run but after trying many methods this was the one that worked. This is also why the sketch has a .tripextension.

Page 145: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 6: Now run it.

Now everything should be ready to go!

Run the processing sketch and check your twitter and webcam archive location for the result.

Something is up with the file downloads.So here's the code, again.

#------------------------# twitter.trip#------------------------#!/bin/bashuser="username"pass="password"trip=$( date +'%A %b %d, %l:%M%p' )stat="laser tripped: "$tripurl=http://twitter.com/statuses/update.xmlresult=`curl -u $user:$pass -d status="$stat" $url`#save webcam picwebcamdate +'%A %b %d, %l:%M%p' > /home/username/someplace

//------------------------// processing code//------------------------import processing.serial.*;Serial myPort;char inBuffer;int wait, now, timeout = 10000;boolean hold = false;

void setup() {  size(200,200);  println(Serial.list());  myPort = new Serial(this, Serial.list()[0], 9600);  fill(#36ff00);}

void draw() {   while (myPort.available() > 0)  {    inBuffer = myPort.readChar();  

    if(inBuffer=='1')    {           if ( !hold )      {        fill(#ff0000);        println("Tripped");        open("/home/username/someplace/twitter.trip");        wait = millis();        hold = true;      }    }  }   now = millis();     if (now > (wait + timeout))  {    hold = false;    fill(#36ff00);  }     rect(0,0,200,200);}

//------------------------// arduino code//------------------------

int ledPin =  13;int analogPin = 0;int ldrVal = 0;int threshold = 500;

void setup(){  Serial.begin(9600);  pinMode(ledPin, OUTPUT);

Page 146: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

  digitalWrite(ledPin, HIGH);}

void loop()                    {  ldrVal = analogRead(analogPin);   if ( ldrVal > threshold )  {     Serial.print("1");     delay(200);   } }

Related Instructables

Do notEnter(Twitter-updates)(WithoutEthernet Sheild)(Photos) byvishalapar

TwitMap:TopographicalColoradoTwitter Map byianisborn

Homesurveillance viaTwitter andYouTube bymaskedavengers

TwittercontrolledArduinoOutputs - no PC- LCD Display +Sensor data toTwitter byXenonJohn

Give Your CatTwitter Powersby bpunkt

Twitter MentionMood Light bypdxnat

simpleTweet_00processing bypdxnat

The TwitteringOffice Chair byrandofo

Page 147: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Twitter Watcher, the #twatchby ian on September 9, 2009

Intro:  Twitter Watcher, the #twatch

The #twatch scrolls the latest trending topics from Twitter on an LCD screen. It's a stand-alone network appliance that stays updated without a PC. It was awesome towatch #iranelection, Michael Jackson, and other historic events scroll by while we developed the #twatch. This Instructable documents the #twatch hardware and design.

In addition to a Twitter trend ticker, the #twatch is also a generic ethernet LCD backpack. It'll show playlists, PC stats, and other info with programs like LCD Smartie. It'salso software upgradable, so it's never outdated.

The #twatch is open source, so you can download our designs and build your own.

Seeed Studio has a few assembled #twatch ethernet LCD packpacks for $45, including worldwide shipping. Get them while they last because we won't makemore soon. If you missed this project, sign up here to be notified of future #twatch preorders.

See this article with its original formatting at DangerousPrototypes.com, more discussion in the #twatch forum. We'll send a free #twatch PCB if you're the first to tweetthe #twatch!

Concept overview

The #twatch grabs the latest trending topics from Twitter, then loads a few tweets for each. The trending topics and tweets scroll on a screen. The #twatch grabs freshtrends and tweets every five minutes so you always see the latest trending topics.

We also added a generic ethernet backpack mode, so the #twatch can also show PC stats from a program like LCD Smartie, more about this feature in part 2.

Page 148: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 149: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 1: Using itThe #twatch is easy to use.

Connect it to a home ethernet network with Internet access. The #twatch requires automatic network configuration (DHCP), this is the default setting on almostevery modern home network.Power it up. The #twatch requires a 6-7volt DC power supply. It uses a 2.1mm DC power plug, the most common type. Universal DC power supplies shouldinclude a 2.1mm plug.Adjust the contrast. LCD screens change with temperature and age, use the adjustment screw to tweak the screen contrast.The #twatch will configure the network settings and begin scrolling the latest trending topics and a few tweets from each. You may need to adjust the contrastagain for the cleanest scrolling effect.

Get #twatch updates at the Dangerous Prototype blog.

Step 2: HardwareWe used the freeware version of Cadsoft Eagle to make the circuit and PCB. Download the latest files from the project Google Code page.

This section lost a lot of formatting at Instructables, you can see the original version here.

Ethernet PIC 18F67J60 microcontroller

The Microchip PIC 18F67J60 is perfect for this project because it combines an ethernet network interface and a 41MHz microcontroller (10MIPs) in a small package foronly a few dollars. It only comes in 64pin+ TQFP packages, but we didn't have a problem soldering it by hand to a professional PCB.

The PIC requires a 3.3volt power supply. The ethernet portion is really power hungry, so we used a giant TO-220 LD117-3.3volt regulator (VR1). We chose a bigregulator because it might have to dissipate a bunch of heat depending on the input power supply. The regulator requires a small input decoupling capacitor (C15) and alarge 10uF output capacitor (C3).

There's a big catch with these chips: they can only be programmed about 100 times. That makes development difficult, so we also designed a development version of the#twatch based on a different chip. More about that design in a future article.

Each PIC power pin gets a 0.1uF decoupling capacitor (C17-C23). The PIC has an internal 2.5volt regulator for the microcontroller and ethernet cores, the regulatorrequires a 10uF tantalum capacitor (C1).

The PIC is programmed through a 5pin ICSP header. The MCLR reset pin is held high with a 10K pull-up resistor (R21), an additional resistor (R4) and capacitor (C16)recommended by the datasheet provide protection against various accidental reset conditions.

The ethernet section mandates a 25MHz external crystal (Q1). Two 33pF capacitors (C4, C5) complete the oscillator circuit.

We used an ethernet jack with integrated magnetics (J2). The jack is a HanRun HR911105A, provided to us by Seeed Studio - be sure to get the same jack, a compatiblejack, or adjust the PCB for a jack you can find. The ethernet interface requires a termination circuit (R30-33, C10-11, L1) and 2.28Kohm 1% bias resistor (R7, not shown).

HD44780 character LCD

Page 150: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

The #twatch supports a 'standard' 4line by 20character 5volt HD44780 LCD with a +5volt backlight. You can usually find them for about $10 on eBay. Be sure to verifythat your LCD matches the #twatch pinout before attaching it. Most LCDs are the same, but not all of them.

Almost all character LCDs operate at 5volts, so we provide a 5volt power supply from a common 7805 regulator (VR2, C14, C2). The LCD with backlight could potentiallyuse a bunch of current, so we used another large To-220 regulator. C12 is a decoupling capacitor for the LCD power supply, but LCDs already have on-board decoupling.C12 need not be populated, we just included it in case of stability issues.

For maximum refresh speed, the LCD is controlled through the full 8bit interface.

Most LCDs are 5volt parts that require about 4.25volts+ to register a high level on the data pins, but the PIC 18F65J60 is only a 3.3volt part. Fortunately, the PIC has abunch of 5volt tolerant pins so we can hold the signal at 5volts with a 10K pull-up resistor (R10-R19), and then ground it by changing the PIC pin direction setting. This isusually called an open drain output.

Some newer LCDs run at 5volts, but still work at 3.3volt interface levels. The #twatch will support this mode if you leave out R10-19 so no pull-up voltage goes onto thepins, and change the firmware to switch the LAT register instead of the TRIS register in HD44780.c.

LCD screen contrast is controlled by a bias voltage, usually generated with a 10Kohm potentiometer. The #twatch PCB has footprints for an inexpensive 3mm SMD pot(R2), and a second space to use a larger, through-hole pot (R2A). Only one should be populated!

Just in case there's noise in the power supply from all the ethernet stuff, we filter the bias voltage through a small ferrite bead (L2). We also included a capacitor foradditional filtering(C13), but we didn't use it since neither element is actually needed.

The #twatch can control simple +5volt backlights up to 400mA or so. The PIC switches a transistor (NPN1) through a 240ohm current limiting resistor (R3, not shown).We used a transistor that can handle 800mA+ with a gain of 250hfe+, so the PIC can switch a large load with it's 20mA maximum pin output current.

R1 is a current limiting resistor for the LCD backlight, if needed. We used a through-hole resistor so it can dissipate a lot of heat with big backlights, and because it's theeasiest size to find locally and solder yourself. If your backlight doesn't require a resistor, just replace R1 with a piece of wire. Our LCD required a 3ohm resistor for a240mA backlight power supply.

Some backlights use a lot of power, so we put the supply pins right next to the power supply and reinforced the ground plane with a bunch of VIAs. Some fancy LCDbacklights require special drive circuits, so be sure yours uses a simple +5volt supply to avoid damage.

Power supply

The #twatch requires a 6-7volt power supply through a 2.1mm power supply jack (J1). 2.1mm plugs are the most common size, and should come with every universalpower supply.

The higher the supply voltage you use, the more heat that has to be dissipated from VR1 and VR2. Remember that the #twatch is a prototype learning board, it's not acomplete and tested commercial product. Take appropriate safety precautions and don't run it unattended.

Image Notes1. LCD section2. PIC/ethernet section

Image Notes1. Internal core regulator capacitor2. 25MHz oscillator3. MCLR pull-up4. Ethernet bias resistor5. PIC 18F67J60

Image Notes1. RJ45 ethernet jack

Page 151: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Image Notes1. Contrast adjust2. Alternate contrast adjuster

Image Notes1. LCD backlight resistor2. Extra ground reinforcement Image Notes

1. 5volt LCD power supply2. 3.3volt PIC power supply3. 2.1mm DC barrel plug, 6-7volt supply input.

Page 152: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 3: PCB and partlistWe used the freeware version of Cadsoft Eagle to make the schematic and PCB. Download the latest files from the project Google Code page.

The PCB is a 2-layer design with small traces and separation (10mil) around the 64pin TQFP PIC chip. We prepared gerbers and sent them to Seeed Studio's PCBservice for open source works. Extra PCBs from our order are available in the Seeed Studio shop. If you buy our extra PCBs be sure to get the HanRun ethernet jack thatfits the board.

Since the mounting holes on 20x4 LCDs vary, we didn't try to fit the PCB to the LCD holes. We made it as small as possible, like SparkFun's serial LCD backpack, so itstays out of the way of the original holes. As a side effect, it's not too terribly awkward behind some smaller screen like this 16x2 LCD at Adafruit.

Parts listClick for a full size placement image [PNG].

Part | Value | PackageIC1 PIC 18F67J60 TQFP-64C1-3 10uF tantalum capacitor, 10volts+ SMC_AC4,5 33pF capacitor 0805C10,11,C14-23 0.1uF capacitor 0805ICSP 5x 0.1" male pin headerJ1 2.1mm SMD power jack SMDJ2 HR911105A ethernet jack RJ-45L1, L2 Ferrite bead, 200ma+ 0805NPN1 NPN transistor, 250hfe+, 800ma+ SOT-23Q1 25MHz SMD crystal HC49UPR2(A) 10K single turn trim resistor 3mm SMD or through holeR3 240 ohms resistor 0805R4-6 390 ohms resistor 0805R7 2,260 ohms resistor, 1% 0805R10-21 10,000 ohms resistor 0805R30-33 49.9 ohms resistor, 1% 0805VR1 LDO 3.3volt regulator (LD1117) TO-220VR2 7805T 5volt regulator TO-220HD44780-LCD 20x4 HD44780 character LCD

Step 4: FirmwareThe latest complete #twatch firmware download is on the project Google Code page. The code is written in C, and is compiled with the Microchip C18 demonstrationcompiler.

TCP/IP stack and base network functions

Microchip's 'free' TCP/IP stack provides all the network functions we need to exist on a home network and grab data from Twitter. The stack is open source and free-as-in-beer, but the Microchip license prohibits distribution. Due to licensing issues, we're only putting our public domain source code in the project Google Code SVN, learnhow to download and compile the source here.

The stack has a Dynamic Host Configuration Protocol client that automatically configures the network settings using the DHCP server on your local network. The #twatchrequires a DHCP server, but the vast majority of networks and routers have this enabled. The IP address, mask, gateway, and first DNS server are displayed on the LCDscreen until valid Twitter data is available.

The stack also includes Microchip's announce server. When the IP address is acquired by DHCP, the #twatch announces its IP address with a broadcast packet to allcomputers on the local network. Use the MCHPDetect.exe utility in the project archive to view these packets.

Finally, we included a ping (IMCP) server. Use any ping client to check if the #twatch is alive on the network.

Twitter TCP client

The Twitter trend following program is a simple TCP client, similar to a web browser, that pulls data from web servers. Twitter's API will give us data in a variety offormats. We used the light-weight JSON format because it's easiest for the low-power PIC chip to decode, check out JSONView if you use Firefox.

After the #twatch automatically configures network settings, the Twitter TCP client takes control and grabs the current trending topics. It searches through the this JSONdatafeed and looks for the "name" tag. Up to 10 trending topics are copied into a 225byte buffer. A separate array stores the end position of each topic in the buffer so wecan retrieve the topics in the next step.

Next, the #twatch searches Twitter for 2 tweets for each topic. It appends each topic to the end of the Twitter JSON search url, special characters like spaces andpunctuation are URL encoded.

Page 153: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

The TCP client parses through the search results and looks for tweets that follow the "text" tag. Tweets have multiple layers of encoding. We decode HTML reservedcharacters like ampersand (&) and quotes (") because the LCD screen can display them. We remove UTF8 international characters because the HD44780 LCD doesn'thave them in its character set.

The parsed, decoded tweets are stored in a 2100byte buffer, an additional array marks the beginning and end of each tweet in the buffer. RAM space was a big problemon the 18F67J60 chip, it only has about 4000bytes total, but the 2100byte buffer seems big enough to handle 20 average-sized tweets. We took special care to protectagainst out of memory problems, and we tested the client under reduced RAM conditions to ensure that it fails gracefully during errors.

Twitter is well known for its occasional down-time. If the #twatch can't connect to Twitter, it displays a connection error message and the retries twice. If it can't connectafter three tries, it waits five minutes before trying again. This gives Twitter a chance to fix their problems without being hammered by #twatch queries.

The #twatch grabs fresh trend and tweet feeds every five minutes. Twitter puts a limit on the number of queries a client may make, so be careful about refreshing moreoften. Twitter allows 150 trending topic updates per hour, and "significantly more" search queries.

Network LCD backpack mode TCP server

The #twatch can also display system status information from programs like LCD Smartie. The #twatch has a TCP server on port 1337 that accepts Matrix Orbitalformatted commands. This also provides control over the LCD backlight. We'll show you how to redirect LCD Smartie from a COM port to the #twatch TCP server in parttwo of our #twatch article.

Page 154: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 5: Bootloader for network firmware upgradesThe #twatch can be updated from a PC on the local network thanks to Microchip's internet bootloader. Remember that the 18F ethernet PICs can only be programmedan average of 100 times, so upgrades are somewhat limited. We've yet to burn out a chip, but we only reached about 55 cycles during development.

If you're using a brand new chip you'll need to program the bootloader into the PIC18F67J60 through the ICSP header, then you can upload the #twatch firmware overthe network. Program twatchv2-bl-vxx.HEX into the chip with a PIC programmer like an ICD2 or PicKit.

When the #twatch powers on, the bootloader runs before the main program starts. The bootloader checks for a connection between the PGD and PGC pins of theprogramming header, shown in the image above. If it finds a connection, the bootloader takes over and waits for new firmware to be uploaded.

There's a very minor chance that the bootloader will accidentally start even without a jumper between the PGC and PGD pins. This won't damage the #twatch, justdisconnect the power supply and try again. Accidental bootloader entry can be prevented by moving the jumper over one position so it connects the PGD and GND pins.

The #twatch bootloader uses the IP address 192.168.1.123 and subnet mask 255.255.255.0. Your computer must also have an IP address that begins with192.168.1.xxx to communicate with the #twatch. We chose the 192.168.1.xxx range because it's the most common default for home routers. If your computer usesanother IP address range, you'll need to temporarily adjust it before you can do the update.

How to upgrade:

Ensure your PC is in the same IP range and subnet as the #twatch. Your PC should have an IP address in the range 192.168.1.xxx, and a subnet mask of255.255.255.0. The default #twatch bootloader IP address is 192.168.1.123, make sure that no other computer connected to the same router already uses thisaddress.Unplug the #twatch power supply.Put a jumper between the PGC and PGD pins.Plug in the network cable, if necessary, and plug in the power supply. The screen may be blank, have solid blocks, or garbage.Use a TFTP utility to send the new firmware to the #twatch IP address, we use TFTP.exe from the Windows command line.The TFTP update reports success or error.Unplug the power supply, remove the update jumper.Plug the power supply back in. The #twatch should start scrolling tweets. If the bootloader starts instead, put a jumper between the PGD and GND pins and tryagain.

Page 155: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 6: Taking it further, get your ownWe designed the #twatch to make full use of the resources on a single chip, an expanded design would add features but be more expensive.

The #twatch could follow your own Twitter feed. It would need a small web server to enter your Twitter login, and an external EEPROM to store the configurationinformation.

The #twatch could also store more tweets or extra information about each tweeter, such as name and location. Microchip doesn't make an integrated ethernet controllerwith more than 4K of RAM, but we could add an external SRAM to store tweets and tweet meta-info.

Updated hardware could add an I/O header for connecting buttons with LCD Smartie.

A 20character by 4line LCD doesn't have a lot of display space. We designed the #twatch interface around this limited amount of space. An updated firmware couldhandle multiple screen sizes.

The bootloader can adopt the IP address acquired by DHCP. A future #twatch firmware update will take advantage of this feature for easier network upgrades.

Next week we'll cover the LCD Smartie compatible TCP server built into the #twatch.

Get one!What's twending on your #twatch? If you want an assembled #twatch or PCB, here's a couple options:

Seeed Studio has a few assembled #twatch ethernet LCD packpacks for $45, including worldwide shipping. Get them while they last because we won't makemore soon. If you missed this project, sign up here to be notified of future #twatch preorders.If you want to build your own, Seeed Studio is selling the extra #twatch v1 and v2 PCBs from our order. Be sure to get an ethernet jack from Seeed, or make sureyou can find one that matches the PCB. We'll write about v1 in a few days, the schematic and PCB are in the project SVN.We'll send a free #twatch v2 bare PCB to the first 2 people who tweet the #twatch.

If you'd like to get involved, join the Dangerous Prototypes open hardware project at Google Code, or come chat in the #twatch forum.

Next week we'll show you how to redirect LCD Smartie system stats to the #twatch TCP server.

Page 156: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Related Instructables

Networked LCDbackpack withLCD Smartie byian

Twitter scrollingpicture frame byian

The Glen theStove Project byChris theCarpenter

Anartwork thatstares back(Photos) byjeremycouillard

Displaymessages fromtwitter on thesmall screen byadunn

TwittercontrolledArduinoOutputs - no PC- LCD Display +Sensor data toTwitter byXenonJohn

DisplayingTwitter feedwithout a PC! byfabrizio.granelli

How to control a16x2 LCD usingan AVRATtiny2313 byroznerd

Page 157: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Twitter scrolling picture frameby ian on September 14, 2009

Intro:  Twitter scrolling picture frame

This instructable will show you how to make a Twitter scrolling picture frame.

You'll need:1. #twatch ethernet LCD backpack and a 4*20 character LCD screen.2. A picture frame that fits the LCD. Ours is 7.5cm by 11cm (3in x 4.5in).3. A piece of plastic sheet, but foam core might work too.4. Tools: cutting blade, screw driver, maybe some screws.

Seeed Studio has a few assembled #twatch ethernet LCD packpacks for $45, including worldwide shipping. Get them while they last because we won't make more soon.If you missed this project, sign up here to be notified of future preorders.

Image Notes1. #twatch Twitter feed. Image Notes

1. PC system stats with LCD Smartie

Page 158: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 1: Cut a holder to fit the frameWe need something that will support the LCD screen and hold it in the frame. We used a ridigid piece of black plastic, but foam core might work too.

Use the existing picture backing to mark the material. Cut out a replacement using a cutting blade. The edges don't need to be neat because the frame will cover them.

Center the LCD on the material and mark the location where the pin header should go through and mate with the #twatch PCB. Cut out a small strip, cut carefully so thatthe LCD screen is held securely in the center of the frame.

Mate the LCD to the #twatch through the hole. Put the electronics/backing sandwich into the picture frame.

Page 159: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 2: Move the standOur picture frame had a stand with a hinge screwed into the existing backing. We removed it, and relocated it to the side of the frame, where it's out of the way of the#twatch LCD backpack and cables.

Step 3: Scroll TwitterPlug in the network cable and power to scroll the latest trending topics and tweets from Twitter.

Seed Studio has a few assembled #twatch ethernet LCD packpacks for $45, including worldwide shipping. Get them while they last because we won't make more soon. Ifyou missed this project, sign up here to be notified of future preorders.

Related Instructables

Networked LCDbackpack withLCD Smartie byian

Twitter Watcher,the #twatch byian

DisplayingTwitter feedwithout a PC! byfabrizio.granelli

TwittercontrolledArduinoOutputs - no PC- LCD Display +Sensor data toTwitter byXenonJohn

Make an EasyButton Tweetthe Hard Way byLayout

Anartwork thatstares back(Photos) byjeremycouillard

@tweet_tree:TwittercontrolledChristmas treeby ian

Displaymessages fromtwitter on thesmall screen byadunn

Page 160: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Give Your Cat Twitter Powersby bpunkt on April 18, 2009

Intro:  Give Your Cat Twitter PowersGive your cat a Twitter account and have her post updates automatically whenever she sits down on her bed or when she leaves her bed. In addition, capture picturesof your cat when she's on her bed and upload those as well so you can keep tabs on her antics while you're away from home.

In this instructable, I'll walk you through the process of

building a cat sensor out of a simple momentary switch, foam core and foam stripsreading the cat sensor on your Mac or PC using Arduino and Processingautomatically posting status updates to Twitter when your cat takes a nap or wakes back uptaking pictures of your cat on the bed with a webcam and uploading the pictures to a webserver

Want to see a twittering cat in action? Follow @zooooey on Twitter.

This instructable is inspired by Tom Igoe's Networked Cat Project in the book "Making Things Talk"

Image Notes1. Cat sensor underneath mat2. One lazy cat3. Webcam to capture pictures of cat4. Arduino board to read switch data5. Old laptop running a Processing program to pull it all together

Page 161: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 1: Theory / OverviewThe overall plan is as follows: We'll first build a cheap "cat sensor". To read that sensor from a PC, we'll use an Arduino board running Firmata firmware. To take picturesof your cat, we'll capture still images from a web cam stream. All the logic will be handled in Processing . We'll use existing libraries to send Twitter updates wheneveryour cat sits down or leaves the bed. When the cat is on the bed, we'll capture still shots and upload those to a web server using FTP. We'll then add links to the picturesto the Twitter messages.

Here's the shopping/scavenging list, from most to least expensive:

1 old laptop or PC with internet connection. Mac or PC will both work fine; Linux will be trickier - you're on your own there with video capture support.1 webcam1 Arduino board + USB cable1 momentary switchstranded wire (I like 24AWG)1 sheet of foamcoresome springy sheet material (e.g. Foamies sheets)

Tools: Just the basics

soldering ironxacto knifehot glue gun

Page 162: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 2: Build a cat sensorWe want to detect when your cat is gets in the bed and when she leaves the bed.The cheapest way to do so is with a momentary switch. Most switches you can pick up at an electronics supply store are much too small; we'll need to increase thesurface area of the switch and make sure that the weight of the cat bed itself does not actuate the switch.

Here's a quick way to do so:

Solder two stranded wires onto the terminals of your momentary switch. Allow enough wire length to reach from the cat bed to wherever you plan to stash yourcomputer.Cut a strip of foamcore (12"x2" maybe), score it in the middle, then fold in half at the hinge. The upper half will be your lever. Cut a switch-sized hole in the bottompart. Hot glue the switch in, then glue a supporting piece of foamcore underneath to give more support to the switch.To add some spring force to the lever that keeps it open normally, cut some short pieces of "Foamies" foam strip, or some other springy material, and glue intoopen end between lever and base.

Then slide the switch underneath your cat bed. The switch should not be actuated by the weight of the bed alone, but should be actuated whenever you apply lightpressure with your hand in various parts of the bed.

Alternatives :

Tom Igoe shows how to detect a cat using Force Sensitive Resistors mounted between two plates of thin plywood in his book Making Things Talk.

Image Notes1. momentary switch2. "Foamies" foam strips from crafts store

Step 3: Connect your cat sensor to Arduino, and Arduino to your PCWe'll use an Arduino board to sense the state of your cat sensor. Instead of writing code for the Arduino board directly, we'll keep all of our logic on the PC in Processing.One easy way to make that possible is to load the Firmata firmware onto the Arduino board, since there is a nice Firmata-based library in Processing. You'll findStandardFirmata under Sketchbook->Examples->Library-Firmata->StandardFirmata on Arduino0015.

Once you've uploaded the firmware, it's time to put the circuit together. There really isn't much to it - we'll use an internall pull-up resistor in the chip, so all you need to dois plug the ends of the two wires you soldered onto your switch into your Arduino board: one goes to ground, another to a digital input (I'll assume #2 in the rest of thetutorial).

Alternatives:Since all we need is a single bit of discrete input, we could also achieve this with any other USB I/O interface such as a USB Bit Whacker or even a Keyboard breakoutboard .

Page 163: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 4: Set up ProcessingTo program the logic of your twittering cat, we'll use Processing .

To make our programming job easier, we'll use a number of different libraries inside Processing.

Download the Arduino library for Processing from http://www.arduino.cc/playground/Interfacing/Processing. Extract the zip file to your Processing librariesdirectory - on the Mac this is in ~/Documents/Processing/libraries/arduino (I had to create libraries subfolder by hand since there was no other library installedyet.) Restart Processing and check under Sketch->Import Library... You should see an Arduino entry.To post twitter updates, download the twitter4j library from http://yusuke.homeip.net/twitter4j/en/index.html. Extract to some place you'll remember. We'll only needthe file twitter4j-2.0.0.jar (your version may vary). Later on, we'll add that jar file to our Processing sketch through Sketch->Add file. This copies the jar file into a"code" subdirectory of your sketch. (It won't show up as a library).To post images via FTP, download edftpj library from http://www.enterprisedt.com/products/edtftpj/. You'll later add the jar file lib/edtftpj.jar to your sketch. There'smore documentation about using this jar in processing at http://processing.org/hacks/hacks:ftpIf you're on Windows, you'll need to download and install WinVDIG 1.01 (version matters!) so the Processing video capture library can grab frames from yourwebcam. Download from http://www.eden.net.nz/7/20071008/

Image Notes1. This is the Processing Sketch directory under ~ or "My Documents"2. Create this libraries folder by hand if it doesn't exist yet3. Drop your arduino library into the created libraries folder. RestartProcessing.

Image Notes1. If you see this library listed here, you've successfully installed Arduino/Firmatasupport.

Page 164: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 5: Detect switch state in ProcessingWhen your cat first jumps on the bed or moves around a bunch, our switch values will probably bounce between on and off for a while. To avoid firing off lots of spuriousupdate messages, we'll "debounce" our switch by requiring that the value has stabilized for a number of iterations before we fire any events.

Here's Processing code that initializes Arduino and checks the switch state in its main loop:

import cc.arduino.*;import processing.serial.*;// Detect Arduino switch state from Processing// via Firmata, with debouncing//-----ARDUINO VARS--------------------Arduino arduino;int matPin = 2; // which input pin are we connected to?int matCounter=0; // counter for debouncing switch inputint bounceLimit=100; //debouncing limitint curMatState = Arduino.HIGH; //current switch stateint lastMatState = Arduino.HIGH; //last switch stateint lastMatEvent = Arduino.LOW; //last event we firedvoid setup() { // ARDUINO arduino = new Arduino(this, Arduino.list()[0]); // v2 arduino.pinMode(matPin, Arduino.INPUT); //set input pin arduino.digitalWrite(matPin, Arduino.HIGH); //enable pull-up}void draw() { // read current mat state pollMatState(); // wait a bit delay(10);}// Read current mat state with debounce timer and toggle check// calls fireMatEvent() when state of mat changed and has been stable for a whilevoid pollMatState() { curMatState = arduino.digitalRead(matPin); if(curMatState == lastMatState) { //still in same state - incrase bounce counter if(matCounter < bounceLimit) { matCounter++; } else if (matCounter==bounceLimit) { //we've debounced enough and are ready to fire if(lastMatEvent != curMatState) { //only fire if this event is difft from last one fireMatEvent(curMatState); lastMatEvent = curMatState; } matCounter++; } else if (matCounter > bounceLimit) { // event already fired - do nothing } } else { //restart count matCounter=0; } lastMatState = curMatState;}// Fire a new mat state change eventvoid fireMatEvent(int state) { if(state==Arduino.LOW) { println("cat is off mat"); } else { println("cat is on mat"); } }

Step 6: Send a Twitter updateSending a Twitter update is very easy with the help of the Twitter4j library.Here's the minimum code to post a status update from Processing. You'll have to add the twitter4j jar file that you downloaded earlier to your Processing sketch thoughthe Sketch->Add File menu.

// Send a status update to Twitter via the twitter4j API// You have to add the twitter4j-x.x.x.jar file to your sketch via Sketch->Add FileString twitterID = "XXX"; //your twitter IDString twitterPassword = "XXX"; //your twitter passwordvoid setup(){}void draw(){ //send new tweet on mouse click if(mousePressed) { sendTweet("Updating my status from Processing."); }}// Send the tweet passed in as String argumentvoid sendTweet(String msg) { //construct a new twitter object Twitter twitter = new Twitter(twitterID,twitterPassword); try { Status status = twitter.update(msg); System.out.println("Updated the status to [" + status.getText() + "]."); } catch (Exception e) { e.printStackTrace(); }}

To make the updates more interesting, you'll probably want a whole set of alternative status messages that you can switch between. Take into account whether your catis on or off the bed. How long she's been there. What time of day it is. Etc...

Step 7: Capture an image when the cat gets into bedTo get started with image capture, look at the Processing example File->Example->Libraries->Video (Capture)->GettingStartedCapture. Make sure you install theWinVDIG component mentioned in step 4 if you're on a Windows PC.

Here's a Processing example that, on Mouseclick, captures a video frame and saves it to file in your sketch's data directory.

// Capture an image from an attached webcam and save it to a unique filenameimport processing.video.*;import java.text.SimpleDateFormat;import java.util.Date;Capture cam;void setup() { size(320,240); // use the default camera cam = new Capture(this, 320, 240); }void draw(){}void mousePressed() { captureImage(makeFilename());}// Capture an image and save it under the passed in filename// in the sketch data directoryString captureImage(String filename) { if (cam.available() == true) { cam.read(); image(cam,0,0); save(dataPath(filename)); println("Captured "+filename); return filename; } else { println("Camera not (yet?) ready."); return null; }} // Create a unique filename based on date & time// @see http://javatechniques.com/blog/dateformat-and-simpledateformat-examples/String makeFilename() { Date now = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd-HHmmss"); return (format.format(now)+".jpg");}

Image Notes1. Zooey cat, sleeping, as captured by my webcam

Step 8: Upload the image via FTPTo upload our captured image on, we'll use FTP. This is the most straightforward solution to make the images accessible to others on the web, but it does require havingaccess to a server that can accept FTP uploads and serve those files to web browsers.

The FTP code I use is taken verbatim from http://processing.org/hacks/hacks:ftp so I suggest you take a look at that page.

Alternatives:

we could also upload the picture using the TwitPic API, but would have to encode the image and generate an HTTP POST request, for which Processingunfortunately doesn't have good library support.We could also post the image to Flickr, using one of the available Flickr API wrappers in Java such as flickrj. I've found Flickr authentication to be a drag though.Finally, to prevent your password from being sent around in plain text, you may wish to use SFTP instead of FTP. Daniel Shiffman has a nice SFTP library forProcessing.

Page 165: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 9: Putting it all together.Now we have all the different pieces, and just need to glue them together in one single Processing sketch - I've attached the complete processing sketch to this step.

You'll have to provide your own twitter and FTP account data to make it work. Otherwise, happy cat-twittering.

File Downloads

twittering_cat_01_export.zip (323 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'twittering_cat_01_export.zip']

Related Instructables

simpleTweet_00processing bypdxnat

GarduinoUpgrade, Nowwith moreTwitter! bynatantus

Web-controlledTwitteringRoomba bymatchlighter

Do notEnter(Twitter-updates)(WithoutEthernet Sheild)(Photos) byvishalapar

TerrariumTwitterMonitoring byMarioBoehmer

Tweet'n'knock -Tweeting theknock (Photos)byfabrizio.granelli

simpleTweet_01python bypdxnat

TwittercontrolledArduinoOutputs - no PC- LCD Display +Sensor data toTwitter byXenonJohn

Page 166: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Enormous led Mood lightby Tesla-inc on June 18, 2011

Intro:  Enormous led Mood light

Enormous led mood light from Tesla on Vimeo.The Enormous led Mood light is basically a huge 3x3x3 led cube,but to make it big each led is put in to a paper lantern.In the end this makes for a great night light or disco light. This instructable will show you step by step how to make a huge 3x3x3 LED cube that will be controlled by anArduino uno. I will include  the code and pins to use near the end : )

Page 167: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 1: Gather Your ToolsTo start of you will need these tools...

.hot glue gun

.soldering iron

. Wire Strippers

.scissors

. ruler Optional ladder 

Image Notes1. hot glue gun

Image Notes1. safety first2. soldering iron

Page 168: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Image Notes1. Wire Strippers

Step 2: Gather Your MaterialsTo start of you will need these materials:

. stranded wire about 24 feet

. solid core wire 5 feet

. fishing string

. paper lanterns(27)

. Arduino uno

. pcb

. 12 Resistors (~220 ohms)

. cat 5 cable

. electrical tape

. 3 NPN Transistors (2N2222, 2N3904, BC547, etc.)

. 27 LEDs Color is optional i used these:http://www.radioshack.com/product/index.jsp?productId=2062588

. Optional- breadbord

Image Notes1. stranded wire

Image Notes1. fishing wire

Page 169: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Image Notes1. you can get these at party city

Image Notes1. Arduino

Image Notes1. pcb from radio shack . here is the linkhttp://www.radioshack.com/product/index.jsp?productId=2102846&numProdsPerPage=602. 12 Resistors (~220 ohms)3. cat 5 cable

Image Notes1. leds : ) !!!

Image Notes1. come in packs of twenty

Page 170: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 3: Make the led lanternsTo make the 27 led lanterns first :test leds first .Then snip two wires 3in long twist the wires with the led leads and tape with electrical tape or solder them.test the leds againnow cut a solid core wire 4 in. and wrap it around the electrical insulation of the led you just made and hot glue it in place.take he paper lenterns and open them up. Next rest the solid core wire on the the lantern and hot glue it in place.now make 26 more! don't forget to label the negative wire

Image Notes1. this is the anode side2. the shorter leg is the cathode or the negative side

Image Notes1. test your leds

Page 171: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 172: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 173: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 4: Constructing the Cubenow its time to construct the mood light .First cut 9 strings five feet in length then with a ruler draw a squarer that is 16 in by 16 in mark at the 0,8,and16 inches . then draw a line from the 8 in mark to the other 8 in mark . do this for both sides and you should end up with a cross . now tape or hot gluethe 5 feet long strings on the 0,8,16 in marks including the center . now you can begin the first layer .Tie the first layer of nine lanterns then measure 5in and cut the fishing wire then pass the fishing wire through the tiny hole underneath the next lantern and tie a knot to keep the lantern beneath from falling do this for all of the next layer now for the last layer do the sameand tie the rows of 3 lanterns to the remaining wire hanging from the ceiling .

Page 174: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 5: Time for the wiringFor the wiring cut 27 five inch long stranded wires to connect all of the cathodes or negative side of an led together in one layerthen cut  16 six inch long wires to connect all the positives in the nine columns of three.

Page 175: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 6: Building the Circuitthe Circuit is very basic. Each of the nine columns will connect to a pin on the Arduino through a current limiting resistor (220 OHMS).Each of the three levels connects to ground via a NPN transistor when activated by an Arduino pin . following the schematic solder 9 resistors to the pcb leaving as muchroom as possible then solder the 3 NPN transistors and there corresponding resistors  to the pcb.

Image Notes1. the 3 NPN transistors2. the 9 (220 ohm) resistors

Page 176: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 7: Wiring the Arduinonow number the resistors 1,2,3,4,5,6,7,8,9, and the transistor Circuit L1,L2,L3 then number the lanterns(1,2,3,4,5,6,7,8,9) and with the cat 5 cable connect the resistors to its corresponding columns by number like resistor 1 to column 1.Connect resistor  No. 1 to pin 2 on the arduino. connect resistor 2 to pin 3 and so for  until you get to resistor 9 connected to pin 10.L1 connects to pin 11; L2 connects to pin 12 and L3 connects to pin 13.

Page 177: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 8: SoftwarePlease rate this instructable if you like it! :) here is the code that i used so that you can copy and paste it: #define DRAW_PWM_DELAY 10#define MAX_INTENSITY 8

* LED Driver 

byte columnPins[] = {2,3,4,6,7,8,11,12,13}; // connections of matrix columsbyte levelPins[] = {5,9,10}; // connections of matrix levels

// initializes the LED driver (sets pin modes and turns all LEDs off)void ledInit() {  for (byte i=0; i<9; i++) {    pinMode(columnPins[i], OUTPUT);digitalWrite(columnPins[i], LOW);}for (byte i=0; i<3; i++) {pinMode(levelPins[i], OUTPUT);digitalWrite(levelPins[i], HIGH);}}

// switch on single LEDs// causes other LEDs to light up if driver is not in initialized state// (you can not address all the 27 LEDs with just 12 pins at a time)void ledOn(byte column, byte level) {digitalWrite( columnPins[column], HIGH );

Page 178: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

digitalWrite( levelPins[level], LOW );}

// same like ledOnvoid ledOff(byte column, byte level) {digitalWrite( columnPins[column], LOW );digitalWrite( levelPins[level], HIGH );}

/********************************************************************************* Basic Drawing API (voxel buffer, cartesian coordinate system, etc.)********************************************************************************/

byte buffer[27]; // voxel buffer

// draws the voxel buffer (ignoring intensities)// any voxel >1 will turn on the corresponding LEDvoid draw(byte n) {int col,lvl;for (byte t=1; t<n; t++) {for (byte i=0; i<27; i++) {if (buffer[i]) {col = i/3;lvl = i%3;ledOn(col,lvl);delayMicroseconds(DRAW_PWM_DELAY);ledOff(col,lvl);} else {delayMicroseconds(DRAW_PWM_DELAY);}}}}

void draw() {draw(1);}

// draws the voxel buffer (takes intensities into account)// this functions uses a software PWM and is about 128 times slower// than the binary draw functionvoid drawPwm() {int col,lvl;for (byte t=1; t<=128; t++) {for (byte i=0; i<27; i++) {if (!(t % (1<<(8-buffer[i])))) {col = i/3;lvl = i%3;ledOn(col,lvl);delayMicroseconds(DRAW_PWM_DELAY);ledOff(col,lvl);} else {delayMicroseconds(DRAW_PWM_DELAY);}}}}

// clears voxel buffervoid clearBuffer() {for (byte i=0; i<27; i++) {buffer[i] = 0;}}

// fills voxel buffervoid fillBuffer(byte value) {for (byte i=0; i<27; i++) {buffer[i] = value;}}

// retrieves values from voxel buffer (using cartesian coordinates)byte getVoxel(char x, char y, char z) {byte i = 9*x - y + 3*z + 13;return buffer[i];}

// sets values from voxel buffer (using cartesian coordinates)void setVoxel(char x, char y, char z, byte value) {byte i = 9*x - y + 3*z + 13;if (i>=0 && i <= 27) {buffer[i] = value;}}

Page 179: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

// interpolates arbitrary points between voxelsvoid setPoint(float x, float y, float z, byte value) {char xint = x>0 ? 1 : -1;char yint = y>0 ? 1 : -1;char zint = z>0 ? 1 : -1;

interpolate(x,y,z,value,0,0,0);interpolate(x,y,z,value,0,yint,0);interpolate(x,y,z,value,0,0,zint);interpolate(x,y,z,value,0,yint,zint);interpolate(x,y,z,value,xint,0,0);interpolate(x,y,z,value,xint,yint,0);interpolate(x,y,z,value,xint,0,zint);interpolate(x,y,z,value,xint,yint,zint);}

void interpolate(float x, float y, float z, byte value, char xint, char yint, char zint) {float d = sqrt(pow(xint-x,2) + pow(yint-y,2) + pow(zint-z,2));byte i = 9*xint - yint + 3*zint + 13;if (i>=0 && i <= 27) {buffer[i] += (value * (1-d));}}

/********************************************************************************* Some Demos********************************************************************************/

// sets pin states manually (driver not used)void demoLowLevel() {ledInit();// nothing visible happens herefor (byte lvl=0; lvl<3; lvl++) {digitalWrite( levelPins[lvl], LOW );}// now we select entire columsfor (byte cycle=0; cycle<2; cycle++) {for (byte col=0; col<9; col++) {digitalWrite( columnPins[col], cycle % 2 == 0 ? HIGH : LOW );delay(100);}}

ledInit();// nothing visible happens herefor (byte col=0; col<9; col++) {digitalWrite( columnPins[col], HIGH );}// now we select entire levelsfor (byte cycle=0; cycle<2; cycle++) {for (byte lvl=0; lvl<3; lvl++) {digitalWrite( levelPins[lvl], cycle % 2 == 0 ? LOW : HIGH );delay(200);}}

ledInit();}

// some rotations (no driver used as well)void demoRotation() {// rotation sequencebyte seq[] = {0,1,2,5,8,7,6,3};

ledInit();// active all levelsfor (byte lvl=0; lvl<3; lvl++) {digitalWrite( levelPins[lvl], LOW );}// middle columndigitalWrite( columnPins[4], HIGH);

// now we select entire columsint cycles = 3*3*9;for (int cycle=0; cycle<cycles; cycle++) {digitalWrite( columnPins[seq[cycle%8]], HIGH);digitalWrite( columnPins[seq[(cycle-1)%8]], LOW);if (cycle >= 3*9) {digitalWrite( columnPins[seq[(cycle+4)%8]], HIGH);digitalWrite( columnPins[seq[(cycle+3)%8]], LOW);}if (cycle >= 2*3*9) {digitalWrite( columnPins[seq[(cycle+2)%8]], HIGH);digitalWrite( columnPins[seq[(cycle+1)%8]], LOW);

Page 180: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

digitalWrite( columnPins[seq[(cycle+6)%8]], HIGH);digitalWrite( columnPins[seq[(cycle+5)%8]], LOW);}delay(100);}

ledInit();}

// direct access to voxel buffer (cartesian coordinates not used)void demoFill() {clearBuffer();for (int cycle=0; cycle<2; cycle++) {for (int i=0; i<27; i++) {if (cycle % 2 == 0) {buffer[i] = 8;} else {buffer[i] = 0;}draw(50);}}}

// treats voxels as bins and fill them bit by bit randomlyvoid demoBinFill() {clearBuffer();for (int i=0; i<100; i++) {buffer[random(0,28)]+=2;drawPwm();}}

// neat random sparklevoid demoSparkle() {for (int density = 0; density<50; density++) {for (int cycle = 0; cycle < 3; cycle++) {clearBuffer();for (int i=0; i<density; i++) {buffer[random(0,28)] = random(0,9);}drawPwm();}}}

// makes all LEDs pulse synchronouslyvoid demoPulse() {for (int cycle=0; cycle<80; cycle++) {fillBuffer(-abs(cycle%16-8)+8);drawPwm();}}

// pulsing wavevoid demoPulseWave() {byte r;for (byte cycle=0; cycle<80; cycle++) {for (char x=-1; x<=1; x++) {for (char y=-1; y<=1; y++) {for (char z=-1; z<=1; z++) {r = (x*x + y*y + z*z);setVoxel(x, y, z, -abs((cycle-r)%16-8)+8);}}}drawPwm();}}

// demonstrates interpolationvoid demoGlowfly() {float dx,dy,dz;byte steps = 10;

float px = random(-100,101)/100.0;float py = random(-100,101)/100.0;float pz = random(-100,101)/100.0;

for(int cycle=0; cycle<8; cycle++) {dx = (random(-100,101)/100.0 - px) / steps;dy = (random(-100,101)/100.0 - py) / steps;dz = (random(-100,101)/100.0 - pz) / steps;

Page 181: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

for (int i=0; i<steps; i++) {px += dx;py += dy;pz += dz;

clearBuffer();setPoint(px, py, pz, MAX_INTENSITY);drawPwm();}}}    

Related Instructables

Carlitos'Project: RGBLED Mood Cubeby RobotShop

Ambient CubeLighting.(Photos) byLftndbt

Get the RBGLED Circuitfrom GlowingIce Cubes bybenthekahn

How To Capture- A Fallen Star.(Photos) byLftndbt

StackableAmbient RGBLED CubeLights by Lftndbt

Tilt activatedLED glow cubeby asporkable

Arduino moodlighting by sapc

How to build aLED moodlamp/ SolderSafety light byjoejoerowley

Page 182: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

LED wind indicatorby janw on June 18, 2011

Author:janwMy hobbies are mainly music and elecronics but I like to read and learn about everything in life.

Intro:  LED wind indicator

I have something with the weather. I always like to know how warm or cold it is, how much rain has fallen, how hard the wind blows and from what direction,... and sothere are lots of sensors around our house to keep me up to date. These sensors give only a limited range of data, so I still need the internet to inform me abouteverything I want to know.

I am lucky because one of the national weather data collecting points is located in the village where I live. And all its data is to be found on the internet, together with thedata of all other collecting points and predicions for the upcoming days in a very handy XML-file.

The only drawback is that you always need a computer to acces that data. So I decided to start buiding a device to display the data without a pc. This wind indicator is atestversion, displaying only the wind direction, its force and a prediction for the next day. It is connected to a pc via a USB to RS232 converter, but the future projectshould be able to work as a stand alone version.

Page 183: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Image Notes1. RS232 to USB2. Programmer

Image Notes1. I made a mistake in the pcb so I had to make a custom cable to ensure thateverything works. I corrected the schematic afterwards

Step 1: What do you need31 LED's10 x 150Ohm resistor1 x 1K5 resistor1 button2 screwterminals1 isp 10pins connectoran atmega8a 100nF capacitora USB to RS232 cable or something similar. ( I use the RX and TX pins of an xbee to USB connector)a programmerpython 2.6

I made this project with smd components, but it can be build with thru hole parts. I also used a lot of copper thru hole links. These are completely optional, you can usea soldered wire to connect the 2 layers. 

Step 2: The circuit

The circuit for this project is very simple.

28 leds are arranged in two matrixes.

One is a 4x4 matrix connected to Port B of the microcontroller. Those leds will point the direction on the compass card.One is a 3x4 matrix connected to Port C of the microcontroller. Those leds will display the force of the wind on the Beaufort scale.

The 3 remaining leds are used as indicators

Two leds on PortD.3 and PortD.4 indicate indicate whether it is actual data or a forcast. One led on PortD.7 flashes when new data is received.

Don´t forget the 150Ohm resistors for the leds,

The button is connected to Pind.2 (the INT0 pin) with a 1K5 pullup resistor on one side and ground on the other side.

The ISP connector is added to the miso, mosi and sck pins Port B and with the reset pin.

RX and TX (PortD.0 and PortD.1) are connected with a screwterminal. This will enable us to add our RX an TX lines from the USB to RS232 cable.

Add a screwterminal for power and don't forget a 100nF capacitor between the lines. 

Testing the uart and the leds:

Page 184: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Page 185: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 3: Programming the microcontrollerI've added the bascom code here. It is still a bit quick and dirty but it gives a good idea on how the device is programmed. I also added a hexfile for those who just want totry it.

The program itself works very simple:

It waits until it receives 4 pairs of bytes. The first byte tells the program what kind of data the second byte holds. Two pairs contain the present data and two pairs containthe forecast.

When the microcontroller has received the 4 pairs it will process the first 2 pairs and display the current data. If the button is pressed an interrupt occurs and themicrocontroller will display the second set of data (aka the forcast) for 5 seconds.

Don't forget to change the fusebits so that Portc.6 is an IO pin instead of reset, but do it after the microcontroller is programmed because afterwards it won't beprogrammable anymore.

File Downloads

windindicator.txt (3 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'windindicator.txt']

windindicator.bas (3 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'windindicator.bas']

Page 186: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

windindicator.hex (3 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'windindicator.hex']

Step 4: Getting the required data to the device.'And now for something completely different...' 

A bit of Python:

It is actually the first time that I write a bit of code in Python. And I must say that I love to learn more of it because it's really great to use.

I added the code written in python 2.6 here and I am open to all comments or suggestions about it because it's also new to me.

The basis for the data is an XML-file that contains the weather data for the Netherlands. Python looks the wanted data up in the file and sents it to com 4 every 5 minutes.

###############################################################################################import urllibimport serialimport timefrom xml.etree.ElementTree import ElementTreeStationId = "6319"speed = {"1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8","9":"9","10":"a","11":"b","12":"c"}direction = {"N":"1","NNO":"2","NO":"3","ONO":"4","O":"5","OZO":"6","ZO":"7","ZZO":"8","Z":"9","ZZW":"a","ZW":"b","WZW":"c","W":"d","WNW":"e","NW":"f","NNW":"g"}url = 'http://xml.buienradar.nl'ser = serial.Serial(3)while True:

print "nieuw"root = ElementTree(file= urllib.urlopen(url))iter = root.getiterator()for element in iter:

if element.tag == "weerstation":

p = element.items()

for name, value in p:

if value == StationId:

for child in element:

if child.tag == "windsnelheidBF":q = "1"q = q + speed[child.text]print qser.write(q)if child.tag == "windrichting":q = "2"q = q + direction[child.text]print qser.write(q)

if element.tag == "dag-plus1":

for child in element:

if child.tag == "windkracht":

q = "3"q = q + speed[child.text]print qser.write(q)

if child.tag == "windrichting":

q = "4"q = q + direction[child.text]print qser.write(q)

ser.closetime.sleep(30)              

###############################################################################################

Page 187: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

File Downloads

weer.py (2 KB)[NOTE: When saving, if you see .tmp as the file ext, rename it to 'weer.py']

Related Instructables

How to fix deadatmega andattiny avr chipsby manekinen

Getting startedwith LCD's andMicroprocessorsby Johnny C.

StrobeDuino -Computer-controlled RGBstrobe/lamp byab5000

Build aComplete AVRSystem andPlayMastermind! bynevdull

Telnet to yourArduino/AVR!by nevdull

Assembling theDragon Rider500 for use withthe AVR Dragonby barney_1

Atmega16/32DevelopmentBoard With LCDby iideetee

Sheevaplug +Python Daemon+ MySQL =RS232 LoggingMade Easy byjimk3038

Page 188: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Simple LED flowersby chiefchace on June 18, 2011

Intro:  Simple LED flowers

Hello, and please enjoy my awesomely simple to make LED flowers. I came up with the idea for the flowers because of my little sisters graduation. She wantedsomething a little more than just a regular flower for her graduation gown. LED flowers are great for any occasion, birthdays, valentines day or any holiday. They aremagnetic so they can be attached to any metal fixture for a bright night light or fridge/hood ornament. (wrap a metal wire with green tape and attach as a stem for abouquet of LED flowers). They can be fixed on purses, backpacks, hats, or shirts with multiple magnets to make for a strong broach. Please look up "LED throwies" tohelp you get an idea of how it works and check out my "LED SPORELINGS" for more creative versions.

Tools needed:-Glue gun + sticks-Scissors

Materials needed:-Florescent spray paint-neon and clear rexlace (plastic lacing)-Packaging peanuts-10mm blue LED (preferably a non-diffused super bright)-3v lithium battery-Button Magnet-Chopsticks-Electrical tape

Page 189: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 1: Prep packaging peanutFirst begin by placing packaging peanut on chopstick and lightly build multiple coats of different florescent colors. i like to spray a base color and then using a differentcolor. barley push down the nozzle to create a splatter effect that gives nice contrast.  

Step 2: Hollow out peanutSecond, hollow out the inside of the packaging peanut (using chop sticks) to prepare for inserting the led.

Step 3: Insert LEDGently hold the top and make sure not to crush its form. Slowly insert LED into peanut, twisting back and forth till it is in the peanut the same length as the second photo.Hot glue the led after it is secure inside the peanut from the bottom to ensure it does not come out.

Page 190: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 4: Poke holes for laceUsing your scissors, poke holes through the top of the peanut to make it easier to weave the lace through. (be careful not to rip unwanted holes, the hot glue will sapthrough)

Step 5: Cut desired lace "petals"

Use the lace to cut as many "petals" and "pistils" you want. I usually use 2-4 laces for petals and 3 pistils both different colors. Glow in the dark lace works great too.

Step 6: Weave Lace in placeNow weave the lace through the holes you previously made and stop till they are even on both sides. Bend back the lace to meet into its original hole creating a "petal".

Page 191: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 7: Hot glue petals and pistilsHot glue (careful not to burn yourself, might be handy to have ice near by) the inside of the peanut down to the LED to form a strong "core". Then add your "pistils" andput a drop of hot glue at the end of them for a nice effect.

Page 192: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/

Step 8: Insert battery and magnetPlace completed led flower into battery and make sure it turns on. Wrap with electrical tape around once then attach magnet and wrap it around once again to securetightly. Give it to your favorite DJ as a broach after he watched you wear it all night or gift it to a family member, put it up in your car, around the house or you local city.keep being creative and it will never run out of battery life.

Related Instructables

Framed ColorChanging LEDArt Demo Video(video) byobeyken

LED BasedArtwork (Photos)by neltnerb

LED LightingProjects andIdeas (Photos)by usLEDsupply

LED TREE bypuffin_juice

LED CLOCKcum NIGHTLAMP byDipankar

DIY CopperStyle LEDPaintingIlluminator byArtificialIntelligence

LED PopsicleStick PictureFrame byrandofo

LED SteampunkRose bySelkeyMoonbeam

Page 193: Make it tweet

http://www.instructables.com/id/Make-it-Tweet/