[英]C# program to communicate with a xbee module using COM Ports / Using USB Serial COM Port
我正在使用usb串行COM端口來發送和接收數據的ac#程序。 該組件是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();
}
}
}
您需要在串行端口上設置正確的參數以匹配設備的設置。 你安裝了XCTU嗎? 記下“搜索設備”對話框中的設置 - 假設它確實找到了您的設備!
對我來說,我發現我實際上只需要設置波特率:
var serialPort = new SerialPort(portName);
serialPort.BaudRate = 115200;
serialPort.Open();
// win!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.