• 0

[C#]How can I receive data through serial port


Question

:cry:

I've tried several hours but could not hit my target.

My project is an interfacing program that can send and receive data from the com port. Now I can send data to the com port. Here is the code (It's very simple. You can go through it in few minutes.)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace WindowsApplication11
{
	public partial class Form1 : Form
	{
		static SerialPort sp = new SerialPort("COM4", 38400, Parity.None, 8, StopBits.One);

		public Form1()
		{
			InitializeComponent();
		}

		private void Y_ValueChanged(object sender, EventArgs e)
		{

		}

		private void rr_ValueChanged(object sender, EventArgs e)
		{

		}

		private void X_ValueChanged(object sender, EventArgs e)
		{

		}

		private void Z_ValueChanged(object sender, EventArgs e)
		{

		}

		private void yy_ValueChanged(object sender, EventArgs e)
		{

		}

		private void pp_ValueChanged(object sender, EventArgs e)
		{

		}

		private void LogBook_TextChanged(object sender, EventArgs e)
		{

		}

		private void send_Click(object sender, EventArgs e)
		{
			string str;
			str = X.Value.ToString() + "," + Y.Value.ToString() + "," + Z.Value.ToString() + "," + yy.Value.ToString() + "," + pp.Value.ToString() + "," + rr.Value.ToString() + "\r";
			sp.WriteLine(str);
			LogBookWrite(str);

		}

		private void LogBookWrite(string sText)
		{
			LogBook.Text += sText;
			LogBook.Text += '\n';
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			sp.Open();

		}


	}
}

The design "Form1" contains 6 NumericUpDown components (X,Y,Z,yy,pp,rr) , 2 textboxes (TextBox1 and LogBook) and a button called "send".

My sending format is "X,Y,Z,yy,pp,rr" + "\n". Such a string is sent when the button is pressed. Also, it's presented in the textbox called "LogBook".

The program can send data of such format without any problem but when I add some codes (in bold letters shown below), I cannot manage to receive data from the serial port.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace WindowsApplication11
{
	public partial class Form1 : Form
	{
		static SerialPort sp = new SerialPort("COM4", 38400, Parity.None, 8, StopBits.One);

		static string message = "";								  //add

		Thread readThread = new Thread(Read);			 //add

		public Form1()
		{
			InitializeComponent();
		}

		private void Y_ValueChanged(object sender, EventArgs e)
		{

		}

		private void rr_ValueChanged(object sender, EventArgs e)
		{

		}

		private void X_ValueChanged(object sender, EventArgs e)
		{

		}

		private void Z_ValueChanged(object sender, EventArgs e)
		{

		}

		private void yy_ValueChanged(object sender, EventArgs e)
		{

		}

		private void pp_ValueChanged(object sender, EventArgs e)
		{

		}

		private void LogBook_TextChanged(object sender, EventArgs e)
		{

		}

		private void send_Click(object sender, EventArgs e)
		{
			string str;
			str = X.Value.ToString() + "," + Y.Value.ToString() + "," + Z.Value.ToString() + "," + yy.Value.ToString() + "," + pp.Value.ToString() + "," + rr.Value.ToString() + "\r";
			sp.WriteLine(str);
			LogBookWrite(str);

		}

		private void LogBookWrite(string sText)
		{
			LogBook.Text += sText;
			LogBook.Text += '\n';
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			sp.Open();
			readThread.Start();						 //add

		}

		public static void Read()					   //add
		{														//add
			message = sp.ReadLine();				//add
			LogBook.Text += message + '\n';	 //add
		}														//add


	}
}

I've just modify the first program, adding several lines (the ones followed with "//add") to form the one shown above. My purpose is to put the data read from sp.ReadLine() into the "LogBook" textbox. (In this way, the "LogBook" textbox will contain both sent and received data.)

However, this program fails to work. I know the problem is that: in the static "Read method", LogBook.Text cannot be accessed. But I haven't come up with an idea to change this program so that it can receive data and present them in the "LogBook" textbox.

How should I attain my goal base on the first program? I mean how should I add codes to it.

Is there anyone that can help me? Take your time. I'm really worry about it. The deadline of the project is approaching.

Thank you very much!!

5 answers to this question

Recommended Posts

  • 0

Use the DataReceived Event.

static void Main(string[] args)

{

System.IO.Ports.SerialPort x = new System.IO.Ports.SerialPort();

x.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(x_DataReceived);

}

static void x_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)

{

//Handle data recieved.

}

  • 0
  MioTheGreat said:

Use the DataReceived Event.

static void Main(string[] args)

{

System.IO.Ports.SerialPort x = new System.IO.Ports.SerialPort();

x.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(x_DataReceived);

}

static void x_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)

{

//Handle data recieved.

}

Thank you for your help. But I've got another question (the one that only can be raised by beginers...).

In the GUI programs above, I can't see a main function. But I think it should exist somewhere.

So, how can I see the main function? Or, it is not auto generated code, so I should declare it explicitly myself, right?

I'm confused with a program without a main function. Can anybody tell me the structure of such kind of program? Then I'll be able to add the code mentioned by MioTheGreat.

Thank you!!

  • 0

Sorry. my internet was crapping out when I was trying to edit my post to make it more helpful.

Why is your serialport static?

Anyway, you can put this line:

x.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(x_DataReceived);

in your

public Form1()

{

InitializeComponent();

x.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(x_DataReceived);

}

  • 0
  MioTheGreat said:

Sorry. my internet was crapping out when I was trying to edit my post to make it more helpful.

Why is your serialport static?

Anyway, you can put this line:

x.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(x_DataReceived);

in your

public Form1()

{

InitializeComponent();

x.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(x_DataReceived);

}

Thanks a lot, MioTheGreat!!

Thanks to your helpful instruction, my program finally works. Yes, I should also change my serialport to a non-static one.

  • 0

Hi

i am also using serial port to receive data from smartphone.

this.serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.serialPort1_DataReceived);
 private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
		{

			MessageBox.Show(e.ToString());
			 MessageBox.Show(sender.ToString());
			 System.IO.Ports.SerialPort s = (System.IO.Ports.SerialPort)sender;
			 s.ReadLine(); // this line occur IO exception  
		}

can anyone guide me how to use this. i can't read line from serial port. i don't know what's the matter.

thanks a lot for helping me. :)

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • PC manufacturers used to trick BIOS copyright strings to get full editions of trial software by Usama Jawad You may have noticed that when you purchase a new PC, it comes with certain software pre-installed. Sometimes, when you open this software, it activates, and you receive the full version of it without paying any additional cost. This is because that PC's manufacturer is a licensee of that software and the fact that a customer gets the full version of a trial software for free serves as a perk for potential buyers. However, many PC manufacturers tried to trick this process in its infancy. During the days of Windows 95, when the Plug and Play specification was still in development, the OS' engineering team was trying to figure out ways through which it could identify PCs that existed prior to the inception of this specification. To that end, one of the methods they tried was searching for copyright strings and firmware dates in the BIOS. Through the course of this investigation, they discovered a rather oddly named copyright string "Not Copyright Fabrikam Computer" in a PC that was actually manufactured by Contoso. In this case, both Fabrikam and Contoso are fictional names that are used to describe this scenario without revealing the actual identity of the OEMs involved. Microsoft engineer Raymond Chen explains in a blog post that these odd copyright strings were actually appearing because Contoso PCs contained a trial version of a software and the company wanted the full version to be activated for customers even though it was not an official licensee. In order to bypass the costly licensing process, what the firm did was that it added the following text to its copyright string: "Copyright Contoso Not Copyright Fabrikam Computer". The trial version of said software would search for the string "Copyright Fabrikam Computer" and end up finding it within the substring of the convoluted copyright string mentioned above, accidentally activating the software's full version. While more robust ways were adopted later to avoid this problem, it's certainly interesting to see that OEMs would go to this length in order to distribute software that they are not officially allowed to. Well, as they say, the past stays in the past.
    • Uhm... a couple of issues with this. First, you're engaging in revisionist history. People weren't dragged from Win 7 to Win 10. You've kind of glossed over a whole cycle there: Win 8/8.1. People stayed on 7 because they hated 8/8.1 and held on until 10 showed up. THEN they actually started to switch voluntarily. Second, it's not about the OS, it's about the workflow. OS fans consistently miss this. People have work to do and they've invested a lot of time, effort and even money building their workflows. It's expensive to change so, that change has to offer real benefits that compensate for the cost of updating workflow and sorry, Win 11 just doesn't. That's the same reason they won't just jump to an entirely new OS - which has an even bigger workflow cost - until there's just no other option. Not only is there the core workflow cost, but the cost of finding new parallel software for the new OS, transferring and possible converting files and dealing with incompatibilities and then redeveloping workflows. It's just not as simple as "switch". And now there IS another option, stay on Win 10 for another year and pray for Win 12 (much as Win 7 users did with Win 8 - which happened when Win 10 came out).
    • Microsoft has some PC VR games that could be played with it.
  • Recent Achievements

    • Week One Done
      DrRonSr earned a badge
      Week One Done
    • Week One Done
      Sharon dixon earned a badge
      Week One Done
    • Dedicated
      Parallax Abstraction earned a badge
      Dedicated
    • First Post
      956400 earned a badge
      First Post
    • Week One Done
      davidfegan earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      616
    2. 2
      ATLien_0
      227
    3. 3
      +FloatingFatMan
      170
    4. 4
      Michael Scrip
      166
    5. 5
      Som
      148
  • Tell a friend

    Love Neowin? Tell a friend!