Have you tried anything else?
If you want to use a serial port, it makes sense to first give the user the opportunity to choose which port to use. This can be done easily by filling out the field with all available ports.
private void Form1_Load(object sender, EventArgs e)
{
string[] portNames = SerialPort.GetPortNames();
foreach (var portName in portNames)
{
comboBox1.Items.Add(portName);
}
comboBox1.SelectedIndex = 0;
}
This code uses a form with comboBox on it called "comboBox1" (default). You will need to add:
using System.IO.Ports;
to the directives used.
(button1) (textbox1) :
private void button1_Click(object sender, EventArgs e)
{
_serialPort = new SerialPort(comboBox1.Text, BaudRate, Parity.None, 8, StopBits.One);
_serialPort.DataReceived += SerialPortOnDataReceived;
_serialPort.Open();
textBox1.Text = "Listening on " + comboBox1.Text + "...";
}
private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
{
while(_serialPort.BytesToRead >0)
{
textBox1.Text += string.Format("{0:X2} ", _serialPort.ReadByte());
}
}
, :
private SerialPort _serialPort;
private const int BaudRate = 9600;
public partial class Form1 : Form
comPort TextBox.
: , click1 - , "SerialPort" . .
:
using System;
using System.IO.Ports;
using System.Windows.Forms;
namespace ComPortTests
{
public partial class Form1 : Form
{
private SerialPort _serialPort;
private const int BaudRate = 9600;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] portNames = SerialPort.GetPortNames();
foreach (var portName in portNames)
{
comboBox1.Items.Add(portName);
}
comboBox1.SelectedIndex = 0;
}
private void button1_Click(object sender, EventArgs e)
{
if(_serialPort != null && _serialPort.IsOpen)
_serialPort.Close();
if (_serialPort != null)
_serialPort.Dispose();
_serialPort = new SerialPort(comboBox1.Text, BaudRate, Parity.None, 8, StopBits.One);
_serialPort.DataReceived += SerialPortOnDataReceived;
_serialPort.Open();
textBox1.Text = "Listening on " + _serialPort.PortName + "...\r\n";
}
private delegate void Closure();
private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
{
if (InvokeRequired)
BeginInvoke(new Closure(() => { SerialPortOnDataReceived(sender, serialDataReceivedEventArgs); }));
else
{
while (_serialPort.BytesToRead > 0)
{
textBox1.Text += string.Format("{0:X2} ", _serialPort.ReadByte());
}
}
}
}
}