SerialPort Read Doesn't Work in C#

匆匆过客 提交于 2020-02-06 04:01:24

问题


i am develop C# windows app.it's read weight from weigh bridge machine to serial port.but,my code doesn't work.i am trying many examples download from internet doesn't work.my code is below:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;

namespace SerialPortTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        String a = "";

        private void button1_Click(object sender, EventArgs e)
        {
        serialPort1 = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
        if (serialPort1.IsOpen == false)
        {
            serialPort1.Open();
        }
        timer1.Start();
        button1.Enabled = false;
        button2.Enabled = true;
        }

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            a = a + serialPort1.ReadExisting();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (a.Length != 0)
            {
                textBox1.AppendText(a);
                a = "";
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen == true)
            {
                serialPort1.Close();
                button2.Enabled = false;
                button1.Enabled = true;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen == true)
            {
                button1.Enabled = false;
                button2.Enabled = true;
            }
            else
            {
                button1.Enabled = true;
                button2.Enabled = false;
            }
        }
    }
}

What i am wrong in my code can any one help me any working code. Thanks in Advance.


回答1:


You didn't register the serialPort1_DataReceived for serialPort1.

serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);



回答2:


You maybe need to extract the binary data from the stream instead of reading the data as a string?

Here's an example of some code that could be inside the DataReceived event handler...

int nb = serialPort1.BytesToRead;
if (nb > 0) 
{
  byte[] buffer = new byte[nb];
  serialPort1.Read(buffer, 0, nb);

  // Depending on the structure of the binary data ...
  int number1 = BitConverter.ToInt32(buffer, 0);
  int number2 = BitConverter.ToInt32(buffer, 4);
  // etc.
}


来源:https://stackoverflow.com/questions/12120787/serialport-read-doesnt-work-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!