How to read specific characters from RS232 serial port data

Viewed 41

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

the problem is it shows all the data which is sent from the indicator but the real weight reading is 15,000.

How can I achieve this?

Thank you

Data sheet of the indicator is as follows

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

}

1 Answers

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", it looks like you have 15,000.01, which very is good, but of course I can't be sure.

All you have to do is to process these data. If you have it in string format, you should use Substring method to get rid of decimal places. For example, with:

string receivedText = DataIN.Substring(0,7);

You'll get "+015000", which you can easily convert to Int32 value, using:

int receivedValue = Convert.ToInt32(receivedText);

And you'll finally get your 15000 as integer.

Related