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.
Photo

Netduino Serial Port Code Review


  • Please log in to reply
31 replies to this topic

#21 airdamien

airdamien

    New Member

  • Members
  • Pip
  • 4 posts

Posted 19 March 2012 - 04:04 AM

Been working on this for an xbee repeater.. I built a ruby server/arduino/xbee/iphone app to allow remote flushing.
FLUSHINGXBEES

I keyed that arduino to only respond to FLUSH:1




Working on the netduino + xbee to run my hottub.
Problem is the control hut is well outside of my normal xbee range..
Solution? add a netduino + xbee in the middle so it can repeat my SPA: commands.

This library works great... my own attempts at handling this were getting bit chopped somehow.

I was getting the buffer problem while testing my repeating code.. set buffer to 9000, commented out the throws.. still would exception out after a couple repeats.

then I found the issue.

comment out the sleep in this method.. everytime it would throw an exception, the bytesrecieved would be 0. I'm guessing anything sent during the sleep caused it.

I've beaten on the code with a terrible loop. it seems fine now. "while true; do echo "SPA:1" >> /dev/cu.usbserial-A800f3ac; done"

  public void PrintClear()
        {
            byte[] bytesToSend = new byte[2];
            bytesToSend[0] = 254;
            bytesToSend[1] = 1;
            serialPort.Write(bytesToSend, 0, 2);
         //   Thread.Sleep(500); // LCD is slow, pause for 500ms before sending more chars
        }


#22 xikky

xikky

    Member

  • Members
  • PipPip
  • 20 posts

Posted 22 March 2012 - 03:19 PM

I am sending data from an ADXL345 attached to Netduino to PC, every 20 milliseconds, using Bluetooth communication; through BlueSMiRF Gold. Data is transferred good while debug because code compiles fine without being effected by threading. But when I run the code, data transferred is wrong because during ReadLine(), new data signal is read from DataReceived and thus effecting the buffer. Is there a way around for this?

#23 J Wilson

J Wilson

    Advanced Member

  • Members
  • PipPipPip
  • 30 posts

Posted 03 April 2012 - 01:38 AM

Hari, Good job. I wish I had found this thread when I was struggling through serial communication. It would have saved me a lot of duplication of effort (but the struggle did me good!) Here are my threads for comparison: http://forums.netdui...b-step-by-step/ http://forums.netdui...tduino-via-usb/ Thanks, John

#24 Wayneio

Wayneio

    Member

  • Members
  • PipPip
  • 24 posts

Posted 18 April 2013 - 10:28 PM

Hi,

 

I have just downloaded this application to learn the netduino (only had it a couple of hours) and I can get the terminal window to show button pressed when pressing the netduino onboard button, but typing the word ON doesn't turn on the LED.

 

Any ideas?



#25 sayantan

sayantan

    Member

  • Members
  • PipPip
  • 10 posts
  • Locationindia

Posted 13 February 2014 - 11:23 AM

HELLO , 

m new in netduino and using netduino plus 1 board , m trying to implement serial communication b/w netduino and computer using rs 232,

// code m using

using System;
using System.Net;
using System.Text;
using System.IO.Ports;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;
 
namespace rs232
{
    public class Program
    {
          static SerialPort serial;
        static OutputPort Led = new OutputPort(Pins.ONBOARD_LED, false);
 
        public static void Main()
        {
            // initialize the serial port for COM1 (using D0 & D1)        
            serial = new SerialPort("COM1",9600, Parity.None, 8, StopBits.One);
            // open the serial-port, so we can send & receive data        
            serial.Open();
            // add an event-handler for handling incoming data        
            serial.DataReceived += new SerialDataReceivedEventHandler(serial_DataReceived);
            // wait forever...        
            Thread.Sleep(Timeout.Infinite);
        }
 
        static void serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int bytesToRead = serial.BytesToRead;
            //start reading the stream 
            if (bytesToRead > 0)
            {
                // get the waiting data 
                byte[] buffer = new byte[bytesToRead];
 
               serial.Read(buffer, 0, buffer.Length);
 
               serial.Write(buffer, 0, buffer.Length);
 
                Led.Write(true);
            }
 
            Led.Write(false);
        }// write your code here
 
 
        }
 
    }
// this is the code m using. the problem m facing is wen using tera term software to obtain the output. unable to receive the data , its onlt transmitting not receiving  the data...pls can ne1 help me out..


#26 Kim Clausen

Kim Clausen

    New Member

  • Members
  • Pip
  • 3 posts

Posted 30 April 2014 - 09:32 AM

I'm using the Serial Port Helper with a Netduino Plus 2 and a Sparkfun Bluetooth Mate Gold. I can send data from the Netduino without problems but when reading I sometimes encounter an exeption - sometimes it is succesfull. I have not been able to identify any pattern in when it is successful and when it fails. The program stops at the read line in the below shown code:

private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
     lock (buffer)
     {
         int bytesReceived = serialPort.Read(buffer, bufferLength, bufferMax - bufferLength);
 
         if (bytesReceived > 0)
         {
             bufferLength += bytesReceived;
             if (bufferLength >= bufferMax)
                 throw new ApplicationException("Buffer Overflow");
         }
      }
}
 

with the following debug output

 

A first chance exception of type 'System.Exception' occurred in Microsoft.SPOT.Hardware.SerialPort.dll
An unhandled exception of type 'System.Exception' occurred in Microsoft.SPOT.Hardware.SerialPort.dll


#27 Jack Chidley

Jack Chidley

    Advanced Member

  • Members
  • PipPipPip
  • 99 posts

Posted 01 May 2014 - 09:12 PM

It's amazing to me how fundamental serial communications are and how, surprisingly, hard it is to do right. Mark shows us how to handle thing properly here http://blog.mark-ste...ergy-bluetooth/

I don't have an direct answer for you but I can show you code that I use and a blog post where I wrote about what I did http://jackminiblog....er-serial-ports {to post this I had to turn off the funny switch thingy}.

My latest code is here: https://github.com/j.../SerialMessages

I am actively working on this as I expand it to cope with Bluetooth (for Windows Phone 8.1 inspired by http://blog.roguecod...luetoothwithWP8 ), eRIC from http://www.lprs.co.uk/ and as a transport for RESTful communications.

Jack

#28 Chris Walker

Chris Walker

    Secret Labs Staff

  • Moderators
  • 7767 posts
  • LocationNew York, NY

Posted 02 May 2014 - 02:48 AM

Hi junktilkim@gmail.com,

In your code, is it possible that buffer[] has gotten disposed? Or that bufferLength has gotten to be a larger number than bufferMax? Or that bufferLength is beyond the range of the buffer length? In other words...when your app stops working on that line, hover over those variables...and see how big the buffer is in bytes and what the other values are at that moment in time.

We use serial ports extensively in several projects here, including in a few of our wireless protocol stacks which use SerialPort extensively. There may be a bug lurking in NETMF somewhere, but I don't ever remember experiencing this type of issue (and UART-based wireless protocol stacks run constantly).

Let's see if we can track down this issue with you,

Chris

#29 odich

odich

    New Member

  • Members
  • Pip
  • 3 posts

Posted 26 May 2014 - 04:54 PM

hello everyone am new to netduino and am trying to receive data inform of bytes from the serial port, everytime data appears the onboard led should be turned on but am only getting the error message unhandled exception of the type system.exception occurred in microsoft.spot.hardware.dll, please anyone out there help me. this is part of my school project as a computer engineer.

 

below is my code, am using pins D0 and D1 for serial connection

 

using System;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;
using System.IO.Ports;
 
namespace NetduinoApplication1
{
    public class Program
    {
        static SerialPort serial;
 
        public static void Main()
        {
            // initialize the serial port for COM1 (using D0 & D1)
            serial = new SerialPort(SerialPorts.COM1, 2400, Parity.None, 8, StopBits.One);
 
            OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);
          // open the serial-port, so we can send & receive data
            try
 
            { serial.Open(); }
 
            catch
            {
                led.Write(true);
            }
            // add an event-handler for handling incoming data
            serial.DataReceived += new SerialDataReceivedEventHandler(serial_DataReceived);
            
            for (int i = 0; i < 3; i++)
            {
                led.Write(true); // turn on the LED
                Thread.Sleep(250); // sleep for 250ms
                led.Write(false); // turn off the LED
                Thread.Sleep(250); // sleep for 250ms
 
            }
 
            // wait forever...
            Thread.Sleep(Timeout.Infinite);
        }
 
        static void serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
 
            // create a byte array
            byte[] bytes = new byte[serial.BytesToRead];
 
            // as long as there is data waiting to be read
            while (serial.BytesToRead > 0)
            {
                // read a single byte
                serial.Read(bytes, 0, bytes.Length);
                // send the same byte back
                Thread.Sleep(2000);
                serial.Write(bytes, 0, bytes.Length);
                OutputPort led1 = new OutputPort(Pins.ONBOARD_LED, false);
                led1.Write(true); // turn on the LED
                Thread.Sleep(250); // sleep for 250ms
                led1.Write(false); // turn off the LED
                Thread.Sleep(250); // sleep for 250ms
 
            }
 
        }
 
    }
}


#30 Kim Clausen

Kim Clausen

    New Member

  • Members
  • Pip
  • 3 posts

Posted 27 May 2014 - 03:33 PM

Hi Chris

 

I have added watches at the copied the value when the app stops (I send the text 'hello'). It is reading the line and things seems ok to me.

		bufferLength	7	int
		bufferMax	1024	int
		bufferMax - bufferLength	1017	int
-		buffer	{byte[1024]}	byte[]
		[0]	104	byte
		[1]	101	byte
		[2]	108	byte
		[3]	108	byte
		[4]	111	byte
		[5]	13	byte
		[6]	10	byte
		[7]	0	byte
		[8]	0	byte
		[9]	0	byte
		[10]	0	byte
                .
                .
                [1023]    0    byte

For now I'm surviving by adding a try/catch around the read call:

                int bytesReceived = 0;
                try
                {
                    bytesReceived = serialPort.Read(buffer, bufferLength, bufferMax - bufferLength);
                }
                catch
                {
                    Debug.Print("SerialPort exception");
                }


#31 Lucas Salomao

Lucas Salomao

    New Member

  • Members
  • Pip
  • 6 posts

Posted 10 June 2015 - 12:50 AM

Hi Hari, hi Chris
 
I'm trying to use this example but without success. I'm desperate to try to read a string for use in some test conditions, to turn on LEDs and get reading the analog channel. Only trying to compile this example I got the following error. Can you help me?

 

Error 1 Cannot deploy the base assembly 'mscorlib', or any of his satellite assemblies, to device - USB:a7e70ea2 twice. Assembly 'mscorlib' on the device has version 4.2.0.0, while the program is trying to deploy version 4.1.2821.0

 

Could you give me some other code Hari?  Chris?

 
Tanks!


#32 Nevyn

Nevyn

    Advanced Member

  • Members
  • PipPipPip
  • 1072 posts
  • LocationNorth Yorkshire, UK

Posted 10 June 2015 - 07:19 AM

Sounds like the Netduino has 4.2 firmware but your project has the NETMF version set to 4.1.  Have you installed the 4.2 SDK and tried resetting the project properties?

 

Regards,

Mark


To be or not to be = 0xFF

 

Blogging about Netduino, .NET, STM8S and STM32 and generally waffling on about life

Follow @nevynuk on Twitter





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

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.