My app uses USB based serial ports to connect to physical hardware devices. I can open any valid USB port and communicate with the external devices. However, when I close the connection, the USB port is left in some sort of indeterminate state for some time, and during that time further attempts to reconnect result in the "Access to port "COM--" is denied" error. However, after some few seconds, attempting to reconnect is successful. How can I determine WHEN the USB port will again support a new connection?
The code looks like this:
private void Setup(string Port)
{
bool ValidPort = false;
int CloseSleep = 10;
_PortName = Port;
_PortType = this;
string[] AvailablePorts = SerialPort.GetPortNames();
foreach(string aPort in AvailablePorts)
{
if (aPort == _PortName)
{
// The required port is listed in the list of available ports)
ValidPort = true;
break;
}
}
if (ValidPort)
{
try
{
if (_ThePort != null)
{
_ThePort.Close();
_ThePort.DataReceived -= ReceivedDataEventHandler;
while(CloseSleep-- > 0)
System.Threading.Thread.Sleep(100);
_ThePort.Dispose();
_ThePort = null;
}
}
catch (Exception ex)
{
EMS_Config_Tool.ModalDialog md = new EMS_Config_Tool.ModalDialog("Closing Port: " + ex.Message, "System Exception");
md.ShowDialog();
}
System.IO.Ports.SerialPort TheNewPort = new System.IO.Ports.SerialPort(Port, 38400);
// Setup the event handlers from Tx and Rx
Handler.DataOutEvent += CommsSender;
TheNewPort.DataReceived += ReceivedDataEventHandler;
TheNewPort.DataBits = 8;
TheNewPort.Parity = Parity.None;
TheNewPort.Handshake = System.IO.Ports.Handshake.None;
TheNewPort.StopBits = System.IO.Ports.StopBits.One;
// We will try 3 times to open the port, and report an error if we fail to open the port
try
{
TheNewPort.Open();
}
catch (Exception)
{
System.Threading.Thread.Sleep(1000);
try
{
TheNewPort.Open();
}
catch (Exception)
{
System.Threading.Thread.Sleep(1000);
try
{
TheNewPort.Open();
}
catch (Exception ex)
{
EMS_Config_Tool.ModalDialog md = new EMS_Config_Tool.ModalDialog("Opening Port: " + ex.Message, "System Exception");
return;
}
}
}
The final catch statement is where the error about Access being denied is issued. Note my attempt to retry opening the port 3 times doesn't really help. If I leave the port alone for about 5 to 10 seconds and retry calling the Setup method it succeeds immediately.
As #Neil said, there are many issues. The best thing to do, in my point of view, is to put the search in a loop, and as soon as the port can be opened, it will be.
I used to do like this :
public Task WaitingPort()
{
while (port is null)
{
port = CheckPort();
}
}
private SerialPort CheckPort()
{
string[] listPort = SerialPort.GetPortNames();
foreach(string namePort in listPort)
{
SerialPort port = new SerialPort(namePort, 9600);
if (!port.IsOpen)
{
try
{
port.Open();
port.ReadTimeout = 1500;
string data = port.Readline();
// I programmed my device to send an "A" until it receives
// "777" to be able to recognize it once opened
if (data.Substring(0, 1) == "A")
{
port.ReadTimeout = 200;
port.Write("777"); // to make it stop sending "A"
return port;
}
else
{
port.Close();
}
}
catch (Exception e1)
{
port.Close();
}
}
}
return null;
}
Of course, this is just some kind of a template which you have to reshape to your use
I have amended my code to use a constrained loop to give it a better chance to work, which it usually does. I was hoping that there was a better way to do it, as I tend to have pretty impatient users who will be posting defect reports if they have to wait 5 or 10 seconds to make a connection....
// We will try several times to open the port, upto 10 times over 5 seconds, and report an error if we finally fail to open the port
try
{
TheNewPort.Open();
}
catch (Exception ex)
{
RetryOpenTimer.Interval = 500;
RetryCount = 10;
RetryOpenTimer.Elapsed += new System.Timers.ElapsedEventHandler(RetryOpenTimer_Elapsed);
WaitForOpen = true;
RetryOpenTimer.Start();
while (WaitForOpen && RetryCount > 0)
{
System.Threading.Thread.Sleep(500);
}
if (WaitForOpen)
{
EMS_Config_Tool.ModalDialog md = new EMS_Config_Tool.ModalDialog("Opening Port: " + ex.Message, "System Exception");
return;
}
}
...
void RetryOpenTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
RetryOpenTimer.Stop();
RetryOpenTimer.Elapsed -= RetryOpenTimer_Elapsed;
try
{
if (RetryCount-- > 0)
{
TheNewPort.Open();
WaitForOpen = false;
}
else
return;
}
catch (Exception)
{
RetryOpenTimer.Start();
RetryOpenTimer.Elapsed += RetryOpenTimer_Elapsed;
}
}
Related
I am developing a desktop application which interacts with Arduino via SerialPort.
I want my application to respond every time arduino writes something on the serial port.
But DataReceivedHandler does not get triggered for all the events.
Here is the connection code -
public static bool connectToArduino()
{
foreach (string name in SerialPort.GetPortNames())
{
SerialPort serialPort = new SerialPort(name);
Console.WriteLine(name);
if (serialPort.IsOpen == false)
{
serialPort.PortName = name;
try
{
Console.WriteLine("Openning serial port.");
serialPort.WriteTimeout = 5000;
serialPort.ReadTimeout = 5000;
serialPort.BaudRate = 115200;
serialPort.Open();
serialPort.Write(Constants.CONNECT_APP_STRING);
Console.WriteLine("Written to serial port.");
string reply = serialPort.ReadLine();
//string reply = serialPort.ReadTo("\n");
Console.WriteLine("Reply is: " + reply);
Console.WriteLine("Read from serial port.");
if (reply == Constants.CONNECT_ACK)
{
Console.WriteLine(name);
Console.WriteLine("Connected with arduino controller");
//serialPort.DataReceived += DataReceivedHandler;
serialController = serialPort;
return true;
}
else if (reply+"\n" == Constants.CONNECT_ARDUINO_STRING) {
serialPort.WriteLine(Constants.CONNECT_ACK);
serialController = serialPort;
MessageBox.Show("Connected with arduino controller");
return true;
}
else
{
serialPort.Close();
}
}
catch (TimeoutException)
{
Console.WriteLine("Timeout occured.");
serialPort.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "ERROR");
Console.WriteLine(ex);
}
}
}
MessageBox.Show("Connection with Arduino failed!");
return false;
}
After this I set the data received handler -
SerialComm.serialController.DataReceived += DataReceivedHandler;
Now, the problem is that sometimes DataReceivedHandler is not being triggered.
I am not able to find a pattern in this. It randomly just skips some events.
Any idea what is going wrong?
Looking at the documentation you can find in the remarks:
The DataReceived event is not guaranteed to be raised for every byte received. Use the BytesToRead property to determine how much data is left to be read in the buffer.
If the event is in your case too unreliable to be trusted catch every incoming information from your device, then you could use an extra thread which would run in the background constantly checking the BytesToRead property and/or constantly reading with ReadExisting which is non-blocking.
I have been working on this for days, but can't fix the problem.
This is what I've got right now ->
Bluetooth handler
protected BluetoothAdapter bluetoothAdapter;
protected BluetoothServer btServer;
protected BluetoothSocket btSocket;
protected BluetoothDevice pairedBTDevice;
protected BluetoothListener btListener;
protected ParcelUuid uuid;
public BluetoothHandler()
{
BluetoothAdapter = null;
}
public void Initialize()
{
BluetoothAdapter = BluetoothAdapter.DefaultAdapter;
// Check if it has a bluetooth interface
if (BluetoothAdapter == null)
{
Console.WriteLine("Bluetooth is not available!");
return;
}
// Check if bluetooth interface is enabled
if (!BluetoothAdapter.IsEnabled)
{
BluetoothAdapter.Enable();
}
int count = 0;
// Get all the devices in the bluetooth list
var listDevices = BluetoothAdapter.BondedDevices;
if (listDevices.Count > 0)
{
foreach (var btDevice in listDevices)
{
// Get the specific controller
if (btDevice.Name == "MOCUTE-032_B52-CA7E")
{
UUID = btDevice.GetUuids().ElementAt(count);
pairedBTDevice = btDevice;
}
count++;
}
}
// Check if bluetooth is enabled
// Check if there is a device
if (BluetoothAdapter.IsEnabled && pairedBTDevice != null)
{
// Check if it's paired
if (pairedBTDevice.BondState == Bond.Bonded)
{
// First start the server
btServer = new BluetoothServer(this);
Thread.Sleep(1000);
// Start a new thread
Thread thread = new Thread(new ThreadStart(Connect));
thread.Start();
}
}
}
protected void Connect()
{
// Check if there is no socket already
if (btSocket == null)
{
try
{
btSocket = pairedBTDevice.CreateRfcommSocketToServiceRecord(UUID.Uuid);
}
catch (IOException ex)
{
throw ex;
}
}
try
{
Console.WriteLine("Attempting to connect...");
// Create a socket connection
btSocket.Connect();
}
catch
{
Console.WriteLine("Connection failed...");
Console.WriteLine("Attempting to connect...");
try
{
btSocket = pairedBTDevice.CreateInsecureRfcommSocketToServiceRecord(UUID.Uuid);
btSocket.Connect();
}
catch
{
Console.WriteLine("Connection failed...");
return;
}
}
Console.WriteLine("Client socket is connected!");
Read();
}
protected void Read()
{
btListener = new BluetoothListener();
btListener.Read(btSocket);
}
Bluetooth server
private BluetoothHandler bluetoothHandler;
private BluetoothServerSocket serverSocket;
private Thread thread;
public BluetoothServer(BluetoothHandler bluetoothHandler)
{
this.bluetoothHandler = bluetoothHandler;
BluetoothServerSocket tmp = null;
try
{
tmp = bluetoothHandler.BluetoothAdapter.ListenUsingRfcommWithServiceRecord("MOCUTE-032_B52-CA7E", bluetoothHandler.UUID.Uuid);
}
catch (IOException ex)
{
throw ex;
}
serverSocket = tmp;
thread = new Thread(new ThreadStart(Run));
thread.Start();
}
protected void Run()
{
System.Console.WriteLine("Server is running...");
while (true)
{
try
{
serverSocket.Accept();
}
catch (IOException ex)
{
System.Console.WriteLine("FAILED! === > " + ex);
}
}
}
Bluetooth listener
protected Stream mmInStream;
public void Read(BluetoothSocket socket)
{
Stream tmpIn = null;
try
{
tmpIn = socket.InputStream;
}
catch (IOException ex)
{
throw ex;
}
mmInStream = tmpIn;
Thread thread = new Thread(new ThreadStart(Run));
thread.Start();
}
protected void Run()
{
byte[] buffer = new byte[1024];
int bytes;
Console.WriteLine("Waiting for events...");
while (true)
{
try
{
if (mmInStream.IsDataAvailable())
{
bytes = mmInStream.Read(buffer, 0, buffer.Length);
}
}
catch (Exception ex)
{
throw ex;
}
}
}
I would like to connect with the following controller ->
So, I would like to catch the buttons events from the controller, but I have no idea anymore..
I've got also the known error: Java.IO.IOException: "read failed, socket might closed or timeout, read ret: -1
The UUID of the controller is: 00001124-0000-1000-8000-00805f9b34fb
I have one example to connect to a Bluetooth(2.0) device on my Github you can check the code and see if you setup is correct here is the link https://github.com/AlejandroRuiz/Mono/blob/master/Arduino/Bluetooth/MainActivity.cs if you have any specific question about the code please let me know also you need to be sure what kind of bluetooth is using because the way to connect to a 4.0 BLE is very different that the old 2.0
The problem is solved. I didn't need a Bluetooth socket. I just used the override methods "KeyDown" and "KeyUp". It works great now :)
If you need a socket and you've got an exception like IOException: read failed, socket might closed then you should read my fix here:
IOException: read failed, socket might closed - Bluetooth on Android 4.3
Do 3 chunks sent by 3 calls to Linux 'C' write(), through TCP, get received as the same, 3 chunks by Windows C# .BeginReceive(), or a single, contiguous chunk, or however many have been received when .BeginReceived is called?
A 'C' app on Linux sends a message by 3 calls to write(), through TCP connection, to a Windows C# app, which receives using BeginReceive().
Does BeginReceive() need to be called three times, to receive each of the three chunks sent by write()? Or is the size received by BeginReceive() equal to the size of what Windows has received when BeginReceive() is called? Which could be all bytes sent by the 3 writes(), or a partial amount, so .BeginReceive() should be called UNTIL all are received?
The Linux C app is running on an embedded TI ARM, and inside the same box the Windows C# app is running a Single Board Computer. The ARM has a direct Ethernet connection to the SBC.
The communication between the ARM and SBC sometimes fails to start at boot time, and I'm reverse engineering the source code to check for bad design.
ARM side is TCP listener, and Windows client initiates the TCP connection.
Using MontaVista(R) Linux(R) Professional Edition 5.0.0 (0702774)
and Windows-7 Visual-Studio 2010 Visual-C#.
Here is the ARM sending software, and the Windows receiving software........................
LINX 'C'
char msgBuffer[64];
sprintf(msgBuffer, START_MSG_ENVELOPE, msgId++, ack);
write(connection->fd, msgBuffer, strlen(msgBuffer));
write(connection->fd, msg, strlen(msg));
write(connection->fd, END_MSG_ENVELOPE, strlen(END_MSG_ENVELOPE));
HERE IS THE WINDOWS C# SIDE OF IT.............................................
private static void makeConnection(Socket clientSocket, int iPortNo)
{
TimeoutObject.Reset();
socketexception = null;
IPAddress ip;
//create the end point
IPEndPoint ipEndPoint;
ip = IPAddress.Parse(ipAddress);
try
{
ipEndPoint = new IPEndPoint(ip, iPortNo);
//connect to the remote host...
clientSocket.BeginConnect(ip, iPortNo, new AsyncCallback(CallBackMethod), clientSocket);
if (TimeoutObject.WaitOne(5 * 1000, false)) //5 secs connection timeout
{
if (!IsConnectionSuccessful)
{
string msg = VNResourceManager.Instance.GetString(VNMessages.DAM_NOT_FOUND);
if (socketexception != null)
msg += ": " + socketexception.Message;
throw new Exception(msg);
}
}
else
{
clientSocket.Close();
throw new TimeoutException(VNResourceManager.Instance.GetString(VNMessages.CONNECTION_TO_DAM_TIMED_OUT));
}
//watch for data ( asynchronously )...
WaitForData();
}
catch (SocketException e)
{
socketexception = e;
throw;
}
}
private static void CallBackMethod(IAsyncResult asyncresult)
{
try
{
IsConnectionSuccessful = false;
Socket socket = asyncresult.AsyncState as Socket;
if (socket.Connected)
{
socket.EndConnect(asyncresult);
IsConnectionSuccessful = true;
}
}
catch (Exception ex)
{
IsConnectionSuccessful = false;
socketexception = ex;
}
finally
{
TimeoutObject.Set();
}
}
public static void WaitForData()
{
try
{
if (asyncCallBack == null)
{
asyncCallBack = new AsyncCallback(OnDataReceived);
}
CSocketPacket theSocPkt = new CSocketPacket();
theSocPkt.thisSocket = clientSocket;
asyncResult = clientSocket.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, asyncCallBack, theSocPkt);
}
catch (SocketException se)
{
notifyErrorEventSubscribers(se);
}
}
public static void send(string message)
{
try
{
byte[] byData = System.Text.Encoding.ASCII.GetBytes(message);
clientSocket.Send(byData);
}
catch (SocketException se)
{
notifyErrorEventSubscribers(se);
throw;
}
}
//[MethodImpl(MethodImplOptions.Synchronized)]
public static void OnDataReceived(IAsyncResult result)
{
try
{
CSocketPacket theSockId = (CSocketPacket)result.AsyncState;
//end receive...
int messageSize = 0;
messageSize = theSockId.thisSocket.EndReceive(result);
Console.WriteLine(">>>>>>>>> messageSize = " + messageSize); // !!!
char[] chars = new char[messageSize + 1];
System.Text.Decoder d = System.Text.Encoding.ASCII.GetDecoder();
int charLen = d.GetChars(theSockId.dataBuffer, 0, messageSize, chars, 0);
string replyMessage = new System.String(chars);
lock (syncLock) //LastIndexOf function accesses the current culture info and we clear it in WM_TIMECHANGE handler (protecting from that race condition here)
{
if (replyMessage.LastIndexOf("\0") > 0)
replyMessage = replyMessage.Remove(replyMessage.LastIndexOf("\0"), 1);
if (replyMessage.LastIndexOf(Terminator) > 0)
replyMessage = replyMessage.Remove(replyMessage.LastIndexOf(Terminator), 1);
}
// Continue the waiting for data on the Socket
WaitForData();
receivedMsg += replyMessage;
// only serialize when we feel we have a message or we have reached the message line limit
if (((receivedMsg.Contains("message") && receivedMsg.Contains("/>")) || receivedMsg.Contains("</message>")) /* || (mRecvdMsgLineCount == Message.kMaxLines) */ )
{
List<XmlMessage> msgList = new List<XmlMessage>();
int index = -1;
do
{
index = receivedMsg.IndexOf("</message>");
if (index != -1)
{
XmlMessage message;
string strMessage = receivedMsg.Substring(0, index + "</message>".Length);
//MessageBox.Show(strMessage);
strMessage = strMessage.TrimStart(new char[] { '\r', '\n' });
receivedMsg = receivedMsg.Remove(0, index + "</message>".Length);
try
{
message = (XmlMessage)XmlMessage.GetXmlSerializer().Deserialize(XmlReader.Create(new StringReader(strMessage)));
}
catch (InvalidOperationException error)
{
string strErrorMessage = error.Message;
if (error.InnerException != null)
strErrorMessage += "\r\n" + error.InnerException.Message;
notifyErrorEventSubscribers(new Exception(strErrorMessage + "\r\n-----------------------------------------------------------------\r\n" + strMessage));
return;
}
msgList.Add(message);
}
} while (index != -1);
StringWriter sw = new StringWriter();
string serializedXml = string.Empty;
string strXmlMessage = string.Empty;
foreach (XmlMessage message in msgList)
{
if (message.ack_required && (message.update == null))
{
XmlMessage messageAcknowledge = new XmlMessage();
messageAcknowledge.ack_required = false;
messageAcknowledge.ack = new ack();
messageAcknowledge.ack.success = true;
messageAcknowledge.ack.id = message.id;
try
{
sendMessage(messageAcknowledge);
}
catch(Exception ex)
{
Logger.Log(EnumLoggingLevel.Error, "SocketCommunicationXMl.OnDataReceived", ex.Message);
}
}
if (dataReceivedEvent != null)
{
dataReceivedEvent(new object(), new DataReceivedEventArgs(message));
}
if ((ackRequiredMsg != null) && (message.ack != null))
{
if ((message.ack.id == ackRequiredMsg.id) && message.ack.success)
{
eventWaitForAck.Set();
}
}
}
}
}
catch (ObjectDisposedException objectDisposedException)
{
// Dispatcher.dispatchDebug(Debug.Level_3,"Socket has been closed", this);
notifyErrorEventSubscribers(objectDisposedException);
}
catch (SocketException se)
{
if (se.ErrorCode == 10054)
{
/*
for (int i = 0; i < 50; i++)
{
Thread.Sleep(1000);
}
try
{
SocketCommunicationDaq.Reconnect();
}
catch(Exception ex)
{
VNMsgBox.Show(ex.Message, MsgButtonType.OkOnly, MsgIconType.Error);
return;
}
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
for (int i = 0; i < 3; i++)
{
try
{
connect();
break;
}
catch (Exception ex)
{
System.Threading.Thread.Sleep(5000);
}
}
*/
Logger.Log(EnumLoggingLevel.Error, "OnDataReceived: ", se.ToString());
}
else
{
notifyErrorEventSubscribers(se);
}
}
}
As others have mentioned, TCP is a streaming protocol, so you never can tell how many DataReceived callbacks it will take to get all 100 bytes. Could be 1, could be 100.
The receive code is fairly complex and performance could be improved (too many string operations). Hard to tell if there are control-flow issues. I would suggest breaking the DataReceived method up to simplify. Here's a reasonable skeleton:
public static void OnDataReceived(IAsyncResult result)
{
//1) copy all data received into a buffer of some sort, like MemoryStream
//2) Dispatch any/all full messages that have been received
// to a queue or handler method (maybe handle on another thread)
//(hold onto any leftover bytes received that are part of the next message)
//Call BeginReceive() again
}
Also, it can help simplify Framing if you use a Length-Prefixed message format.
As #nos already stated, number of receives does not equal the number of sends, regardless of the client application was written in.
See also When does TcpClient's NetworkStream finish one read operation?
I wrote a message last week but would like to add another more simple question again to clarify.
I have a serial port console application. There are 20 virtual ports. My application successfully working but doesnt change received data value until I restart the application. I am not sure why it happens.
This issue appeared after FIFO enabled property was set to true.
How can i refresh serial port?
Thanks
--- here is the codes :
static void serialportinstances()
{
for (int ix =1; ix < 20; ix++)
{
if (sportlar.ContainsValue("COM"+ix.ToString()) ==false)
{
try
{
SerialPort ekle = new SerialPort("COM" + ix.ToString(), 1200, Parity.None, 8, StopBits.One);
//ekle.DtrEnable = true;
//ekle.RtsEnable = true;
try
{
ekle.NewLine = "\r";
ekle.Open();
ekle.DataReceived += new SerialDataReceivedEventHandler(datareceived);
Console.WriteLine(String.Format("Dinamik SP {0} başarıyla açıldı", ekle.PortName));
}
catch (Exception eu)
{
Console.WriteLine(String.Format("Dynamic SP {0} açılamadı!", ekle.PortName));
}
sportlar.Add(ekle, "COM" + ix.ToString());
}
catch (Exception ee)
{
Console.WriteLine("port could not be created");
}
}
}
}
and datareceiving handler ;
static void datareceived(object sender, SerialDataReceivedEventArgs e)
{
lock (mylockobject)
{
SerialPort spn = (SerialPort)sender;
try
{
string s = spn.ReadLine();
GetWeightPWI(spn.PortName, s);
Thread.Sleep(1);
}
catch (Exception ee)
{
Console.WriteLine("error : " + ee.ToString());
}
}
}
and parsing the received data here :
private static void GetWeightPWI(string portadi, string alinan)
{
Console.WriteLine("PORT NAME : "+portadi+" and received data : "+alinan.toString());
}
I'm trying to open each port and send <mccon> serially, for which my microcontroller will respond <connected>\n after which the C# code must exit the for each loop.
I'm having a problem at the serialPort.PortName = str; line. After two iterations, it does not continue further.
I tried doing this manually too. I made a drop down and selected ports one by one. After the second port, it does not allow to change the serial Port. But in case I select within two tries, it works fine.
I know OOP in C++. But I'm new to C#. I'm not sure why the loop fails.
public Form1()
{
InitializeComponent();
send_button.Enabled = false;
//Availabe COM ports
SerialPort tmp;
foreach(string str in SerialPort.GetPortNames())
{
tmp = new SerialPort(str);
if (tmp.IsOpen == false)
{
serialPort.PortName = str;
try
{
//Open serial port
serialPort.Open();
serialPort.BaudRate = 9600;
serialPort.WriteTimeout = 10;
serialPort.ReadTimeout = 10;
serialPort.Write("<mccon>");
readtxt.Text = serialPort.ReadTo("\n");
if (readtxt.Text == "<connected>")
{
send_button.Enabled = true;
port_combobox.Enabled = false;
break;
}
else
{
serialPort.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
I don't have multiple serial ports, but when I compiled and executed your code, I noticed that you are not closing the serial port if it errors during the read. I suggest you modify your code as follows:
SerialPort tmp;
foreach (string str in SerialPort.GetPortNames())
{
tmp = new SerialPort(str);
if (tmp.IsOpen == false)
{
serialPort.PortName = str;
try
{
//open serial port
serialPort.Open();
serialPort.BaudRate = 9600;
serialPort.WriteTimeout = 10;
serialPort.ReadTimeout = 10;
serialPort.Write("<mccon>");
String s = serialPort.ReadTo("\n");
if (s == "<connected>")
{
break;
}
else
{
serialPort.Close();
}
}
catch (TimeoutException)
{
serialPort.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
I'm not sure the effect on changing the port name while it's open, but it could well cause the issues you are seeing.
Could you execute this code and return what it shows? It might show some information about the Arduino port which you can then use for the serialport.
Add a reference to System.Management and also add the using, and then try the code:
using System.Management;
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_PnPEntity");
foreach (ManagementObject queryObj in searcher.Get())
{
if (queryObj["Caption"].ToString().ToUpper().Contains("ARDUINO"))
{
Console.WriteLine(queryObj["Caption"]);
foreach (PropertyData pd in queryObj.Properties) { Console.WriteLine(pd.Name + " : " + pd.Value); }
}
}
}
catch (ManagementException e)
{
Console.WriteLine(e.Message);
}
Console.ReadKey();