I need to read and write data to a serial port with a single click of a button.
A sensor board is attached to my PC, with a micro controller on it.
I have to do the following things with a single click:
- Send some data to the micro controller, like the sensor's register address
 - Read the data the controller sends back
 - Send the address of another sensor
 - Read the data
 - Etc
 
Afterwards, I have to do some calculation with the received data.
How can I send and read data multiple times with a single click of a button ?
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());
        }
        private void button1_Click(object sender, EventArgs e)
        {
            serialPort1.PortName = comboBox1.Text;
    serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
            serialPort1.Open();
            serialPort1.Write("$g helloboard!"); // A message sending to micro controller. After that micro controller send back a message. 
        }
        string str;
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int bytes = serialPort1.BytesToRead;
            byte[] buffer = new byte[bytes];
            serialPort1.Read(buffer, 0, bytes);
            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            str = enc.GetString(buffer);
        }
    }
}
				
                        
A simple (and dirty) solution is to have something like this
and in your Callback
serialPort1_DataReceivedadd:This is just for testing purposes. It is far from a good solution, next task would be to do the working in a background thread, so your GUI doesnt get blocked, and of course to define a condition that breaks the while-loop.