Serial Port Data Receieved Event not firing C#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • cnixuser
    New Member
    • Dec 2006
    • 80

    Serial Port Data Receieved Event not firing C#

    Hello, I have a basic application written which is designed to data over a serial cable and then receive a response back. I am not getting any triggers to my data received event. I have tried connecting the pc I am running this application on to another PC which is also sending hex characters ;however, when I run the application I am getting no trigger of the data received event and am completely clueless as to why. Any help that could be provided would be greatly appreciated.

    Below is my code and App.config contents:

    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO.Ports;
    
    namespace DEXtransactionParserTestApp
    {
        public static class SerialPortCommands
        {
            public static bool received = false;
            private static SerialPort dexConnection = new SerialPort();
            // -- Properties ---------------------------------------------------------
    
            // -- Public methods -----------------------------------------------------
    
            #region PortControl
    
            public static void InitializePort(string PortNumber, Parity par,int dataBits, int baudRate)
            {
                dexConnection.PortName = PortNumber;
                dexConnection.Parity = par;
                dexConnection.BaudRate = baudRate;
                dexConnection.DataBits = dataBits;
                dexConnection.DataReceived += new SerialDataReceivedEventHandler(dexConnection_DataReceived);
            }
    
            
            public static void EnablePort()
            {
                if (!dexConnection.IsOpen)
                    dexConnection.Open();
            }
    
            public static void DisablePort()
            {
                if (dexConnection.IsOpen)
                    dexConnection.Close();
            }
            #endregion
    
            #region Communication
            public static void SendASCIIMessage(string Message)
            {
                //dexConnection.Write(Message);
                int test21 = 0X05;
                byte[] test = new byte[1];
                test[0] = (byte)test21;
                dexConnection.Write(test, 0, 1);
                //dexConnection.Write(ConvertToBytes(Message),0,ConvertToBytes(Message).Length);
            }
    
            
            #endregion
    
            // -- Helper methods -------------------------------------------------------------
            private static byte[] ConvertToBytes(string ascii)
            {
                byte[] asciiBytes = Encoding.ASCII.GetBytes(ascii);
                return asciiBytes;
            }
            // -- Events ---------------------------------------------------------------------
            private static void dexConnection_DataReceived(object sender, SerialDataReceivedEventArgs e)
            {
                received = true;
                Console.WriteLine("Response From VMD:");
                Console.WriteLine(dexConnection.ReadExisting().ToString());
                Console.ReadLine();
                //throw new Exception("The method or operation is not implemented.");
    
    
                //TODO: General code to determine which method to call to process a response
    
                //TODO: Add code to process "event" messages from the VMD
    
                //TODO: Add code to process "report" data from VMD
    
                //TODO: Add code to process "handshake" signals from VMD
            }
    
        }
    }
    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    using System.Text.RegularExpressions;
    using System.IO.Ports;
    using System.Configuration;
    using System.Threading;
    namespace DEXtransactionParserTestApp
    {
        class Program
        {
            public static string[] records;
    
            static void Main(string[] args)
            {
                System.Windows.Forms.Application.DoEvents();
                #region testVersionStuff1
                //string viewSplitRecord = "";
    
                //string ReportLine1 = "DXS*RST7654321*VA*V0/6*1";
                //string ReportLine2 = "ST*001*0001";
                //string ReportLine3 = "ID1*112233445566*ABC1234*0101*Building 1**777888999";
                //string rep1and2 = ReportLine1;
                //rep1and2 += ReportLine2;
                ////string[] sites = rep1and2.Split('*');
                ////string[] sites = ReportCapture.currRep.Split("crlf");
                ////string[] sites = ReportCapture.currRep.Split('*');
                //records = Regex.Split(ReportCapture.currRep, "crlf");
                //processRecord(records[0]);
                //string[] sites = Regex.Split(ReportCapture.currRep, "crlf");
                //string[] viewSplitField = sites[0].Split('*');
                //foreach (string s in sites) 
                //{ /*Console.WriteLine(s)*/
                //    viewSplitRecord += s+"\n"; //;
                    
                    
                //}
                //Console.Write(viewSplitRecord[0]);
                //Console.WriteLine(viewSplitField[0]);
    
                //Console.ReadLine();
                #endregion
    
                
                    Parity spPar;
                    if (ConfigurationManager.AppSettings["parityType"].ToString() == "EVEN")
                    {
                        spPar = Parity.Even;
                    }
    
                    if (ConfigurationManager.AppSettings["parityType"].ToString() == "ODD")
                        spPar = Parity.Odd;
    
                    else
                        spPar = Parity.None;
    
                    SerialPortCommands.InitializePort(ConfigurationManager.AppSettings["portNumber"].ToString(), spPar, Int32.Parse(ConfigurationManager.AppSettings["DataBits"].ToString()), Int32.Parse(ConfigurationManager.AppSettings["BaudRate"].ToString()));
                    SerialPortCommands.EnablePort();
                    Console.WriteLine("Type Message to send to the VMD\nthen press Enter:");
                    string Message = Console.ReadLine();
                    while (!SerialPortCommands.received)
                    {
    
                        SerialPortCommands.SendASCIIMessage(Message);
                        Thread.Sleep(1100);
                        //Console.ReadLine();
                        //Console.WriteLine("Response From VMD");
                        //SerialPortCommands.DisablePort();
                }
    
                Console.ReadLine();
                SerialPortCommands.DisablePort();
            }
            #region unUsedReportCode
            //public static string processRecord(string theRecord)
            //{
            //    string processedReocrd = "";
            //    Match m = Regex.Match(theRecord, "^[A-Za-z0-9]*\\\\*");
            //    Console.WriteLine(m);
            //    Console.WriteLine("\n" + "\n");
    
            //    switch (m.ToString())
            //    {
            //        case "ID1":
            //            ID1Process(theRecord);
            //            break;
    
            //        case "DXS":
            //            break;
    
            //        case "VA1":
            //            break;
    
            //        case "DXE":
            //            break;
    
            //        case "ST":
            //            break;
    
            //        case "CA2":
            //            break;
            //        case "CA3":
            //            break;
    
            //        case "CA4":
            //            break;
    
            //        case "PA1":
            //            break;
    
            //        case "PA2":
            //            break;
    
            //        case "DA2":
            //            break;
    
            //        default:
            //            break;
    
    
            //    }
            //    return processedReocrd;
            //}
    
            //public static string ID1Process(string ID1Record)
            //{
            //   ID1Record = Regex.Replace(ID1Record, "ID1"+Regex.Escape("*"), "");
            //   Console.WriteLine(ID1Record);
               
            //   //System.Windows.Forms.MessageBox.Show(ID1Record);
    
            //   //SerialPort port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
            //    return ID1Record;
            //}
    
            //public byte[] ConvertToBytes(string ascii)
            //{
            //    byte[] test = Encoding.ASCII.GetBytes("test");
            //    return test;
            //}
            #endregion
    
        }
    }
    Code:
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <appSettings>
    
        <!--Serial Port Object initialization Settings-->
        <add key="portNumber" value="COM1"/>
        <add key="parityType" value="NONE"/>
        <add key="BaudRate" value="9600"/>
        <add key="DataBits" value="7"/>
        
      </appSettings>
    </configuration>
  • jhaxo
    New Member
    • Dec 2007
    • 57

    #2
    Instead of running your program, have you tried running hyperterminal to verify the connection, wiring, port, baud rate, handshaking and so on are all correct? Hyperterminal is available using programs...acce ssories...commu nications.

    For me the most common mistake is not using a null modem cable when i should be. followed by the computers port not being enabled at all.

    Let me know.

    Comment

    • Plater
      Recognized Expert Expert
      • Apr 2007
      • 7872

      #3
      Pc to PC requires using a special connector (just swap the RX and TX and you have basic functionality)
      Do you use the correct Serial Port, sometimes they are not what you would think they are.
      Did you make sure to set flow control to none?

      Comment

      • cnixuser
        New Member
        • Dec 2006
        • 80

        #4
        Originally posted by jhaxo
        Instead of running your program, have you tried running hyperterminal to verify the connection, wiring, port, baud rate, handshaking and so on are all correct? Hyperterminal is available using programs...acce ssories...commu nications.

        For me the most common mistake is not using a null modem cable when i should be. followed by the computers port not being enabled at all.

        Let me know.
        I went out and bought a different null modem cable, once I did that the data_received event fired properly. The problem was with the old cable apparantly. Thanks! Hyper terminal, wouldn't work on the old cable either, but once I bought a new cable everything worked like a charm!

        Comment

        • cnixuser
          New Member
          • Dec 2006
          • 80

          #5
          Originally posted by Plater
          Pc to PC requires using a special connector (just swap the RX and TX and you have basic functionality)
          Do you use the correct Serial Port, sometimes they are not what you would think they are.
          Did you make sure to set flow control to none?
          I don't believe that the flow control was set to none, it would seem to set as "Hardware" can that cause problems later on down the road?

          Comment

          • cnixuser
            New Member
            • Dec 2006
            • 80

            #6
            A quick addition to my original question:

            The following code will result in a hex byte with the value of 05 to be written to the serial port correct?
            Code:
                        int test21 = 0x05;
                        byte[] test = new byte[1];
                        test[0] = (byte)test21;
                        dexConnection.Write(test, 0, test.Length);

            Comment

            • Plater
              Recognized Expert Expert
              • Apr 2007
              • 7872

              #7
              Well unless you actually use flow control, better to set it to none.
              Hardware uses extra signal lines to control when data can be sent or not (whereas software uses special hex codes to determine when data can be sent or not)

              Comment

              Working...