Netduino plus 2: First steps

Netduino plus 2: First steps

NetduinoI while ago I bought a Netduino plus 2. This open-source electronics prototyping platform is based on the .Net Micro Framework. The advantage of the plus 2 is, the presence of a network connection. This  connection makes it possible to connect the Netduino to the internet.

After setting up the development environment (Visual C# 2010, .Net Micro Framework, .Net Micro Framework Toolbox and Netduino SDK) to programming can start.

Netduino Plus 2

In this post I will show some code I used for my first steps into progamming the Netduino. The program will use the on-board button and LED.  When the button is pressed, a URL will be called and when the response from the URL is ok, the LED will blink.

This is the C# code which will run on the Netduino

[code]

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;
using Toolbox.NETMF.NET;

namespace ButtonPress
{
public class Program
{
private const string _Server = "example.com";

public static void Main()
{
// Initialize onboard LED
var led = new OutputPort(Pins.ONBOARD_LED, false);

// Initialize onboard button
var button = new InputPort(Pins.ONBOARD_SW1, false, Port.ResistorMode.Disabled);

while (true)
{
// Read button state
var buttonPressed = button.Read();

// If the button was pressed, send info to URL
if (buttonPressed)
{
// Send information
var ack = SendInformation2Url();

// If send was ok, blink LED once
if (ack)
{
BlinkLED(led, 1);
}
else // otherwise blink LED 3 times
{
BlinkLED(led, 3);
}
}
}
}
}
[/code]

Code for calling a URL

[code]
// Send information to URL
private static bool SendInformation2Url()
{
var result = false;

var socket = new IntegratedSocket(_Server, 80);
var session = new HTTP_Client(socket);

var response = session.Get("/buttonpress.php");
if (response.ResponseCode == 200)
{
result = true;
}

return result;
}
[/code]

The code for blinking the LED

[code]
// Blink the LED
private static void BlinkLED(OutputPort led, int count)
{
for (int i = 0; i < count; i++)
{
led.Write(true);
Thread.Sleep(250);
led.Write(false);
Thread.Sleep(250);
}
}
[/code]

This is the code behind the buttonpress.php:

[code]
<?php
$fp = fopen(‘buttonspress.log’, ‘a’);
fprintf($fp, "%s: button was pressed\n", date(‘Y-m-d H:i:s’));
fclose($fp);
?>
[/code]

This is all the code you need for reading the on-board button state, calling a URL and letting the on-board LED blink.