I have a very small code that shows available COM ports.
My question is:
Is there an easy way to have the program to run in the tray and only popup when a new COM port is available and is it possible to add the name for the COM port that you can see in device manager ec "USB serial port"?
I often add/remove a USB->RS232 comverter and find it a pain in the ass because I must go into the device manger to see what COM port it is assigned to. It's not the same each time
Maybe there already is a small app that can do this but I havent found it on Google yet
using System;
using System.Windows.Forms;
using System.IO.Ports;
namespace Available_COMports
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//show list of valid com ports
foreach (string s in SerialPort.GetPortNames())
{
listBox1.Items.Add(s);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
public static void Main()
{
// Get a list of serial port names.
string[] ports = SerialPort.GetPortNames();
Console.WriteLine("The following serial ports were found:");
// Display each port name to the console.
foreach(string port in ports)
{
Console.WriteLine(port);
}
Console.ReadLine();
}
Take a look at this question. It uses WMI to find available COM ports. You could keep track of what COM ports exist, and only notify about new ones.
To find out when devices are hot-plugged, you want to handle WM_DEVICECHANGE. Call RegisterDeviceNotification to enable delivery of these notifications.
The code to get the COM number of certain device.
List<USBDeviceInfo> devices = new List<USBDeviceInfo>();
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_PnPEntity");
foreach (ManagementObject queryObj in searcher.Get())
{
devices.Add(new USBDeviceInfo(
(string)queryObj["DeviceID"],
(string)queryObj["PNPDeviceID"],
(string)queryObj["Name"]
));
}
foreach (USBDeviceInfo usbDevice in devices)
{
if (usbDevice.Description != null)
{
if (usbDevice.Description.Contains("NAME OF Device You are Looking for")) //use your own device's name
{
int i = usbDevice.Description.IndexOf("COM");
char[] arr = usbDevice.Description.ToCharArray();
str = "COM" + arr[i + 3];
if (arr[i + 4] != ')')
{
str += arr[i + 4];
}
break;
}
}
}
mySerialPort = new SerialPort(str);
Related
i want to make my application can refresh serial port in c#. when list of port(In ComboBox) is empty and i hit button refresh, it's work perfectly and show the list of active port. but if i disconnected the Serial Port and i hit refresh button, actually it's must make the list of port(In Combobox) is empty because the serial port is disconnected. So how to make when i hit refresh button and the condition is disconnected, we make all of port list(in Combobox ) is empty ?
this is my code in refresh button:
private void button2_Click_2(object sender, EventArgs e)
{
if(String.IsNullOrEmpty(cboPort.Text))
{
comm.SetPortNameValues(cboPort);
for (int i = 0; i < cboPort.Items.Count; i++)
{
string value = cboPort.GetItemText(cboPort.Items[i]);
if (String.IsNullOrEmpty(value))
{
string a = cboPort.SelectedIndex.ToString();
return;
}
else
{
cboPort.SelectedIndex = 0;
}
}
}
else if ((cboPort.Text) != " " && cboPort.SelectedIndex == -1)
{
cboPort.Text = " ";
return;
}
}
this is my code in setportnamevalues :
public void SetPortNameValues(object obj)
{
foreach (string str in SerialPort.GetPortNames())
{
((ComboBox)obj).Items.Add(str);
}
}
my expetation is :
1. i connect serial port
2. i run my app
3. i disconnect serial port
4. i hit refresh
5. final result is port list empty in combobox
thanks for helping and responses, i am still new in c#. Greetings!
i Finally get the answer.
this is modification of setportnamevalues :
public void SetPortNameValues(object obj)
{
string[] ports = SerialPort.GetPortNames(); // load all name of com ports to string
((ComboBox)obj).Items.Clear(); //delete previous names in combobox items
foreach (string port in ports) //add this names to comboboxPort items
{
((ComboBox)obj).Items.Add(port); //if there are some com ports ,select first
}
if (((ComboBox)obj).Items.Count > 0)
{
((ComboBox)obj).SelectedIndex = 0;
}
else
{
((ComboBox)obj).Text = " "; //if there are no com ports ,write Empty
}
}
in here modification in button action :
private void button2_Click_2(object sender, EventArgs e)
{
comm.SetPortNameValues(cboPort);
}
yeah, finally i get what i want.
My solution as below
Initialize COM list
Add serialPort_OnClick event for combobox so that whenever user click on combobox, the COM items will be reloaded
private void InitializePortSetting()
{
mDateTime = DateTime.Now;
//1. Setting port list
// Get a list of serial port names.
portList = SerialPort.GetPortNames();
Console.WriteLine("The following serial ports were found:");
// Display each port name to the console.
foreach (string port in portList)
{
port_name.Items.Add(port);
}
}
private void serialPort_OnClick(object sender, EventArgs e)
{
port_name.Items.Clear();
port_name.Text = "";
//port_name.Dispose();
// Get a list of serial port names.
portList = SerialPort.GetPortNames();
Console.WriteLine("The following serial ports were found:");
// Display each port name to the console.
foreach (string port in portList)
{
port_name.Items.Add(port);
}
}
I am just a beginner in c#. I am now trying to interface arduino with a GUI application. And i need a small function to automatically detect the port which I have connected Arduino. I tried using nested "try and catch" blocks but it failed. can anyone suggest a good way to automatic select the port in which arduino is connected and open that port such that we can move directly to coding other switches that do different functions in that arduino.
Recently i had the same situation and i wrote this method to check for our device, all you need to set your device to send specific Pattern on Specific input. In this example if you send 0x33 then your device have to send 0x8A to identify itself.
public enum SerialSignal
{
SendSync = 0x33,
ReceiveSync = 0x8A,
}
private static SerialPort _arduinoSerialPort ;
/// <summary>
/// Polls all serial port and check for our device connected or not
/// </summary>
/// <returns>True: if our device is connected</returns>
public static bool Initialize()
{
var serialPortNames = SerialPort.GetPortNames();
foreach (var serialPortName in serialPortNames)
{
try
{
_arduinoSerialPort = new SerialPort(serialPortName) { BaudRate = 9600 };
_arduinoSerialPort.Open();
_arduinoSerialPort.DiscardInBuffer();
_arduinoSerialPort.Write(new byte[] { (int)SerialSignal.SendSync }, 0, 1);
var readBuffer = new byte[1];
Thread.Sleep(500);
_arduinoSerialPort.ReadTimeout = 5000;
_arduinoSerialPort.WriteTimeout = 5000;
_arduinoSerialPort.Read(readBuffer, 0, 1);
// Check if it is our device or Not;
if (readBuffer[0] == (byte)SerialSignal.ReceiveSync){
return true;
}
}
catch (Exception ex)
{
Debug.WriteLine("Exception at Serial Port:" + serialPortName + Environment.NewLine +
"Additional Message: " + ex.Message);
}
// if the send Sync repply not received just release resourceses
if (_arduinoSerialPort != null) _arduinoSerialPort.Dispose();
}
return false;
}
public partial class Form1 : Form
{
SerialPort serial = new SerialPort();
static SerialPort cport;
public Form1()
{
InitializeComponent();
button1.Enabled = true;
button2.Enabled = false;
button3.Enabled = false;
}
private void button1_Click(object sender, EventArgs e)
{
int i;
try
{
string[] ports = SerialPort.GetPortNames();
foreach(string newport in ports)
{
cport = new SerialPort(newport, 9600);
cport.Open();
cport.WriteLine("A");
int intReturnASCII = serial.ReadByte();
char returnMessage = Convert.ToChar(intReturnASCII);
if (returnMessage == 'B')
{
button2.Enabled = true;
break;
}
else
{
cport.Close();
}
}
}
catch (Exception )
{
Console.WriteLine("No COM ports found");
}
}
I undertand that I'm a bit late, But I have created a simple and free C# NuGet library that allows for interaction between the host PC and an Arduino board!
Examples in the ReadMe.txt file.
ArduinoFace - NuGet
I've been lurking here for a while, and have learned a ton just poking through questions. I'm pretty stumped on something, though. I'm using C#, and I'm trying to use IO.Ports to communicate with a USB device.
I've got code working that assumes the correct serial port, but sometimes my device winds up on a different port when plugged in, and I'd like to be able to run my code without having to change one variable and recompile. So, I want the code to poll the user for a port number, try to open the port, catch IOException when the port name's wrong, and re-poll until a valid port is given.
This is what I have so far:
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
}
}
}
I am not sure what you are asking, but I think you should list the available ports before choosing one. The following code may work; it compiles, but it is not tested.
This is also not a good way to do it. A better way would be to list the ports before you plug in your device, then list the ports again to see the new port that showed up after you plugged in the device.
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
Currently i am programming USB Bluetooth Dongle in C# 2010. I want to program in such a way that it automatically pairs with the Bluetooth device found. I don't want the user to manually accept the pairing request in both Mobile phone as well as in Windows 7. I am using my phone (X Peria S) to test this. Is this method of programming possible? I tried to code this using 32feet.net library for the Bluetooth, here is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using InTheHand.Net;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Guid service = BluetoothService.BluetoothBase;
private BluetoothClient bluetoothClient;
public Form1()
{
InitializeComponent();
}
private void Search_Bluetooth(object sender, EventArgs e)
{
BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable;
bluetoothClient = new BluetoothClient();
Cursor.Current = Cursors.WaitCursor;
BluetoothDeviceInfo [] bluetoothDeviceInfo = bluetoothClient.DiscoverDevices(10);
comboBox1.DataSource = bluetoothDeviceInfo;
comboBox1.DisplayMember = "DeviceName";
comboBox1.ValueMember = "DeviceAddress";
comboBox1.Focus();
Cursor.Current = Cursors.Default;
}
private void Pair(object sender, EventArgs e)
{
if (comboBox1.SelectedValue != null)
{
try
{
bluetoothClient.Connect(new BluetoothEndPoint((BluetoothAddress)comboBox1.SelectedValue, service));
MessageBox.Show("Connected");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
When i run this project i see the list of Bluetooth device in the surrounding but when ever i want to pair with it gives me an error saying "A connection attempt failed because the connected party did not properly respond a period of time"
I think the problem is private Guid service = BluetoothService.BluetoothBase but i am not sure, am i using the right service .BluetoothBase to pair with my phone?
Is there any existing solution for this? Any help and suggestion is highly appreciated.
Thanks.
You have to know the PIN for your dongle that will be requested during authentication.
If you want to connect to e.g. a mobile bluetooth RS-232 dongle, you have to know the PIN, but you don't have to accept the connection on the remote device (RS-232 dongle) because of the lack of a user interface. But on a mobile phone you have to.
I wrote the following interface:
interface IStackAdapter
{
IList<IRemoteBTDevice> DiscoveredDevices { get; }
void LoadStack();
void DoInquiry();
void DoConnection(IRemoteBTDevice rd);
void ReleaseLink();
}
Next, I implemented that interface for each different bluetooth stack. Here is the connection for a Widcomm stack:
/// <summary>
/// Connects to a remote device.
/// </summary>
/// <param name="rd">Remote device that the adapter is supposed to connect to.</param>
public void DoConnection(IRemoteBTDevice rd)
{
BluetoothAddress remoteAddress = new BluetoothAddress(Convert.ToInt64(rd.Id, 16));
BluetoothDeviceInfo bdi = new BluetoothDeviceInfo(remoteAddress);
try
{
if (!bdi.Authenticated)
{
string pair = rd.Pin; /* PIN for your dongle */
bool paired = BluetoothSecurity.PairRequest(bdi.DeviceAddress, pair);
}
}
catch (Exception ex)
{
//Log and rethrow
}
}
If you use a Windows Phone you can use the PeerFinder in Windows Phone to connect:
PeerFinder.AlternateIdentities["Bluetooth:PAIRED"] = "";
var available_devices = await PeerFinder.FindAllPeersAsync();
HostName hostName = null;
for (int i = 0; i < available_devices.Count; i++)
{
PeerInformation dispositivo = available_devices[i];
if (dispositivo.DisplayName.ToUpper() == /*Name of you device */)
{
hostName = dispositivo.HostName;
break;
}
}
if (hostName != null)
{
var socket = new StreamSocket();
await socket.ConnectAsync(hostName, "1");
}
So I'm working in Unity3D, programming in C#, and I heard that one can read data from a Bluetooth adaptor via SerialPort. I have several Bluetooth USB adaptors that I've tried to connect on my PC using this method. However, when I try to open the SerialPort, I get an error message that says port does not exist. I only included the code relevant to the question, but portI is a string ("COM11" or "COM12") and PortIn is of type SerialPort.
void OnGUI() {
GUI.Label(new Rect(btnX, btnY, btnW, btnH), "PortIn = " + portI);
if(!connected) {
for (int i = 0; i<ports.Length; i++) {
if(GUI.Button(new Rect(btnX, btnY + btnH + (btnH * i), btnW, btnH), ports[i])) {
portI = ports[i];
}
}
}
if(GUI.Button(new Rect(btnX + (btnW * 2 + 20), btnY, btnW, btnH), "Connect")) {
portIn = new SerialPort(portI, 9600);
portIn.ReadTimeout = 1000;
if (!portIn.IsOpen) {
portIn.Open();
}
connected = true;
}
}
}
Here is some code I'm working on and it gets data from the bluetooth connection to a standalone pc build (or in the editor) as long as the COM port (in my case COM9) is the same as the bluetooth device when you pair it.
After you pair it go to Bluetooth Settings > COM Ports and see what port is there with the name of your device. It might say COM8 or COM9 or whatever. If the device is paired and the COM Port is the same in the code as it is in your Bluetooth Settings, AND the timeout number and baud rate are the same as in the application you are sending the data from... then you will get something from this code when you run it. This is just meant to help make a connection to the serial over bluetooth connection.
Hope it helps someone. I've gotten a lot of great advice from reading these forums ;)
using System.Collections;
using System.IO.Ports;
public class checker : MonoBehaviour {
public static SerialPort sp = new SerialPort("COM9", 9600, Parity.None, 8, StopBits.One);
public string message, message1;
public string message2;
void Start() {
OpenConnection();
}
void Update() {
message2 = sp.ReadLine();
}
void OnGUI() {
GUI.Label(new Rect(10, 180, 100, 220), "Sensor1: " + message2);
}
public void OpenConnection() {
if (sp != null)
{
if (sp.IsOpen)
{
sp.Close();
message = "Closing port, because it was already open!";
}
else
{
sp.Open();
sp.ReadTimeout = 1000;
message = "Port Opened!";
}
}
else
{
if (sp.IsOpen)
{
print("Port is already open");
}
else
{
print("Port == null");
}
}
}
void OnApplicationQuit() {
sp.Close();
}
}
It should be possible. The bluetooth rfcomm/spp services emulate a serial port. A COM port if it's on Windows. Baudrate doesn't matter in this emulation, it will always go as fast as possible.
You need to have the devices paired and connected though.
To what device are you connecting? Try to make a connection first with Putty or some terminal application.