使用 VSPE 的 WPF 中的串行端口通信问题

Posted

技术标签:

【中文标题】使用 VSPE 的 WPF 中的串行端口通信问题【英文标题】:Serial port communication issue in WPF using VSPE 【发布时间】:2013-12-03 08:27:54 【问题描述】:

我开发了一个用于串口通信的 wpf 应用程序。我使用模拟器VSPE for windows 7。我可以成功发送和接收数据。我未来的意图是将设备连接到我的 USB 驱动器。我将向我的 USB 发送一个字符串值,它会作为确认的结果发回一个字符串。我可以使用与串行端口通信相同的代码吗?我将在此处包含我的代码。

public partial class MainWindow : Window
     
    FlowDocument mcFlowDoc = new FlowDocument();
    Paragraph para = new Paragraph();

    SerialPort serial = new SerialPort();
    string recieved_data;

    public MainWindow()
    
        InitializeComponent();
        InitializeComponent();
        //overwite to ensure state
        Connect_btn.Content = "Connect";
    

    private void Connect_Comms(object sender, RoutedEventArgs e)
    
        if (Connect_btn.Content == "Connect")
        
            //Sets up serial port
            serial.PortName = Comm_Port_Names.Text;
            serial.BaudRate = Convert.ToInt32(Baud_Rates.Text);
            serial.Handshake = System.IO.Ports.Handshake.None;
            serial.Parity = Parity.None;
            serial.DataBits = 8;
            serial.StopBits = StopBits.One;
            serial.ReadTimeout = 2000;
            serial.WriteTimeout = 50;
            serial.Open();
            serial.DtrEnable = true;

            //Sets button State and Creates function call on data recieved
            Connect_btn.Content = "Disconnect";
           serial.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(Recieve);

        
        else
        
            try // just in case serial port is not open could also be acheved using if(serial.IsOpen)
            
                serial.Close();
                Connect_btn.Content = "Connect";
            
            catch
            
            
        
    

    #region Recieving

    private delegate void UpdateUiTextDelegate(string text);
    private void Recieve(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    
        // Collecting the characters received to our 'buffer' (string).
        recieved_data = serial.ReadExisting(); 
        Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(WriteData), recieved_data);
    
    private void WriteData(string text)
    
        // Assign the value of the recieved_data to the RichTextBox.
        para.Inlines.Add(text);
        mcFlowDoc.Blocks.Add(para);
        Commdata.Document = mcFlowDoc;
    

    #endregion


    #region Sending        

    private void Send_Data(object sender, RoutedEventArgs e)
    
        SerialCmdSend(SerialData.Text);
        SerialData.Text = "";
        serial.Close();
    
    public void SerialCmdSend(string data)
    
        if (serial.IsOpen)
        
            try
            
                // Send the binary data out the port
                byte[] hexstring = Encoding.ASCII.GetBytes(data);
                //There is a intermitant problem that I came across
                //If I write more than one byte in succesion without a 
                //delay the PIC i'm communicating with will Crash
                //I expect this id due to PC timing issues ad they are
                //not directley connected to the COM port the solution
                //Is a ver small 1 millisecound delay between chracters
                foreach (byte hexval in hexstring)
                
                    byte[] _hexval = new byte[]  hexval ; // need to convert byte to byte[] to write
                    serial.Write(_hexval, 0, 1);
                    Thread.Sleep(1);
                
            
            catch (Exception ex)
            
                para.Inlines.Add("Failed to SEND" + data + "\n" + ex + "\n");
                mcFlowDoc.Blocks.Add(para);
                Commdata.Document = mcFlowDoc;
            
        
        else
        
        
    

    #endregion


【问题讨论】:

【参考方案1】:

如果您打算使用虚拟串行端口适配器(串行到 USB 电缆),那么可以!

否则,可能不会。这实际上取决于您将如何使用 USB。 USB HID 设备需要不同的代码。

当我使用串行设备进行开发并稍后转移到其他东西时,我经常做这种事情。在 OO 世界中,这是接口的主要候选者!

public IDevice

    IDeviceConnection Connect(int timeout);


public IDeviceConnection: IDispose //Dispose() disconnects your device. Enables using() statements

    int WriteData();
    byte[] ReceiveData();

正确实现这两个,您可以通过您选择的任何机制交换串行和 USB 版本。请注意,需要将代码分成类才能完成这项工作。将所有内容都放在表单的代码文件中是不好的做法。

【讨论】:

以上是关于使用 VSPE 的 WPF 中的串行端口通信问题的主要内容,如果未能解决你的问题,请参考以下文章

没有与连接的串行端口通信?

以编程方式与 OS X 或 Linux 中的串行端口通信

欧姆龙plc如何查看有没有写通讯程序

从类中的串行端口访问 WinForms 控件

使用 C# 通过“USB 虚拟串行端口”与 USB 设备通信?

如何在 C# 中实现串行端口通信以控制现金存款机 [关闭]