Home > Back-end >  How to read specific characters from RS232 serial port data
How to read specific characters from RS232 serial port data

Time:09-21

I am trying to retrieve weight data from a weight indicator which sends data through the RS232 com port ( Converted through USB)

following is the application I designed to receive data

enter image description here

Code is as follows

namespace Weight_Test { public partial class Form1 : Form { string dataIN;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        string[] ports = SerialPort.GetPortNames();
        cbComPort.Items.AddRange(ports);
        btnOpen.Enabled = true;
        btnClose.Enabled = false;
    }

    private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
        dataIN = serialPort1.ReadExisting();
        this.Invoke(new EventHandler(ShowData));
    }

    private void ShowData(object sender, EventArgs e)
    {
        txtWeight.Text = dataIN;
    }

    private void btnOpen_Click(object sender, EventArgs e)
    {
        try
        {
            serialPort1.PortName = cbComPort.Text;
            serialPort1.BaudRate = Convert.ToInt32(9600);
            serialPort1.DataBits = Convert.ToInt32(8);
            serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), "One");
            serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), "None");

            serialPort1.Open();
            btnOpen.Enabled = false;
            btnClose.Enabled = true;
        }
        catch (Exception err)
        {
            MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            btnOpen.Enabled = true;
            btnClose.Enabled = false;
        }
    }

    private void btnClose_Click(object sender, EventArgs e)
    {
        if (serialPort1.IsOpen)
        {
            serialPort1.Close();
            btnOpen.Enabled = true;
            btnClose.Enabled = false;
        }
    }
}

}

CodePudding user response:

It all seems to work properly. All you need is processing of received data.

You said that your result should be 15,000.

Depends on what sensor you use, it can supply specified resolution, accuracy. Please edit your post and give us some information from datasheet about sending data.

Since you got " 01500001F

  •  Tags:  
  • c#
  • Related