I am working a c# program which use the usb serial COM Port to transmit and receive data. The component is XBEE module which I want ot access but the code I wrote dosen't detect any serial port on my Computer. 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? Take note of the settings in the "search for devices" dialog - assuming it does find your device!

For me, I found I actually just needed to set the baud rate:
var serialPort = new SerialPort(portName);
serialPort.BaudRate = 115200;
serialPort.Open();
// win!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With