我要给个仪器发送指令,但是呢这个仪器不太好使,需要满足它的周期才能返回好的数据,不然就会出现乱码,我用早先用LabVIEW做的一个串口程序,指令发送周期是1500ms收到的数据是很好的,没有乱码。
但是我现在用c#来做,却老是收到乱码数据,我设置timer的周期也是1500ms啊,为什么会出现截然不同的结果呢?        private void Device_Load(object sender, EventArgs e)
        {
            Creatlabel();
            Iniform();
            timersend.Enabled = false;
            if (conf.Openport(serialPort, Comname, boudrate, parity, databit, stopbit))
            {
                MessageBox.Show("通讯成功");
                timersend.Enabled = true;
            }            else
            {
                MessageBox.Show("通讯失败,请检查串口是否被占用?");
            }
            timersend.Interval = 2000;
        }
        private void SendCommand()
        {
            int i;
            string sendstr;
            for (i = 0; i < Equiment.Length; i++)
            {
           //     RRSTSB0000ZU
                sendstr = "RRSTSB" + Equiment[i].PadLeft(4, '0') + "ZU";
                serialPort.WriteLine(sendstr);                Delay(2000);
            }
        }
        private void Delay(int mm)
        {
            DateTime current = DateTime.Now;            while (current.AddMilliseconds(mm) > DateTime.Now)
            {
                Application.DoEvents();
            }
            return;
        }我把timer的周期从1000设到2000可是好像一点改善都没有,希望大家帮忙解决下。
难道LabVIEW的时间跟c#的时间概念不一样?

解决方案 »

  1.   

    乱码就是出现  RRSTSB 0147 0000 0002 C0999 -0000 -0000 0000 0000 0002 C0999 -0000 -0000 0000 0000 0002 C0??-0000 -0000 0000 0000 0004 C0999 -0000 -0000 0000 0000 0005 0002 ZU
    一些问号,我用indeof('?')好像不能识别这个?难道这个?是中文状态下的问号
      

  2.   

    每次第一条返回是正确的没有乱码,我的波特率设置的是9600。从第二次开始就会出现乱码,然后我发现加了延时也就是上面那个delay之后cpu占用达到50%。
    都是字符类型的数据。
      

  3.   

    现在的问题是,我在发送下一条指令之前停顿1s,然后再发第二条指令,这样就能收到正确的数据,但是这个延时函数占用很大的系统资源。cpu占有50%,但是用System.Threading.Thread.Sleep(1000);的话程序感觉像是给卡住了一样,点其他地方很久才反应过来。
            private void Delay(int mm)
            {
                DateTime current = DateTime.Now;            while (current.AddMilliseconds(mm) > DateTime.Now)
                {
                    Application.DoEvents();
                }
                return;
            }这个延时函数效率不太高。
      

  4.   

    我想请教下怎么做?我现在就是用sleep来做停顿1s然后再发数据,这样数据也接收完了,出现乱码的现象就少了,基本正常。