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

人气:1,017 发布:2022-10-16 标签: c# wpf serial-port

问题描述

我开发了一个用于串口通信的WPF应用程序。我使用了Windows7的模拟器VSPE。我可以成功地发送和接收数据。我未来的目标是将一个设备连接到我的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 + "
" + ex + "
");
                mcFlowDoc.Blocks.Add(para);
                Commdata.Document = mcFlowDoc;
            }
        }
        else
        {
        }
    }

    #endregion

}

推荐答案

如果您计划使用虚拟串口适配器(串口到USB线),则可以!

否则,可能不是。这真的取决于你将如何使用USB。USB HID设备需要不同的代码。

我经常做这种事情,当我使用串口设备进行开发时,然后移到其他设备上。在面向对象的世界中,这是接口的首选!

public IDevice
{
    IDeviceConnection Connect(int timeout);
}

public IDeviceConnection: IDispose //Dispose() disconnects your device. Enables using() statements
{
    int WriteData();
    byte[] ReceiveData();
}
正确地实现这两个版本,您可以通过您选择的任何机制来交换串口和USB版本。请注意,需要将代码分成几个类才能使其工作。将所有内容都放在窗体的代码文件中是不好的做法。

521