Click here to Skip to main content
15,892,965 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i need to test whether serial port sending /receiving data , i have two c# winforms applications.
one application is:
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel=Microsoft.Office.Interop.Excel;
using System.IO;
using System.Threading;
using System.IO.Ports;



namespace Hand_Held_Data_Transporter
{
    public partial class Form1 : Form
    {
        int[] stream_buffer;
        String final = null;
        String upload1 = null, upload2 = null, upload3 = null, upload4 = null, upload5 = null, upload6 = null, upload7 = null;
        
        

        /*private static Microsoft.Office.Interop.Excel.Workbook mWorkBook;
        private static Microsoft.Office.Interop.Excel.Sheets mWorkSheets;
        private static Microsoft.Office.Interop.Excel.Worksheet mWSheet1;
        private static Microsoft.Office.Interop.Excel.Application oXL;*/

        public Form1()
        {
            InitializeComponent();
            progressBar1.Enabled = false;
            progressBar2.Enabled = false;

            serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);
           
        }



        private void Browse_Click(object sender, EventArgs e)
        {

            OpenFileDialog fdlg = new OpenFileDialog();
            fdlg.Filter = "All Files(*.*)|*.*";
            if (fdlg.ShowDialog() == DialogResult.OK)
            {


                textBox1.Text = fdlg.FileName;
                File.ReadAllText(textBox1.Text);

            }
        }

       



        private void Upload_Click(object sender, EventArgs e)
        {

           // StringBuilder sb = new StringBuilder();
  

            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(textBox1.Text, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
            Excel.Range xlRange = xlWorksheet.UsedRange;

            int rowCount = xlRange.Rows.Count;
            int colCount = xlRange.Columns.Count;
            progressBar1.Visible = true;
            

            int k = 100 / rowCount;

            for (int i = 1; i <= rowCount; i++)
            {

               
                for (int j = 1; j <= colCount; j++)
                {

                    if (j == 1)
                      upload1 = xlRange.Cells[i, j].Value.ToString();
                 

                        //upload1 = xlRange.Cells[i, j].Value.ToString();
                    if (j == 2)
                        upload2 = xlRange.Cells[i, j].Value.ToString();
                   
                  
                    if (j == 3)
                        upload3 = xlRange.Cells[i, j].Value.ToString();
                
                    if (j == 4)
                        upload4= xlRange.Cells[i, j].Value.ToString();
                    
                     if (j == 5)
                         upload5 = xlRange.Cells[i, j].Value.ToString();
                     
                    if (j == 6)
                        upload6= xlRange.Cells[i, j].Value.ToString();
                    
                    if (j == 7)
                        upload7 = xlRange.Cells[i, j].Value.ToString();
                    

                    final = "$ POST," + upload1 + "," + upload2 + "," + upload3 + "," + upload4 + "," + upload5 + "," + upload6 + "," + upload7 + " # ";


                }

                if (serialPort1.IsOpen)

                   serialPort1.Write(final);
                Thread.Sleep(1000);

              serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);

                MessageBox.Show(final);
                if (progressBar1.Value < 100)
                {
                    Thread.Sleep(1000);
                    progressBar1.Value += k;
                }


            }
            progressBar1.Value = 100;

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            progressBar1.Visible = false;
            progressBar2.Visible = false;
           serialPort1.Open();

           string[] ArrayComPortsNames = null;
           int index = -1;
           string ComPortName = null;

           ArrayComPortsNames = SerialPort.GetPortNames();
           do
           {
               index += 1;
               comboBox1.Items.Add(ArrayComPortsNames[index]);
           }

           while (!((ArrayComPortsNames[index] == ComPortName)
                         || (index == ArrayComPortsNames.GetUpperBound(0))));
           Array.Sort(ArrayComPortsNames);

           //want to get first out
           if (index == ArrayComPortsNames.GetUpperBound(0))
           {
               ComPortName = ArrayComPortsNames[0];
           }
           comboBox1.Text = ArrayComPortsNames[0];



         
        }

and another application is:
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//using Hand_Held_Data_Transporter;
using System.IO.Ports;

namespace handheld_Responce
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            serialPort1.Open();
            serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);
        }

        private void send_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {




        }

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                String RecievedData;
                RecievedData = serialPort1.ReadExisting();
                if (!(RecievedData == ""))
                {
                    textBox2.Text += RecievedData;
                }
            }
        }
    }
}




plz tell me how can i communicate both applications

[edit]Code block added - OriginalGriff[/edit]
Posted
Updated 12-Dec-13 21:05pm
v2

1 solution

Well, for starters, stop adding DataRecieved handlers so often. If you do it in your constructor, there is no need to do it again, particularly no every time you press a button!

Then I would start by just sending a changing character from one app to the other to prove it works at all: Open the serial port, then sit in a loop:
C#
for (int i = 0; i < 1000; i++)
   {
   serialPort1.Write((i % 10).ToString();
   Thread.Sleep(100);
   }
If you are receiving ok on the other app, then you can look at starting to send actual data.
 
Share this answer
 
Comments
Member 10263519 13-Dec-13 4:25am    
plz where can i keep that code and how to test plz help me. qm very new to serial port
OriginalGriff 13-Dec-13 4:27am    
Put it in a button click event handler - it's only to check if you are communicating at all, before you move on to actual data.
Member 10263519 13-Dec-13 5:01am    
i ran that by keeping that in a button.

first i debugged the two applications. then i clicked the button in which i placed that code .it's giving error as

invalidOperation exception was unhandled
Cross-thread operation not valid: Control 'textBox2' accessed from a thread other than the thread it was created on.
OriginalGriff 13-Dec-13 5:24am    
Ah! now we are getting somewhere - it's the second (receiving) application that is causing the error message.
If you look at MSDN:
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived(v=vs.110).aspx
You will see that it says:
"The DataReceived event is raised on a secondary thread when data is received from the SerialPort object. Because this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception. If it is necessary to modify elements in the main Form or Control, post change requests back using Invoke, which will do the work on the proper thread."

You need to Invoke your textbox!
textBox2.Invoke((MethodInvoker)delegate { textBox2.Text += RecievedData; });
Member 10263519 13-Dec-13 5:31am    
thanq soooooooooooo much for your quick reply........

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



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