none
RS 232 COMMUNICATION IN C# RRS feed

  • Question

  • HI

    IM SRIRAM

    I'VE CREATED A PROGRAM FOR RS 232 COMMUNICATION , IN WHICH IM COMMUNICATING WITH A CONTROLLER,THE PROGRAM RECEIVES THE DATA FROM THE CONTROLLER, BUT WHEN I SEN SOME DATA THE CONTROLLER DOES NOT RECEIVES ANY SIGNAL???

    THIS IS MY PROGRAM AS FOLLOWS

    using System;
    using System.Data;
    using System.Text;
    using System.Drawing;
    using System.IO.Ports;
    using System.Windows.Forms;
    using System.ComponentModel;
    using System.Collections.Generic;

    using SerialPortTerminal.Properties;

    namespace SerialPortTerminal
    {
        public enum DataMode { Text, Hex }
        public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error };

        public partial class frmTerminal : Form
        {
            //Local Variables

            // The main control for communicating through the RS-232 port
            private SerialPort comport = new SerialPort();

            // Various colors for logging info
            private Color[] LogMsgTypeColor = { Color.Blue, Color.Green, Color.Black, Color.Orange, Color.Red };

            // Temp holder for whether a key was pressed
            private bool KeyHandled = false;
           

            //Constructor
            public frmTerminal()
            {
                //Build the form
                InitializeComponent();

                //Restore the users settings
                InitializeControlValues();

                //Enable/Disable controls based on the current state
                EnableControls();

                //When data is recieved through the port, call this method
                comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
            }
            
            /// <summary> Save the user's settings. </summary>
            private void SaveSettings()
            {
                Settings.Default.BaudRate = int.Parse(cmbBaudRate.Text);
                Settings.Default.DataBits = int.Parse(cmbDataBits.Text);
                Settings.Default.DataMode = CurrentDataMode;
                Settings.Default.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text);
                Settings.Default.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text);
                Settings.Default.PortName = cmbPortName.Text;

                Settings.Default.Save();
            }

            /// <summary> Populate the form's controls with default settings. </summary>
            private void InitializeControlValues()
            {
                cmbParity.Items.Clear(); cmbParity.Items.AddRange(Enum.GetNames(typeof(Parity)));
                cmbStopBits.Items.Clear(); cmbStopBits.Items.AddRange(Enum.GetNames(typeof(StopBits)));

                cmbParity.Text = Settings.Default.Parity.ToString();
                cmbStopBits.Text = Settings.Default.StopBits.ToString();
                cmbDataBits.Text = Settings.Default.DataBits.ToString();
                cmbParity.Text = Settings.Default.Parity.ToString();
                cmbBaudRate.Text = Settings.Default.BaudRate.ToString();
                CurrentDataMode = Settings.Default.DataMode;

                cmbPortName.Items.Clear();
                foreach (string s in SerialPort.GetPortNames())
                    cmbPortName.Items.Add(s);

                if (cmbPortName.Items.Contains(Settings.Default.PortName))
                    cmbPortName.Text = Settings.Default.PortName;
                else if (cmbPortName.Items.Count > 0)
                    cmbPortName.SelectedIndex = 0;
                else
                {
                    MessageBox.Show(this, "There are no COM Ports detected on this computer.\nPlease install a COM Port and restart this app.", "No COM Ports Installed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.Close();
                }
            }

            /// <summary> Enable/disable controls based on the app's current state. </summary>
            private void EnableControls()
            {
                //Enable/disable controls based on whether the port is open or not
                gbPortSettings.Enabled = !comport.IsOpen;
                txtSendData.Enabled = btnSend.Enabled = comport.IsOpen;

                if (comport.IsOpen)
                    btnOpenPort.Text = "&Close Port";
                else
                    btnOpenPort.Text = "&Open Port";
            }

            /// <summary> Send the user's data currently entered in the 'send' box.</summary>
            private void SendData()
            {
                if (CurrentDataMode == DataMode.Text)
                {
                    //Create an ASCII encoding variable
                    Encoding ascii = Encoding.ASCII;
                    //Create an Unicode variable
                    Encoding unicode = Encoding.Unicode;
                  
                    //Convert the string into a byte[]
                    byte[] unicodeBytes= unicode.GetBytes(txtSendData.Text);

                    //Perform the conversion from one encoding to the other
                    byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);

                    //Convert the new byte[] into a char[] and then into a string.
                    //This is a slightly different approach to converting to illustrate
                    //the use of GetCharCount/GetChars
                    char[] asciiChar = new char[ascii.GetCharCount(asciiBytes,0,asciiBytes.Length)];
                    ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChar, 0);

                    string sNEW = new string(asciiChar);
                    //Send the user's text straight out the port
                    comport.WriteLine(sNEW);
                    //Show in the terminal window the user's text
                    Log(LogMsgType.Outgoing, txtSendData.Text + "\n");
                }
                else
                {
                    try
                    {
                        //Convert the user's string of hex digits (ex: B4 CA E2) to a byte array
                        byte[] data = HexStringToByteArray(txtSendData.Text);

                        //Send the binary data out the port
                        comport.Write(data, 0, data.Length);

                        //Show the hex digits on in the terminal window
                        Log(LogMsgType.Outgoing, ByteArrayToHexString(data) + "\n");
                    }
                    catch (FormatException)
                    {
                        //Inform the user if the hex string was not properly formatted
                        Log(LogMsgType.Error, "Not properly formatted hex string: " + txtSendData.Text + "\n");
                    }
                }
                txtSendData.SelectAll();
            }

            /// <summary> Log data to the terminal window. </summary>
            /// <param name="msgtype"> The type of message to be written. </param>
            /// <param name="msg"> The string containing the message to be shown. </param>
            private void Log(LogMsgType msgtype, string msg)
            {
                rtfTerminal.Invoke(new EventHandler(delegate
                {
                    rtfTerminal.SelectedText = string.Empty;
                    rtfTerminal.SelectionFont = new Font(rtfTerminal.SelectionFont, FontStyle.Bold);
                    rtfTerminal.SelectionColor = LogMsgTypeColor[(int)msgtype];
                    rtfTerminal.AppendText(msg);
                    rtfTerminal.ScrollToCaret();
                }));
            }

            /// <summary> Convert a string of hex digits (ex: E4 CA B2) to a byte array. </summary>
            /// <param name="s"> The string containing the hex digits (with or without spaces). </param>
            /// <returns> Returns an array of bytes. </returns>
            private byte[] HexStringToByteArray(string s)
            {
                s = s.Replace(" ", "");
                byte[] buffer = new byte[s.Length / 2];
                for (int i = 0; i < s.Length; i += 2)
                    buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
              
                return buffer;
            }

            /// <summary> Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2)</summary>
            /// <param name="data"> The array of bytes to be translated into a string of hex digits. </param>
            /// <returns> Returns a well formatted string of hex digits with spacing. </returns>
            private string ByteArrayToHexString(byte[] data)
            {
                StringBuilder sb = new StringBuilder(data.Length * 3);
                foreach (byte b in data)
                    sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
                
                return sb.ToString().ToUpper();
            }

            private DataMode CurrentDataMode
            {
                get
                {
                    if (rbHex.Checked)
                        return DataMode.Hex;
                    else
                        return DataMode.Text;
                }
                set
                {
                    if (value == DataMode.Text)
                        rbText.Checked = true;
                    else
                        rbHex.Checked = true;
                }
            }

            //Event Handlers
            
            private void frmTerminal_Shown(object sender, EventArgs e)
            {
                Log(LogMsgType.Normal, String.Format("Application Started at: {0}\n", DateTime.Now));
            }

            private void frmTerminal_FormClosing(object sender, FormClosingEventArgs e)
            {
                //The form is closing, save the user's preferences
                SaveSettings();
            }

            private void rbText_CheckedChanged(object sender, EventArgs e)
            {
                if (rbText.Checked)
                    CurrentDataMode = DataMode.Text;
            }
            private void rbHex_CheckedChanged(object sender, EventArgs e)
            {
                if (rbHex.Checked)
                    CurrentDataMode = DataMode.Hex;
            }

            private void cmbBaudRate_Validating(object sender, CancelEventArgs e)
            {
                int x;
                e.Cancel = !int.TryParse(cmbBaudRate.Text, out x);
            }
            private void cmbDataBits_Validating(object sender, CancelEventArgs e)
            {
                int x;
                e.Cancel = !int.TryParse(cmbDataBits.Text, out x);
            }

            private void btnOpenPort_Click(object sender, EventArgs e)
            {
                // If the port is open, close it.
                if (comport.IsOpen)
                    comport.Close();
                else
                {
                    //Set the port's settings
                    comport.BaudRate = int.Parse(cmbBaudRate.Text);
                    comport.DataBits = int.Parse(cmbDataBits.Text);
                    comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text);
                    comport.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text);
                    comport.PortName = cmbPortName.Text;
                 
                    //Open the port
                    comport.Open();
                }

                //Change the state of the form's controls
                EnableControls();

                //If the port is open, send focus to the send data box
                if (comport.IsOpen)
                    txtSendData.Focus();
            }

            private void btnSend_Click(object sender, EventArgs e)
            {
                SendData();
            }

            private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
            {
                //This method will be called when there is data waiting in the port's buffer
                
                //Determain which mode (string or binary) the user is in
                if (CurrentDataMode == DataMode.Text)
                {
                    //Read all the data waiting in the buffer
                    string data = comport.ReadExisting();

                    //Display the text to the user in the terminal
                    Log(LogMsgType.Incoming, data);
                }
                else
                {
                    //Obtain the number of bytes waiting in the port's buffer
                    int bytes = comport.BytesToRead;

                    //Create a byte array buffer to hold the incoming data
                    byte[] buffer = new byte[bytes];

                    //Read the data from the port and store it in our buffer
                    comport.Read(buffer, 0, bytes);

                    //Show the user the incoming data in hex format
                    Log(LogMsgType.Incoming, ByteArrayToHexString(buffer));
                }
            }

            private void txtSendData_KeyDown(object sender, KeyEventArgs e)
            {
              //If the user presses [ENTER], send the data now
              if (KeyHandled = e.KeyCode == Keys.Enter)
              {
                  e.Handled = true;
                  SendData();
              }
            }
            private void txtSendData_KeyPress(object sender, KeyPressEventArgs e)
            {
                e.Handled = KeyHandled;
            }
          }
        }

    Saturday, August 11, 2012 8:47 AM

Answers

  • How do you know that no data is being sent?  I assume you are3 getting to either the Write() or Writeline() methods.  Here a few reasons your controller may not be responsing to the commands

    1) You are sending the wrong number of bits (7 or 8), the number of stop bits are wrong,  or the parity is wrong.

    2) The control lines (DSR, DTR, RTS,) are not set correctly.  This could be either a cable wiring problem and/or you are setting the control port incorrectly.

    3) Handshaking is in the wrong mode.  Hand shaking can be set to XONXOFF or to use the control lines.

    4) The baud rate is set wrong

    Here is a similar posting

    http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/b8b39587-e54c-4144-b2ed-5ed837f50795/


    jdweng

    Saturday, August 11, 2012 9:55 AM
  • Please notice. When You are using the .WriteLine method an additional character specified in the .NewlIne property of serialport class will be sent at the end of each frame. This may cause issues in the controller. Please check this.

    regards Ellen


    Ich benutze/ I'm using VB2008 & VB2010

    Saturday, August 11, 2012 10:27 AM

All replies

  • How do you know that no data is being sent?  I assume you are3 getting to either the Write() or Writeline() methods.  Here a few reasons your controller may not be responsing to the commands

    1) You are sending the wrong number of bits (7 or 8), the number of stop bits are wrong,  or the parity is wrong.

    2) The control lines (DSR, DTR, RTS,) are not set correctly.  This could be either a cable wiring problem and/or you are setting the control port incorrectly.

    3) Handshaking is in the wrong mode.  Hand shaking can be set to XONXOFF or to use the control lines.

    4) The baud rate is set wrong

    Here is a similar posting

    http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/b8b39587-e54c-4144-b2ed-5ed837f50795/


    jdweng

    Saturday, August 11, 2012 9:55 AM
  • Please notice. When You are using the .WriteLine method an additional character specified in the .NewlIne property of serialport class will be sent at the end of each frame. This may cause issues in the controller. Please check this.

    regards Ellen


    Ich benutze/ I'm using VB2008 & VB2010

    Saturday, August 11, 2012 10:27 AM
  • Hi Sir, i have used the same code. How is it possible to change my output to Binary instead of Hex-decimal number?

    Any Suggestions are humbly appreciated.
    Thankyou
    Thursday, August 21, 2014 10:33 AM
  • What do you mean by OUTPUT?  You can only output to your computer monitor or printer STRINGS.  You can save binary to a file or to another application.   So please define what you  mean by OUTPUT. 

    jdweng

    Thursday, August 21, 2014 1:09 PM