5
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;

namespace WindowsFormsApp7
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            getavaialbleports();
        }

        void getavaialbleports()
        {
            String[] ports = SerialPort.GetPortNames();
            comboBox1.Items.AddRange(ports);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (comboBox1.Text == "" || comboBox2.Text == "")
                {
                    textBox2.Text = "Please select port settings";
                }
                else
                {
                    serialPort1.PortName = comboBox1.Text;
                    serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
                    serialPort1.Open();
                    button1.Enabled = false;
                }
            }

            catch(UnauthorizedAccessException)
            {
                textBox2.Text = "Unauthorised Access";
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            serialPort1.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            serialPort1.WriteLine(textBox1.Text);
            textBox1.Text = "";
        }

        private void button4_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = serialPort1.ReadLine();
        }        
    }
}

I'm able to send data from the above code but for reception I'm not able to read data from it. There are no build errors. Please help me out to solve this problem.

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
Manu kumar
  • 51
  • 1
  • 1
  • 5
  • 2
    What do you mean you are not able to read data? Does the application hang on the ReadLine() call? What data do you expect to read? – Krzysztof Bracha May 19 '17 at 12:12
  • @KrzysztofBracha yes sir it will get hanged on the the read line. I want to read data coming from the serial port. I am using teraterm to pass the input. – Manu kumar May 20 '17 at 04:00

2 Answers2

2

You can implement "SerialPortDataReceivedEvent" to read data from serial port. Before opening connection to serial port register with "DataReceivedEvent", Inside button1_Click event add below code.

serialPort1.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_DataReceived);

Then add below event handler

private static void mySerialPort_DataReceived(
                    object sender,
                    SerialDataReceivedEventArgs e)
{
    SerialPort sp = (SerialPort)sender;
    string indata = sp.ReadExisting();
    //data received on serial port is asssigned to "indata" string
    //Console.WriteLine("Received data:");
    //Console.Write(indata);
}

Also, try to configure other properties like Parity, StopBits, DataBits etc. similar to the device on other end (with which you are trying to communicate).

Update data on UI: what you need is a delegate method that sets the Text property of your text box with a given string. You then call that delegate from within your mySerialPort_DataReceivedhandler via the TextBox.Invoke() method. Something like this:

public delegate void AddDataDelegate(String myString);
public AddDataDelegate myDelegate;

private void Form1_Load(object sender, EventArgs e)
{
  //...
  this.myDelegate = new AddDataDelegate(AddDataMethod);
}

public void AddDataMethod(String myString)
{
 textbox1.AppendText(myString);
}

private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
 SerialPort sp = (SerialPort)sender;
 string indata = sp.ReadExisting();

 textbox1.Invoke(this.myDelegate, new Object[] {indata});       
}

Let us know if you need further clarification.

Hope this helps..

Ketan
  • 79
  • 1
  • 9
  • thanks for your help sir . I was able to receive data. How to display the same in textbox. Can u help me out to find the syntax of that. I tried different formats but i didn't succeed in that but i am able to display the same in message box. – Manu kumar May 20 '17 at 04:42
  • Okay. For that you will have to make sure you don't end up freezing your UI-form. DataReceivedEvent runs on separate thread so you can not update UI from that thread. You can display received data to textbox in multiple ways, I would recommend using "delegates" to do that, you can also use RichTextBox instead of textbox. Depending upon your application's requirement. You can refer this link for updating UI from datareceivedEvent: "http://stackoverflow.com/a/11591116/5134119" – Ketan May 22 '17 at 06:35
  • i tried from the above solution but in the DataReceivedEvent i can't able to add textbox1 invoke command. Is there any libraries need to be added apart from system.Io.Ports. – Manu kumar May 23 '17 at 06:38
  • What is the error? Invoke comes from System.Windows.Forms namespace. – Ketan May 23 '17 at 08:53
0

In my opinion, first just try test, when initing serial port add

serialPort1.DataReceived += new 
SerialDataReceivedEventHandler(port_DataReceived);

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    int bytesToRead = serialPort1.BytesToRead;
    System.Diagnostics.Debug.WriteLine(bytesToRead);
}

after that in Output window you will sea is there any data in port or not

Monadire
  • 21
  • 3