简体   繁体   English

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

[英]C# program to communicate with a xbee module using COM Ports / Using USB Serial COM Port

I am working ac# program which use the usb serial COM Port to transmit and receive data. 我正在使用usb串行COM端口来发送和接收数据的ac#程序。 The component is XBEE module which I want ot access but the code I wrote dosen't detect any serial port on my Computer. 该组件是XBEE模块,我想要访问但我写的代码不会检测到我的计算机上的任何串行端口。 Any one who can help me rectifying my mistake. 任何能帮助我纠正错误的人。

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

You need to set the correct parameters on the serial port to match the settings of the device. 您需要在串行端口上设置正确的参数以匹配设备的设置。 Have you installed XCTU ? 你安装了XCTU吗? Take note of the settings in the "search for devices" dialog - assuming it does find your device! 记下“搜索设备”对话框中的设置 - 假设它确实找到了您的设备!

XCTU发现设备对话框

For me, I found I actually just needed to set the baud rate: 对我来说,我发现我实际上只需要设置波特率:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM