Pages

Thursday, May 19, 2011

Display JSON results

JSON (JavaScript Object Notation) is a great straight forward way to transfer information from one application/server to another. It's string-based, array-oriented, and does not carry with it the redundancy of XML or (shudder) SOAP. And the best feature in a web application: it's immediately transferable to a JavaScript object, without the need for (an explicit) parsing.

Add to the mix jQuery - a JavaScript framework that makes using JavaScript and writing dynamic web pages a snap. Once I picked it up, I couldn't go back. jQuery is now embraced by many - including Microsoft and Google, who include it in their default web templates, and provide hosted CDN versions of its latest versions.

jQuery shines when it comes to AJAX transactions - you can get a JSON result from a web service using one instruction! Going over the reply is also a snatch. I found myself many times just needing to dump the results on the page - either for debugging purposes, or so I could copy/paste them somewhere.

Here is a short code snippet that I use to get a JSON result from a local web service (a remote request requires JSONP - future post), and dumps the results in a form of a list. It assumes a single-level array reply and that you have a <DIV> element on the page called "result":


        


Explanation:
  1. Line 1 includes version 1.5.2 of jQuery from the Microsoft CDN
  2. Line 4 will make sure the function will run when the document has been fully loaded and drawn
  3. Line 5 calls the JSON service and sends the results to a function
  4. Line 8 iterates over the result object and creates an array of <LI> elements
  5. Line 14 creates a new <UL> element, applies a CSS style to it, attaches the <LI> elements and places it inside the result <DIV>
That simple!

Monday, May 2, 2011

Netduino Project 2: Morsey

As discussed in my last post, I've created a small test app called Morsey to practice my LED lighting skills on the Netduino.

The functionality is simple: the application takes a constant English string and turns it into a string of dashes and dots, signaled by the LED. The signaling is started/stopped by clicking the on board button.

The code:
There are 3 code files:
  1. The main program file, that runs the main thread and the Morse thread, as well as the button event.
    static void button_OnInterrupt(uint data1, uint data2, DateTime time)
    {
     bool isButtonDown = (data2 != 0);
     if (isButtonDown)
     {
      displayMessage = !displayMessage;
     }
     
     if (displayMessage)
     {
      if(morseThread.ThreadState == ThreadState.Unstarted)
       morseThread.Start();
      else
       morseThread.Resume();
     }
     else 
     {
      morseThread.Suspend();
      led.Off(); 
     }
    }
    
  2. The MorseCharacters class. I copied the 2 Morse arrays from Scott Hanselman's great Netduino post (sorry Scott, just lazy and it's faster to C&P than to type all those dashes and dots :)).
  3. The LED class - the same one I used in the TrafficLight project, with the addition of a single function:
    public void WriteMorse(String message) 
    {
     MorseCharacters converter = new MorseCharacters();
     String morseMessage = converter.ConvertMessageToMorse(message);
     if (morseMessage != String.Empty)
     {
      foreach (char c in morseMessage)
      {
       switch (c)
       {
        case '.':
         Dot();
         break;
        case '-':
         Dash();
         break;
        case ' ':
         //delay for twice the character gap between words
         Thread.Sleep(delay * 2); 
         break;
        default:    //handle errors here
         break;
       }
      }
     }
    }
    

To get the full code, clone the git at https://github.com/TravelingTechGuy/Morsey

Sunday, May 1, 2011

1st Netduino Project: Traffic Light

While I'm dabbling in HTML5, iPhone and Android projects at this particular point in time, I chose to open this blog with a project I'm passionate about. I've been following the Arduino revolution for years now, but always from a far. Although I have some electronics background in my ancient past (try: middle school electronics kits), I see myself a s a software professional. Having had the distinct "pleasure" of working in assembler, I decided that's as close I'd ever get to speaking to real hardware.

And then I found out about the Microsoft .Net micro framework. It seems I can take my .Net skills and transfer them to the hardware world! I can make LED lights turn on and off! I can react to button clicks rather than keyboard and mouse events! But on a more serious note, I can implement a standalone web server that allows me to perform operations remotely. I can read/write to an SD card. I can control a vast collection of electronic components and analyze information from a myriad of sensors. All this with a very small upfront investment. I'm in.

What do you need:
  1. An arduino board that supports the .Net micro framework. There are several out there, but I chose the Netduino Plus. At $60 it provides an Ethernet port and a microSD card reader on board, saving you the need to wire those later. I got it off Amazon, along with the breadboard (see 3).
  2. Free software: SDK and drivers (most software associated with Arduino is open source, even (shock!) the .Net micro framework from Microsoft. This page has a full list of what you'll need, including a good installation guide that will take you through installing, writing your first program and debugging it. 
  3. To develop software you use Visual Studio (you can use the free Visual C# Express version). 
  4. Some cheap components. I got a mini breadboard for $3. A breadboard allows you to play with circuits and components without the need to solder anything. There are no mistakes and most components are tolerant with the involved voltages. Heck, I found out that one of the LEDs I got was dual-colored - you get a different color if you plug it in the other way. That was a nice surprise.
    I also got a couple of wires and color LEDs from my local FRY's (at $0.49 each - you can get them at $5/40 - I just didn't need that many).
  5. Plenty of internet reading: instructions, projects, suggestions. I enrolled in the Netduino forums and have been so far assisted with some issues. Every one there is enthusiastic and helpful. All are hobbyists - none are trolls.
  6. A free weekend.
Later on you may want to buy more components, like shields (Arduino add-on boards) sensors (light, touch, accelerometers), wireless network adapter (like XBee), LCD screens, joysticks - whatever.
My recommendation is: even though the components are relatively cheap (with the exception of XBee and a GPS shield, they are almost always below $20, most are even cheaper), avoid buying them until you feel sure you've grasped the basics and are ready to proceed.

Programming:
The "Hello, World" project of  the Arduino world is called "Blinky". You get to blink the on-board LED, and later read the on-board button to control the LED.

Visual Studio automates the deployment of  allows you to do a step-by-step debugging on the device. This is an amazing way to develop for hardware. Of course, you get the assortment of tools you're already used to as a .Net developer.

I asked myself what can I do with an LED, and came out with the done-to-death idea of a Morse code Signal Emitter (I called it "Morsey"). You feed it an English string and it yields a string of dashes and dots using the LED. The next step was to use the button to start/stop the signaling. And then came the notion of using a separate thread to be able to pause and resume the signaling - in short, I spent time honing my skills, such as they are, preparing for more complex projects.

Traffic Light project:
But before I was ready to move on to my next project, which will involve an LCD display ($10 on Amazon), I decided to test my breadboard skills and developed this small project called "Traffic Light".
Made of one tiny breadboard, 3 colored LEDs, 7 wires and about 40 lines of code, it simulates a traffic light's color change, using a separate thread, and the LED class I carried over from "Morsey".

You can see the end result in this video and I should really start to remember not to talk while zooming with this camera - it records the zoom noise over your voice):



I found a nice (free) application called Fritzing that allowed me to design my circuit design and share it with other hobbyists. Here's what the above circuit looks as a Fritzing design:
And Fritzing automatically turns it into a schema you can use to share with electronics professionals, using standard conventions. Just in case you'd like to mass-produce your project one day:

If you want to get the full code, including these images and the Fritzing file, just git it here: https://github.com/TravelingTechGuy/TrafficLight.

And yes, I wrote "Git", not "get". If you don't know what Git is, or how to use it, the page also provides a zip download, but you better get used to it, as I'm going to use github to share all my code on this blog (and thanks to Jason for introducing me to git in the first place).

Well, this is done, on to the next project.