Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
C#
public partial class Form1 : Form
 {
     /* defining the required global variables*/
    SerialPort serialport = new SerialPort();// creating the object for serial port
    byte[] b = new byte[240];
    byte[] bb = new byte[100];
    string[] s = new string[100];
    string[] s1 = new string[100];
    int index2 = 0, index1;
    string[] portnames;
    private int bytenum;
    byte[] finalarray = new byte[40];
     public Form1()
     {
         InitializeComponent();//initializing the components
     }
     #region

     private void Form1_Load(object sender, EventArgs e)
     {
         serialport.DataReceived += new SerialDataReceivedEventHandler(DataReceived);
         btndcnct.Enabled = false;
         portnames = SerialPort.GetPortNames();//getting the port names
         for (int i = 0; i < portnames.Count(); i++)
         {
             cmbx_list.Items.Add(portnames[i]);
         }
         cmbx_list.SelectedIndex = 0;
         serialport.ReceivedBytesThreshold = 1;
         serialport.Encoding = ASCIIEncoding.ASCII;
         serialport.DataBits = 8;
         serialport.WriteTimeout = 60000;
         serialport.ReadTimeout = 60000;
         serialport.ReadBufferSize = 100;
         serialport.RtsEnable = Enabled;
     }
     #endregion
     private void btncnct_Click(object sender, EventArgs e)
     {
         if (serialport.IsOpen)//to check the condition for the serial port
         {
             serialport.DiscardInBuffer();
             serialport.DiscardOutBuffer();
             serialport.Close();
         }
         try
         {
             serialport.PortName = cmbx_list.SelectedItem.ToString();
             serialport.Handshake = Handshake.None;
             serialport.Parity = Parity.None;
             serialport.BaudRate = 9600;
             serialport.StopBits = StopBits.One;
             serialport.Open();
             btncnct.Enabled = false;
             btndcnct.Enabled = true;
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);//to show the error message
         }
         lbl_info.Text = cmbx_list.SelectedItem.ToString() + " Connected";
     }

     private void btndcnct_Click(object sender, EventArgs e)
     {
         serialport.Close();
         btncnct.Enabled = true;
         btndcnct.Enabled = false;
         lbl_info.Text = cmbx_list.SelectedItem.ToString() + " Disconnected";
     }

     private void btnsend_Click(object sender, EventArgs e)
     {
         string txtsend = textBox1.Text;
         string[] splitvalues = txtsend.Split(' ');
         byte[] bytes = splitvalues.Select(s => Convert.ToByte(s, 16)).ToArray();
         for (int i = 0; i < bytes.Count(); i++)
         {
             serialport.Write(bytes, i, 1);
         }
         lbl_sent.Text=bytes.Count().ToString() + " Bytes";
         System.Threading.Thread.Sleep(2000);

         try
         {
             for (index1 = 0;  index1 <= bytes.Length; index1++)
             {
                  s1[index1] = "";

               }
             index2 = 0;

             //textBox2.AppendText(textBox1.Text + Environment.NewLine);
             for ( index1 = 0; index1 < textBox1.Text.Length; index1++)
             {
                 s[index1] = textBox1.Text;
                 string buff = StringInfo.GetNextTextElement(s[index1], index1);
                 if (buff == "")
                 {
                     index2++;
                     index1++;
                     s1[index2] = (StringInfo.GetNextTextElement(textBox1.Text, index1)).ToString();
                 }
                 else
                 {
                     s1[index2] += buff;
                 }
             }
             for (int i = 0; i <= index2; i++)
             {
                 b[i] = Convert.ToByte(s1[i]);
             }
             for (int j = 0; j <= index2; j++)
             {
                 serialport.Write(b, j, 1);
             }
             lbl_info.Text=("Data sent Succefully through "+cmbx_list.SelectedItem.ToString());
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }
     }
     private void DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
     {
         bytenum = serialport.BytesToRead;
         serialport.ReceivedBytesThreshold = 50;
         textBox2.BeginInvoke(new MyDelegate(rcvtext));
     }

     public delegate void MyDelegate();
     public void  rcvtext()
     {
         byte[] bytearray = new byte[bytenum];
         serialport.Read(bytearray, 0, bytenum);
         for (int i = 0; i < bytenum; i++)
         {
             textBox2.Text += (Convert.ToByte(bytearray[i]).ToString();
         }

     }
     private void btnccl_Click(object sender, EventArgs e)
     {
         textBox1.Clear();
         textBox2.Clear();
         lbl_sent.Text = "";
         lbl_info.Text = "";
         btncnct.Enabled = true;
         btndcnct.Enabled = false;
     }

     private void btn_close_Click(object sender, EventArgs e)
     {
         this.Close();
     }
 }
Posted
Updated 12-Jul-15 21:40pm
v3
Comments
Kornfeld Eliyahu Peter 13-Jul-15 3:50am    
Where?
Suvendu Shekhar Giri 13-Jul-15 4:50am    
Please post only relevant code with the question and not the complete class/file so that it would be easier for us to identify the exact issue.

1 solution

I'm not sure exactly what you expect that code to do:
C#
private void DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    bytenum = serialport.BytesToRead;
    serialport.ReceivedBytesThreshold = 50;
    textBox2.BeginInvoke(new MyDelegate(rcvtext));
}

public delegate void MyDelegate();
public void  rcvtext()
{
    byte[] bytearray = new byte[bytenum];
    serialport.Read(bytearray, 0, bytenum);
    for (int i = 0; i < bytenum; i++)
    {
        textBox2.Text += (Convert.ToByte(bytearray[i]).ToString();
    }

}

But for starters that's a very poor way to do it: you risk losing data and generally getting messed up by trying to pass the count via a class level variable.
Either pass it via a method parameter, or (better) fetch it from the serial port directly as part of the tcvtext method.

What you are doing with the data once you have read it deosn;lt make a lot of sense either:
C#
textBox2.Text += (Convert.ToByte(bytearray[i]).ToString();

So...you take a byte value, convert it to a string, then try to convert the string back to a byte in order to add it to a string?
What part of that made any sense?
If you want to add the "Raw" data to the textbox then either use your loop "as is" but change that line to:
C#
textBox2.Text += (char) bytearray[i];
(or better, use a StringBuilder as an intermediary), or replace the whole loop and convert the whole array:
C#
textBox2.Text += System.Text.Encoding.ASCII.GetString(bytearray);

If you are trying to output the values as readable hex values, that's even easier:
C#
textBox2.Text += BitConverter.ToString(bytearray);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900