• 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

    • Model of the planet?  Last time I checked, Earth was a "Poisonous craphole dumpsterfire" model but I hear it's going to be recalled and scrapped before long...  
    • Prices have been unchanged for a looooong time, so really, it's time for a new price bracket, no matter how annoying it is. AAA titles just cost too much to develop these days. Personally, though, I tend to play mostly indie titles that are much lower priced and usually are far better games anyway.
    • Personally I don't usually play most games enough to justify paying £75 / $100 for a single game. I recently got a Switch 2 which came bundled with Mario Kart World, due to some discount codes I worked out I paid approx. £30 for Mario Kart World getting it bundled with the console. If I had paid £75 for Mario Kart World I'll be honest I would have been very disappointed with it. The big open world is essentially empty and lacking any real content, the changes to go GP mode mean you only really do one lap in most races... compared to Mario Kart 8 which has pretty much always been available for around £40 you have to ask why the game is almost double the cost? Look at all the content available in a Forza Horizon game compared to Mario Kart. For £30 I feel the game is ok, its not bad, however its not amazing either.
    • It was just a copy pasta from his other replies...
    • I think that the last game I bought on day-one was something like Ghost of Tsushima. I've come to realise that I don't have enough time (or sometimes inclination) to game as much as I used to, and I've got plenty of games to keep me occupied if I do decide to play. So I don't see the need to buy a game when it first releases - I wait until it goes on sale. If I'm really excited about a game and the price is under £50 then I would consider it, but anything over that price point gets ignored until the price comes down.
  • Recent Achievements

    • Apprentice
      Wireless wookie went up a rank
      Apprentice
    • Week One Done
      bukro earned a badge
      Week One Done
    • One Year In
      Wulle earned a badge
      One Year In
    • One Month Later
      Wulle earned a badge
      One Month Later
    • One Month Later
      Simmo3D earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      603
    2. 2
      ATLien_0
      281
    3. 3
      +FloatingFatMan
      179
    4. 4
      Michael Scrip
      151
    5. 5
      Steven P.
      111
  • Tell a friend

    Love Neowin? Tell a friend!