4

I'm trying to send my rs232 device multiple SerialPort.Write commands right after each other. However, I don't think it can handle multiple WRITE commands at once.

Currently, I'm just using Thread.Sleep(500) to delay between WRITEs, but is there a way to detect when the perfect time to send is? Or with buffers?

example code

Interface

private void btn_infuse_Click(object sender, RoutedEventArgs e) {
        cmd.SetTargetInfusionVolume(spmanager, double.Parse(tbox_targetvolume.Text));
        cmd.StartInfuse(spmanager);//cmd object of Command class
}

Command Class

public void StartInfuse(SPManager spm){
        spm.Write("RUN");//spm object of serialportmanager class
    }
    public void SetTargetInfusionVolume(SerialPortManager spm, double num) {
        spm.Write("MLT " + num.ToString());
    }

SerialPortManager class

       public void Write(string sData) {
        if (oSerialPort.IsOpen) {//oSerialPort object of SerialPort class
            try {
                oSerialPort.Write(sData + "\r");
            }
            catch { MessageBox.Show("error"); }
        }
    } 
Charles
  • 50,943
  • 13
  • 104
  • 142

1 Answers1

1

If your serial port settings (especially, as Hans Passsant mentioned, flow control) are correct, then the problem with speed is most likely that your device can't handle messages fast enough to keep up with you if you send them too fast, or that it expects "silent" gaps between messages in order to delineate them.

In this case, a Sleep() to introduce a transmission delay is a very reasonable approach. You will need to find a sensible delay that guarantees the device handles your messages successfully, ideally without stalling your application for too long.

All too often this involves trial and error, but consult the documentation for the device, as quite a few devices use gaps in transmission to indicate the end of a message packet (e.g. often they may expect you to be silent for a short time after a message, e.g. if they specified 10 bits worth of "silent time" on a 2400 bps link, this would correspond to 10/2400ths or just over 4 milliseconds). This can all be compromised a bit by windows, though, as it tends to buffer data (i.e. it will hang on to it for a few milliseconds to see if you are going to ask it to transmit anything more) - you may therefore need a significantly longer delay than should strictly be required to get this to work - maybe 15-20ms. And of course, I could be barking up the wrong tree and you may find you need something as large as 500ms to get it to work.

Jason Williams
  • 56,972
  • 11
  • 108
  • 137