0

I developed a wpf application for serial port communication. I used the emulator VSPE for windows 7. I can successfully send and receive data. My future intention is to connect a device to my USB drive. I will send a string value to my USB and it will send a string back as a result of acknowledgement. Can i use the same code i used for serial port communication. I will include my code here.

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

}
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
user1665130
  • 51
  • 10

1 Answers1

0

If you are planning to use a virtual serial port adapter (a serial-to-usb cable) then yes!

Otherwise, probably not. This really depends on how you will be using USB. A USB HID device will require different code.

I do this sort of thing a lot, when I develop with a serial device and move to something else later. In the OO world this is a prime candidate for interfaces!

public IDevice
{
    IDeviceConnection Connect(int timeout);
}

public IDeviceConnection: IDispose //Dispose() disconnects your device. Enables using() statements
{
    int WriteData();
    byte[] ReceiveData();
}

Implement both of these properly and you can swap serial and USB versions by whatever mechanism you choose. Notice that the code will need to be seperated into classes to make this work. Putting everything in the code file for a form is bad practice.

Gusdor
  • 14,001
  • 2
  • 52
  • 64