C#程序使用COM端口/使用USB串行COM端口与xbee模块通信

时间:2012-11-24 16:18:11

标签: c# .net winforms

我正在使用一个c#程序,它使用USB串行COM端口来传输和接收数据。该组件是XBEE模块,我想要访问但我写的代码不会检测到我的计算机上的任何串行端口。任何能帮助我纠正错误的人。

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

namespace WindowsFormsApplication3
{
    public partial class Test : Form
    {
        private StringBuilder receivedData = new StringBuilder();

        public Test()
        {
            InitializeComponent();
        }

        private void Test_Load(object sender, EventArgs e)
        {
            Array ports = System.IO.Ports.SerialPort.GetPortNames();
            for (int x = 0; x <= ports.Length; comboBox1.Items.Add(ports.GetValue(x))) ;
            timer1.Start();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            serialPort1.PortName = comboBox1.Text;
            if (!serialPort1.IsOpen)
            {
                serialPort1.Open();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                serialPort1.Close();
            }
        }

        private void Test_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                serialPort1.Close();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                serialPort1.Write(textBox2.Text + "\n\r");
            }
        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            receivedData.Append(serialPort1.ReadExisting());
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            textBox1.Text = receivedData.ToString();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您需要在串行端口上设置正确的参数以匹配设备的设置。你安装了XCTU吗?记下“搜索设备”对话框中的设置 - 假设它确实找到了您的设备!

The XCTU Discover Devices dialog

对我来说,我发现我实际上只需要设置波特率:

var serialPort = new SerialPort(portName);
serialPort.BaudRate = 115200;
serialPort.Open();
// win!