473,395 Members | 1,629 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

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:

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.IO.Ports;
  5.  
  6. namespace DEXtransactionParserTestApp
  7. {
  8.     public static class SerialPortCommands
  9.     {
  10.         public static bool received = false;
  11.         private static SerialPort dexConnection = new SerialPort();
  12.         // -- Properties ---------------------------------------------------------
  13.  
  14.         // -- Public methods -----------------------------------------------------
  15.  
  16.         #region PortControl
  17.  
  18.         public static void InitializePort(string PortNumber, Parity par,int dataBits, int baudRate)
  19.         {
  20.             dexConnection.PortName = PortNumber;
  21.             dexConnection.Parity = par;
  22.             dexConnection.BaudRate = baudRate;
  23.             dexConnection.DataBits = dataBits;
  24.             dexConnection.DataReceived += new SerialDataReceivedEventHandler(dexConnection_DataReceived);
  25.         }
  26.  
  27.  
  28.         public static void EnablePort()
  29.         {
  30.             if (!dexConnection.IsOpen)
  31.                 dexConnection.Open();
  32.         }
  33.  
  34.         public static void DisablePort()
  35.         {
  36.             if (dexConnection.IsOpen)
  37.                 dexConnection.Close();
  38.         }
  39.         #endregion
  40.  
  41.         #region Communication
  42.         public static void SendASCIIMessage(string Message)
  43.         {
  44.             //dexConnection.Write(Message);
  45.             int test21 = 0X05;
  46.             byte[] test = new byte[1];
  47.             test[0] = (byte)test21;
  48.             dexConnection.Write(test, 0, 1);
  49.             //dexConnection.Write(ConvertToBytes(Message),0,ConvertToBytes(Message).Length);
  50.         }
  51.  
  52.  
  53.         #endregion
  54.  
  55.         // -- Helper methods -------------------------------------------------------------
  56.         private static byte[] ConvertToBytes(string ascii)
  57.         {
  58.             byte[] asciiBytes = Encoding.ASCII.GetBytes(ascii);
  59.             return asciiBytes;
  60.         }
  61.         // -- Events ---------------------------------------------------------------------
  62.         private static void dexConnection_DataReceived(object sender, SerialDataReceivedEventArgs e)
  63.         {
  64.             received = true;
  65.             Console.WriteLine("Response From VMD:");
  66.             Console.WriteLine(dexConnection.ReadExisting().ToString());
  67.             Console.ReadLine();
  68.             //throw new Exception("The method or operation is not implemented.");
  69.  
  70.  
  71.             //TODO: General code to determine which method to call to process a response
  72.  
  73.             //TODO: Add code to process "event" messages from the VMD
  74.  
  75.             //TODO: Add code to process "report" data from VMD
  76.  
  77.             //TODO: Add code to process "handshake" signals from VMD
  78.         }
  79.  
  80.     }
  81. }
  82.  
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.IO;
  5. using System.Text.RegularExpressions;
  6. using System.IO.Ports;
  7. using System.Configuration;
  8. using System.Threading;
  9. namespace DEXtransactionParserTestApp
  10. {
  11.     class Program
  12.     {
  13.         public static string[] records;
  14.  
  15.         static void Main(string[] args)
  16.         {
  17.             System.Windows.Forms.Application.DoEvents();
  18.             #region testVersionStuff1
  19.             //string viewSplitRecord = "";
  20.  
  21.             //string ReportLine1 = "DXS*RST7654321*VA*V0/6*1";
  22.             //string ReportLine2 = "ST*001*0001";
  23.             //string ReportLine3 = "ID1*112233445566*ABC1234*0101*Building 1**777888999";
  24.             //string rep1and2 = ReportLine1;
  25.             //rep1and2 += ReportLine2;
  26.             ////string[] sites = rep1and2.Split('*');
  27.             ////string[] sites = ReportCapture.currRep.Split("crlf");
  28.             ////string[] sites = ReportCapture.currRep.Split('*');
  29.             //records = Regex.Split(ReportCapture.currRep, "crlf");
  30.             //processRecord(records[0]);
  31.             //string[] sites = Regex.Split(ReportCapture.currRep, "crlf");
  32.             //string[] viewSplitField = sites[0].Split('*');
  33.             //foreach (string s in sites) 
  34.             //{ /*Console.WriteLine(s)*/
  35.             //    viewSplitRecord += s+"\n"; //;
  36.  
  37.  
  38.             //}
  39.             //Console.Write(viewSplitRecord[0]);
  40.             //Console.WriteLine(viewSplitField[0]);
  41.  
  42.             //Console.ReadLine();
  43.             #endregion
  44.  
  45.  
  46.                 Parity spPar;
  47.                 if (ConfigurationManager.AppSettings["parityType"].ToString() == "EVEN")
  48.                 {
  49.                     spPar = Parity.Even;
  50.                 }
  51.  
  52.                 if (ConfigurationManager.AppSettings["parityType"].ToString() == "ODD")
  53.                     spPar = Parity.Odd;
  54.  
  55.                 else
  56.                     spPar = Parity.None;
  57.  
  58.                 SerialPortCommands.InitializePort(ConfigurationManager.AppSettings["portNumber"].ToString(), spPar, Int32.Parse(ConfigurationManager.AppSettings["DataBits"].ToString()), Int32.Parse(ConfigurationManager.AppSettings["BaudRate"].ToString()));
  59.                 SerialPortCommands.EnablePort();
  60.                 Console.WriteLine("Type Message to send to the VMD\nthen press Enter:");
  61.                 string Message = Console.ReadLine();
  62.                 while (!SerialPortCommands.received)
  63.                 {
  64.  
  65.                     SerialPortCommands.SendASCIIMessage(Message);
  66.                     Thread.Sleep(1100);
  67.                     //Console.ReadLine();
  68.                     //Console.WriteLine("Response From VMD");
  69.                     //SerialPortCommands.DisablePort();
  70.             }
  71.  
  72.             Console.ReadLine();
  73.             SerialPortCommands.DisablePort();
  74.         }
  75.         #region unUsedReportCode
  76.         //public static string processRecord(string theRecord)
  77.         //{
  78.         //    string processedReocrd = "";
  79.         //    Match m = Regex.Match(theRecord, "^[A-Za-z0-9]*\\\\*");
  80.         //    Console.WriteLine(m);
  81.         //    Console.WriteLine("\n" + "\n");
  82.  
  83.         //    switch (m.ToString())
  84.         //    {
  85.         //        case "ID1":
  86.         //            ID1Process(theRecord);
  87.         //            break;
  88.  
  89.         //        case "DXS":
  90.         //            break;
  91.  
  92.         //        case "VA1":
  93.         //            break;
  94.  
  95.         //        case "DXE":
  96.         //            break;
  97.  
  98.         //        case "ST":
  99.         //            break;
  100.  
  101.         //        case "CA2":
  102.         //            break;
  103.         //        case "CA3":
  104.         //            break;
  105.  
  106.         //        case "CA4":
  107.         //            break;
  108.  
  109.         //        case "PA1":
  110.         //            break;
  111.  
  112.         //        case "PA2":
  113.         //            break;
  114.  
  115.         //        case "DA2":
  116.         //            break;
  117.  
  118.         //        default:
  119.         //            break;
  120.  
  121.  
  122.         //    }
  123.         //    return processedReocrd;
  124.         //}
  125.  
  126.         //public static string ID1Process(string ID1Record)
  127.         //{
  128.         //   ID1Record = Regex.Replace(ID1Record, "ID1"+Regex.Escape("*"), "");
  129.         //   Console.WriteLine(ID1Record);
  130.  
  131.         //   //System.Windows.Forms.MessageBox.Show(ID1Record);
  132.  
  133.         //   //SerialPort port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
  134.         //    return ID1Record;
  135.         //}
  136.  
  137.         //public byte[] ConvertToBytes(string ascii)
  138.         //{
  139.         //    byte[] test = Encoding.ASCII.GetBytes("test");
  140.         //    return test;
  141.         //}
  142.         #endregion
  143.  
  144.     }
  145. }
  146.  
Expand|Select|Wrap|Line Numbers
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <configuration>
  3.   <appSettings>
  4.  
  5.     <!--Serial Port Object initialization Settings-->
  6.     <add key="portNumber" value="COM1"/>
  7.     <add key="parityType" value="NONE"/>
  8.     <add key="BaudRate" value="9600"/>
  9.     <add key="DataBits" value="7"/>
  10.  
  11.   </appSettings>
  12. </configuration>
Jun 12 '08 #1
6 11654
jhaxo
57
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...accessories...communications.

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.
Jun 13 '08 #2
Plater
7,872 Expert 4TB
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?
Jun 13 '08 #3
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...accessories...communications.

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!
Jun 13 '08 #4
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?
Jun 13 '08 #5
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?
Expand|Select|Wrap|Line Numbers
  1.             int test21 = 0x05;
  2.             byte[] test = new byte[1];
  3.             test[0] = (byte)test21;
  4.             dexConnection.Write(test, 0, test.Length);
Jun 13 '08 #6
Plater
7,872 Expert 4TB
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)
Jun 13 '08 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Jacob | last post by:
Has anyone successfully received serial communications from a COM port/RS232C device? It's easy to connect and write to a serial device with Framework 2.0, but when I try to read from the input...
6
by: Peter Krikelis | last post by:
Hi All, I am having a problem setting up input mode for serial communications. (Sorry about the long code post). The following code is what I use to set up my comm port.
7
by: Kevin | last post by:
Hi all I am having a problem reading from a serial port, first of all I have now resorted to using the MSComm ActiveX control on my Windows Forms to provide me with the interface to my serial...
6
by: Leandro Berti via DotNetMonster.com | last post by:
Hi All, I wrote a code to do serial communication with an equipament. When i use the code outside of threaded class it seens work properly, but when i put inside a class and execute a thread in...
3
by: Tom Brown | last post by:
Hey people, I've written a python app that r/w eight serial ports to control eight devices using eight threads. This all works very nicely in Linux. I even put a GUI on it using PyQt4. Still...
7
by: davetelling | last post by:
I'm a newbie that is still struggling with OOP concepts & how to make things work they way I want. Using Visual C# Express, I have a form in which I added a user control to display a graph, based...
1
by: laura salhuana | last post by:
Hi: I am trying to write a serial communication GUI application. My application has the following specifications. When I set my board up in hyperterminal I do the following set up: bits per...
2
by: Lou | last post by:
I have a class that creates an instance of the seril Port. Every thing works fine except whenever I receive data I cannot display the recieved data. I get no errors but the recived data seems to...
4
by: max_mont | last post by:
Hi all, I'm a newbie in .NET technology. I've already developed Serial communication applications in C++ (WIN32). And I wanted to migrate to .NET technology. There is a serial component in...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.