c#串口获取/设置结构

时间:2014-07-20 10:18:52

标签: c# pic basic

我正在尝试开发2个程序,这些程序必须通过串行端口相互通信。一个用C#编写的用于PC的程序和一个用BASIC编写的程序放在PIC芯片上。我想要建立的是C#中的某种get / set结构来获取/设置PIC上的属性。 关于我如何在BASIC中设置协议的示例,有一个名为“_onTime”的属性,使用2个子例程:

SubGetOnTime:

    ' return the time the motor is on
    HRSOut _onTime

 Return


 SubSetOnTime:

    ' inform that we are ready te receive the value by sending a 0
    HRSOut 0;

    ' wait for the user to send the new value
    _onTime = HRSin, {SERIALDELAY , Main}

    ' also save to the eeprom, if changed
    If _onTime <> ERead EE_onTime Then EWrite EE_onTime, [_onTime]

 Return

Main:

    ' send FF: we are ready
    HRSOut BIN 0xff

    ' clear the received command
    Clear _receivedCommand

    ' Wait for a new command, if nothing received within 1 second, restart loop (goto Main)
    _receivedCommand = HRSin, {SERIALDELAY , Main}

    ' Depending on the received command, chose what action to perform
    Select _receivedCommand

        Case 1
            GoSub SubTrigger            ' 1: Test motor
        Case 2
            GoSub SubGetOnTime          ' 2: Get ON time
        Case 3
            GoSub SubSetOnTime          ' 3: Set ON time
    EndSelect
' go back to Main
GoTo Main

这很简单,它确实有效,我可以使用终端获取/设置_onTime变量。程序不断地将FF写入端口,通知程序正在运行并等待命令发送。发送命令时,将触发相应的子例程。当循环是GetLoop时,将返回该值。如果它是一个Set方法,程序首先发送一个0,通知子循环已准备好接收该值,然后等待通过串口发送该值。

现在是C#部分。我有点不知道应该如何处理串行get / set通信。我知道如何设置它,并使用SerialPort类等通过串口发送/接收值...但我基本上想要的是这样的例子:

public int OnTime
{
  get { return this.GetOnTime(); }
  set
  {
    if (this.GetOnTime() != value)
    {
      this.SetOnTime(value);
      this.OnPropertyChanged("OnTime");
    }
  }
}

private int GetOnTime()
{
  // Well, create the port(named port in this example, and send the GetOnTime command (can be an enum, or static class with properties returning int values)
  // Could be possible that i have to cast the integer value to a byte value...
  port.Write(Commands.GetOnTime);

  // this is where I get stuck
  // How do I wait now for the serial port to return the value so that this method can return the value?
}

我想到的是使用bool _hasReceivedDatavar _lastReceivedValue,我在调用port.Write(Commands.GetOnTime)之前将其设置为false / null,并由DataReceived回调填充的SerialPort类。然后我可以使用while循环来等待值?

while (!this._hasReceivedData){}

当然,这个while循环应该有一些TimeOut以防错误存在等等。 但是,我觉得这不是正确的方法。我想知道你们中的一些人是否有更聪明的解决方案?

0 个答案:

没有答案