SerialPort读取在C#中不起作用

时间:2012-08-25 09:28:34

标签: c# .net serial-port

我正在开发C#windows app.it从称重桥机器到串口读取重量。但是,我的代码不起作用。我正在尝试从互联网下载的许多示例无效。我的代码如下:

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

我的代码错误可以帮助我任何工作代码。 提前致谢。

2 个答案:

答案 0 :(得分:5)

您没有为serialPort1注册serialPort1_DataReceived。

serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);

答案 1 :(得分:0)

您可能需要从流中提取二进制数据,而不是将数据作为字符串读取?

以下是可能在DataReceived事件处理程序中的一些代码示例...

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