Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Serial Ports and Threading

Posted on 2007-12-06
6
Medium Priority
?
296 Views
Last Modified: 2013-12-03
I am writing a code that will output a set of bit array through the com port and too hyperterminal on another computer.  I need to have this transfer till i press stop button on my GUI interface.  I know we need to use threading to do this task.  The code below outputs the bits to hyperterminal once.  I would like to know how to make it a constant loop till i press stop.  Suggestions would be wonderful.

 public void TransmitData()
        {
            byte[] bytearray = new byte[512];
            try
            {
                SerialPort port = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One);
                port.Open();
                for (int i = 0; i < 512; i++)
                {
                    bytearray[i] = (byte)array[i];
                }
                port.Write(bytearray, 0, 512);
                port.Close();
            }
            catch
            {
                MessageBox.Show("Please Connect Serial Cable");
            }
        }
0
Comment
Question by:jmkotman
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 6

Expert Comment

by:so3
ID: 20426071
Put 2 buttons on the form.
  private void button1_Click(object sender, EventArgs e)
        {
            TransmitData();
        }
 
        bool working = true;
        public void TransmitData()
        {
            byte[] bytearray = new byte[512];
            try
            {
                working=true;
                SerialPort port = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One);
                port.Open();
 
                while (working)
                {
                    Application.DoEvents();
                    if (!working) break;
                    port.Write("write data");
                }
                port.Close();
            }
            catch
            {
                MessageBox.Show("Please Connect Serial Cable");
            }
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            working = false;
        }

Open in new window

0
 
LVL 3

Expert Comment

by:Dimkov
ID: 20426080
make while(1) loop inside the function
Created thread which points to this function.

Then you have command like thread.start, thread.stop, that tell when the thread sholud work or stop

just an idea :)
0
 
LVL 16

Accepted Solution

by:
gnoon earned 2000 total points
ID: 20426165
Just an implementation of Dimkov's idea
// a shared flag indicate that writing data should be continue
bool _continue;
 
/// <summary>
/// Keep transmit data to COM2 port until stop is pressed.
/// </summary>
public void TransmitData(byte[] data)
{
    try
    {
        using(SerialPort port = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One))
        {
            port.Open();
            while(_continue)
            {
                port.Write(data, 0, data.Length);
                try{System.Threading.Thread.Sleep(100);}catch(Exception){}
            }
        }
    }
    catch(Exception)
    {
        MessageBox.Show("Please Connect Serial Cable");
    }
}
 
public void StartTransmitInAnotherThread()
{
    // make a copy of data
    byte[] data = new byte[512];
    for(int i=0; i<data.Length && i<array.Length; i++)
        data[i] = (byte)array[i];
 
    // start new thread of transmit
    System.Threading.Thread t = new System.Threading.Thread(this.TransmitData);
    t.Name = "SerialPortThread";
    t.IsBackground = true;
    t.Start(data);
}
 
private void btnStart_Click(object sender, System.EventArgs e)
{
    // prevent click start twice
    btnStart.Enabled = false;
    btnStop.Enabled = true;
 
    // set flag to keep writing data
    _continue = true;
 
    // start transmit
    StartTransmitInAnotherThread();
}
 
private void btnStop_Click(object sender, System.EventArgs e)
{
    btnStart.Enabled = true;
    btnStop.Enabled = false;
 
    // set flag to stop writing data
    _continue = false;
}

Open in new window

0
Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

 

Author Comment

by:jmkotman
ID: 20428813
I just implamented So3's code and it worked, but does that have anything to do with threading?  I am implamenting gnoon's code and i am receiving the compile error The best overloaded method match for 'System.threading.thread.thread(System.threading.threadstart)' has some invalid arguments.  This error is refering to: System.Threading.Thread t = new System.Threading.Thread(this.TransmitData);

Thanks for your help
0
 
LVL 6

Expert Comment

by:so3
ID: 20429363
No, my code is not with threading because i don't think that you need it. From what i understood you need to use only one function (with start and stop function). For what you need it will not take the processor so you can use it without threading(and also is a easy solution)
0
 
LVL 16

Expert Comment

by:gnoon
ID: 20433051
>i am receiving the compile error The best overloaded method match for 'System.threading.thread.thread(System.threading.threadstart)' has some invalid arguments
Sorry for that. I did not test it in VS before post.

Compile error because TransmitData does not matched with signature function needed by ParameterizedThreadStart class. It requires a function having a parameter of type Object.

Change the code of TransmitData to this, you will get it compiled

public void TransmitData(object param)
{
    byte[] data = (byte[]) param;
    try
    {
        ....
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After several hours of googling I could not gather any information on this topic. There are several ways of controlling the USB port connected to any storage device. The best example of that is by changing the registry value of "HKEY_LOCAL_MACHINE\S…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…

670 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question