0

我的问题是:如何使用 wpf 应用程序从串口接收数据?我已经尝试了很多次,但仍然无法得到它;这是我的 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”。但是如何从 C# 应用程序接收它呢?请写一个这样的 wpf 应用程序的例子。

4

1 回答 1

0

使用 Backgroundworker 启动一个新线程。

public Form1()
{
    InitializeComponent();
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true;
}

private void startAsyncButton_Click(object sender, EventArgs e)
{
    if (backgroundWorker1.IsBusy != true)
    {
        // Prepare the SerialPort here

        backgroundWorker1.RunWorkerAsync();
    }
}

private void cancelAsyncButton_Click(object sender, EventArgs e)
{
    if (backgroundWorker1.WorkerSupportsCancellation == true)
    {
        // Cancel the asynchronous operation.
        backgroundWorker1.CancelAsync();
    }
}

// This event handler is where the time-consuming work is done.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;

    while(!worker.CancellationPending)
    {
        string message = _serialPort.ReadLine();
        worker.ReportProgress(someValue, message);
    }
}

// This event handler updates the progress.
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    resultLabel.Text = (e.ProgressPercentage.ToString() + "% " + e.UserState);
}

// This event handler deals with the results of the background operation.
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled == true)
    {
        resultLabel.Text = "Canceled!";
    }
    else if (e.Error != null)
    {
        resultLabel.Text = "Error: " + e.Error.Message;
    }
    else
    {
        resultLabel.Text = "Done!";
    }
}
于 2012-06-17T09:08:45.223 回答