0
Reply

Serial Communcation Data Read C#

Muhammad Umair Akbar

Muhammad Umair Akbar

Jun 11 2015 5:02 AM
377

Hello Everyone
 
I have a board attached with some sensors.I need to perform these steps.
1:.Send some commands to microcontroller and then read the data after sending each command.
2:. Then I have to do some calculations on received data and then saved it in to a text file.
 
I am stuck at data read from Serial Port.
I know how to write data but I don't know how to call data read event every time(after sending different commands to microcontroller).
Here is my code.Your help will be appreciated.
 

 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 WindowsFormsApplication2
{

public partial class Form1 : Form
{

public Form1()
{

InitializeComponent();
comboBox1.Items.AddRange(SerialPort.GetPortNames());
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
}
private void button1_Click(object sender, EventArgs e)

{
serialPort1.PortName = comboBox1.Text;


serialPort1.Open();
serialPort1.Write("$g helloboard!"); 
 
}
string abc;
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{

int bytes = serialPort1.BytesToRead;
byte[] buffer = new byte[16];
serialPort1.Read(buffer, 0, 16);

System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
abc = enc.GetString(buffer);


  }

}