Serial Port Reading

Can't get a Serial port to read data

Page 1 of 1

6 Replies - 41006 Views - Last Post: 24 March 2010 - 07:30 AM Rate Topic: ***** 1 Votes

#1 shintetsu_80  Icon User is offline

  • D.I.C Head

Reputation: 31
  • View blog
  • Posts: 105
  • Joined: 01-July 08

Serial Port Reading

Post icon  Posted 01 July 2008 - 10:22 AM

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:
#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());
	}
  }
}



Is This A Good Question/Topic? 0
  • +

Replies To: Serial Port Reading

#2 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1641
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: Serial Port Reading

Posted 01 July 2008 - 10:46 AM

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
Was This Post Helpful? 0
  • +
  • -

#3 shintetsu_80  Icon User is offline

  • D.I.C Head

Reputation: 31
  • View blog
  • Posts: 105
  • Joined: 01-July 08

Re: Serial Port Reading

Posted 01 July 2008 - 10:56 AM

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.
Was This Post Helpful? 0
  • +
  • -

#4 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1524
  • View blog
  • Posts: 5,960
  • Joined: 21-March 08

Re: Serial Port Reading

Posted 02 July 2008 - 06:02 AM

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

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: 02 July 2008 - 06:12 AM

Was This Post Helpful? 0
  • +
  • -

#5 shintetsu_80  Icon User is offline

  • D.I.C Head

Reputation: 31
  • View blog
  • Posts: 105
  • Joined: 01-July 08

Re: Serial Port Reading

Posted 02 July 2008 - 12:29 PM

View Posteclipsed4utoo, on 2 Jul, 2008 - 06:02 AM, said:

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

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:

//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: 02 July 2008 - 12:30 PM

Was This Post Helpful? 1
  • +
  • -

#6 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1524
  • View blog
  • Posts: 5,960
  • Joined: 21-March 08

Re: Serial Port Reading

Posted 02 July 2008 - 01:00 PM

just an FYI, only use ReadLine() if the equipment is going to send a carraige return when it has completed.
Was This Post Helpful? 0
  • +
  • -

#7 Guest_Lasrevinu*


Reputation:

Re: Serial Port Reading

Posted 24 March 2010 - 07:30 AM

View Posteclipsed4utoo, on 02 July 2008 - 12:00 PM, said:

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


eclipsed4utoo is right,if the equipement sends "\r" when it has completed sending data, ReadLine() works,
readTo() is almost the same, you read until you find the finalisation chacater
readTo("\r") is a readline

do u have any idea in how to deal with data without any finalisation character?
if you know just the number of bytes to read, i would use :
serialPort1.ReadTimeout = 500;

Quote

int bytes = serialPort1.BytesToRead;
byte[] buffer = new byte[bytes];
serialPort1.Read(buffer, 0, bytes);


but it doesn't seem to work properly,
i get data of a size when i debug, cause it has the time to get into the buffer
have you ever had the same issue
Was This Post Helpful? 0

Page 1 of 1