Click here to Skip to main content
16,013,930 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
See more:
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 System.IO.Ports;
using System.Timers;



namespace serialcomm
    
{ 
    public partial class Form1 : Form
    {
        SerialPort ComPort = new SerialPort();
        private Queue<byte> recievedData = new Queue<byte>();
        
        
        public Form1()
        { 
            InitializeComponent();
        }

        private void ports_Click(object sender, EventArgs e)
        { 
             
            
    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];
            // baud rate values

    cboBaudRate.Items.Add(300);
    cboBaudRate.Items.Add(600);
    cboBaudRate.Items.Add(1200);
    cboBaudRate.Items.Add(2400);
    cboBaudRate.Items.Add(9600);
    cboBaudRate.Items.Add(14400);
    cboBaudRate.Items.Add(19200);
    cboBaudRate.Items.Add(38400);
    cboBaudRate.Items.Add(57600);
    cboBaudRate.Items.Add(115200);
    cboBaudRate.Items.ToString();
    //get first item print in text
    cboBaudRate.Text = cboBaudRate.Items[0].ToString();
            // handshaking bits
    cboHandShaking.Items.Add("None");
    cboHandShaking.Items.Add("XOnXOff");
    cboHandShaking.Items.Add("RequestToSend");
    cboHandShaking.Items.Add("RequestToSendXOnXOff");
    cboHandShaking.Items.ToString();
    cboHandShaking.Text=cboHandShaking.Items[0].ToString();
            
           // data bits
            cboDataBits.Items.Add("7"); 
            cboDataBits.Items.Add("8");
            cboDataBits.Items.ToString();
            cboDataBits.Text = cboDataBits.Items[0].ToString();
            // stop bits
            cboStopBits.Items.Add("One");
            cboStopBits.Items.Add("OnePointFive");
            cboStopBits.Items.Add("Two");
            //get the first item print in the text
            cboStopBits.Text = cboStopBits.Items[0].ToString();

            //Parity 
            cboParity.Items.Add("None");
            cboParity.Items.Add("Even");
            cboParity.Items.Add("Mark");
            cboParity.Items.Add("Odd");
            cboParity.Items.Add("Space");
            cboParity.Text = cboParity.Items[0].ToString();
               
        }

       
        
        private void button1_Click(object sender, EventArgs e)
        { 
           

    if (button1.Text == "Closed")
    {
        button1.Text = "Open";
        ComPort.PortName = Convert.ToString(comboBox1.Text);
        ComPort.BaudRate = Convert.ToInt32(cboBaudRate.Text);
        ComPort.DataBits = Convert.ToInt32(cboDataBits.Text);
        ComPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cboStopBits.Text);
        ComPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), cboHandShaking.Text);
        ComPort.Parity = (Parity)Enum.Parse(typeof(Parity), cboParity.Text);
        
        ComPort.Open();
        button1.BackColor = Color.Green;
    }
    else if (button1.Text == "Open")
    {
        button1.Text= "Closed";
        ComPort.Close();
        button1.BackColor = Color.Red;
    }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }



        public class CommTimer
        {
            public System.Timers.Timer tmrComm = new System.Timers.Timer();
            public bool timedout = false;
            public  CommTimer()
            {
                timedout = false;
                tmrComm.AutoReset = false;
                tmrComm.Enabled = false;
                tmrComm.Interval = 1000; //default to 1 second
                tmrComm.Elapsed += new ElapsedEventHandler(OnTimedCommEvent);
            }

            public void OnTimedCommEvent(object source, ElapsedEventArgs e)
            {
                timedout = true;
                tmrComm.Stop();
            }

            public void Start(double timeoutperiod)
            {
                tmrComm.Interval = timeoutperiod;             //time to time out in milliseconds
                tmrComm.Stop();
                timedout = false;
                tmrComm.Start();
            }


        }



      

        private void button2_Click(object sender, EventArgs e)
        {
            string str = textBox1.Text;
            byte[] raw = new byte[textBox1.TextLength/2];
            for (int i = 0; i < raw.Length; i++)
            {
                raw[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);



            }
           ComPort.Write(raw,0,raw.Length);
           ComPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);

           
        }

        private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
             CommTimer tmrComm = new CommTimer();
            tmrComm.Start(4000);
             while ((ComPort.BytesToRead == 0) && (tmrComm.timedout == false))
            {
                Application.DoEvents();
            }

             int dataLength = ComPort.BytesToRead;
             byte[] data = new byte[dataLength / 2];
             string str = ComPort.ReadExisting();

             for (int i = 0; i < dataLength; i++)
             {
                 data[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
                 if (dataLength > 0)
                 {
                     textBox2.Text = Convert.ToString(data);
                 }

                tmrComm.tmrComm.Dispose();
                ComPort.DiscardInBuffer();
                ComPort.DiscardOutBuffer();
                ComPort.Close();

            }
        }
                        

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
                                  
  }

}
Posted
Updated 30-Oct-14 20:34pm
v2
Comments
Garth J Lancaster 31-Oct-14 2:37am    
what have you done so far to diagnose this ? have you stepped through the program in debug mode ? what is connected to the serial port ?
Member 11145129 31-Oct-14 2:47am    
energy meter
Member 11145129 31-Oct-14 2:54am    
is there any problem wid code ...pls help

The whole idea to read something in the timer event is bad. More exactly, it's not working. The ports is read not by any moments of time, but then data is written from the other end of your RS-232 cable. When you try to read data, and the data is not put in the buffer, it's fine. This call behaves like a blocking call, so your reading threads gets to the wait state, until it get awaken, by getting data in a buffer, or some other reason (timeout, thread abortion/termination).

Therefore, do this: put all your serial communication in a separate thread, along with all the logic responsible for the communication. For notification of the event on the UI, use the UI thread invocation mechanism explained in my past answers referenced below.w Window">^].

The idea is: you cannot call anything related to UI from non-UI thread. Instead, you need to use the method Invoke or BeginInvoke of System.Windows.Threading.Dispatcher (for both Forms or WPF) or System.Windows.Forms.Control (Forms only).

You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].

—SA
 
Share this answer
 
There isn't really anything we can do - we don't have any access to your system or the hardware your code is trying to communicate with.

And that probably isn't your "working" code because the indentation is all over the place, which normally only happens when you have compilation errors and Visual Studio can't work out what you are trying to write. If it is, try pressing CTRL+K CTRL+D to reformat the whole document and correct the indentation (it makes the code a lot more readable).

So it's up to you: use the debugger to "follow" the code and work out what is and isn't happening.

But one of the things you can't do is access controls such as text boxes in the DataRecieved event - it is always on a different thread, so it will always cause cross thread problems if you access UI elements. You have got to Invoke them.
 
Share this answer
 
well, you havnt answered my question about what have you've done to diagnose this - where does the program stop or hang or anything ? honestly, I'd pare most of your code back to

setup serial port
send (whatever command device needs)
read result

and skip the timeout stuff, until you know you can talk to the device in any fashion - even better, find a generalised serial port program, maybe like hyperterm or such, and when you can use that to talk to the device, then you can start replicating the settings, commands etc in your program, and building up functionality - else you don't even know if you have hardware issues for example
 
Share this answer
 
v2
Comments
CPallini 31-Oct-14 10:21am    
My 5.
Garth J Lancaster 1-Nov-14 19:13pm    
molto bene, grazie :-)

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