dai henry

dai henry

  • NA
  • 1
  • 9.2k

Read data from rs232 port

Jul 24 2012 6:15 AM
I have the code as below to get data from weight balance (Model: VIBRA HAW30)

public partial class Form1 : Form
    {
        string InputData = String.Empty;
        System.IO.Ports.SerialPort port = new System.IO.Ports.SerialPort();
        delegate void SetTextCallback(string text);
        public Form1()
        {
            InitializeComponent();
            port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (port.IsOpen)
                port.PortName = "COM10";

            // try to open the selected port:
            try
            {
                port.PortName = "COM10";

                port.BaudRate = 9600;
                port.DataBits = 8;
                port.Parity = Parity.None;
                port.StopBits = StopBits.One;
                port.DtrEnable = true;
                port.Handshake = Handshake.None;
                port.DtrEnable = true;
                port.Open();
            }
            // give a message, if the port is not available:
            catch
            {
                MessageBox.Show("Serial port " + port.PortName +
                "cannot be opened!", "RS232 tester", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (port.IsOpen) port.WriteLine(textBox2.Text);
            else MessageBox.Show("Serial port is closed!",
                                 "RS232 tester",
                             MessageBoxButtons.OK,
                                 MessageBoxIcon.Error);
            textBox2.Clear();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
        }
        private void port_DataReceived_1(object sender, SerialDataReceivedEventArgs e)
        {
            InputData = port.ReadExisting();

            if (InputData != String.Empty)
            {
                this.BeginInvoke(new SetTextCallback(SetText), new object[] { InputData });
            }
        }
        private void SetText(string text)
        {
            this.textBox1.Text += text;
        }
    }

The result as below, how can I get the weight (? kg)


Please help me,
Thanks, Dai Nguyen Quang

Attachment: readrs232.rar

Answers (1)