Welcome to Dream.In.Code
Getting C# Help is Easy!

Join 107,218 C# Programmers for FREE! Ask your question and get quick answers from experts. There are 1,831 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!



Serial Port Reading

 
Reply to this topicStart new topic

Serial Port Reading, Can't get a Serial port to read data

shintetsu_80
post 1 Jul, 2008 - 10:22 AM
Post #1


New D.I.C Head

*
Joined: 1 Jul, 2008
Posts: 4

I started learning C# a few months back and I really like the language. However, I cannot seem to read data from and accelarometer that is connect to the serial port. The device is dumb. As soon as you open the port it streams data. I'm pretty familiar with doing this very same procedure because I have done this in three other languages but I cannot get it to work in C#.

What is working:
I have been able to establish a connection to the port and open and close the port and set the port values.
Baud = 9600; 8-N-1;
I have established a working connection in hyperterminal.

What (I think) the problem is:
I'm pretty sure it's either the event handler or the .readExisting command. I've stepped through the code and the event handler never executes. I also wrote code that would just reads from the serial port but when I step over the .read command the program gets stuck. I've tried different types of the read command (.ReadLine, .readExisting,.....) but the program gets stuck on them all except for the .readExisting command which is quickly executes and returns nothing.

Simple Console Program that is not working:
CODE

#region Namespace Inclusions
using System;
using System.IO.Ports;
#endregion

namespace SerialConsoleExample
{
  class SerialPortProgram
  {
    // Create the serial port with basic settings
    private SerialPort port = new SerialPort("COM5", 9600, Parity.None, 8, StopBits.One);

    [STAThread]
    static void Main(string[] args)
    {
      // Instatiate this class
      new SerialPortProgram();
    }

    private SerialPortProgram()
    {
        Console.WriteLine("Incoming Data:");
              
        // Begin communications
        if (port.IsOpen)
        {
            port.Close();
        }
        port.Open();

        port.NewLine = "\n";
        Console.WriteLine(port.ToString());
        Console.WriteLine(port.PortName);
        Console.WriteLine(port.NewLine.ToString());
        Console.WriteLine(port.IsOpen.ToString());
        Console.WriteLine(port.ReadExisting());                
        
        //Enter an application loop to keep this thread alive
        //Application.Run();
        int i = 0;
        while (i < 1000)
        {
            // Attach a method to be called when there      // is data waiting in the port's buffer
            port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
            Console.WriteLine(port.ReadExisting());
            i++;
        }
        port.Close();
    }

    private void port_DataReceived(object sender,      SerialDataReceivedEventArgs e)
    {
      // Show all the incoming data in the port's buffer
      Console.WriteLine(port.ReadExisting());
    }
  }
}
User is offlineProfile CardPM

Go to the top of the page


PsychoCoder
post 1 Jul, 2008 - 10:46 AM
Post #2


DIC.Rules == true;

Group Icon
Joined: 26 Jul, 2007
Posts: 7,128



Thanked 50 times

Dream Kudos: 7700

Expert In: VB, VB.Net, C#, SQL, ASP, ASP.Net, Web Development, HTML, CSS, Win32 API, Javascript, mySQL, J#, GDI

My Contributions


You have posted this in the wrong forum, Im going to move it to the C# forum where it can get the attention it deserves
User is offlineProfile CardPM

Go to the top of the page

shintetsu_80
post 1 Jul, 2008 - 10:56 AM
Post #3


New D.I.C Head

*
Joined: 1 Jul, 2008
Posts: 4

Thanks PsychoCoder!
I've actually tried to run my accelerometer with the SerialPortCommunicator code that you provided in that very nice tutorial "Serial Port Communication in C#" but I'm having the same problem with the event handler not firing.
User is offlineProfile CardPM

Go to the top of the page

eclipsed4utoo
post 2 Jul, 2008 - 06:02 AM
Post #4


D.I.C Head

**
Joined: 21 Mar, 2008
Posts: 92



Thanked 4 times
My Contributions


here is the code that I use to receive data through a serial port.

C#

public SerialPort sp;
string dataReceived = string.Empty;
private delegate void SetTextDeleg(string text);

private void FormLoad()
{
sp = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
this.sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
sp.Open();
}

void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
Thread.Sleep(500);
string x = sp.ReadLine(); // will read to the first carriage return
this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { x });
}
catch
{ }
}

private void si_DataReceived(string data)
{
dataReceived = data.Trim();

// Do whatever with the data that is coming in.
}



Off Topic: why doesn't my code format like other poster's code does?

This post has been edited by eclipsed4utoo: 2 Jul, 2008 - 06:12 AM
User is offlineProfile CardPM

Go to the top of the page

shintetsu_80
post 2 Jul, 2008 - 12:29 PM
Post #5


New D.I.C Head

*
Joined: 1 Jul, 2008
Posts: 4

QUOTE(eclipsed4utoo @ 2 Jul, 2008 - 06:02 AM) *

here is the code that I use to receive data through a serial port.

C#

public SerialPort sp;
string dataReceived = string.Empty;
private delegate void SetTextDeleg(string text);

private void FormLoad()
{
sp = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
this.sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
sp.Open();
}

void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
Thread.Sleep(500);
string x = sp.ReadLine(); // will read to the first carriage return
this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { x });
}
catch
{ }
}

private void si_DataReceived(string data)
{
dataReceived = data.Trim();

// Do whatever with the data that is coming in.
}



Off Topic: why doesn't my code format like other poster's code does?



Thanks eclipsed4utoo!

I've already solved the problem but I'm still going to try your solution when I get a chance. Here's the solution I have:

CODE

//call this after port.Open()
port.DtrEnable = true;


I call this right after I open the serial port. The .DtrEnable command gets or sets a value that enables the Data Terminal Ready (DTR) signal during serial communication.

I'm surprised that more serial communication HOW TO's don't include this little bit of code. This is the first time I've ever tried this in C# but it's seems pretty important to me. If it's not maybe somebody can explain to me why it's not.

Thanks for the help!

This post has been edited by shintetsu_80: 2 Jul, 2008 - 12:30 PM
User is offlineProfile CardPM

Go to the top of the page

eclipsed4utoo
post 2 Jul, 2008 - 01:00 PM
Post #6


D.I.C Head

**
Joined: 21 Mar, 2008
Posts: 92



Thanked 4 times
My Contributions


just an FYI, only use ReadLine() if the equipment is going to send a carraige return when it has completed.
User is offlineProfile CardPM

Go to the top of the page

Fast ReplyReply to this topicStart new topic
Time is now: 8/28/08 01:38AM

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month