NetMF Electric Longboard Part 2

In part 1 I got the wireless WiiChuck working with a plug n play setup using a SeeedStudio Grove base shield, Wii Chuck adaptor, modified 5CM cable and FEZ Lemur. The FEZ Lemur is limited to a 5VDC supply which wasn’t going to work so well with the 6VDC output of my HobbyKing HK150 ESC without some extra electronics.

GHI Electronics also sell the FEZ Panda III which has a 6VDC-9VDC voltage range and more processing power which would be useful for my next project a dual motor longboard with traction control and anti lock braking .

I also figured vibration could be a problem for the plug n play setup so I built a custom shield for my wireless Wii Chuck dual motor longboard control using an Arduino protoshield, and a Wii-Nunchuck breakout board. The shield provides a solid mount for the wireless Wii chuck dongle and power for the NetMF board from the output of the ESC.

 

FEZ Panda III Protoshield for longboard with RC Servo for testing

FEZ Panda II Protoshield for longboard RC Servo test

I tested the shield wiring using a Radio Control (RC) Servo so the scope of disaster was greatly reduced. (The red jumper wire is supplying 3v3 to the servo for testing)

using System;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using Toolbox.NETMF.Hardware;

public class Program
{
   private const int NunchukYMinimum = 0;
   private const int NunchukYMaximum = 255;
   private const int PWMPeriodMicroseconds = 20000;
   private const int DurationMinimum = 1250;
   private const int DurationMaximum = 1750;

   public static void Main()
   {
      WiiNunchuk Nunchuk = new WiiNunchuk();
      PWM pwm = new PWM(GHI.Pins.FEZPandaIII.PwmOutput.D6, PWMPeriodMicroseconds, DurationMinimum, PWM.ScaleFactor.Microseconds, false);

      pwm.Start();

      while (true)
      {
         // Reads all values
         Nunchuk.Read();

         Debug.Print(Nunchuk.AnalogStickX.ToString() + " " + Nunchuk.AnalogStickY.ToString());

         uint duration = (uint)map(Nunchuk.AnalogStickY, NunchukYMinimum, NunchukYMaximum, DurationMinimum, DurationMaximum);

         Debug.Print("Duration " + duration.ToString());
         pwm.Duration = duration;

         Thread.Sleep(100);
      }
   }

   private static long map(long x, long inputMinimum, long inputMaximum, long outputMinimum, long outputMaximum)
   {
      return (x - inputMinimum) * (outputMaximum - outputMinimum) / (inputMaximum - inputMinimum) + outputMinimum;
   }
}

I then connected the setup to my longboard ESC and it worked. (need a right angle connection for FEZ Panda III power)

Longboard with FEZ Panda III board based controller

Longboard with FEZ Panda III board based controller

The proof of concept software worked, the next step is to add throttle mapping and failure mode handling e.g. loss of communications with the Wiichuck.

NetMF Electric Longboard Part 1

When I first built my electric longboard I started with a devicter devduino V2 running a modified version of the Wiiceiver code from AustinDavid.com. This plug n play setup has worked really well and proved quite robust considering the hostile environment it is working in.

devduino V2 longboard controller, wiresless Wiichuck ESC and batteries

devduino V2 controller

I had been thinking about purchasing a dual motor kit and experimenting with traction control and anti lock braking (after a couple of close calls indoor on a tiled floor) which would require a bit more processing power.

The first version of my NetMF controller will be powered by a GHI Electronics FEZ Lemur which is an ARM Cortex M4 based System on a Chip (SoC) running at 84MHz.

The FEZ Lemur is an Arduino pinout-compatible mainboard but with the Inter-Integrated Circuit (I2C) pins on D2-Serial Data Line(SDA) and D3-Serial Clock Line (SCL).

My first proof of concept (PoC) uses a standard wii Nunchuk and some jumper wires.

FEZ Lemur and Nunchuck connected with jumper wires and seeedstudio adaptor

FEZ Lemur Wii NunChuck interface

Bill of materials (Prices in USD as at Mar 2016)

I then tested my hardware setup with an application based on the driver software written by Szymon Kobalczyk and it worked. I have used this software on a couple of projects but have never been able to get to work with my wireless Wii Nunchuk.

I compared the Arduino wiiceiver code and the C# version and found the initialisation process was different. I then did some research and found that the WiiNunChuk driver of the .Net Micro Framework Toolbox by Stefan Thoolen used a similar approach as the wiiceiver code.

using System;
using System.Threading;
using Microsoft.SPOT;
using Toolbox.NETMF.Hardware;

public class Program
{
   public static void Main()
   {
      WiiNunchuk nunchuk = new WiiNunchuk();

      while (true)
      {
         // Reads all values
         nunchuk.Read();

         Debug.Print(nunchuk.AnalogStickX + " " + nunchuk.AnalogStickY);

         Thread.Sleep(100);
      }
   }
}

I then tried the wireless Wii NunChuk device and it worked (The tape is to stop the wireless dongle falling off due to vibration when mounted on my skateboard)

FEZ Lemur Wireless Wii NunChuck interface

FEZ Lemur Wireless Wii NunChuck interface

The PoC was working so now I needed to make it more robust and plug n play. For many of my projects I use the Seeedstudio Grove system which provides plug n play digital inputs, digital outputs, analog inputs and I2C connectivity for *duino (and other) format devices.

The Seeedstudio base shield V2 can be configured for *duino devices which implement I2C connectivity on the Analog Input pins 4 & 5 or dedicated pins SDA & SCL pins.

FEZ Lemur Wireless Wii NunChuck PnP interface

FEZ Lemur Wireless Wii NunChuck interface

To get the SeeedStudion Base Shield to work with my FEZ Lemur I had to put a twist in the jumper cable to get the SDA & SCL the right way round and plug it into the D2 socket.

NOTE : put some tape on the top of the MicroSD card socket to stop a accidental short circuit.

Seeedstudio 5CM cable with SDA & SCL Pins reversed.

5CM cable with SDA & SCL Pins reversed

Connecting to G30_G30...Connected
128 128
128 128
128 128
128 128
128 128
128 128
128 128
128 170
80 209
63 255
128 255
128 255
128 255
128 255
244 255
255 255
255 250
255 210
255 128
255 128
255 128
255 107
255 5
255 0
255 0
128 0
128 0
41 0
24 0
0 103
0 128
0 128
8 235
77 255
128 255
128 255
128 128
128 128

Next step is to get inerface to the 150A Electronic Speed Control(ESC) working.

Xively GPS Location data upload V2

In the previous post I assembled the xively request XML using a StringBuilder rather than using the XML support available in the NetMF. To use the NetMF XML library I needed to add a reference to the DPWS extensions (MFDpwsExtensions) and change the using statement at the top of the module from System.Text to System.Ext.Xml

static void xivelyFeedUpdate(string ApiKey, string feedId, string channel, double latitude, double longitude, double altitude)
{
byte[] buffer;

using (XmlMemoryWriter xmlwriter = XmlMemoryWriter.Create())
{
xmlwriter.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");
xmlwriter.WriteStartElement("eeml");
xmlwriter.WriteStartElement("environment");
xmlwriter.WriteStartElement("location");

xmlwriter.WriteStartAttribute("domain");
xmlwriter.WriteString("physical");
xmlwriter.WriteEndAttribute();

xmlwriter.WriteStartAttribute("exposure");
xmlwriter.WriteString("outdoor");
xmlwriter.WriteEndAttribute();

xmlwriter.WriteStartAttribute("disposition");
xmlwriter.WriteString("mobile");
xmlwriter.WriteEndAttribute();

xmlwriter.WriteStartElement("name");
xmlwriter.WriteString("Location");
xmlwriter.WriteEndElement();

xmlwriter.WriteStartElement("lat");
xmlwriter.WriteString(latitude.ToString("F5"));
xmlwriter.WriteEndElement();

xmlwriter.WriteStartElement("lon");
xmlwriter.WriteString(longitude.ToString("F5"));
xmlwriter.WriteEndElement();

xmlwriter.WriteStartElement("ele");
xmlwriter.WriteString(altitude.ToString("F1"));
xmlwriter.WriteEndElement();

xmlwriter.WriteEndElement();
xmlwriter.WriteEndElement();
xmlwriter.WriteEndElement();

buffer = xmlwriter.ToArray();
}

try
{
using (HttpWebRequest request = (HttpWebRequest)WebRequest.Create(xivelyApiBaseUrl + feedId + ".xml"))
{
request.Method = "PUT";
request.ContentLength = buffer.Length;
request.ContentType = "text/xml";
request.Headers.Add("X-ApiKey", xivelyApiKey);
request.KeepAlive = false;
request.Timeout = 5000;
request.ReadWriteTimeout = 5000;

// request body
using (Stream stream = request.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);                }
using (var response = (HttpWebResponse)request.GetResponse())
{
Debug.Print("HTTP Status:" + response.StatusCode + " : " + response.StatusDescription);
}
}
}
catch (Exception ex)
{
Debug.Print(ex.Message);
}
}

I was expecting the XML libraries to be quite chunky, but on my Netduino Plus 2 there wasn’t a huge size difference, the StringBuilder download was 49K8 bytes and the XMLWiter download was 56K1 bytes.

When I ran the StringBuilder and XMLWriter versions they both had roughly 92K6 bytes of free memory.

Realistically there was little to separate the two implementations

Xively GPS Location data upload V1

For one of the code club projects we looked at the National Marine Electronics Association (NMEA) 0183 output of my iteadStudio GPS Shield + Active Antenna. We used the NetMF Toolbox NMEA GPS processing code with a couple of modifications detailed here.

IteadStudio GPS

IteadStudio GPS shield and Antenna

For another project we had used Xively a “Public Cloud for the Internet of Things”. The Xively API has support for storing the position of a “thing” and it didn’t look like it would take much effort to extend the original GPS demo to trial this. The xively Location & waypoints API is RESTful and supports JSON & XML

void xivelyFeedUpdate(string ApiKey, string feedId, string channel, double latitude, double longitude, double altitude)
{
try
{
using (HttpWebRequest request = (HttpWebRequest)WebRequest.Create(xivelyApiBaseUrl + feedId + ".xml"))
{
StringBuilder payload = new StringBuilder();
payload.Append(@"<?xml version=""1.0"" encoding=""UTF-8""?><eeml><environment><location domain=""physical"" exposure=""outdoor"" disposition=""mobile""><name>Location</name><lat>");
payload.Append(latitude.ToString("F5"));
payload.Append("</lat><lon>");
payload.Append(longitude.ToString("F5"));
payload.Append("</lon><ele>");
payload.Append(altitude.ToString("F1"));
payload.Append("</ele></location></environment></eeml>");

byte[] buffer = Encoding.UTF8.GetBytes(payload.ToString());

request.Method = "PUT";
request.ContentLength = buffer.Length;
request.ContentType = "text/xml";
request.Headers.Add("X-ApiKey", xivelyApiKey);
request.KeepAlive = false;
request.Timeout = 5000;
request.ReadWriteTimeout = 5000;

// request body
using (Stream stream = request.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);
}
using (var response = (HttpWebResponse)request.GetResponse())
{
Debug.Print("HTTP Status:" + response.StatusCode + " : " + response.StatusDescription);
}
}
}
catch (Exception ex)
{
Debug.Print(ex.Message);
}
}

The position of the “thing” is displayed like this

Xively poisition

The position of my car

The XML was constructed using a stringbuilder (NetMF 4.2) as this appeared easier/smaller than using the baked in XML functionality.

Netduino Plus PulseRate Monitor V2

In the final couple of code club sessions we built a pulse rate monitor to show a practical application for the NetMF InterruptPort, and communication between threads using the Interlocked class (Increment & exchange). This was then enhanced to display the data locally and upload it to the cloud to illustrate a basic HTTP interaction and serial communications.

The application displays the approximate pulse rate in Beats Per Minute (BPM) on a 16×2 character LCD display and also uploads the information to a free developer account at Xively a “Public Cloud for the Internet of Things”.

Netduino Plus 2 rate monitor

The xively trial account has a limit of 25 calls a minute, rolling 3 minute average (Dec 2013) which was more than adequate for our application and many other educational projects.

The xively API supports managing products, managing devices,  reading & writing data, reading & wiring metadata, querying historical data and searching for data feeds, using a RESTful approach.

The NetduinoPlus2 has full support for the NetMF system.http and sufficient memory so that there is plenty of room left for an application. If you are using a Netduino Plus (or other NetMF device with limited memory) an approach which reduces memory consumption is detailed here.

The xively data API supports JSON, XML and CSV formats for upload of data and for the pulse rate monitor we used CSV. The following code was called roughly every 20 seconds.

static void xivelyFeedUpdate( string ApiKey, string feedId, string channel, string value )
{
try
{
using (HttpWebRequest request = (HttpWebRequest)WebRequest.Create(xivelyApiBaseUrl+ feedId + ".csv"))
{
byte[] buffer = Encoding.UTF8.GetBytes(channel + "," + value);


request.Method = "PUT";
request.ContentLength = buffer.Length;
request.ContentType = "text/csv";
request.Headers.Add("X-ApiKey", ApiKey);
request.KeepAlive = false;
request.Timeout = 5000;
request.ReadWriteTimeout = 5000;


// request body
using (Stream stream = request.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);
}


using (var response = (HttpWebResponse)request.GetResponse())
{
Debug.Print("HTTP Status:" + response.StatusCode + " : " + response.StatusDescription);
}
}
}
catch (Exception ex)
{
Debug.Print(ex.Message);
}
}

The pulse rate information can then displayed by xively in tables and graphs.

Pulse Rate data gaph at xively

Pulse Rate data display

At the end of term presentation several parents and family members were doing press-ups and other exercises to see how high their pulse rate went and how quickly it recovered.

Bill of materials (Prices as at Dec 2013)

SeeedStudio Grove GPS IteadStudio Shield Comparison

I use the SeeedStudio Grove system for prototyping and teaching. One of the modules is a Global Positioning System (GPS) unit based on the u-blox 5 engine. To get this unit to work you just plug it into the UART socket on the base shield and load the necessary software onto an Arduino (or compatible) board. My day job is working on Microsoft .Net applications so I use a Netduino Plus or a Netduino plus 2.

SeeedStudio GPS unit

SeeedStudio base shield and GPS unit

The Seeedstudio 4 wire connector system has some advantages but for a couple of projects I was looking at I needed to be able to run on a different serial port and access the one pulse per second output. I had a look at several other vendors and the iteadstudio GPS Shield + Active Antenna which is based on the u-blox 6 engine looked like a reasonable alternative.

IteadStudio GPS

IteadStudio GPS shield and Antenna

After some testing I found that the Iteadstudio GPS shield appears to have a shorter time to first fix after a power cycle, I averaged 10 sets of readings for each device and found that in my backyard it took on average 46sec for the Iteadstudio shield and 55sec for the SeeedStudio device.

Both devices output National Marine Electronics Association (NMEA) 0183 sentences and I use the NetMF Toolbox NMEA code to process the data streams. I have modified the NetMF toolbox code with an additional event handler which empties the serial input buffer if there is an error and one of the validation checks needed to be tweaked as it was possible to get an exception due to an empty string.

Around line 45

this._Uart = newSerialPort(SerialPort, BaudRate);
this._Uart.ErrorReceived += newSerialErrorReceivedEventHandler(_Uart_ErrorReceived);
this._Uart.DataReceived += newSerialDataReceivedEventHandler(_Uart_DataReceived);


void _Uart_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
{
if (_Uart.IsOpen)
{
_Uart.Flush();
}
}

Around line 323

// Have we received a full line of data?
int Pos = this._Buffer.IndexOf("\r\n");
if (Pos >= 1)
{

With these modifications my Netduino Plus 2 can runs for days at a time without buffer overflows or other issues, you just need to be careful to make your event handlers block for as little time as possible.

I have been looking at building an NetMF NMEA driver which runs on a background thread and doesn’t use any string manipulation methods e.g. string.splt so the garbage collector has less to do, but this will be a topic for a future post.

HTTP Headers Request reduction

The requests generated by the HTTP_Client were a bit chunky with user-agent strings, content type etc.

POST http://gpstrackerhttpheaders.cloudapp.net/posV4.aspx HTTP/1.1
Accept: */*
Accept-Language: en
User-Agent: NETMFToolbox/0.1 (textmode; Netduino; IntegratedSocket; HTTP_Client)
Host: gpstrackerhttpheaders.cloudapp.net
x-Pos: 5C-86-4A-00-3F-63 20130130080711 F -43.00000 172.00000 16.9 1.28 0 0
Content-Type: application/x-www-form-urlencoded
Content-Length: 0
Connection: Close

I then modified the HTTP_Client so that the accept, accept language, user agent, and content Type headers could be removed if not necessary.

POST http://gpstrackerhttpheaders.cloudapp.net/posV4.aspx HTTP/1.1
Host: gpstrackerhttpheaders.cloudapp.net
x-Pos: 5C-86-4A-00-3F-63 20130130081228 F -43.00000 172.00000 31.4 1.31 0 0
Content-Length: 0
Connection: Close

This reduced the size of the request down to 186 bytes which was comparable with the smallest System.http HTTPRequest. But, the durations looked a bit odd..

1295,1381,1323,1347,1281,1264,1351,1305,1350,1269
Average duration 1317 mSec

This was roughly 200mSec slower than the larger request version. After some digging I think the TCP socket was buffering (Nagle algorithm send coalescing) the send.

I then modified IntegratedSocket.cs connect method to disable this buffering

EndPoint Destination = new IPEndPoint(address.AddressList[0], (int)this._Port);
// Connects to the socket
this._Sock.Connect(Destination);
this._Sock.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);

I then checked the request durations again

10 requests to gpstrackerhttpheaders.cloudapp.net
1026,1248,983,1027,966,843,1009,983,834,915
Average duration 983 mSec

10 requests to IP Address
584, 595,578,597,581,595,577,593,580,599
Average duration 588 mSec

These were faster than any of the results with the baked in HttpWebRequest in System.http.

So I fired up .Net Reflector and had a look at the decompiled System.http code and though there are calls socket.SetSocketOption in EstablishConnection I can’t see any way for a user to set the NoDelay socket option as allowWriteStreamBuffering appears not to be used.