我在这里潜伏了一段时间,并且学到了很多东西只是在探究问题。不过,我对某事感到很难过。我正在使用C#,我正在尝试使用IO.Ports与USB设备进行通信。
我有代码工作,假设正确的串口,但有时我的设备在插入时会在不同的端口上结束,我希望能够运行我的代码而无需更改一个变量并重新编译。因此,我希望代码轮询用户的端口号,尝试打开端口,在端口名称错误时捕获IOException,然后重新轮询直到给出有效端口。
这是我到目前为止所做的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
namespace USBDev1
{
class Program
{
static void Main(string[] args)
{
String portname = "COM";
SerialPort port = new SerialPort();
port.BaudRate = 9600;
bool loopthing = true;
while (loopthing == true)
{
Console.WriteLine("Which port?");
portname = "COM" + Console.ReadLine();
try
{
port.PortName = portname;
port.Open();
loopthing = false;
}
catch (System.IO.IOException e)
{
Console.WriteLine("Didn't work, yo");
throw (e);
}
}
// Body code
}
}
}
答案 0 :(得分:1)
我不确定你在问什么,但我认为你应该在选择之前列出可用的端口。以下代码可能有效;它编译,但没有经过测试。
这也不是一个好方法。更好的方法是在插入设备之前列出端口,然后再次列出端口以查看插入设备后显示的新端口。
SerialPort port;
bool isCorrectPortFound = false;
// Try different ports until a device reacts when a character is written to it
while (!isCorrectPortFound)
{
// Get all open ports
string[] ports = SerialPort.GetPortNames();
// Menu choice for a port to select
char portSelect = '0';
// Write the port names to the screen
foreach (string s in ports)
{
portSelect++;
Console.Write(portSelect);
Console.Write(". ");
Console.WriteLine(s);
}
Console.WriteLine();
Console.Write("Select from port 1 to " + portSelect.ToString() + " > ");
int selectedPort = (Console.Read()) - '0'; // Character value of 1 to ...
try
{
// Assume selectedPort is a valid integer, set baud, etc. as per your choice.
port = new SerialPort(ports[selectedPort] /* COMportBaudRate,
COMportParity,
COMportDataBits,
COMportStopBits */);
// OK, port is open, write to the device. The device
// must respond visually, blinking a LED or something.
port.Write("A");
Console.WriteLine();
Console.Write("Did the device get your message? (y n) > ");
int a = (Console.Read()) - 'a';
if (a + 'a' == 'y')
isCorrectPortFound = true;
else
{
port.Close();
port = null;
}
}
catch (Exception ex)
{
// Display a message box, exit, etc.
}
}
// Do other stuff