Read and write data multiple times on a serial port with a single click

2.7k views Asked by At

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);
        }
    }
}
1

There are 1 answers

1
h3n On BEST ANSWER

A simple (and dirty) solution is to have something like this

    private bool data_received = true;
    private void button1_Click(object sender, EventArgs e)
    {
        while (true)
        {
            if (data_received)
            {
                data_received = false;
                serialPort1.Write("$get register 42");
            }
            System.Threading.Thread.Sleep(1);
        }
    }

and in your Callback serialPort1_DataReceived add:

data_received = true;

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.