Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I had a GUI designed using C# windows forums, they are communicating using USB serial communication to communicate with Hardware electronics.

I want use the same GUI with some other hardware electronics but i am using RS232 to USB converter to send data from electronics to PC. is it possible to detect RS232 to USB converter as USB device and use the same GUI? when i tried with VID or PID which they are trying for USB communication its not working. do i need any drivers?

I tried susscefully to establish serial communcation via serialport class in c#. I was able to receive and send data to electronics. The thing is to design the entire GUI will take alot of time for me. If i am able to use same GUI then it would really nice.

I have attched simple code how they are looking for USB. any suggestions how can i use same code?

C#
 // in the main form.....
 private void USB_USBConnected(object sender, ConnectedEventArgs e)
        {

            if (USB.Connected)
            {
                Serial.SerialConnected += new EventHandler<ConnectedEventArgs>(Tpvt_SerialConnected);
                Tpvt = new Serial(USB.ComPort, USB.MaxBaudRate);
                if (Tpvt.Connected)
                {
                    ThreadSafeToolStripSetText(ConnectToolStripStatusLabel, Tpvt.ConnectionStatus);
                   
               }
            }
            else
            {
                Tpvt.Disconnect();
            }
           
        }
in usb class.....

namespace SMart_2
{		
	public static class USB
	{

		#region PROPPERTIES

		//Connected to SMART
		private static bool _connected = false;
		public static bool Connected { get { return _connected; } }

		//Com port name
		private static string _comPort;
		public static string ComPort { get { return _comPort; } }

		//Should be SMART
		private static string _name;
		public static string Name {	get { return _name; } }

		//SMART id number ranging from 1001
		private static int _id;
		public static int Id { get { return _id; } }

		//SMART max baud rate number ranging from 1001
		private static int _maxBaudRate;
		public static int MaxBaudRate { get { return _maxBaudRate; } }
		
		private static ManagementEventWatcher _w;

		public static event EventHandler<ConnectedEventArgs> USBConnected;
		public static event EventHandler<MessageEventArgs> USBException;

		#endregion

		#region PRIVATE METHODS

		//Send event to MainForm that SMART is connected
		private static void NotifyUSBConnected()
		{
			if (USBConnected != null)
			{
				object obj = new object();
				ConnectedEventArgs e = new ConnectedEventArgs(_connected);
				USBConnected(obj, e);
			}
		}

		//Send event to MainForm about exception
		private static void NotifyUSBException(string text)
		{
			if (USBException != null)
			{
				object obj = new object();
				MessageEventArgs e = new MessageEventArgs(text);
				USBException(obj, e);
			}
		}
		
		//Analyse USB string, find Vendor ID, Product ID and TurboPVT ID
		private static void AnalyseUSBString(string usbString, out string vid, out string pid, out string id)
		{
			int vidStart;
			int pidStart;
			int idStart;
			int idLength;

			usbString = usbString.Replace("\"","");
			
			vidStart = usbString.IndexOf("VID_") + 4;
			vid = usbString.Substring(vidStart, 4);
			
			pidStart = usbString.IndexOf("PID_") + 4;
			pid = usbString.Substring(pidStart, 4);

			idStart = usbString.IndexOf("ID:") + 3;
			idLength = usbString.Length - idStart;
			id = usbString.Substring(idStart, idLength);
		}

		#endregion

		#region PUBLIC METHODS

		// Use Wmi to search for SMART
		public static void Search()
		{			
			string usbString;
			string comPort;
			string name;
			string maxBaudRate;
			string vid;
			string pid;
			string id;
			
			ManagementObjectSearcher searcher = null;
			
			try
			{
				searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_SerialPort");

				foreach (ManagementObject queryObj in searcher.Get())
				{
					if (!_connected)
					{
						usbString = queryObj["PNPDeviceID"].ToString();
						AnalyseUSBString(usbString, out vid, out pid, out id);
						
						if (vid == "03EB" && pid == "2018")
						{
							comPort = queryObj["DeviceID"].ToString().ToUpper();
							name = queryObj["Description"].ToString();
							maxBaudRate = queryObj["MaxBaudRate"].ToString();
														
							if (name == "Smart")
							{								
								_comPort = comPort;
								_name = name;
								_id = int.Parse(id);
								_maxBaudRate = int.Parse(maxBaudRate);
								_connected = true;
								NotifyUSBConnected();
							}
						}
					}
				}
			}

			catch (Exception ex)
			{
				NotifyUSBException(string.Format("Error while querying for WMI data: {0}", ex.Message));
				return;
			}
			finally
			{
                if (searcher != null)
                {
                    searcher.Dispose();
                }
			}
		}

		#endregion

		#region ADD EVENT HANDLERS

		//Adds eventhandler for insertion of new USB device
		public static void AddInsertUSBHandler()
		{
			WqlEventQuery q;
			//ManagementEventWatcher w;
			ManagementScope scope = new ManagementScope("root\\CIMV2");
			scope.Options.EnablePrivileges = true;

			try
			{
				q = new WqlEventQuery();
				q.EventClassName = "__InstanceCreationEvent";
				q.WithinInterval = new TimeSpan(0, 0, 3);
				q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'";
				_w = new ManagementEventWatcher(scope, q);
				_w.EventArrived += OnUSBInserted;
				_w.Start();
				
			}
			catch (Exception ex)
			{
				NotifyUSBException(string.Format("Error while adding insert USB event handler: {0}", ex.Message));
				if (_w != null)
				{
					_w.Stop();
				}
			}
		}

		//Adds eventhandler for removal of USB device
		public static void AddRemoveUSBHandler()
		{
			WqlEventQuery q;
			ManagementScope scope = new ManagementScope("root\\CIMV2");
			scope.Options.EnablePrivileges = true;

			try
			{
				q = new WqlEventQuery();
				q.EventClassName = "__InstanceDeletionEvent";
				q.WithinInterval = new TimeSpan(0, 0, 3);
				q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'";
				_w = new ManagementEventWatcher(scope, q);
				_w.EventArrived += OnUSBRemoved;
				_w.Start();
			}
			catch (Exception ex)
			{
				NotifyUSBException(string.Format("Exception in adding remove USB handler: {0}", ex.Message));
				if (_w != null)
				{
					_w.Stop();
				}
			}
		}

		#endregion

		#region EVENTS

		//Event for USB inserted
		private static void OnUSBInserted(object sender, EventArrivedEventArgs e)
		{
			try
			{
				Search();
			}
			catch (Exception ex)
			{
				NotifyUSBException(string.Format("Exception in USBInserted event: {0}", ex.Message));
			}
		}


		//Event for USB removal
		private static void OnUSBRemoved(object sender, EventArrivedEventArgs e)
		{
			string usbString;
			string vid;
			string pid;
			string id;

			try
			{
				ManagementBaseObject mbo = (ManagementBaseObject)e.NewEvent["TargetInstance"];
				using (ManagementObject o = new ManagementObject(mbo["Dependent"].ToString()))
				{
					usbString = o.ToString();
					AnalyseUSBString(usbString, out vid, out pid, out id);

					if (vid == "03EB" && pid == "2018" && int.Parse(id) == _id)
					{
						_connected = false;
						_name = "";
						_comPort = "";
						_id = 0;
						_maxBaudRate = 0;
						NotifyUSBConnected();
					}
				}
			}
			catch (Exception ex)
			{
				string test = ex.Message;
				if (!ex.Message.Equals("The specified port does not exist."))
					NotifyUSBException(string.Format("Exception in USBRemoved event: {0}", ex.Message));
			}
		}

		#endregion

	}
}
Posted
Updated 28-Sep-15 23:05pm
v2

1 solution

For your purpose I would discard the code you found "somewhere on the net" and take a look at this article.
Serial Comms in C# for Beginners[^]

As you have a USB to RS232 converter it will enumerate as one or more Virtual COM Ports (VCP).
In most ways this is the same as connecting to a physical serial port.

The way to start communicating with your device is via the class SerialPort[^]. You can find some starter examples there too.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900