Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I use dataReceived event of the SerialPort Port Object in C#?
    text
    copied!<p>I am attempting to create a small application to collect data received from an external sensor attached to COM10. I have successfully created a small C# console object and application that opens the port and streams data to a file for a fixed period of time using a for-loop. </p> <p>I would like to convert this application to use the dataReceived event to stream instead. After reading the <a href="http://blogs.msdn.com/bclteam/archive/2006/10/10/Top-5-SerialPort-Tips-_5b00_Kim-Hamilton_5D00_.aspx" rel="nofollow noreferrer">Top 5 SerialPort Tips</a>, I still can't seem to it to work and don't know what I am missing. I rewrote the console application so that all the code is in Main and is pasted below. Can someone please help enlighten me as to why the event handler port_OnReceiveDatazz is not being called even though I know that there is data being sent to the port by the hardware?</p> <p>Thanks</p> <p>Azim</p> <p>PS: Thanks to <a href="https://stackoverflow.com/questions/466474/how-do-i-use-datareceived-event-of-the-serialport-port-object-in-c#466577">@Gabe</a>, <a href="https://stackoverflow.com/questions/466474/how-do-i-use-datareceived-event-of-the-serialport-port-object-in-c#466510">@Jason Down</a>, and <a href="https://stackoverflow.com/questions/466474/how-do-i-use-datareceived-event-of-the-serialport-port-object-in-c#466518">@abatishchev</a> for all the suggestions. I am stumped and can't seem to get the event handler to work. Perhaps it has something to do with the device. I can live with just reading the port in a thread and streaming the data straight to file.</p> <hr> <p><strong>Code</strong></p> <hr> <pre><code>namespace serialPortCollection { class Program { static void Main(string[] args) { const int bufSize = 2048; Byte[] buf = new Byte[bufSize]; //To store the received data. SerialPort sp = new SerialPort("COM10", 115200); sp.DataReceived += port_OnReceiveDatazz; // Add DataReceived Event Handler sp.Open(); sp.WriteLine("$"); //Command to start Data Stream // Wait for data or user input to continue. Console.ReadLine(); sp.WriteLine("!"); //Stop Data Stream Command sp.Close(); } // My Event Handler Method private static void port_OnReceiveDatazz(object sender, SerialDataReceivedEventArgs e) { SerialPort spL = (SerialPort) sender; const int bufSize = 12; Byte[] buf = new Byte[bufSize]; Console.WriteLine("DATA RECEIVED!"); Console.WriteLine(spL.Read(buf, 0, bufSize)); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload