Showing posts with label zigbee. Show all posts
Showing posts with label zigbee. Show all posts

Friday, August 7, 2009

Droplet

Several months ago I released XBeeArduinoService. Since then I have been working on the next version. It's now available and has a new name: Droplet.

What's New
  • Menu/Navigation: The first version relied on a dedicated button for each service. This worked but doesn't scale well since you will quickly run out of buttons. Now it uses a menu to display the available services. Along with the menu are four buttons for navigation: Next, Previous, Select, and Escape.


  • Pagination: Previously, each message was limited to 80 characters, which of course is not much. Now messages that exceed 80 characters are formatted into multiple pages. A multi-page message is indicated by an arrow "⇾" character in the bottom right corner. When this character is present, selecting the Next button loads the next page.

  • Push Services: these are services that run in the background and send messages (or droplets) to the remote. I have written push services for Twitter, Gmail and Google Calendar. Note: these are different from pull services, which are user initiated and are listed on the menu.
  • History: You can now access previous messages that were sent to the LCD. This is helpful if you clicked the Next button too quickly, or you want to see any messages that were sent while you were away (e.g. missed tweets, calendar events). Selecting the Previous button while any message is displayed will load the previous message.
  • New Services: Twitter, Twitter Search, Google Calendar, IMAP "Push" Email (e.g Gmail) and Top News.
  • Light and Sound: A red LED flashes when a Push Service sends a message (tweets/calendar/email) and optionally a buzzer can sound. The Google Calendar service sounds the buzzer if "#buzzer#" appears in a Google Calendar event description. It effectively becomes a Google alarm clock when using the buzzer option with Google Calendar.
  • Multiple Remotes: This version includes better support for multiple remotes. You can use the XBee broadcast address (0x00000000ffff) to send messages to all remotes or target one or more specific remotes.
A Demo

Parts

For this version I added the following parts:
Circuit

In an attempt to not repeat myself, in this entry I'm only going to cover what's new, so you'll want to familiarize yourself with the previous version.

Now to wire up the new parts. Connect the buzzer to the Arduino Analog 0 and the negative terminal to GND. Yeah, that's right, Arduino lets you repurpose the Analog pins as Digital outputs. Analog 0-5 can accessed as Digital pins 14-19. Pretty neat, huh? Here's some more info.

Wire the LED to the Arduino Digital 5 pin and GND, placing your resistor in series.

Wire each push button to GND and the following Arduino Pin:

Next: Digital 2
Previous: Analog 1 (We are also repurposing this pin to be Digital, same as the buzzer pin)
Select: Digital 3
Escape: Digital 4

In case you're wondering whether it's safe or even a good practice to connect a button without a pull-up/down resistor, keep reading. In the previous version I was using a pull up resistor to drive the pin to a known state while the button was in its normally-open position. It turns out there's an easier way to do this by using the Arduino's internal pull up resistors. The pull-up resistors are enabled by setting the pin mode to INPUT, then turning them on with a digital write HIGH. In this configuration, the pin will read HIGH until the button is depressed, when it will read LOW, and we don't need to mess with any resistors! Thanks to todbot for this technique.

XBee Configuration

The XBee configuration is identical to the previous version.

Software

Download the project software from Google Code. This download includes everything you need to get it up and running except for Java (requires Java 5) and Eclipse. Eclipse is recommended but isn't required and if you are experienced with Java you can use your IDE of choice or run from the command-line. Being Java, this software will run on a variety of platforms (Windows, Mac, Linux etc.). The only limiting factor is the RXTX serial library and I've included binaries for Windows, Mac and Linux (Arduino uses RXTX also).

As before, you need to install two Arduino libraries. XBee-Arduino for XBee communication and LCD4x20 to display text on the LCD. Unzip the downloaded file and you will find these files in the "Arduino" folder of the project:

LCD4x20-781.zip
xbee-arduino-0.1.2.zip

Unzip each file and install in your ARDUINO_HOME/hardware/libraries folder
(where ARDUINO_HOME is the location of Arduino on your system. On my machine it's /Users/andrew/Documents/devsoft/arduino-0016/hardware/libraries)

After installation, you should have XBee and LCD4x20 folders under ARDUINO_HOME/hardware/libraries. Note: the LCD library was updated since the previous version, so if you have the previous version, delete the LCD4x20.o file, to force Arduino to recompile the library.

Now upload the Sketch to the Arduino. The sketch (DropletRemote.pde) is located in "Droplet/Arduino/DropletRemote". But before uploading we need to make one minor change. Find the following line:

XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x403e0f30);

and replace the 64-bit address with the (SH + SL) of your XBee coordinator. See the previous blog entry for info on how to get your SH + SL address. Remember to put the XBee Shield jumpers in the "USB" position to upload the Sketch and return the jumpers to the "XBee" position after a successful upload.

Now for the Service Gateway. As before, create an Eclipse project and point it to the Droplet folder. Refer to the previous version if necessary. There are just a few things to change in the Java file. Open DropletDemo.java in Eclipse. This file is located in "/src/com/rapplogic/droplet/impl/" In this file you'll need to specify the address of the remote XBee for the variable "remoteXBee". Also specify the COM port and baud rate of the XBee coordinator.

Since we are using Google and Twitter, you'll need to specify the login information to access your accounts if you want these services. Open google.credentials and specify your Google/Gmail username and password. Now open twitter.credentials and specify your Twitter username and password.

The demo starts up all available services, but possibly you are not interested in running them all. If this is the case, comment out the services you do not want with the Java comment syntax "//" at the beginning of the line. Note: the weather services requires a zip code, so if you are using these services search for "20175" and replace with your zip code. Save the file.

Ok now we're ready to run it. Power up the Arduino, connect the XBee coordinator to the computer and start the application by selecting "Run" from the "Run" menu. Choose one of the services on the LCD menu and click the Select button and you should see the resulting message on the LCD. Woohoo!

Creating Custom Services

The service API has changed significantly since the last version, making it easier to write your own Droplet services. First you need to decide whether you want to create a Pull Service or Push Service. A Pull Service is listed on the menu and is only activated by a button press on the remote. A Push Service runs in the Java application on a periodic basic and sends messages to the remote.

Pull Services

Adding a Pull Service requires an implementation of the PullService interface. This can be accomplished by creating a class that implements the interface, or for simple services, using an anonymous inner class, as in this example. The PullService interface requires that you implement the execute method:

public IContent execute(Integer serviceId, XBeeResponse response, ServiceContext serviceContext) throws Exception

This method provides the following arguments:
  • serviceId: this is the menu position of the service, starting at 0. If you have a single service that supports multiple menu items, you'll need to refer to this variable.
  • response: the XBeeResponse received from the Arduino. This is useful if you need to know the remote that sent the request or any of details of the transmission, such as RF strength.
  • serviceContext: this object exposes several methods of the Droplet API, the most important method for Pull Services being the format method. This method is acessed by serviceContext.getFormatter().format(String); it takes an arbitrary String, of any length, and formats it for display on a LCD. This method will handle pagination if the String doesn't fit on the LCD. This method also optimizes the String for display on the LCD, according to the PaginationRules class. (see Javadoc for details of all Droplet classes/interfaces).
Within this method you can do whatever you need (send an email, turn on your sprinklers etc.), but the service method must return in a timely manner, specifically 6 seconds, although this is configurable. This method returns an instance of IContent, which really a fancy container of the text to be displayed on the LCD. You can return null but the framework will still send a default message to the remote. Here's an example:
PullService time = new PullService() {
public IContent execute(Integer serviceId, XBeeResponse response, ServiceContext serviceContext) throws Exception {

return serviceContext.getFormatter().format("The current time is " + new Date() + ". You will see this response on your LCD after the service executes. You can even use linefeed characters \n to format the response");
}
};
The last activity is to register your service with the Droplet framework. The first argument of the register method is the position of the item in the menu. The position starts at 0, so the second item in the menu is 1.
droplet.registerPullService(1, time);
Now you will need to add your new service as the second menu item in the Arduino Sketch. After the Sketch has been uploaded you should be able to select the second menu item on the remote and it will activate your service. Note: if you change the number of items in the menu, make sure to update the menuSize variable to the new number.

Push Services

There are three types of Push Services: Realtime, Delayed and Runnable. A Realtime service returns a message to be delivered immediately to the remote. A Delayed service returns a message to be delivered to the remote at some point in the future. And finally, a Runnable service occupies a dedicated thread and runs all the time. The Realtime and Delayed services are further divided into two subtypes: Recurring and OneTime, where Recurring services are invoked periodically, and OneTime services are invoked only once.

To create a Realtime service, you will need to extend the RealTimeAlertPushService and implement either the RecurringService or OneTimeService interface. To simplify things, there is a SimpleRealtimeRecurringPushService class that extends RealTimeAlertPushService and implements RecurringService, along with some default values.

Unlike Pull Services, Push Services need to know the 64-bit address of the remote XBee that should receive the message. Optionally you could specify a broadcast address to send to all remotes. Here's an example of a Push Service that sends a wake up alert every weekday at 6 AM. The service returns an instance of the Alert class. An Alert contains properties for determining whether or not the LED should flash or the buzzer should sound. While Pull Services always return a message to the LCD for display, Push Services may return null, in which case nothing is sent.
XBeeAddress64 remoteXBee = new XBeeAddress64(0x00,0x13,0xa2,0x00,0x40,0x0a,0x3e,0x02);

SimpleRealtimeRecurringPushService wakeUp = new SimpleRealtimeRecurringPushService(remoteXBee) {

@Override
public Alert execute(ServiceContext serviceContext) throws Exception {
Calendar cal = Calendar.getInstance();

int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) {
// it's the weekend. you can sleep in
return null;
}

int minute = cal.get(Calendar.MINUTE);
int hour = cal.get(Calendar.HOUR_OF_DAY);

if (hour == 6 && minute == 0) {
// wake up!
Alert alert = new Alert();
alert.setContent(serviceContext.getFormatter().format("It's Wake Up Time !!!!!!"));
alert.setRemoteXBeeAddress(this.getRemoteXBeeAddress());
// flash the LED
alert.setFlashLed(true);
// sound the alarm!
alert.setSoundAlarm(true);

return alert;
}

// not time yet
return null;
}
};

// run once a minute (delay is in milliseconds, so multiple by 1000)
wakeUp.setDelay(60000);
wakeUp.setName("WakeUp");

// register the service with the framework
droplet.registerPushService(wakeUp);
For more examples, look in the com.rapplogic.droplet.impl.services.* packages for the source code to all services.

What's Next?
  • Plug Computer. I recently received a SheevaPlug. SheevaPlug is a low power ARM computer, about the size of a wall adapter, that runs Linux. My goal is to run the Droplet Java application on the SheevaPlug.
  • Extra Pins. After everything is wired-up, we still have 6 Arduino pins left: 4 Analog or Digital (Analog 2-5, Digital 16-19) and 2 Digital (12, 13), so you could wire up some dedicated "Radio" buttons, sensors, or even add a second LCD.
  • Case. Ok, this thing is a bit ungainly. At some point I'll start working on a case to hide the internals.
  • Larger Display. I've been on the lookout for a low cost alternative to the 4x20 LCD, with support for displaying more than 80 characters.

Comments are great but if you have questions please send email instead since I may not see the comments for a few days or a possibly longer. My email can be found from the "view my complete profile" link in the right column.

Friday, May 8, 2009

Arduino+XBee+LCD Info Device

This is an Arduino based wireless device that can display arbitrary content (weather, news etc) at the touch of a button, via an XBee radio. Currently it supports weather by zip code and displays on a 4x20 LCD, but it's designed to easily expand to additional services. Some ideas for other services include: calendar events, traffic, next bus/train, tweets, news, mail, adjust thermostat, next track (itunes), turn on/off/dim light etc. This is mostly useful for quick information when you are not close enough to a computer (nightstand, living room, kitchen etc.) I chose weather as the initial service since it's relatively useful and part laziness since my wife asks me for the forecast every morning so she can plan her outfit.

How it Works

The system consists of a Service Gateway and one or more remote Arduinos. The remote Arduino consists of an XBee radio, LCD, and one or more buttons that are hardwired to a particular service (e.g. weather, news). When the button is pressed, it uses the XBee-Arduino library to send an XBee packet to the Service Gateway and displays the subsequent response on the LCD.


The Service Gateway is an XBee-API application that connects to an XBee Coordinator. The Service Gateway receives the request from the remote XBee and sends back a packet containing character data for display on the LCD. The Service Gateway doesn't need to know anything about the remote Arduino; as long as they have the same Channel and PAN ID, they can communicate.


Parts List
* One thing to keep in mind about eBay orders from China is they can take 3 weeks or longer for delivery.
** You can substitute an Arduino for a lower cost variant such as Adafruit's Boardino and corresponding XBee Adapter Kit
*** It's possible to substitute with Series 1 (802.15.4) XBees but this will require some code modifications.

Installation and Setup

The first order of business is to configure the XBees. You should have two series 2 XBee radios, one configured with coordinator firmware and the other with end device firmware. I'm recommend using ZB Pro firmware. ZNet should also work but has a limit of 72 bytes per packet so you won't be able to use the entire 80 characters of the display.

Place your XBee coordinator in the USB Explorer and use X-CTU to apply the following configuration:

Click the "Restore" button to clear out any previous configurations

Set PAN ID to an arbitrary value. The end device must also use this exact value

ID=1AAA

Set the node identifier to an arbitrary string. This serves as a convenient way to identify your devices
NI=COORDINATOR

Set API mode to 2 (escape control bytes)
AP=2

Click the "Write" button to save the configuration

Be sure to take note of the Serial High (SH) and Serial Low (SL) values as you will need this later

Now place your XBee end device in the USB Explorer and configure. If you are using ZB Pro firmware, this firmware does not support a disabled sleep option, so you need to perform a trick to keep the end device awake. See this blog entry for details. The end device configuration is identical to the coordinator except for the node identifier:

Click the "Restore" button

Set PAN ID to the same value as the coordinator

ID=1AAA

Set the node identifier to an arbitrary string.
NI=ARDUINOXBEE

Set API mode to 2 (escape control bytes)
AP=2

Click the "Write" button to save the configuration

Wire It Up

Now we're going to wire up the Arduino. Attach your Arduino XBee Shield to your Arduino and place your end device XBee in the shield.

Connect your LCD to a breadboard and wire to Arduino. I wired it up as follows but you can use any digital pins (except 13). This only requires 6 Arduino pins in 4-bit mode, woot! Here's the Winstar WH2004 LCD schematic for reference:

Pin 1 (VSS) - 5V
Pin 2 (Vdd) - GND
Pin 3 (Contrast) - GND
Pin 4 (RS) - Arduino Digital 6
Pin 5 (Read/Write) - GND
Pin 6 (Enable) - Arduino Digital 7
Pin 7 (Data Bus 0) - Arduino Digital 8
Pin 8 (Data Bus 1) - Arduino Digital 9
Pin 9 (Data Bus 2) - Arduino Digital 10
Pin 10 (Data Bus 3) - Arduino Digital 11
Pin 15 (Backlight Power)- 4.2V*
Pin 16 (Backlight Ground) - GND

All pins not listed should be left unconnected

* Now you might be wondering what to do about 4.2V when Arduino is 5V, I was. I found a nifty solution on the Arduino forum that involves a couple 1N4004 diodes to drop voltage close to 4.2. Each 1N4004 has a drop of around 0.7V. I probably could have used one but I ended up using two so I wouldn't go over the 4.2V. With two diodes I'm measuring 3.5V but this seems to work just fine. An LED should also work in place of a 1N4004.

Now connect a pushbutton input so that it provides 0V when depressed and of course 5V when open. Here's a great tutorial on Arduino and buttons.

Ok, so now we have everything wired up and it's time to load the software.

Software

We are using two Arduino libraries: XBee-Arduino and LCD4x20. The XBee-Arduino library provides XBee packet communication, allowing us to send requests for data and display responses on the LCD. The LCD4x20 Arduino Library is based on LCD4Bit but contains modifications to work specifically for a 4x20 HD44780 LCD. The problem with this particular LCD is that line 1 wraps to line 3, line 3 to line 2 and line 2 to line 4; this library corrects this problem and adds some additional features. Because this LCD doesn't shift character data properly, the library maintains a 80 byte buffer in order to perform shifts (e.g. line feed) by rewriting the character data to the display.

Download XBee-Arduino xbee-arduino-0.1.2.zip

Unzip and install in
ARDUINO_HOME/hardware/libraries

Download the LCD4x20 library and similarly install in

ARDUINO_HOME/hardware/libraries

Download the Service Gateway and Arduino Sketch for this project and unzip.

We're going to need to make a few changes to the Arduino Sketch. Open the Arduino sketch (in XBeeArduinoService/Arduino/XBeeArduinoLcd) and find the lines, starting with "rsPin" and specify the Arduino digital pin for each corresponding LCD pin. You don't need to change anything if you wired it according to my suggestions.
Now replace the 64-bit address on the following line with the (SH + SL) of your XBee coordinator. You copied it down, right?
XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x403e0f30);

Save the Sketch.

Upload the Sketch

While the Arduino is unpowered, set the USB/XBee jumpers on the Arduino XBee Shield to the USB position (this directs the Arduino's serial port to USB so we can upload). Connect the Arduino to your computer and upload the Sketch. Note: you may see a few warnings in red font -- this is ok. If successful, your LCD will be displaying a message: "XBeeArduinoLcd v1.0...".

Unplug the Arduino and return jumpers in the XBee position. Now you can power your Arduino externally and place anywhere within XBee range of your computer!

Now for the Service Gateway setup

Service Gateway

Download "Eclipse IDE for Java" for your platform from Eclipse and install (this usually involves only unzipping it).

Start Eclipse and select Import from the File menu. Expand the General folder and select "Existing Projects into Workspace".
Select File->New->Java Project
Give the project a name, maybe "XBeeArduinoService"
Check the "create project from existing source" radio button
Browse to the location where you unzipped the project and select the "XBeeArduinoService" folder
Hit "Finish"

It should automatically find the libraries and be ready to go.

In the left window, expand the project, the "src" folder and the "com.rapplogic.xbeearduinoservice" package. Now open XBeeArduinoWeatherService.java. We will need to update a few variables. At the top of the file, find the comPort variable and replace with the COM port of the USB Explorer. For Windows users, you can find the COM port by going to Start->(right-click)My Computer->Manage, then Select Device Manager and Ports. It should appear as USB Serial Port. For Mac users it will appear under /dev/tty.usbserial*, so an ls -l dev/tty.usbserial (tab tab) before and after the device is plugged in should tell you the com port.

The last change is to enter the zip code for your local weather:
Weather weather = getWeather("97007", true);
Save it. (Eclipse compiles it automatically)

Place your XBee coordinator in the USB Explorer and connect to your computer.

Now we need to create a Run Configuration:

Select "Run Configurations..." from the "Run" menu

Select "Java Application"

Press the "new" button icon

It should automatically find "com.rapplogic.xbeearduinoservice.XBeeArduinoWeatherService"

Click Run. Now that the service is running, press the Arduino button and get your weather!

Top stop the service, press the red square button. Now to start it again you only need to select "Run" from the "Run" menu.

Creating your own Services

To add another service you will need to wire a second push button to an available digital input on the Arduino. Then define the service with a unique number at the top of the Sketch, for example:

define ITUNES_NEXT_TRACK 2

Create a variable that holds the button's digital input:

int itunesButton = 3;

At the bottom of the file add a if statement to detect if the button was pressed:

if (digitalRead(itunesButton) == LOW) {
requestService(ITUNES_NEXT_TRACK);
}

For the Service Gateway, you'll need to write the code that implements the service and returns a String to be displayed on the LCD. Open the XBeeArduinoWeatherService.java (or create your own class) and add a call to your service method in processRequest method, like so:
protected String processRequest(int requestType) throws Exception {
switch (requestType) {
case 1:
// weather
Weather weather = getWeather("97007", true);
return weather.toString();
case 2: // matches the service id (ITUNES_NEXT_TRACK) in the Sketch
// itunes next track
return this.changeItunesTrackAndReturnSongInfo();
}
}
where you have defined a method
String changeItunesTrackAndReturnSongInfo() {
// changes the itunes track and returns the current song for display
...
}

The service will truncate the response to 80 characters since that is the size of the display.

The processRequest method must respond within getServiceTimeoutMillis() milliseconds (defaults to 6000 or 6 seconds) or it will timeout and send the "Application Timeout" message to LCD. You can change this timeout by calling setServiceTimeoutMillis method. However, if you change this timeout, you should also change the Arduino timeout (APPLICATION_TIMEOUT) to the same value, plus a buffer of 1 or 2 seconds. The buffer is necessary to account for the round trip packet transmission time. Packets are usually delivered in under 100ms but packet size, distance, interference, and all sorts of factors can result in delays.

Adding another remote Arduino is easy and requires no modifications to the Service Gateway. Just configure the remote Arduino with the same PAN ID (ID) and it will automatically join the network. You can add up to eight with a single coordinator and to scale beyond that you would just need to introduce a router.

What's Next?

Here are some ideas for phase 2:

- "Continue" feature to handle messages larger than 80 characters (LCD screen size)
- LCD menu system for accessing more services than we have available digital inputs
- Low power remote. Without the LCD backlight, and by putting the XBee in sleep mode, the remote Arduno could be powered by batteries, making it much more mobile
- Alert framework. Alerts are initiated by the Java service and displayed on the LCD. An example might be a twitter tweet or meeting reminder. Alerts would initiate a LED blinking routine to capture ones attention.
- Low power device such as the BeagleBoard to replace a PC as the service gateway. I don't like the idea of leaving a computer on all the time as it wastes electricity. Right now I'm using an old notebook that doesn't use much power.
- A nice looking enclosure