当前位置:编程学习 > C#/ASP.NET >>

C#串口问题:发送数据没有反应

我用串口连接设备,如果设备收到数据,灯会闪一下。波特率是38400,其他参数默认,为什么我的设置和串口助手一样,但是我发送出去的数据设备的灯就不闪,而用串口助手,则可以正常接收,并返回正常的数据。

我的程序偶尔也会接收到串口数据,我用另一个测试程序读二进制格式,结果只有这样的值:0,128,15,255,string格式都是乱码。对了,编码是ASCII。

我发的数据有R1;R2;L1-1=0;(分号表示一句独立的命令结束)


代码如下,这是一个测试代码,所以很多地方写得都很不安全,我们假设计算机上有一个可用的串口。
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace SPTest
{
    public partial class Form1 : Form
    {
        private SerialPort sp = new SerialPort();

        private delegate void AddText(string str);
        private AddText addText;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, System.EventArgs e)
        {
            this.sp.BaudRate = 38400;
            this.sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
            this.addText += delegate { };
            

            this.addText += new AddText(this.addTextTarget);

            foreach (string portname in SerialPort.GetPortNames())
            {
                this.comboBoxPorts.Items.Add(portname);
            }
        }

        void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string str = this.sp.ReadExisting();
            this.Invoke(this.addText, new object[] { str });
        }

        private void buttonOpenClose_Click(object sender, System.EventArgs e)
        {
            if (this.sp.IsOpen)
            {
                this.sp.Close();
                this.buttonOpenClose.Text = "Open";
            }
            else
            {
                this.sp.PortName = this.comboBoxPorts.SelectedItem.ToString() ;
                this.sp.Open();
                this.buttonOpenClose.Text = "Close";
            }
        }

        private void buttonSend_Click(object sender, System.EventArgs e)
        {
            if (this.sp.IsOpen)
            {
                this.buttonSend.Enabled = false;
                for (int i = 0; i < 20; i++)
                { 
                    this.sp.Write(this.textBoxSend.Text);
                    Thread.Sleep(100);
                }
                this.buttonSend.Enabled = true;
            }
        }

        private void addTextTarget(string str)
        {
            this.textBoxReceice.Text += str;
        }
    }
}
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,