Error with DataReceive serial communication
Page 1 of 112 Replies - 877 Views - Last Post: 28 February 2012 - 08:01 PM
#1
Error with DataReceive serial communication
Posted 28 February 2012 - 12:20 PM
Replies To: Error with DataReceive serial communication
#2
Re: Error with DataReceive serial communication
Posted 28 February 2012 - 12:37 PM
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Threading;
namespace COMportListener
{
class Program
{
static SerialPort _serialPort;
static void Main(string[] args)
{
//create a new serial port object with default settings
_serialPort = new SerialPort();
//Allow user to set port parameters.
Console.WriteLine("Please set the port parameter");
_serialPort.PortName = SetPortName(_serialPort.PortName);
_serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
_serialPort.Parity = SetPortParity(_serialPort.Parity);
_serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
_serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
Console.WriteLine("Incoming Data from port:" +_serialPort.PortName);
_serialPort.DataReceived += new SerialDataReceivedEventHandler(Port_DataReceived);
try
{
if (_serialPort.IsOpen == true)
{
_serialPort.Close();
}
if (!_serialPort.IsOpen)
{
_serialPort.Open();
Console.WriteLine("Port opened at " + DateTime.Now + "\n");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public static string SetPortName(string defaultPortName)
{
string portName;
Console.WriteLine("Available Ports:");
foreach (string s in SerialPort.GetPortNames())
{
Console.WriteLine(" {0}", s);
}
Console.WriteLine("COM port ({0}):", defaultPortName);
portName = Console.ReadLine();
if (portName == "")
{
portName = defaultPortName;
}
return portName;
}
public static int SetPortBaudRate(int defaultPortBaudRate)
{
string baudRate;
Console.Write("Baud Rate({0}): ", defaultPortBaudRate);
baudRate = Console.ReadLine();
if (baudRate == "")
{
baudRate = defaultPortBaudRate.ToString();
}
return int.Parse(baudRate);
}
public static Parity SetPortParity(Parity defaultPortParity)
{
string parity;
Console.WriteLine("Available Parity options:");
foreach (string s in Enum.GetNames(typeof(Parity)))
{
Console.WriteLine(" {0}", s);
}
Console.Write("Parity({0}):", defaultPortParity.ToString());
parity = Console.ReadLine();
if (parity == "")
{
parity = defaultPortParity.ToString();
}
return (Parity)Enum.Parse(typeof(Parity), parity);
}
public static int SetPortDataBits(int defaultPortDataBits)
{
string dataBits;
Console.Write("Data Bits({0}): ", defaultPortDataBits);
dataBits = Console.ReadLine();
if (dataBits == "")
{
dataBits = defaultPortDataBits.ToString();
}
return int.Parse(dataBits);
}
public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
{
string stopBits;
Console.WriteLine("Available Stop Bits options:");
foreach (string s in Enum.GetNames(typeof(StopBits)))
{
Console.WriteLine(" {0}", s);
}
Console.Write("Stop Bits({0}):", defaultPortStopBits.ToString());
stopBits = Console.ReadLine();
if (stopBits == "")
{
stopBits = defaultPortStopBits.ToString();
}
return (StopBits)Enum.Parse(typeof(StopBits), stopBits);
}
private static void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//retrieve number of bytes in the buffer
int bytes = _serialPort.BytesToRead;
//create a byte array to hold the awaiting data
byte[] dataBuffer = new byte[bytes];
//Read the data and store it
_serialPort.Read(dataBuffer, 0, bytes);
//display the data
string s = System.Text.ASCIIEncoding.ASCII.GetString(dataBuffer);
Console.WriteLine("Data" +s+" was received at " + DateTime.Now);
Console.WriteLine(_serialPort.ReadExisting());
Console.WriteLine("Data Received");
}
}
}
#3
Re: Error with DataReceive serial communication
Posted 28 February 2012 - 12:43 PM
I've fixed your post.
#4
Re: Error with DataReceive serial communication
Posted 28 February 2012 - 01:15 PM
#5
Re: Error with DataReceive serial communication
Posted 28 February 2012 - 02:07 PM
int bytes = _serialPort.BytesToRead;
it doesn't get hit?
If not, then no data is coming into the serial port.
Why exactly did you make the event handler static?
private static void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
#6
Re: Error with DataReceive serial communication
Posted 28 February 2012 - 02:09 PM
Rick372010 What this shows us is that you aren't familiar with breakpoints and how to debug your own code. Learning to debug one's own code is an essential skill. Sadly, one that apparently few college courses teach. Silly if you ask me.
Placing breakpoints and walking through the code line by line allows you to actually WATCH it execute. Visualizing what your code does will let you see why it behaves the way it does.
It would be well worth your time to do the tutorials on FAQ 2. A couple hours learning this skill will save you hundreds of hours of confusion in one project alone.
TOP most asked:
What does this error message mean?
FAQ 2: How do I debug
FAQ 3: How do I make Form1 talk to Form2
FAQ (Frequently Asked Questions - Updated Feb 2012
#7
Re: Error with DataReceive serial communication
Posted 28 February 2012 - 02:44 PM
eclipsed4utoo, on 28 February 2012 - 02:07 PM, said:
int bytes = _serialPort.BytesToRead;
it doesn't get hit?
If not, then no data is coming into the serial port.
Why exactly did you make the event handler static?
private static void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
I did set a breakpoint there and that code is never executed. I made the handler static simply because it was the only way to get the call to the handle to work.
#8
Re: Error with DataReceive serial communication
Posted 28 February 2012 - 02:55 PM
And now remembering that, does your application start then stop almost immediately? You have no code that stops the console of completing once the code in the Main method is done.
#9
Re: Error with DataReceive serial communication
Posted 28 February 2012 - 02:59 PM
tlhIn`toq, on 28 February 2012 - 02:09 PM, said:
Rick372010 What this shows us is that you aren't familiar with breakpoints and how to debug your own code. Learning to debug one's own code is an essential skill. Sadly, one that apparently few college courses teach. Silly if you ask me.
Placing breakpoints and walking through the code line by line allows you to actually WATCH it execute. Visualizing what your code does will let you see why it behaves the way it does.
It would be well worth your time to do the tutorials on FAQ 2. A couple hours learning this skill will save you hundreds of hours of confusion in one project alone.
TOP most asked:
What does this error message mean?
FAQ 2: How do I debug
FAQ 3: How do I make Form1 talk to Form2
FAQ (Frequently Asked Questions - Updated Feb 2012
Yes, I agree with you, they don't teach enough debugging in college. However, I did set a few breakpoints and step through my code. The event handler is never accessed. I appreciate the tutorial you have recommended. I actually wrote my program based on the serial communication tutorial (FAQ11).
#10
Re: Error with DataReceive serial communication
Posted 28 February 2012 - 03:54 PM
eclipsed4utoo, on 28 February 2012 - 02:55 PM, said:
And now remembering that, does your application start then stop almost immediately? You have no code that stops the console of completing once the code in the Main method is done.
Yeah you're right about that. I actually pasted that code when I had moved the _serialPort.Close() statement. I've added it at the end of my main function
if (!_serialPort.IsOpen)
{
_serialPort.Open();
_serialPort.DtrEnable = true;
_serialPort.RtsEnable = true;
Console.WriteLine("Port opened at " + DateTime.Now + "\n");
_serialPort.DataReceived += new SerialDataReceivedEventHandler(Port_DataReceived);
Console.WriteLine("Incoming Data from port:" + _serialPort.PortName);
Console.WriteLine(_serialPort.ReadExisting());
_serialPort.Close();
}
Even with this statement the program just says the port it opened and time stamp. Is the SerialDataReceiveEventHandler doing the actual listening? I havent been able to find a function such as "TcpListener" where I know im listening for incoming traffic. I believe this is where my program fails.
This post has been edited by tlhIn`toq: 28 February 2012 - 04:04 PM
Reason for edit:: [code] your code here [/code] its not THAT tough
#11
Re: Error with DataReceive serial communication
Posted 28 February 2012 - 04:09 PM
How do you expect to receive data if you close the port?
Also, you have subscribed to the DataREceived event. THAT handler method should display the data when it comes in. You don't need/want the two lines after that here in this method.
if (!_serialPort.IsOpen)
{
_serialPort.Open();
_serialPort.DtrEnable = true;
_serialPort.RtsEnable = true;
Console.WriteLine("Port opened at " + DateTime.Now + "\n");
_serialPort.DataReceived += new SerialDataReceivedEventHandler(Port_DataReceived);// Do your displaying in the Port_DataReveived() method, not below this line
//Console.WriteLine("Incoming Data from port:" + _serialPort.PortName);
//Console.WriteLine(_serialPort.ReadExisting());
//_serialPort.Close(); // Don't close the port here - duh
}
#12
Re: Error with DataReceive serial communication
Posted 28 February 2012 - 07:44 PM
In reality, a console app is not a good way to test getting data from the serial port for the reason stated above. A WinForms/WPF application is better suited as it's designed to sit idle. Console applications are not designed to just sit and do nothing.
#13
Re: Error with DataReceive serial communication
Posted 28 February 2012 - 08:01 PM
eclipsed4utoo, on 28 February 2012 - 07:44 PM, said:
In reality, a console app is not a good way to test getting data from the serial port for the reason stated above. A WinForms/WPF application is better suited as it's designed to sit idle. Console applications are not designed to just sit and do nothing.
Thanks for your suggestion eclipsed4utoo. I write a windows app version of this. As you mentioned, its's designed to sit idle and it is exactly what I need.
|
|

New Topic/Question
Reply



MultiQuote




|