## Archive for February, 2011

### Flashing LED Using an Astable 555

Sunday, February 20th, 2011

This project will use the 555 timer IC to flash an LED with the eventual aim of using the timer to provide a regular timing pulse.

## Objective

Use the 555 timer to flash an LED with a period of 1 second.

## Components

The timer being used is a standard NE555N timer. This is a cheap general purpose timer circuit and has been around for many years. In fact I remember using them when I first became interested in electronics at school.

The circuit for setting this chip up in astable mode is as follows:

So along with the chip itself we will need 3 resistors, 2 capacitors and an LED. Thye values of R1, R2 and C1 determine the frequency of the pulses according to the following equation:

A frequency of 1 Hz was chosen to make the pulses clearly visible to the observer. A little reordering of the equation and a sift through some standard components gave the following values for these components:

 Component Value R1 1 KOhm R2 2 KOhms (two 1 KOhm resistors in series) C1 470 micro Farad

## Putting it all together

Gathering all of the components together along with some breadboard gave a LED flashing at approximately 1 Hz. I say approximately as I’ll need to feed that output through a logic analyser / oscilloscope to verify the exact frequency.

Saturday, February 12th, 2011

The aim of this experiment was to test the analog input.  The simplest way I could think of to do this is to hook up a potentiometer to one of the analog pins and then display the values using the debugger.

First task is to wire up the board.  The final wiring looked like this:

I say final wiring as my initial version looked a little different.  The first version did not have the 3.3V output connected to Aref and as a result I found myself getting very odd results from the analog input pin.

The code to read data from the Netduino looks like the following:

```public static void Main()
{

analog.SetRange(0, 1023);
while (true)
{
}
}
```

Running the application and turning the potentiometer results in a range of values from 0 to 1023.

### RGB LED and PWM

Saturday, February 12th, 2011

Lots of abbreviations in this post but the aim is simple. Going back to working with LEDs, the idea is to control a RGB LED using the Netduino. The LED I have purchased is a common cathode LED the details of which can be found here.

The LED can be used either as a status display (using each of the three colours for a different status) or the three colours can be mixed to provide mixed colour output. This entry describes how to use the Netduino to provide a mixed colour output using PWM.

## Wiring Up The Circuit

The LED is a common cathode LED with three anodes, one for each colour (Red, Green and Blue). This will require three pins on the Netduino in order to control the changing colours. Each of the three pins will require a current limiting resistor in order to ensure that we don’t try to draw too much current from the Netduino and burn out the pins. A quick application of Ohms law to ensure that we do not try and draw more than 8mA gave the following nearest equivalent resistors:

 Colour Voltage Resistor Red 2V 220 ohms Green 3.2V 20 ohms (2 x 10 ohms) Blue 3.2V 20 ohms (2 x 10 ohms)

The next step is to hook up the LED to the Netduino. This is done using three of the four PWM pins on the board. By using PWM we can vary the power supplied to each of the three pins on the LED. This will allow control of the amount of each colour generated which in turn will determine the colour of the LED. The image below shows the circuit set up on breadboard:

## Software

The software uses PWM to control the power supplied to the LED. I found two articles which helped in understanding how this works, the first on Wikipedia and the second by Philip on the Netduino forums. The basic principle is that by varying the amount of time a pin is powered we can change the average power supplied by the pin. The following code show how this can be achieved using three of the Netduino’s PWM pins:

```public static void Main()
{
PWM red;
PWM green;
PWM blue;

red = new PWM(Pins.GPIO_PIN_D6);
blue = new PWM(Pins.GPIO_PIN_D5);
green = new PWM(Pins.GPIO_PIN_D9);

while (true)
{
for (uint redDuration = 0; redDuration < 4000; redDuration += 1000)
{
red.SetPulse(10000, redDuration);
for (uint greenDuration = 0; greenDuration < 4000; greenDuration += 1000)
{
green.SetPulse(10000, greenDuration);
for (uint blueDuration = 0; blueDuration < 4000; blueDuration += 1000)
{
blue.SetPulse(10000, blueDuration);
}
}
}
}
}
```

The program simply cycles through a series of values for each of the selected pins and changes the amount of time each pin is active. The result is a LED which constantly changes colour.

### Silverlight on the Netduino

Tuesday, February 1st, 2011

Having been working with the Netduino Plus for a few week I wanted to look at the possibility of using the network to communicate with the board. Having browsed the forums on the Netduino home page I found a few discussions about using this board as a web server including using a WiFly board to hook up to a wireless network. The SDK also comes with several examples of network programming with the micro framework.

## Objective

Allow the PC to send and receive data to the Netduino Plus over a wired network.

## Main Program

The Netduino Plus board does not have the same resources available to the programmer you would normally find in a PC environment. This leaves the programmer with little to work with. The HTTP server supplied as a sample with the micro framework occupies a substantial amount of memory on the board.

One of the simpler examples provided with the framework implements a very simple server. A little bit of redesign and coding converted this into a very basic web server. The server is capable of serving a few file types (HTML, JPG, CSS, Javascript and XAP) to the client.

The main program is a simple affair. It contains a few definitions to support the file locations for the web files along with a small amount of code to offer “I am alive” feedback to the user.

For the “I am alive” feedback I have chosen to use the on board LED and button. The LED will flash twice when the user presses the on board button. A small power saving I know.

The final job of the main program is to instantiate the web server. This will start the server listening on the specified port.

```private static OutputPort _onBoardLED;
private static InterruptPort _onBoardButton;

public static void Main()
{
_onBoardLED = new OutputPort(Pins.ONBOARD_LED, false);
_onBoardButton = new InterruptPort(Pins.ONBOARD_SW1, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth);
_onBoardButton.OnInterrupt += new NativeEventHandler(onBoardButton_OnInterrupt);

_webServer = new WebServer(WEB_ROOT, WebServer.HTTP_PORT);

}

///
/// Flash the on board LED to let the user know we are still alive.
///
private static void onBoardButton_OnInterrupt(uint data1, uint data2, DateTime time)
{
if (data2 == 0)
{
_onBoardLED.Write(true);
_onBoardLED.Write(false);
_onBoardLED.Write(true);
_onBoardLED.Write(false);
}
}
```

The code for this can be found in SimpleWebServer.zip.

The files served provides a static web site to the client (a trip back to the 1990s).

## Web Server

The web server class contains the methods to create a non blocking web server which will listen to the network on the specified socket and process the requests.

The constructor for the class sets up the local variables and creates a new thread to listen for requests:

```public WebServer(string webFilesLocation, int portNumber)
{
_webRoot = webFilesLocation;
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Listen(int.MaxValue);
}
```

The Listen method does the main work of listening to the socket, getting the request and converting it to a string which can be processed and finally closing the socket.

```private void Listen()
{
while (true)
{
using (Socket client = _socket.Accept())
{
int requestSize;
byte[] buffer;
string request;

requestSize = client.Available;
Debug.Print("Request received from " + client.RemoteEndPoint.ToString() + " at " + DateTime.Now.ToString("dd MMM yyyy HH:mm:ss"));
request = new string(Encoding.UTF8.GetChars(buffer));
Debug.Print(request);
ProcessRequest(client, request);
buffer = null;
request = null;
client.Close();
}
}
}
```

The method which processes the request is a simple method which is designed to check the first list of the request and verify that the web server can understand the protocol of the request. This server can only process HTTP 1.1 get requests. The first line of such a request should come through as something like the following:

GET filename.html HTTP/1.1

The ProcessRequest method looks something like the the following:

```private void ProcessRequest(Socket client, string request)
{
string[] firstLine;

firstLine = request.Substring(0, request.IndexOf('n')).Split(' ');
if (firstLine[0].ToLower() != "get")
{
Send(client, HTTP_501_NOT_IMPLEMENTED);
}
else
{
if (firstLine[2].ToLower() != "http/1.1r")
{
Send(client, HTTP_505_HTTP_VERSION_NOT_SUPPORTED);
}
else
{
SendFile(client, firstLine[1]);
}
}
}
```

The constants in upper case contain response strings indicating that the web server has encountered an error.

The key work for sending the files and processing commands can be found in the SendFile method. The first thing this method does is to check on the file name to see if it is the “special command” file. If it is then the query string is passed to the command processor. All other requests are processed as request for files which should exist on the server. The system works out if it understands the file type and if it does then the file is sent to the client.

One design decision taken was to restrict the output to the client to 256 byte chunks. This decision was made in order to conserve memory.

## Commands

The eventual aim is to connect sensors etc. to the Netduino and then read the data from them over the network. In order to test the theory a “dummy” sensor was added to the command processor. This simply returned the number of milliseconds from the current time divided by 100.

```TimeSpan time;

tme = Utility.GetMachineTime();
Send(client, "Time " + time.Hours + ":" + time.Minutes + ":" + time.Seconds);
```

By using the command.html file and the QueryString we can test the system by making a simple request from the web browser. For instance:

http://192.168.10.100/Command.html?GetTemperature

could be interpreted as a request to read the temperature from a sensor attached to the board.

## Silverlight Client

The next step was to look at dynamic content. The board is not powerful enough to support conventional technologies such as PHP or ASP. Silverlight offers the ability to move the dynamic content creation away from the web server and onto the client desk top. To demonstrate this, a simple Silverlight application was created to be served by the web server (hence the support for XAP files). The initial version simply said hello to the user.

So far, so good. The web server was serving HTML and Silverlight files to the client.

The next step was to flesh out the Silverlight client to hold sensor data and display this to the user. This part of the application is implemented in MVVM. For this I needed a class to hold a sensor reading and a class (TemperatureReading)to hold a collection of sensor readings (TemperatureViewModel).

```public class TemperatureReading
{
///
/// Date and time the reading was recorded.
///
public DateTime When { get; set; }

///
/// Temperature.
///
public double Temperature { get; set; }

///
/// Constructor
///
/// <param name="when" />When was the reding taken
{
When = when;
Temperature = temperature;
}
}
```

The ViewModel holding the temperature readings is as follows:

```public class TemperatureViewModel : INotifyPropertyChanged
{
#region Properties

///
///
{
set
{
}
}

///
///
{
}

#endregion

#region Constructor(s)

///
/// Default constructor
///
public TemperatureViewModel()
{
}

#endregion

#region INotifyPropertyChanged Members

///
/// Event used to notify any subscribers that the data in this class has changed.
///
public event PropertyChangedEventHandler PropertyChanged;

///
/// Let any subscribers know that some data has changed.
///
/// <param name="properties" />Array of name of the properties which have changed.
private void RaisePropertyChanged(params string[] properties)
{
if ((properties != null) && (PropertyChanged != null))
{
foreach (string property in properties)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}

#endregion

#region Methods

///
///
{
}

#endregion
}
```

Now we have somewhere to store the data we need to display the interface and then add a way of getting the data into the application.

The MainPage.xaml displays the data in a DataGrid and a chart. There is also a button for starting and stopping the collection of data. The DataGrid and the Chart are both bound to an instance of the TemperatureViewModel class.

The data for the class is collected periodically by using a web request from an instance of the WebClient class. This is then parsed and added to the collection of readings and the interface updated automatically through the magic of the RaiseProipertyChanged method of the TemperatureViewModel class.

The source can be found here: SilverlightOnNetduino.zip.

## Building the Server

The web server code was modified to provide simulated readings from a temperature sensor. This is simply the current number of milliseconds divided by 100. The data is stored in a DataGrid and a presented to the user:

Adding the Silverlight Toolkit charting control to the application allowed the data to be plotted:

The next step is to tie this up to a real sensor and serve data to the users desktop.