问题描述
我已连接1台设备,该设备生成了一些随机数字,我想通过我的 Windows应用程序读取该数字.
I have attached 1 device which generated some random number and i want to read that number through my Windows application.
我正在使用以下代码:
public static void Main()
{
SerialPort mySerialPort = new SerialPort("COM19");
mySerialPort.BaudRate = 115200;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort.Open();
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
mySerialPort.Close();
}
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Debug.Print("Data Received:");
Debug.Print(indata);
}
使用此代码,我可以成功获取数据.
With this code I am successfully getting data.
但是这里的问题是我已经对来自设备管理器的 com端口(Com19)
进行了硬编码,我检查了我的设备连接到哪个端口,所以我已经硬编码了,但是我不想为此.
But problem here is I have hardcoded my com port(Com19)
that is from device manager I have checked that to which port my device is connected so I have hardcoded that but I don't want to do this.
相反,我将为用户提供 1下拉列表
,在该列表中,用户将仅看到与用户设备连接的端口.因此,当从此连接的设备中获取数据时,我将使用该用户选择的下拉端口.
Instead I will give user 1 dropdown
in which user will see only that port to which user device is connected. So when fetching data from this connected device I will use that user selected dropdown port.
我对Windows应用程序非常陌生,从未做过与串行端口相关的任何事情.
I am very much new to windows application and never done anything related to serial port.
推荐答案
当我将arduino连接到com端口时.我已经使用了这段代码(假设arduino返回了带有来自Arduino的信息"的文本):
When I have arduino connected to com port. I have use this code (assuming that arduino returned text with "Info from Arduino" inside):
SerialPort currentPort; // global variables
bool ArduinoPortFound = false;
...
try
{
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
currentPort = new SerialPort(port, 9600);
if (ArduinoDetected())
{
ArduinoPortFound = true;
break;
}
else
{
ArduinoPortFound = false;
}
}
}
catch { }
......
private bool ArduinoDetected()
{
try
{
currentPort.Open();
System.Threading.Thread.Sleep(1000);
string returnMessage = currentPort.ReadLine();
currentPort.Close();
if (returnMessage.Contains("Info from Arduino"))
{
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
return false;
}
}
更新:或者,您也可以使用 Windows管理规范(WMI)
UPDATE:Or you can also use Windows Management Instrumentation (WMI)
有关此的文章:如何以友好名称通过编程方式找到COM端口
这篇关于如何知道外部设备连接在哪个串行端口上并从该设备读取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!