Monday, September 6, 2010

Arduino Map






Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

Determine Postition Of Sun With Arduino

//Provides sun position (relative) from static variables

#include <math.h>
#define pi    3.14159265358979323846
#define twopi (2*pi)
#define rad   (pi/180)
#define EarthMeanRadius     6371.01 // In km
#define AstronomicalUnit    149597890 // In km

//Input Variables --------------------- TIME HAS TO BE IN UT (UNIVERSAL TIME)! NO TIME ZONES OR SUMMER TIMES --------
//My last modifications were probably at this time on this date!
int Year = 2010; //year
int Month = 7; //month
int Day = 3; //day
float Hours = 16; //hour
float Minutes = 38; //minutes

float Longitude = 1.4756; //enter longitude here
float Latitude = 1.5763; //enter latitude here
//--------

//Program Variables
float ZenithAngle;
float Azimuth;
        float RightAscension;
float Declination;
        float Parallax;
        float ElevationAngle;

float ElapsedJulianDays;
float DecimalHours;
float EclipticLongitude;
float EclipticObliquity;
//--------

void setup() {
 Serial.begin(9600);
}

void sunPos(){


// Auxiliary variables
float dY;
float dX;

// Calculate difference in days between the current Julian Day
// and JD 2451545.0, which is noon 1 January 2000 Universal Time

float JulianDate;
long int liAux1;
long int liAux2;
// Calculate time of the day in UT decimal hours
DecimalHours = Hours + (Minutes / 60.0);
// Calculate current Julian Day
liAux1 =(Month-14)/12;
liAux2=(1461*(Year + 4800 + liAux1))/4 + (367*(Month
- 2-12*liAux1))/12- (3*((Year + 4900
+ liAux1)/100))/4+Day-32075;
JulianDate=(float)(liAux2)-0.5+DecimalHours/24.0;
// Calculate difference between current Julian Day and JD 2451545.0
ElapsedJulianDays = JulianDate-2451545.0;

// Calculate ecliptic coordinates (ecliptic longitude and obliquity of the
// ecliptic in radians but without limiting the angle to be less than 2*Pi
// (i.e., the result may be greater than 2*Pi)

float MeanLongitude;
float MeanAnomaly;
float Omega;
Omega=2.1429-0.0010394594*ElapsedJulianDays;
MeanLongitude = 4.8950630+ 0.017202791698*ElapsedJulianDays; // Radians
MeanAnomaly = 6.2400600+ 0.0172019699*ElapsedJulianDays;
EclipticLongitude = MeanLongitude + 0.03341607*sin( MeanAnomaly )
+ 0.00034894*sin( 2*MeanAnomaly )-0.0001134
-0.0000203*sin(Omega);
EclipticObliquity = 0.4090928 - 6.2140e-9*ElapsedJulianDays
+0.0000396*cos(Omega);

// Calculate celestial coordinates ( right ascension and declination ) in radians
// but without limiting the angle to be less than 2*Pi (i.e., the result may be
// greater than 2*Pi)

float Sin_EclipticLongitude;
Sin_EclipticLongitude= sin( EclipticLongitude );
dY = cos( EclipticObliquity ) * Sin_EclipticLongitude;
dX = cos( EclipticLongitude );
RightAscension = atan2( dY,dX );
if( RightAscension < 0.0 ) RightAscension = RightAscension + twopi;
Declination = asin( sin( EclipticObliquity )*Sin_EclipticLongitude );

// Calculate local coordinates ( azimuth and zenith angle ) in degrees

float GreenwichMeanSiderealTime;
float LocalMeanSiderealTime;
float LatitudeInRadians;
float HourAngle;
float Cos_Latitude;
float Sin_Latitude;
float Cos_HourAngle;
GreenwichMeanSiderealTime = 6.6974243242 +
0.0657098283*ElapsedJulianDays
+ DecimalHours;
LocalMeanSiderealTime = (GreenwichMeanSiderealTime*15
+ Longitude)*rad;
HourAngle = LocalMeanSiderealTime - RightAscension;
LatitudeInRadians = Latitude*rad;
Cos_Latitude = cos( LatitudeInRadians );
Sin_Latitude = sin( LatitudeInRadians );
Cos_HourAngle= cos( HourAngle );
ZenithAngle = (acos( Cos_Latitude*Cos_HourAngle
*cos(Declination) + sin( Declination )*Sin_Latitude));
dY = -sin( HourAngle );
dX = tan( Declination )*Cos_Latitude - Sin_Latitude*Cos_HourAngle;
Azimuth = atan2( dY, dX );
if ( Azimuth < 0.0 )
       Azimuth = Azimuth + twopi;
Azimuth = Azimuth/rad;
// Parallax Correction
Parallax=(EarthMeanRadius/AstronomicalUnit)
*sin(ZenithAngle);
ZenithAngle=(ZenithAngle //Zenith angle is from the top of the visible sky (thanks breaksbassbleeps)
+ Parallax)/rad;
                ElevationAngle = (90-ZenithAngle); //Retrieve useful elevation angle from Zenith angle
}

void loop(){
  sunPos(); //Run sun position calculations
  Serial.print("Elevation Angle:  ");
  Serial.println(ElevationAngle, 0); //Print Elevation (Vertical) with no decimal places as accuracy is not really great enough
  Serial.print("Azimuth:  ");
  Serial.println(Azimuth, 0); //Print Azimuth (Horizontal) with no decimal places
  if(ElevationAngle < 0)
  Serial.println("The sun has set. Get some sleep!");
  delay(10000); //Delay 10 seconds - Values aren't going to have changed anyway as they are currently static variables!
}

Funnel IO - Wireless Freedom...



I had ordered one Funnel IO around 10 days back. Eagerly waiting for it to come. A specifically designed to exploit the wireless abilities of the Arduino board.
Having a unique characteristic of being programmed wireless, this board packs loads of features like programmability with FTDI cable.
On-board pin configuration holes for XBee chip for fast interfacing.
Can’t wait to get my hands on one. Will keep you posted on any new developments.

Arduino Taskbar Icon FIx

Ever wondered why the Arduino IDE generates a Java application like icon on your taskbar? well, because its a Java application..!! Now aI have got something interesting for you.
You can really change the way that icon looks and turn it into the original more perky Arduino icon. I have tested it on my Windows 7 and works fine. A 10 second job… :)
All you need to do is to download this and copy the extracted files to your arduino/java/bin folder.
This is how it will look like:

Robotics and Physical Computing Workshop

robotics and physical- computing workshop
topics include programming of microcontroller, designing of robots, interfacing various sensors and interfacing with other platforms
platforms and software interfacing include:
 arduino
 matlab
 processing
 flash
 autoit
 wireless sensor networks (over 433 MHz and 2.4 GHz unlicensed bands)
exclusive introduction to microsoft robotics studio
all course material will be freely provided to participants
fees: 200 INR per participant
timings: saturdays: 1pm to 5pm & sundays: 9am to 1pm
duration: 1 month
contact info: hardik pandya (9824340535)
adesh shah (9558528374)
registrations from 6th sep and batches start from 18th sep
(limited vacancy – register soon)
VASCSC will award certificates to all participants on completion

AutoIt - Just Overpowers You...

Well, I have come to know about a great script generator on Windows platform. Used mostly to generate externally excited events, we have interfaced Nanchuck and come up with something like a Nunchuck mouse application. We have been successful in moving the cursor… Clicking algorithm coming in a day or two. But it could not have been possible without the AutoIt.
Guys, do have a look at the AutoIt tool at www.autoitscript.com to know its awesome functionality. Well, in the general introduction and examples section, the Mouse Cursor Randomizer itself is a great little tweak you can use to frighten the hell out of your friends. It virtually inhibits the user from controlling the mouse and moves cursor randomly on the screen. You must have a look at that.
I would share the mouse.au3 script here. Paste it in your editor and see the execution.
Func exitthescript()
Exit
EndFunc
HotKeySet(“{F3}”, “exitthescript”)
While 1
$posx = Random( 1, 1000 )
$posy = Random( 1, 1000 )
MouseMove( $posx, $posy )
Sleep( 100000000000000000000000 )
WEnd
Func exitthescript() Exit EndFunc HotKeySet(“{F3}”, “exitthescript”)
While 1
$posx = Random( 1, 1000 )
$posy = Random( 1, 1000 )
MouseMove( $posx, $posy )
Sleep( 100000000000000000000000 )
WEnd

Wii Nunchuck and Arduino


For past ten days, I was desperate to get that neat little Accelerometer that came in the 250/- Rs Nunchuck to work with my Duemilanove. Finally I got it running and I am documenting it here.
How To Connect:
The Real Photograph:
The Nunchuck uses the I2C communication bus for the output signals. The color codes I had to use for the nunchuck I used were:
Red – Power (+3.3 V strictly)
White – Ground
Green – Analog In 4
Black – Analog In 5
Here, the Green and Black wires are coming as SDA and SCK signals as a TWI communication.
Here’s my code:
#include <Wire.h>
#include <string.h>

#undef int
#include <stdio.h>

uint8_t outbuf[6];  // array to store arduino output
int cnt = 0;
int ledPin = 13;

void
setup ()
{
  beginSerial (19200);
  Serial.print ("Finished setup\n");
  Wire.begin ();  // join i2c bus with address 0x52
  nunchuck_init (); // send the initilization handshake
}

void
nunchuck_init ()
{
  Wire.beginTransmission (0x52); // transmit to device 0x52
  Wire.send (0x40);  // sends memory address
  Wire.send (0x00);  // sends sent a zero.
  Wire.endTransmission (); // stop transmitting
}

void
send_zero ()
{
  Wire.beginTransmission (0x52); // transmit to device 0x52
  Wire.send (0x00);  // sends one byte
  Wire.endTransmission (); // stop transmitting
}

void
loop ()
{
  Wire.requestFrom (0x52, 6); // request data from nunchuck
  while (Wire.available ())
    {
      outbuf[cnt] = nunchuk_decode_byte (Wire.receive ()); // receive byte as an integer
      digitalWrite (ledPin, HIGH); // sets the LED on
      cnt++;
    }

  // If we recieved the 6 bytes, then go print them
  if (cnt >= 5)
    {
      print ();
    }

  cnt = 0;
  send_zero (); // send the request for next bytes
  delay (100);
}

// Print the input data we have recieved
// accelerometer data is 10 bits long
// so we read 8 bits, then we have to add
// on the last 2 bits.  That is why I
// multiply them by 2 * 2
void
print ()
{
  int joy_x_axis = outbuf[0];
  int joy_y_axis = outbuf[1];
  int accel_x_axis = outbuf[2] * 2 * 2;
  int accel_y_axis = outbuf[3] * 2 * 2;
  int accel_z_axis = outbuf[4] * 2 * 2;

  int z_button = 0;
  int c_button = 0;

 // byte outbuf[5] contains bits for z and c buttons
 // it also contains the least significant bits for the accelerometer data
 // so we have to check each bit of byte outbuf[5]
  if ((outbuf[5] >> 0) & 1)
    {
      z_button = 1;
    }
  if ((outbuf[5] >> 1) & 1)
    {
      c_button = 1;
    }

  if ((outbuf[5] >> 2) & 1)
    {
      accel_x_axis += 2;
    }
  if ((outbuf[5] >> 3) & 1)
    {
      accel_x_axis += 1;
    }

  if ((outbuf[5] >> 4) & 1)
    {
      accel_y_axis += 2;
    }
  if ((outbuf[5] >> 5) & 1)
    {
      accel_y_axis += 1;
    }

  if ((outbuf[5] >> 6) & 1)
    {
      accel_z_axis += 2;
    }
  if ((outbuf[5] >> 7) & 1)
    {
      accel_z_axis += 1;
    }

  Serial.print (joy_x_axis, DEC);
  Serial.print ("\t");

  Serial.print (joy_y_axis, DEC);
  Serial.print ("\t");

  Serial.print (accel_x_axis, DEC);
  Serial.print ("\t");

  Serial.print (accel_y_axis, DEC);
  Serial.print ("\t");

  Serial.print (accel_z_axis, DEC);
  Serial.print ("\t");

  Serial.print (z_button, DEC);
  Serial.print ("\t");

  Serial.print (c_button, DEC);
  Serial.print ("\t");

  Serial.print ("\r\n");
}

// Encode data to format that most wiimote drivers except
// only needed if you use one of the regular wiimote drivers
char
nunchuk_decode_byte (char x)
{
  x = (x ^ 0x17) + 0x17;
  return x;
}

16*2 LCD Pin Outs

The following table shows the pin details of the LCD.
LCD Pin Number Symbol Function
1 Vss Display power ground
2 Vdd Display power +5V
3 Vo Contrast Adjust. Altered by adjusting the voltage to this pin, grounding it sets it to maximum contrast.
4 RS Register select
5 R/W
6 E Enable strobe
7 DB0 Data Bus 0
8 DB1 Data Bus 1
9 DB2 Data Bus 2
10 DB3 Data Bus 3
11 DB4 Data Bus 4
12 DB5 Data Bus 5
13 DB6 Data Bus 6
14 DB7 Data Bus 7
15 A
LED backlight power +5V
16 K LED backlight power ground

Why Arduino Matters...

In January 1975, Popular Electronics ran a cover story about a new computer for hobbyists. The Altair 8800 came as a kit and cost $439 (the equivalent of $1,778.58 in today’s dollars). It came with no on-board memory. You programmed it by entering Intel 8080 opcodes by hand via a series of switches on the front panel. Buying 4k of memory, the ability to read in programs from paper tape, and a teletype interface would increase the price 6 fold. You had to solder the thing together by hand. By comparison with the big university and corporate mainframes it was basically useless.
But Popular Electronics was the Make Magazine of its day and engineering schools had begun to require their graduates to learn some programming, so Forest Mims and Ed Roberts, the two guys in Albuquerque who’d put the Altair together, figured they could probably sell a few hundred in the first year to this emerging group of hackers avant la lettre.
They took 1,000 orders in the first month. Six months after the release they’d sold 5,000. By October of that year their company had 90 employees.
Why was the Altair such a runaway success? After all, by comparison to the cutting edge computers of its day, it was underpowered and extremely difficult to work with. The answer is ownership. The Altair offered bourgeoning hackers their first chance at a computer that would be fully and completely theirs. They could take it home, throw it up on their work bench, take it apart, put it back together and try to get it to do totally new unimagined things. They could program their Altairs to play Fool on the Hill through a transistor radio. They could build a board to let the Altair drive a color TV in Times Square. They could starta small company to sell programming languages for it. They could get together with their fellow Altair owners to share programs and cool hacks.
This last point can’t be emphasized enough. The Altair crystallized growing local groups of DIY computer enthusiasts like the Homebrew Computer Club in Silicon Valley. It gave them an outlet for their energies and an example of what could be done. It made them believe that their incredible fantasy of having their own computers might really come true.
And after that, there was no stopping them. This new generation of hackers dedicated itself with an almost religious zeal to spreading the idea of computer ownership across the world. They invented the personalcomputer — a whole industry dedicated to the notion that computers could make life better and work easier for everyone, not just huge institutions. The Homebrew Computer club alone included the founders of Apple, Ozborne (builders of the first portable), and a raft of other industry pioneers.
Today, the world of physical computing closely resembles the personal computer industry circa 1975. We’ve been around for a few years struggling around the edges with tools and products that were designed, priced, and packaged for serious industry, but we haven’t made any money and we haven’t moved the world. That’s about to change.
Recently, our Altair arrived. It’s called the Arduino. This is 2009 so instead of being built by two engineers in Albuquerque, it was built by an open source international cabal of programmers and professors.
A lot of people complain that it’s underpowered and overpriced (even though it only costs $8.64 in 1975 dollars). But you don’t need special hardware to program it. It lets you do all the basic tasks with just a line or two of perfectly comprehensible code. And there’s a thriving community of people busily using it to do all the useless, fun, creative things they’d always dreamed of if only they could get their hands on a computer that could sense and control the world around it. They’re using it to teach houseplants to call for help if they need watering. And they’re using it to play music on glasses of water.
If the Arduino is the Altair of physical computing then what will be its VisiCalc? What will be the killer application that makes the physical computer of the future a necessity for business. If the Arduino is the Altair, what will physical computing’s Mac look like? I don’t think anyone today knows the answers to these questions.
But the answers are coming. In the next few years, physical computing has as much of a shot at changing the world as technologies ever get. And this is the time to get involved. Unlike the web, personal computer, and green energy industries, physical computing is a space where two guys in a garage can come along and invent something that will touch billions of people around the world without anyone else’s permission. That’s because what’s needed in physical computing is not advanced research, massive infrastructure investment, or huge production facilities. What’s needed is close attention to applying the existing technology to solving human-scale problems. Microcontrollers and sensors, CNC milling machines and laser cutters, GPS devices and accelerometers need to be transformed into tools that regular people can use to improve their daily lives: to make themselves more connected to the people and places around them, to entertain, educate, and distract them.
In 30 years, when people tell the story of the Physical Computing Revolution and how it changed the world, what will they say about you?

First Arduino Prototype

For those who might be wondering how the first Arduino board must have looked like, here is the snap.

Arduino Documentary Trailer

Arduino documentary is finally in the making. They have launched its trailer. The whole movie is in the pipeline and will be out soon.
Check out the full featured trailer at: http://arduinothedocumentary.org/

Roadtrip To A Job Interview (A Successful One)

Well, it was quite an unexpected thing to occur after I was finally home. I was a bit tired as the day was very hectic and involved the placement process of Day Zero. Futures First were the firm which came to recruit on the first day. It all started at 9 in the morning with the pre-placement talks and introduction to the company. And then followed a series of tests which eliminated and filtered out those who were not qualified. Having cleared both the tests, I was still a bit precarious to appear in the final elimination round which was at 5PM in the evening. But that was more than just fun. All 15 survivors of the last stage were asked to play a game of a poker-like structure of betting and winning more than your partners. The questions were asked and the stakes were put. At the end, this very engrossing game meant that 5 of us were to be further eliminated. Then remained 10 of us. From Electronics and Communication, I was there along-with my classmates Samarth and Akash. Needless to say, we were through to the final round of Personal Interviews with the company personnel. As after the game we were instructed to go home and come for the interviews on Monday, I and Akash came back home to get a good day’s meal. Nothing to eat for the whole day and we were starving like anything. We decided to go to Freezeland to have some sandwiches as a reward for what we achieved so far that day. So off we went to Freezeland. I was on my way to the restaurant when my phone rang. I pulled over my vehicle and picked it up to find Rohit Makhija at the other end panting heavily and telling me that I was supposed to report at the InfoCity at Gandhinagar in about 45 minutes in formals and alongwith all the documents for the interview. I was more surprised than shocked to see that it was 9:30 PM at night..!! But I called home to keep a glass of milk ready and called Akash (who was also on the way) to immediately return home and get ready for it.
– In 20 minutes time –
We were in my car headed towards Gandhinagar for a 30 km ride to the interview place. Samarth was already there and had talked with us about the venue and time. Fortunately Akash had brought some Bhaji-pav sandwiches (yes, I am not joking) and a bottle full of juice. So it was kind of a fun-trip. We were least bit serious and concerned about the interviews as we thought more of the serene atmosphere outside. In about 20 minutes, we were in Gandhinagar. Finding the Tower 1 of InfoCity was a cakewalk and in no time, we were there. Now the atmosphere there was quite placid. No sign of anyone there on the campus. We waited for Samarth and other 3 from Computer branch to arrive. Then they finally arrived and the time was 10:45 PM. Reporting time was 11PM and we made our way up there to the Futures First office.
We were duly welcomed with very warm hospitality. We were then ushered to the Conference Room. We then filled up a form regarding our future prospects and the reason for our interest in the company. There we were served with the finest of the coffees I have ever tasted. Well, we later discovered that it was the magic of the automatic coffee machine from Nescafe. Not much time passed when the first one was called in for the interview. A Computer guy was the first to go in. We were all anxious and a bit nervous. But it took about 25 to 30 minutes for him to get done with it. Then went in Parth from Computers. Again for another 30 minutes. First from Electronics to go in was Samarth. He was pretty confident and we all were cracking jokes and enjoying ourselves in between some nervous moments. He went in and rather came out quickly. He was interviewed for only about 15 minutes. My turn soon came and I was ready. I was called in after Samarth and I entered the cabin, with an air of confidence. It was about 1 AM in the morning. But the interview people seemed least bit sleepy. They were pretty sure of their interview method. I was interviewed by Mr. Nikhil for about 40 to 45 minutes constantly and was asked why I was so interested in it though being strong technically. I made my best efforts and was really happy the way I performed. After me, was Akash. He was more interested in this company than any of us, telling this very frankly.
He rather was surprised the way his interview went. Because he was asked questions about his future planning and long term goals, he could not figure it out instantaneously. He was a bit slow and thoughtful in answering which did him in. It cost him and his lasted only 20 minutes. He personally thought he mistook the approach as we talked about it on our way back.
Then after all interviews were over, I was asked to stay back. I felt as if in a moment or two, I was going to be offered the job. I felt really nervous. But, when they called me in the cabin again, I came to know that it was the coveted HR interview stage I was heading to. I was shocked, but I pulled my self together and made myself ready for another dose of questions ranging from ‘Where do you see yourself in 5 years?’ to ‘How many plants do you see in this room?’. I was literally bombarded with questions at 3 AM in the morning. But I knew the best solution and held my composure. I can say I did pretty well, and convinced them that I was up for it no matter what pressure there was to be. Then after a scrutinized analysis of my mindset and capabilities, they let me go. It was about 60 minutes that my second interview lasted. But I felt more elated that I did really well. The guys in the conference room were all with questioning eyes about what I was doing in there until then. They were expecting me to be offered the job. When I said the things I was asked, they were surprised to see the amount of research those people do on the person they are hiring. But soon everything got over. It was 4:30 AM in the morning. We finally came out of the office with everyone done with the interviews.
We had not eaten a single thing since morning. We were starving. So we went to the God blessed canteen which was still open at that time in InfoCity. Two sandwiches and we were on our way back home again.
All said and done, I think my first job interview was by far the most memorable experience of my life. I will surely cherish it for a long long time. Thank you Samarth and Akash and all 3 computer guys including Pratik and Parth. I surely had a great time with you people. :)

XBee - Different Ways To Connect

Xbee radios can be connected in countless ways.  The limits are imagination and only to small degree budget.
This post is an overview of some of the strategies for making electrical connections with equipment in our labs.  The start simple and become more complex.
!!!!REMEMBER XBEES ARE 3.3V DEVICES!!!
Strategy 1: xbee explorer
explorer_wout_xbee
explorer_wxbee1
Available online and in the cabinet.
These are as easy as plugging in the radio and attaching the USB cable.  These boards supply the needed 3.3V automatically.  Look for the thin white outline on the board for orientation of the radio –  the “top” of the radio should face away from the cable connection.
If you solder header pins to the main board it can be attached to a breadboard — and then to your arduino.  As shown it can make direct connections to any software with serial capabilities.

Strategy 2: RS232-USB Breakout Boards
usb_rs232
Available online (rs-232xbee board) and in the cabinet.
This strategy is similar to the xbee explorer board above — but now split into two boards.  The right board carries the radio, the left board handles communication protocols (it can be used with lots of devices other than xbees too!).
Because you have two boards you now need to make power and serial connections — not just snap in the radio.  Grounds (green on left, black on right) for each board must be connected to the ground bus (blue rail on breadboard).  Power (3.3V) for the radio is brought from the RS232 breakout board to the radio via the yellow wire (details below).
Serial connections go from Rx of RS232 to Tx of xbee and vice versa.  The xbee boards label Rx as Din and Tx as Dout.  This is called crossing over (look at ends of blue and white wires above).  it may help to think of connecting ears (Rx) to voice (Tx) when speaking — but, then again maybe it won’t.
POWER — is 3.3V!
You need to be more aware of voltages with this strategy.  The RS232-USB board on the left can supply 5V
and 3.3V.  Power connect should go from the SECOND pin (yellow #2 below) on the RS-232 board to pin one (1) of the xbee breakout board. Pin 1 carries 5V — so you need to double check before connecting the USB cable.
powerreminder
xbeebreakout
xbeewires

Strategy 3: Use Your Arduino Board
For this strategy you must remove your micro-controller chip — you can then use the Arduino board as if it were an RS232 breakout board.  Removing the chip straight forward (if you don’t have a chip puller, a screwdriver can be used to gently lift it out)– just go slow and be patient.  Remember to note the orientation of your chip — the notch faces the outside of the board.  You will want to re-place the chip in the same orientation.
dechipxbee
As in the breakout board strategy (#2) above — you need to make 4 connections: 3.3V, ground (gnd), Rx adn Tx.  In this case the Rx and Tx lines do not cross over (look carefully at the ends of the white and blue wires).
dechipserial
3.3 volt power can be obtained from the board (detail below).   The radio is wired as above.
dechippower

XBee - A Brief Primer

The physical aspects of the Xbee chips are introduced in the hardware section (below).  Here, we will discuss the software aspects of the configuration. 
There are two different modes of operations that Xbees can run in.  They are: 
1.       Transparent mode
2.       API mode
In transparent mode, the Xbees essentially act as a dumb serial line replacement.  In other words, each Xbee simply forwards everything that comes in through its antenna to its Din port, and sends everything that comes in through its Dout port through its antenna and into the air.  This is functionally equivalent to simply having a serial line connected between the two Xbee chips.
In API mode, Xbee operation is not nearly as simple.  API stands for Application Programming Interface, and in this mode you can send commands to and from the Xbees to perform various tasks.  Further, it is in this mode that the Zigbee protocol is used for Xbee Series 2 chips.  In other words, whereas transparent mode acts as a dumb serial line replacement, API mode unleashes the full power of the Xbees and allows us to construct a real wireless network consisting of our two devices.
When in API mode, there are three more modes that each Xbee chip – or any chip on a Zigbee network – can operate in.  These modes are:
1.       Coordinator mode
2.       Router mode
3.       End Device mode
These modes are essentially listed in order of decreasing functionality.  Coordinators are the most powerful nodes in Zigbee networks, and can coordinate activity within one network while also interacting with the outside world.  Other nodes in the network “report to” the coordinator.  Router nodes have the capability of forwarding packets from one node to another (acting as an intermediary in the network, or a router).  End device nodes cannot act as routers but can communicate with routers or the network coordinator.  On series 2 Xbee chips (which we used), it is necessary to change the firmware on the chips to change between API and transparent mode and also between Coordinator, Router, and End Device mode.
In our application, we used the Xbee connected to the PC as a coordinator, and the remote Xbee as an end device.  This allowed us to use the Xbee connected to the PC to send commands to a remote Xbee, and also to set up automatic I/O sampling on the remote Xbee.  Xbees that are within the network of a certain coordinator are said to be “associated” with that coordinator node.
To configure Xbees, you can use Digi’s own X-CTU software, which was created specifically for configuring Xbee and similar chips offered by Digi, or you can simply connect to the Xbee chips via a serial terminal (such as Hyperterminal) and send them a series of commands.  You can also use a network coordinator to send commands to be executed on a remote Xbee within that coordinators network.  The Xbee chips have various registers that store different parameters.  For example, the parameter AP is what determines whether the Xbee is in transparent or API mode.  When AP=0, transparent mode is enabled.  When AP=2, API mode is enabled (AP = 1 also enables API mode, but with slight differences that we won’t discuss here).

Open Source Arduino Clock

I stumbled upon a nice little clock code based on Arduino. I am sharing it here. You can also edit it and use it make your own such modified one.
#define vers = “1.01″
#define ledPin 13
#define secondPin 4
#define minutePin 5
#define hourPin 6
#define weekdayPin 7
int second=0, minute=0, hour=0, weekday=1; // declare time variables
// these time variables are declared globally so they can be used ANYWHERE in your program
void setup() { 
blinkLED(ledPin, 4, 100); // blink an LED at the start of the program, to show the code is running
Serial.begin(9600); // start up serial communications
pinMode(secondPin, INPUT); //pins for normally closed switches to set the time
pinMode(minutePin, INPUT);
pinMode(hourPin, INPUT);
pinMode(weekdayPin, INPUT);
digitalWrite(secondPin, HIGH); // writing an input high turns on pull-up resistors
digitalWrite(minutePin, HIGH);
digitalWrite(hourPin, HIGH);
digitalWrite(weekdayPin, HIGH);
}
void loop() {
static unsigned long lastTick = 0; // set up a local variable to hold the last time we moved forward one second
// (static variables are initialized once and keep their values between function calls)
// move forward one second every 1000 milliseconds
if (millis() – lastTick >= 1000) {
lastTick = millis();
serialOutput();
second++;
}
// move forward one minute every 60 seconds
if (second > 59) {
minute++;
second = 0; // reset seconds to zero
}
// move forward one hour every 60 minutes
if (minute > 59) {
hour++;
minute = 0; // reset minutes to zero
}
// move forward one weekday every 24 hours
if (hour > 23) {
weekday++;
hour = 0; // reset hours to zero
}
// reset weekdays on Saturday
if (weekday > 7) {
weekday = 1;
}
checkButtons(); // runs a function that checks the setting buttons
}
void checkButtons() {
static boolean secPressed=false, minPressed=false, hourPressed=false, wkdayPressed=false; //track button state
if (digitalRead (secondPin)==LOW && secPressed == false) { // if a normally closed switch is pressed
second++; // advance by one second
secPressed = true; // note the pressed state
}
if (digitalRead (secondPin)==HIGH) secPressed = false; // reset the state when the button is released
if (digitalRead (minutePin)==LOW && minPressed == false) {
minute++;
minPressed = true;
}
if (digitalRead (minutePin)==HIGH) minPressed = false;
if (digitalRead (hourPin)==LOW && hourPressed == false) {
hour++;
hourPressed = true;
}
if (digitalRead (hourPin)==HIGH) hourPressed = false;
if (digitalRead (weekdayPin)==LOW && wkdayPressed == false) {
weekday++;
secPressed = true;
if (digitalRead (weekdayPin)==HIGH) wkdayPressed = false;
}
}
void printWeekday (int dayNum) {
// print a weekday, based on the day number
switch (dayNum) {
case 1:
Serial.print (“Sunday”);
break;
case 2:
Serial.print (“Monday”);
break;
case 3:
Serial.print (“Tuesday”);
break;
case 4:
Serial.print (“Wednesday”);
break;
case 5:
Serial.print (“Thursday”);
break;
case 6:
Serial.print (“Friday”);
break;
case 7:
Serial.print (“Saturday”);
break;
}
}
void serialOutput() {
// this function creates a clock you can read through the serial port
// your clock project will have a MUCH more interesting way of displaying the time
// get creative!
printWeekday(weekday); // picks the right word to print for the weekday
Serial.print(“, “); // a comma after the weekday
Serial.print(hour, DEC); // the hour, sent to the screen in decimal format
Serial.print(“:”); // a colon between the hour and the minute
Serial.print(minute, DEC); // the minute, sent to the screen in decimal format
Serial.print(“:”); // a colon between the minute and the second
Serial.println(second, DEC); // the second, sent to the screen in decimal format
}
// this utility function blinks the an LED light as many times as requested
void blinkLED(byte targetPin, int numBlinks, int blinkRate) {
for (int i=0; i&lt;numBlinks; i++) {
digitalWrite(targetPin, HIGH); // sets the LED on
delay(blinkRate); // waits for a blinkRate milliseconds
digitalWrite(targetPin, LOW); // sets the LED off
delay(blinkRate);
}
}

Common XBee Project Mistakes

Your XBee project isn’t working? Here’s some common mistakes that both beginners and experts make:
  • Not using the latest firmware (especially if ATD0 or ATIR is giving an error)*
  • No reference voltage to VREF pin on the 802.15.4 radios (analog and digital reads give wrong values)
  • Forgetting that AT commands use hexadecimals
  • Hitting return after +++ (or otherwise not respecting 1 second default guard time)
  • Conversely, _not_ hitting return after an AT command
  • Letting the XBee time out of command mode before issuing an AT command (you’ll know because you get no response)
  • Forgetting to write the configuration to firmware with ATWR (unless your application configures the radio interactively)
  • Not using ATRE (restore factory defaults) before re-configuring a previously used radio (previous settings lurk unless you manually reset them all)
  • Looking for analog output on the analog input pins instead of pins 6 and 7 (P0, P1)
  • Using a voltage regulator without decoupling capacitors (10uF on input, 1uF on output is good)
  • Mixing up TX and RX pins (fastest way to check this is switch the wires and see if it starts working)
  • Using ZigBee version (ZB Pro or ZNet 2.5) when 802.15.4 version would do just fine (if you don’t need to make a mesh network)
  • Trying to read more than 1.2 Volts on the ZB Pro and ZNet 2.5 analog inputs (that’s the limit)
  • Buying Pro radios when you don’t need them. (Cost more, bigger, use a lot more battery)
  • Deciding the XBees are flaky. (You may not be using them correctly, but they are very reliable)
  • Deciding an XBee is burned out when it’s set to a different baud rate (check ON and ASSC lights)
  • Deciding an XBee is burned out when it is just sleeping (Check ON light to see if it blinks occasionally)
  • Forgetting to supply power or ground (ON light may go on and ASSC light may blink but both will be significantly dimmer)
  • Not contacting Digi sooner for support, especially if your radio seems dead or you keep getting an error you don’t understand. 
XBee Arduino Mistakes
  • Sending continuously without any delay (try 10ms delay)
  • Not removing RX and TX connections before uploading code (Arduino will give an error)
  • Not removing RX connection when reseting, if you are continuously receiving data. (Arduino will never reset)
XBee LilyPad Mistakes
  • Hooking up more than 4 Volts to the 3.3V pin
  • Using switches without pull-down resistors (but not if you use the internal pull-ups)
  • Not using a pull-up or pull-down resistor on pins 5 and 7 (these don’t have internal pull-ups at all)
  • Using sensors without voltage divider resistors (if your sensor needs that circuit)
  • Using too-resistive conductive thread for power and ground (try fabric or wires)
* Windows and X-CTU are required for firmware upgrades