Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.

AxelG's Content

There have been 52 items by AxelG (Search limited from 26-April 23)


By content type

See this member's


Sort by                Order  

#33447 Netduino Firmware v4.2.0 RC5 (Netduino + Netduino Plus)

Posted by AxelG on 11 August 2012 - 03:54 PM in Beta Firmware and Drivers

Hi AxelG,

Just to confirm... You're connecting two Netduinos together and are using flow control...and are losing data?


Yes, that is the scenario. Using no flow control works well as long as I can read data fast enough. I am going to play with various baud rates and see what changes.

If that's the scenario, does the same thing happen when you connect two serial ports together on one Netduino?

I will try that.


P.S. RC6 should be shipping in a few days. There is a serial port bugfix that recently made it into the NETMF core...so we may want to hold off digging in for a few days and see if the bugfix is related.

Cool. I will try that as well.



#33377 Netduino Firmware v4.2.0 RC5 (Netduino + Netduino Plus)

Posted by AxelG on 10 August 2012 - 03:54 PM in Beta Firmware and Drivers

Testing scenario for Serial Ports in 4.2 RC5

Scenario:
  • Hooked up a ND to ND+ on COM2 (TX to RX)
  • ND was sender, ND+ was reader
  • ND had no flow control, ND+ was set to Handshake.RequestToSend
  • Logic Analyzer was hooked to RX, TX and RTS/CTS pins on ND+
  • Wrote two applications, Reader and Sender (Projects.zip)
  • Sender running on ND sends 200 byte packages to reader running on ND+
  • Reader reads the 200 byte blocks and reports on whether it got all of the data.

Outcome:
  • Handshake.RequestToSend seems to have no affect on the hardware.
  • Sending the data slowly enough for the reader to stay caught up with the writer works fine.
  • When the reader goes off to do something else (simulated by a Thread.Sleep()) the SerialPort.Read() method throws “System.ArgumentException” (Debug 2.txt)
  • If the writer sends data to the buffer (SerialPort.Write() method) too fast, the “SerialErrorReceivedEventHandler” handler fires with “SerialError.TXFull”
One Solution Idea:
  • Use XON/XOFF flow control.
  • Set no delay in reading the data.
  • Set one second delay between sending packages.
Outcome:
  • Lost data. Reading the packages as fast as possible shows lost data (Debug 3.txt) This happens even when sending data in 200 byte packages with a delay between packages.
  • Turning off flow control, fixes the problem at slow speeds, until you set a read delay which causes data loss.

Any ideas on how I can send large blocks of data without losing bytes?

Attached Thumbnails

  • LA Failure.jpg

Attached Files




#33454 Netduino Firmware v4.2.0 RC5 (Netduino + Netduino Plus)

Posted by AxelG on 11 August 2012 - 08:43 PM in Beta Firmware and Drivers

Chris:
Thanks for the feedback. Here is how I spent my morning.

I used one ND with COM1 hooked to COM2 and got exactly the same results. All works fine as long as I can read the data fast enough. If not, there are very unpredictable results including crashing the ND. If I use any type of handshake; all bets are off and data is lost. I will eagerly await the RC6 build and re-test.

(I have not ported this back to 4.1 to see what happens there, that would require reflashing my NDs. and I am basically lazy that way! :) )


Here is another very peculiar thing related to serial ports. I posted about this in an earlier thread concerning 'System.InvalidOperationException' in the 'System.IO.Ports.SerialPort.HandlePinReservations' call. I am wondering if my 4.2 implementation is FUBAR? Here is the scenario:

Running a simple test application:
using System.IO.Ports;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;


namespace NetduinoApplication2
{
    public class Program
    {
        public class netduino
        {
            //Changing from const to static causes the sp.Open() method to throw a 'System.InvalidOperationException' Exception
            public const Cpu.Pin SomePin = Pins.GPIO_PIN_A4;
            //public static Cpu.Pin SomePin = Pins.GPIO_PIN_A4;
            public InterruptPort SomeInterrupt = new InterruptPort(SomePin, true, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth);
        }

        protected static netduino MCU = new netduino();

        public static void Main()
        {
            SerialPort sp = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One);
            sp.Open();
            Debug.Print("finished OK!");
        }
    }
}

Notice the definition for SomePin. If I define SomePin as static, the debug trace looks like this on the sp.Open() call:
Step into: Stepping over non-user code 'System.IO.Ports.SerialPort.Open'
Step into: Stepping over non-user code 'System.IO.Ports.SerialPort.Open'
Step into: Stepping over non-user code 'System.IO.Ports.SerialPort.HandlePinReservations'
Step into: Stepping over non-user code 'Microsoft.SPOT.Hardware.HardwareProvider.HwProvider.get'
Step into: Stepping over non-user code 'System.IO.Ports.SerialPort.HandlePinReservations'
Step into: Stepping over non-user code 'System.IO.Ports.SerialPort.HandlePinReservations'
A first chance exception of type 'System.InvalidOperationException' occurred in Microsoft.SPOT.Hardware.dll
Step into: Stepping over non-user code 'System.IO.Ports.SerialPort.HandlePinReservations'
A first chance exception of type 'System.InvalidOperationException' occurred in Microsoft.SPOT.Hardware.SerialPort.dll
An unhandled exception of type 'System.InvalidOperationException' occurred in Microsoft.SPOT.Hardware.SerialPort.dll

If I define as a const, all is good and no exception.

Not to make this even more confusing, but when I run the debugger and step through the code, when I get to the call for 'HandlePinReservations' I get a dialog box asking me to locate the following file:
C:\Documents\Secret Labs\Projects\Production\SecretLabs.NETMF.Hardware.Netduino\NetduinoHardwareProvider.cs (See attachment SourceScreen.jpg)

Any ideas on what is going on and where I might go next? The loss of data part is really the troubling part. I need to have an effective handshake so I can read and process larger chunks of data.

Attached Thumbnails

  • Source Screen.JPG



#33883 Netduino Firmware v4.2.0 RC5 (Netduino + Netduino Plus)

Posted by AxelG on 18 August 2012 - 11:24 PM in Beta Firmware and Drivers

Chris: I just confirmed that the same serial port issue exists in the latest 4.2 build (posted three days ago) If I use any flow control, I lose data. If I don't use flow control, I have to make sure to read data fast enough.... This happens with one ND, COM1 to COM2 or two netduinos connected with null-modem cable.



#34567 Netduino Firmware v4.2.0 RC5 (Netduino + Netduino Plus)

Posted by AxelG on 02 September 2012 - 04:28 PM in Beta Firmware and Drivers

Any idea on what I should try next? I hit a wall with the serial port problems in this 4.2 build and really can't move forward until they are working.



#33370 Netduino Firmware v4.2.0 RC5 (Netduino + Netduino Plus)

Posted by AxelG on 10 August 2012 - 01:02 PM in Beta Firmware and Drivers

Hi AxelG,

From the logic analyzer...can you tell where the data is being lost? Is it being lost on the Netduino (i.e. buffer overflow)?

Chris


If you look at the data in Data.jpg, that is the data coming from the XBee into the ND, and all of the bytes are in that stream. I can only assume the data is getting lost after it enters the Netduino. I am working on a Netduino to Netduino set of applications to reproduce. So far I am able to force the same exception I was seeing in the 4.1 release:

"A first chance exception of type 'System.ArgumentException' occurred in Microsoft.SPOT.Hardware.SerialPort.dll
Exception: Exception was thrown: System.ArgumentException param name stack System.IO.Ports.SerialPort::Read
NDPlusSerialReader.Program+DoReader::Serial_DataReceived
System.IO.Ports.SerialPort::DataEventHandler"

I will post more later today.



#33881 Netduino Firmware v4.2.0 RC5 (Netduino + Netduino Plus)

Posted by AxelG on 18 August 2012 - 10:43 PM in Beta Firmware and Drivers

Arbiter: When I do that, all works well. I am trying to abstract the hardware later from the rest of my code. I need to know what pin was used later because I share interrupts and what to know which pin caused the interrupt.



#33161 Netduino Firmware v4.2.0 RC5 (Netduino + Netduino Plus)

Posted by AxelG on 06 August 2012 - 12:30 PM in Beta Firmware and Drivers

HI AxelG,


Can you post a small repro app for us to look at? Generally speaking, NETMF 4.1 code should run as-is under NETMF 4.2.

Chris


I will try to later this week, but this is part of a larger program and I will need to create a smaller app to reproduce. Basically, I am defining the port, then assigning some interrupts and event handlers, and then opening the port - which is where I get this failure; but only on COM2. COM1 works fine...

I was also dealing with BSODs yesterday and just decided to update all my NDs to 4.2. That helped a lot; but still getting them on reboots.



#33120 Netduino Firmware v4.2.0 RC5 (Netduino + Netduino Plus)

Posted by AxelG on 04 August 2012 - 07:08 PM in Beta Firmware and Drivers

I finally got around to upgrading to 4.2 to enable the SD card on my ND. Worked great. Took a bit of "translation" for the pinouts as it seems that nobody calls SPI pins the same thing. After getting that to function, I updated my code to 2.4 libraries, recompiled and now I am throwing the following error when opening up COM2: A first chance exception of type 'System.InvalidOperationException' occurred in Microsoft.SPOT.Hardware.dll A first chance exception of type 'System.InvalidOperationException' occurred in Microsoft.SPOT.Hardware.SerialPort.dll An unhandled exception of type 'System.InvalidOperationException' occurred in Microsoft.SPOT.Hardware.SerialPort.dll I change to COM1; everything is fine. I tried forcing Handshaking to be none (I am not using pins 7 or 8 for anything else, nor am I using pins 2 or 3 for anything else) Any ideas where I should look next? Runs fine on my ND+ under 4.1 (I am sure it is something obvious)



#33347 Netduino Firmware v4.2.0 RC5 (Netduino + Netduino Plus)

Posted by AxelG on 10 August 2012 - 02:28 AM in Beta Firmware and Drivers

HI AxelG,


Can you post a small repro app for us to look at? Generally speaking, NETMF 4.1 code should run as-is under NETMF 4.2.

Chris


I wound up flashing my ND+ to 4.2 anyway and noticed a couple things:
1) My USB is a lot more stable - no more BSODs (I also removed a bluetooth driver that may have been causing problems)
2) The extra code space is nice! Thanks.
3) I am seeing strange behavior with the Serial Port - losing data. (Posting a separate thread)
4) The COM2 problem went away (ArgumentOutOfRange no longer happens when opening the COM port.



#33348 Netduino Firmware v4.2.0 RC5 (Netduino + Netduino Plus)

Posted by AxelG on 10 August 2012 - 02:51 AM in Beta Firmware and Drivers

Unusual behavior with Serial Ports in 4.2 RC5 on ND and ND+ (Losing data…)

I have a project that requires two XBee/ZigBee modems to communicate and transfer large (for Zigbee) data packets from 1k to about 100k in size.

My plan is to use SD cards to buffer data as it come in and goes out the modems, stitching the packets together as they come in. Simple enough….

I am using the Grommet (Copyright © 2009 http://grommet.codeplex.com) drivers for the low-level networking, which I really like because they started out very light-weight and I made them lighter by removing some methods I will not need.

The project is too large to post the entire code base in this thread, but I plan to post later on as an extension of these drivers.

Here is my trouble: I am losing data after the receiving XBee passes it to the ND/ND+ and when it is read out of the serial buffer. Attached is the Logic trace showing data leaving XBee #1, and being passed from XBee #2 into the ND. The data loss happens at different places at different times. If I slow the transmissions way down (one message every two seconds) I get nearly zero lost bytes. As soon as I remove this delay; lost data.

Here is the setup:
  • ND with XBee1 and SD shield on SPI
  • ND+ with XBee2 and SD card installed
  • Both ND/ND+ share common XBee drivers codebase (All XBee and serial port code is shared)
  • I have tried hardware flow control on both ND/ND+ and is enabled on XBee.
  • (As a footnote, CTS never de-asserts on either XBee, it always remains low, and never goes low on ND)
  • I have SerialErrorReceivedEventHandler enabled, and it never fires.
  • Everything is running at 9600 baud, 8N1. (I want to try faster speeds to see if that makes a difference, but CTS flow control should handle buffering data for me?)

Attached is a far-away view of the data in the LA. The left side is showing the modem setup exchange, and the right side is showing the data packets: you can see the packeting leaving one XBee and arriving at the other… These are two messages with 200 byte packages.

Also attaching a zoomed in view to compare with what I am reading out of the Serial Port buffer.

Here is the code that is reading the buffer. Fairly simple. Called by the SerialDataReceivedEventHandler event:
private void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {

            //One at a time please....
            lock (readLock)
            {
                Debug.Print("Read unlocked with " + SerialPort.BytesToRead + " bytes to read");

                //FIXIT - May not need, but for some reason the event fires with nothing to read....
                int timeout = 100;
                while (SerialPort.BytesToRead <= 0 && timeout-- > 0) Thread.Sleep(10);

                byte[] buf = new byte[1];
                if (SerialPort.BytesToRead > 0)
                {
                    try
                    {
                        while (SerialPort.BytesToRead > 0)
                        {
                                
			   //If there is data, there is a incomplete frame, and we have a complete header
                            while ((SerialPort.BytesToRead > 0) && 
                                  (!frameBuilder.IsComplete) && 
                                  (frameBuilder.HeaderIsComplete)))
                            {
			       //Don’t forget about the checksum byte…  The + 1
                                byte[] buffer = new byte[frameBuilder.dataNeeded + 1];
                                //reading the data frame and the checksum byte
                                int bytesRead = SerialPort.Read(buffer, 0, frameBuilder.dataNeeded + 1);
                                Debug.Print("Read chunk of " + bytesRead.ToString() + " f: " + buffer[0].ToString() + " l: " + buffer[bytesRead-1].ToString() + " need " + (frameBuilder.dataNeeded + 1).ToString());
                                //Add the newly read data to the framBuilder buffer
                                frameBuilder.Append(buffer, bytesRead);
                            }
                            if (frameBuilder.IsComplete)
                            {
                                // got a frame, do something
                                ReceivedApiFrame(frameBuilder.GetApiFrame());
                                // Create a thread, launch fire event, etc
                                frameBuilder.Reset();
                            }
			    //Check to see is a header needs to be read (first three bytes)
                            if ((!frameBuilder.HeaderIsComplete) && (SerialPort.BytesToRead > 0))
                            {
                                SerialPort.Read(buf, 0, 1);
                                Debug.Print("Read byte for header " + buf[0].ToString());
                                frameBuilder.Append(buf, 1);
                            }
                            //Don't beat a hasty retreat after reading the frame…
                            timeout = 100;
                            while (SerialPort.BytesToRead <= 0 && timeout-- > 0) Thread.Sleep(10);
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.Print("Error reading data from serial " + ex.Message);
                    }
                }
                else Debug.Print("Nothing to read");//FIXIT – Get rid of this if() in production, ignore

                Debug.Print("Ending read " + local.ToString());
            }
        }

Here is the relevant Debug file to try and convince myself I am not going nuts... The data is really not there...

Read byte for header 126 <- good
Read byte for header 0 <- good
Read byte for header 212 <- good
Allocated 212 bytes to API Frame <- reading 200 bytes plus Zigbee frame
Read chunk of 16 f: 144 l: 52 need 213 <- extra room for checksum byte
Read chunk of 16 f: 34 l: 109 need 197
Read chunk of 15 f: 101 l: 109 need 181
Read chunk of 14 f: 32 l: 50 need 166
Read chunk of 15 f: 48 l: 87 need 152
Read chunk of 15 f: 97 l: 100 need 137
Read chunk of 14 f: 60 l: 48 need 122
Read chunk of 15 f: 54 l: 48 need 108
Read chunk of 15 f: 58 l: 99 need 93
Read chunk of 14 f: 114 l: 100 need 78
Read chunk of 15 f: 97 l: 49 need 64
Read chunk of 14 f: 32 l: 97 need 49
Read chunk of 15 f: 114 l: 105 need 35
Read chunk of 17 f: 99 l: 100 need 20
Read chunk of 3 f: 97 l: 110 need 3 <- finished, without checksum error!
Resetting frame
Staring processing thread… <- thread off to process the packet
(Here is where it goes horribly wrong….)
Read byte for header 126 <- good, found header start byte
Read byte for header 162 <- BAD! This is NOT a valid high-byte length
Error in length: 162
Resetting frame
Read byte for header 0
ERROR!!! Expected start byte: 0
Read byte for header 64
ERROR!!! Expected start byte: 64
Read byte for header 141
ERROR!!! Expected start byte: 141
Read byte for header 28
ERROR!!! Expected start byte: 28
Read byte for header 195
ERROR!!! Expected start byte: 195


The serial buffer contained the following bytes: (Refer to the attached LA image)
126(~), 162, 0, 64(@), 141, 28, 195…
But the XBee sent the following to the ND:
126(~), 0, 212, 144, 0, 19, 162, 0, 64(@), 141, 28, 195…
MISSING BYTES

Any ideas are welcome. I need to get some sleep!

Attached Thumbnails

  • Analyzer.jpg
  • Data.jpg



#42831 4X20 LCD display with I2C Interface

Posted by AxelG on 05 January 2013 - 10:23 PM in Project Showcase

I attached the driver code to the first post.




#42926 4X20 LCD display with I2C Interface

Posted by AxelG on 07 January 2013 - 06:48 PM in Project Showcase

I have these working just fine on a N+2:

 

Here is a video of it working on my BoxCar:

 

http://sdrv.ms/UwMKxE

 

LMK if you want a code sample.

 

I would love to see the code samples!




#46286 4X20 LCD display with I2C Interface

Posted by AxelG on 27 February 2013 - 02:28 AM in Project Showcase

I looked at my code again, and it is not what you are looking to do, but here are the display methods so you can see what I did:

 

        /// <summary>        /// Writes a string array to the device.  Truncates strings to the number of columns allowed,         ///  or wraps if enough room.        /// </summary>        /// <param name="data">string array with each element mapped to a line on the LCD.  Will         ///   truncate if too many are sent</param>        /// <param name="format">C = center each line</param>        private void write(string[] data, char format = ' ')        {            int NumRows = data.Length;            if (NumRows > _rows) NumRows = _rows;            //base.clear();            //truncate the strings, and center if needed            lock (LCDLock)            {                for (int i = 0; i < NumRows; i++)                {                    if (data[i].Length > _cols) data[i] = data[i].Substring(0, _cols);                    if(data[i].Length != 0) write(data[i], 0, (byte)i, format);                }            }        }        /// <summary>        /// Takes in a string, and breaks it up into four strings suitable for the display        /// </summary>        /// <param name="value">String to be converted</param>        /// <returns>string array containing one element for each row on the display</returns>        public string[] MakeTextBlock(string value)        {            int LastSpace = 0;            string[] TextBlock = new string[_rows];            for (int i = 0; i < _rows; i++) TextBlock[i] = "";            for (int pass = 0; pass < _rows; pass++)            {                int SegLen = _cols;                if (value.Length < LastSpace + _cols) SegLen = value.Length - LastSpace;                int ThisSpace = 0;                string part = value.Substring(LastSpace, SegLen);                ThisSpace = part.Length;                if (part.Length >= _cols)                {                    for (int i = 0; i < part.Length; i++) if (part[i] == ' ') ThisSpace = i;                }                TextBlock[pass] = part.Substring(0, ThisSpace);                LastSpace += ThisSpace + 1;                if (LastSpace >= value.Length) break;            }            return TextBlock;        }        /// <summary>        /// Write the string at a specific location, with a specific formatting        /// </summary>        /// <param name="value">Value to display</param>        /// <param name="col">Starting column </param>        /// <param name="row">Row to display</param>        /// <param name="format">C = Centered on the row</param>        private void write(string value, byte col, byte row, char format = 'c')        {            string NewString = "";            if ((format == 'c' || format == 'C') && value.Length < _cols && col == 0)            {                for (int space = 0; space < (_cols - value.Length) / 2; space++) NewString += " ";                NewString = NewString + value;            }            else NewString = value;            lock (LCDLock)            {                base.setCursor(col, row);                write(NewString);                //if (row == TEMPROW && NewString.Trim().Length != 0) LastTempLine = DateTime.Now;            }        }        /// <summary>        /// Send string to the current cursor position        /// If the string is longer than number of columns, the string will be broken        ///   up into parts and written across multiple lines.        /// </summary>        /// <param name="value">string value to display</param>        private void write(string value)        {            if (value.Length > _cols)            {                write(MakeTextBlock(value), 'c');            }            else            {                byte[] Buffer = Tools.Chars2Bytes(value.ToCharArray());                lock (LCDLock)                    base.write(Buffer);            }        }



#46201 4X20 LCD display with I2C Interface

Posted by AxelG on 25 February 2013 - 03:54 AM in Project Showcase

Thanks for the great project! I was wondering if you would be able to post you display class so I can see how you implement the LCD sreen? Thanks again!

Sorry it has taken some time to respond, I have been working on another project and just now getting back here.  I moved the MakeTextBlock() method into a display class that is quite specific to my project and may not make much sense posted as a helper-class.

 

Essentially this method uses a four element array of strings, one fore each line of the display.  This way it is easy to handle wrapping text on the screen; pass in a large string and the string gets broken into four smaller strings broken at the space character (and optionally centered on each line)

 

I can look at breaking out a more generic class if you are still interested; but it really isn't anything that special...




#42743 4X20 LCD display with I2C Interface

Posted by AxelG on 04 January 2013 - 11:06 PM in Project Showcase

I updated my code to call the reset() method every time I need to clear the LCD, and that has worked all day today with 1,000+ screen updates an no garbage.  Seems like bruit-force approach but is seems to be working for now.

 

I also posed the driver code if anyone is interested.




#42715 4X20 LCD display with I2C Interface

Posted by AxelG on 04 January 2013 - 02:58 PM in Project Showcase

My holiday present to myself this year was the following 4X20 LCD: (link)

 

It is based on the HD4478 LCD driver chip, front ended with an I2C interface, popular because it only uses two ports on your MCU.

 

The information provided by the vendor is sparse, and in some cases incorrect.  The address of the device is listed as 0X27 but is actually 0x3F.  I was able to locate the Arduino (C++) driver for the I2C interfaced version, so I translated the Arduino driver into C#.

 

I then integrated Stefan Thoolens (http://www.netmftoolbox.com/) MultiI2C class to drive the I2C port.

 

After playing with the timing on the initialization a bit, it seems to be working well.  I added some text management methods to the driver to simplify displaying text on four lines.  The LCD is set up in such a way that it is actually driving two 40 character lines of text, wrapped on the screen.  This made it confusing for me to keep straight, so these new methods made it easier to keep track of the text.

 

Hardware connection is a snap.  Netduino (running 4.2) connected with 5v, ground, A4, and A5 to the LCD module.  This LCD is using an I2C interface, so you need pullups on the A5 and A4 wires.  I used 2.2k (corrected to 1.8k below) resistors on the 3V3 port.  Worked great.

 

One nagging issue is that after running for some time, the screen will start displaying garbled data.  I have not been able to pinpoint the reason; maybe bus speed, bad data wires, poor power?  If I figure that out, I will post an update.***

 

Thanks to everyone on the forum for inspiration and ideas to get this working; especially Stefan for a great toolbox.  Let me know what bugs you find or ideas on improvements.

 

***UPDATE: The garbage issue is resolved: I think.

Problem was that my pullup resistors were too high of a value (changed for 1k8.  I remembered my analog circuit class I took 30 years ago and realized these resistors are part of a RC circuit that affect the signal shape on the wire.  To high = smaller slope.  There was also a small bug in the code that was not sending the initialization bytes correctly (I will upload the working copy.  I also moved some of the text management methods out of this class into a separate display class)

Attached Files




#42733 4X20 LCD display with I2C Interface

Posted by AxelG on 04 January 2013 - 07:44 PM in Project Showcase

Thanks for the quick replies.

 

I wrote a reset() method in the driver, and I have attached it to the onboard switch.  Hitting the switch resets the screen.  Seems like there should be a better way...

 

Maybe I will remove the i2c interface and go to a native HD4478 8 bit driver...




#33874 Announcing: .NET MF 4.2 upgrade for all Netduino hardware

Posted by AxelG on 18 August 2012 - 04:55 PM in General Discussion

Great News! I was able up update my ND/ND+ and everything went really well! Easy.... Thanks for the updates!



#43718 Netduino Plus 2 and LCD 20x4

Posted by AxelG on 19 January 2013 - 01:27 AM in Netduino Plus 2 (and Netduino Plus 1)

I used the same exact hardware on the ND and ND+ (version 1) and posed an article with light-weight driver here.




#29351 DHCP issues with Netduino Plus

Posted by AxelG on 17 May 2012 - 10:06 PM in Beta Firmware and Drivers

Hoping to keep the discussion moving on the socket-related questions. I am new to the Netduino Plus with about 2 weeks under my belt of playing with it. A lot of my time is spent in .NET Visual Studio Emulator mode and moving to the hardware when I need to work on the hardware integration parts. I have noticed a few quirks with various differences between emulator and hardware deployed versions; this socket problem is one I am playing with and have not found a reliable workaround; yet. I reset all of my networking settings to static IP through MFDeploy.exe, and make my router aware of the NDP MAC address and reserved IP address; until I get a successful network ping on that static IP address. This sometimes takes a couple router resets to get right so Netduino responds to a ping. I am running a "tried-and-true" windows socket service on port 8484 on a completely different server. It is a basic service listening on port 8484 for a simple "HELLO" to come across the Tcp socket. The following snippet of a program works fine in emulator mode and I can connect 100% of the time. When I deploy to the hardware; no good. It sometimes connects, and generally stays connected; but when it fails to connect - forget it. It just keeps timing out. (this code is in a loop that keeps trying to connect until it does in the "real" software) I am including code and the associated debug output. Any insight on what I can try next would be helpful. Oh, I flashed to 4.1.1 from 4.1.0.6 and fixed my SD card issues; but seemed to make this issue worse (but I may have just been tired and hopped up on Coke Zero...) I have not tried 4.2 yet. -->(snip)<-- public class Program { public static void Main() { int port = 8484; string server = "192.168.5.102"; ShowNetworks(); try { Debug.Print("Defininig new socket "); Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Debug.Print("Defininig new static endpoint and connecting to "+ server + "on port " + port.ToString()); IPHostEntry hostEntry = Dns.GetHostEntry(server); serverSocket.Connect(new IPEndPoint(hostEntry.AddressList[0], port)); Debug.Print("Sending a HELLO statemnt to the waiting service"); Byte[] bytesToSend = Encoding.UTF8.GetBytes("HELLO\n" + "12345678910\n"); serverSocket.Send(bytesToSend, bytesToSend.Length, 0); } catch (SocketException se) { Debug.Print("SocketException when connecting to " + server + "."); Debug.Print("Socket Error Code: " + se.ErrorCode.ToString()); Debug.Print(se.ToString()); } } private static void ShowNetworks() { NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in adapters) { int i = 0; foreach (string s in adapter.DnsAddresses) { i++; Debug.Print("DNS Address : " + s); } if (i == 0) Debug.Print("No DNS Address"); Debug.Print("Default Gateway: " + adapter.GatewayAddress); Debug.Print("IP Address : " + adapter.IPAddress); Debug.Print("Is DHCP Enabled: " + adapter.IsDhcpEnabled); Debug.Print("Is Dynamic DNS : " + adapter.IsDynamicDnsEnabled); Debug.Print("Interface Type : " + adapter.NetworkInterfaceType.ToString()); Debug.Print("MAC Address : " + ToHexString(adapter.PhysicalAddress)); Debug.Print("SubnetMask : " + adapter.SubnetMask + "\n"); } } } -->(Debug Output)<-- No DNS Address Default Gateway: 192.168.5.1 IP Address : 192.168.5.50 Is DHCP Enabled: False Is Dynamic DNS : False Interface Type : 6 MAC Address : 5C-86-4A-00-4F-1D SubnetMask : 255.255.255.0 Defininig new socket Defininig new static endpoint and connecting to 192.168.5.102on port 8484 #### Exception System.Net.Sockets.SocketException - CLR_E_FAIL (1) #### #### Message: #### Microsoft.SPOT.Net.SocketNative::connect [IP: 0000] #### #### System.Net.Sockets.Socket::Connect [IP: 001d] #### #### NetduinoPlusApplication1.Program::Main [IP: 0044] #### #### SocketException ErrorCode = 10053 #### SocketException ErrorCode = 10053 A first chance exception of type 'System.Net.Sockets.SocketException' occurred in Microsoft.SPOT.Net.dll #### SocketException ErrorCode = 10053 #### SocketException ErrorCode = 10053 SocketException when connecting to 192.168.5.102. Socket Error Code: 10053 System.Net.Sockets.SocketException The thread '<No Name>' (0x1) has exited with code 0 (0x0). Done. Waiting for debug commands... The program '[3] Micro Framework application: Managed' has exited with code 0 (0x0).



#43999 Multithreading and writing to SD card

Posted by AxelG on 23 January 2013 - 06:40 AM in Netduino Plus 2 (and Netduino Plus 1)

Thanks for this reply. Could you explain what is meant by a "locking scheme"?

Sure:

In my code I open the Filestream once and keep it open.  It would be a bad thing if multiple threads interacted with the the stream at "the same time".  I therefore create an object to lock it (private object LockMe = new object();) and any time I am reading or writing to the filestream I make sure the code holds a lock on this object (lock(LockMe) { //Code here } )

 

This way, you can ensure only one thread is interacting with the filestream at any given time.  Just make sure the scope of LockMe is shared between all threads.

 

I hope this helps.  You can google "C# lock()"  for more reference.




#43717 Multithreading and writing to SD card

Posted by AxelG on 19 January 2013 - 01:16 AM in Netduino Plus 2 (and Netduino Plus 1)

I have written a couple applications that have multiple threads accessing the SD card at the same time; it works but you need to be careful with a couple things.  You hit on the first one; one thread per file (reading and writing).  If you need two threads, simple locking mechanism can ensure read/seek/write transactions remain pure.  Since each thread keeps their own file structures (Assuming you are not sharing them!); mostly you are OK.

 

I have also found that dealing with the SD card is quite resource intensive; especially when mixed with time-sensitive sensor reading.  It is easy to create bottlenecks in the code that create data flow problems. Multi-threading on the netduino is not parallel processing; it just allows you to branch execution into separate places in your code - processor time is shared between the threads so only one instruction is running at a time.  The right locking scheme can make all of the difference.

 

SD cards also use SPI.  This is another area to make sure you code is aware there are multiple SPI devices.




#33402 Camera Modules for any Netduino

Posted by AxelG on 11 August 2012 - 05:35 AM in Netduino Plus 2 (and Netduino Plus 1)

I have NGO and no SD card yet

Maybe you could update the driver to send data out a serial port to some receiving system as it is read from the camera. You could get fancy and maybe perform a post to a waiting web server; assuming you have an Ethernet or wifi shield.



#33180 Camera Modules for any Netduino

Posted by AxelG on 06 August 2012 - 09:38 PM in Netduino Plus 2 (and Netduino Plus 1)

Posted Image Ok! Thank


I can confirm that these drivers work very well. Easy to use and bug free (so far ;) ) I trimmed them up a bit as I did not need all of the features written in the driver. Took me about a hour to get everything hooked up and running.

You must also have a ND with a SD card to use the drivers. That means either a ND+ or ND flashed to 4.2 and a SD shield of some kind. If you use the latter, you will have to add the mount and unmount commands to the driver.

Hope you enjoy; I know I did! :)




home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.