dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 12 of 12

Thread: Data Received From Serial Port not

  1. #1
    Join Date
    Feb 2018
    Posts
    6

    Data Received From Serial Port not

    hi all

    i am received following string from Device and store in database

    N1Z1802200000000000001000000S009000570101640048500851202880033800265003140015000536000280001400048004420013100098002530

    Problem is date

    1.) complete data not show in Text box
    2.) Data save in database in shape of multi record . Kindly advise me .

    ===code Start =======
    Code:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.IO.Ports;
    using System.Data.OleDb;
    using MY251_Final.Screens.Templates;
    using System.Configuration;
    
    namespace M235_Final
    {
        public partial class TestingUtilityForm : TemplateForm
        {
            OleDbConnection connection = new OleDbConnection();
            
            // String DataOut;
            String DataIN;
            public TestingUtilityForm()
            {
                InitializeComponent();
                
                connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Interfacing.accdb";
            }
    
            private void TestingUtilityForm_Load(object sender, EventArgs e)
            {
                connection.Open();
    
                connectionStatusLabel.Text = "Connection Establish";
    
                connection.Close();
    
                // Create Function to get Serial Port 
                string[] ports = SerialPort.GetPortNames();
                comPortsComboBox.Items.AddRange(ports);
            }
    
            private void openButton_Click(object sender, EventArgs e)
            {
                try
                {
                    serialPort1.PortName = comPortsComboBox.Text;
                    serialPort1.BaudRate = Convert.ToInt32(baudComboBox.Text);
                    serialPort1.DataBits = Convert.ToInt32(dataBitsComboBox.Text);
                    serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stopBitsComboBox.Text);
                    serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), parityComboBox.Text);
                    serialPort1.Open();
                    progressBar1.Value = 100;
                }
    
                catch (Exception Err)
    
                {
                    MessageBox.Show(Err.Message,"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    
                }
            }
    
            private void closeButton_Click(object sender, EventArgs e)
            {
                if (serialPort1.IsOpen)
                {
                    serialPort1.Close();
                    progressBar1.Value = 0;
                }
            }
    
            private void sendDataButton_Click(object sender, EventArgs e)
            {
    
            }
    
            private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
            {
                DataIN = serialPort1.ReadExisting();
    
                this.Invoke(new EventHandler(ShowData));
                
                try
                {
                   connection.Open();
                   OleDbCommand command = new OleDbCommand();
                   command.Connection = connection;
                   command.CommandText = "insert into tblData(MYdata) values('"+ DataIN + "')";
                   command.ExecuteNonQuery();
                   DataIN = null;
                                
                   connection.Close();
                    
                }
                catch (Exception ex)
    
                {
                    MessageBox.Show("error"+ex);
    
                }
            }
    
            private void ShowData(object sender, EventArgs e)
            {
    
                int dataINLength = DataIN.Length;
                dataInLengthLabel.Text = String.Format("{0:00}", DataIN.Length);
    
            INdataTextBox.Clear();
            INdataTextBox.Text += DataIN;
    
            }
    
            private void portStatusLabel_Click(object sender, EventArgs e)
            {
                
             }
    
            private void clearButton_Click(object sender, EventArgs e)
            {
                INdataTextBox.Text = "";
                dataInLengthLabel.Text = "";
            }
            private void INdataTextBox_TextChanged(object sender, EventArgs e)
            {
               int DataOutLength = INdataTextBox.TextLength;
              dataInLengthLabel.Text = String.Format("{0:00}", DataOutLength);
            }
    
            private void connectionStatusLabel_Click(object sender, EventArgs e)
            {
                
            }
    
            private void showDataButton_Click(object sender, EventArgs e)
            {
                try
                {
                    connection.Open();
                    OleDbCommand command = new OleDbCommand();
                    command.Connection = connection;
                    string query = "select * from tblData";
                    command.CommandText = query;
    
                    OleDbDataAdapter da = new OleDbDataAdapter(command);
                    DataTable dt = new DataTable();
                    da.Fill(dt);
                    dataGridView1.DataSource = dt;
    
                    connection.Close();
                }
                catch (Exception ex)
    
                {
                    MessageBox.Show("error" + ex);
    
                }
            }
        }
        }
    =======End Code==============

    Name:  DataProblem2.jpg
Views: 87
Size:  24.0 KB
    Last edited by 2kaud; February 23rd, 2018 at 04:33 AM. Reason: Added code tags

  2. #2
    Join Date
    Feb 2018
    Posts
    6

    Re: Data Received From Serial Port not

    i am working in C#

  3. #3
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    19,262

    Re: Data Received From Serial Port not

    [moved from Visual C++ Forum]
    Victor Nijegorodov

  4. #4
    Arjay's Avatar
    Arjay is offline Moderator / MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    12,836

    Re: Data Received From Serial Port not

    You'll want to moving the serial port reading code into a separate thread. If you keep it in the main thread, ui actions (like a user moving the mouse) can interfere with the serial port readind and result in a loss of data.

  5. #5
    Join Date
    Feb 2018
    Posts
    6

    Re: Data Received From Serial Port not

    Quote Originally Posted by Arjay View Post
    You'll want to moving the serial port reading code into a separate thread. If you keep it in the main thread, ui actions (like a user moving the mouse) can interfere with the serial port readind and result in a loss of data.

    Thanks for your reply you means transfer following code to new thread

    ====
    Code:
    private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
    DataIN = serialPort1.ReadExisting();
    this.Invoke(new EventHandler(ShowData));
    try
    {
    connection.Open();
    OleDbCommand command = new OleDbCommand();
    command.Connection = connection;
    command.CommandText = "insert into tblData(MYdata) values('"+ DataIN + "')";
    command.ExecuteNonQuery();
    DataIN = null;
    connection.Close();
    }
    catch (Exception ex)
    {
    MessageBox.Show("error"+ex);
    }
    }
    Kindly advise or guide line for new thread
    Last edited by 2kaud; February 23rd, 2018 at 04:34 AM. Reason: Added code tags

  6. #6
    Arjay's Avatar
    Arjay is offline Moderator / MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    12,836

    Re: Data Received From Serial Port not

    Actually, let me back up. I believe the serialPort1_DataReceived handler is already running in a separate thread. More likely you are spending too much time in that handler method saving to the database. The handler needs to return very quickly otherwise you'll lose data. As a test comment out the db saving code in the handler and use Debug.WriteLine to display the incoming serial port data in the debugger window. Then run the program under the debugger and check to make sure you are getting all the data you're expecting.

    If you verify the data is coming in properly, then you need to find an approach that lets you store data quickly so your event handler can return rapidly. What I generally do in this case is to use a thread safe queue, an event, and a 2nd thread. The callback handler pushes the serial port data onto the queue and sets the event. The 2nd thread is waiting on the event and when the event is set, wakes up and processes the items in the queue by saving them to the database. With this approach, the database saving can take longer without blocking the serial port handler.

  7. #7
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,511

    Re: Data Received From Serial Port not

    [When posting code please use code tags. Go Advanced, select the formatted code and click '#'].

    Cheers!
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2017 (15.9.3)

  8. #8
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,511

    Re: Data Received From Serial Port not

    If data is being lost, this could be due to incorrect or no flow control settings. These are set for the DCB (Device Control Block). Details regarding DCB and flow control is detailed at

    https://msdn.microsoft.com/en-us/lib...#serial_topic6
    https://msdn.microsoft.com/en-us/lib...(v=vs.85).aspx
    (sorry but the example code is c).

    You may need to adjust the SerialPort class Handshake property as appropriate. See
    https://msdn.microsoft.com/en-us/lib...code-snippet-1
    https://msdn.microsoft.com/en-us/lib...v=vs.110).aspx
    Last edited by 2kaud; February 23rd, 2018 at 04:55 AM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2017 (15.9.3)

  9. #9
    Join Date
    Feb 2018
    Posts
    6

    Re: Data Received From Serial Port not

    Thanks for our replay i am stuck and not solved my problem

    can you tell me how to clear serial port buffer .

    My first record save successfully. but when transfer next record problem show .

  10. #10
    Arjay's Avatar
    Arjay is offline Moderator / MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    12,836

    Re: Data Received From Serial Port not

    Quote Originally Posted by sqadree View Post
    Thanks for our replay i am stuck and not solved my problem

    can you tell me how to clear serial port buffer .

    My first record save successfully. but when transfer next record problem show .
    In post #6 I outlined an debugging approach to determine whether the serial port handler is receiving all the data. Did you try this?

  11. #11
    Join Date
    Feb 2018
    Posts
    6

    Re: Data Received From Serial Port not

    Quote Originally Posted by Arjay View Post
    In post #6 I outlined an debugging approach to determine whether the serial port handler is receiving all the data. Did you try this?
    Thanks for your Replay . Yes Data Raceived.

    we found when i write following code under .private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    ==========================
    this.Invoke(new EventHandler(ShowData));


    connection.Open();
    OleDbCommand command = new OleDbCommand();
    command.Connection = connection;
    command.CommandText = "insert into tblData(MYdata) values('"+ DataIN + "')";
    command.ExecuteNonQuery();
    DataIN = null;
    connection.Close();
    =============================
    My Data Is Missing

    i create private void button3_Click(object sender, EventArgs e)
    when i click on button data is transfer successfully without any problem .
    ===============================
    connection.Open();
    OleDbCommand command = new OleDbCommand();
    command.Connection = connection;
    command.CommandText = "insert into tblData(MYdata) values('"+ DataIN + "')";
    command.ExecuteNonQuery();
    DataIN = null;
    connection.Close();
    ===============================

    i want to update my database automatically when serial port send data . for this purpose i think i need custom event.

    can you give me any advise how to solved this issue . how to create custom Thread and event

  12. #12
    Join Date
    Feb 2018
    Posts
    6

    Re: Data Received From Serial Port not

    hi Arjay can you tell me how to create separate thread to avoid UI actions .

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)