如何使USB串口通信适应RS232到USB串口通信。 [英] How to adapt USB serial communication to RS232 to USB serial port communication.

查看:126
本文介绍了如何使USB串口通信适应RS232到USB串口通信。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用C#windows论坛设计的GUI,他们使用USB串行通信进行通信,以便与硬件电子设备进行通信。



我想使用与其他硬件电子设备相同的GUI,但我使用RS232转USB转换器将数据从电子设备发送到PC。是否可以将RS232到USB转换器检测为USB设备并使用相同的GUI?当我尝试使用VID或PID时,他们正在尝试进行USB通信,但它无法正常工作。我需要任何驱动程序吗?



我非常想通过c#中的serialport类建立串行通信。我能够接收和发送数据到电子产品。问题是设计整个GUI会花费我很多时间。如果我能够使用相同的GUI那么它会非常好。



我已经附上了简单的代码,他们正在寻找USB。任何建议我如何使用相同的代码?



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?

 // 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

	}
}

推荐答案

为了您的目的,我会丢弃您在网上某处找到的代码并查看本文。

C#中的串口通信初学者 [ ^ ]



因为你有一个USB转RS232转换器,它将枚举为一个或多个虚拟COM端口(VCP)。

在大多数情况下这与连接物理串口相同。



开始与设备通信的方法是通过类SerialPort [ ^ ]。您也可以在那里找到一些入门示例。
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.


这篇关于如何使USB串口通信适应RS232到USB串口通信。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆