-2

我想从串口读取数据,但不知道该怎么做。

我正在使用 Arduino,所以这是我的代码:

    int switchPin = 7;
int ledPin = 13;
boolean lastButton = LOW;
boolean currentButton = LOW;
boolean flashLight = LOW;

void setup()
{
  pinMode(switchPin, INPUT);
  pinMode(ledPin, OUTPUT);

  Serial.begin(9600);
}

boolean debounce(boolean last)
{
  boolean current = digitalRead(switchPin);
  if (last != current)
  {
    delay(5);
    current = digitalRead(switchPin);
  }
  return current;
}

void loop()
{
  currentButton = debounce(lastButton);
  if (lastButton == LOW && currentButton == HIGH)
  {
    Serial.println("UP");

    digitalWrite(ledPin, HIGH);
  }
  if (lastButton == HIGH && currentButton == LOW)
  {
    Serial.println("DOWN");

    digitalWrite(ledPin, LOW);
  }

  lastButton = currentButton;
}

如您所见,一切都很简单:按下按钮后设备将“DOWN”或“UP”发送到串行端口。我想从我的 WPF 应用程序中接收它。这是它的代码:

    namespace Morse_Device_Stuff
{
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private SerialPort port;


        private bool recordStarted = false;

        private void recordButton_Click(object sender, RoutedEventArgs e)
        {

            SerialPort port = new SerialPort("COM3", 9600);
            port.Open();
            recordStarted = !recordStarted;
            string lane;

            if(recordStarted)
            {

                (recordButton.Content as Image).Source = new BitmapImage(new Uri("stop.png", UriKind.Relative));


                port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

            }

            else
            {
                (recordButton.Content as Image).Source = new BitmapImage(new Uri("play.png", UriKind.Relative));
            }

            port.Close();
        }

        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            textBox.Text += port.ReadExisting();
        }
    }
}

按下按钮后没有任何变化,我的 TextBox 仍然是空的。

有什么不好的?

4

1 回答 1

0

端口在 recordButton_Click 函数内关闭。由于 DataReceived 是异步调用的,因此没有任何反应。使 SerialPort 端口变量类成员,并从 recordButton_Click 中删除 port.Close 行。

您可以在其他地方关闭端口,例如,当窗体关闭时。

此外,您不应直接在 port_DataReceived 函数内更改 textBox.Text,因为它是在任意线程上下文中调用的。使用 Dispatcher.BeginInvoke 将此操作重定向到主应用程序线程。

于 2012-06-17T08:54:06.347 回答