通过WPF从串口接收的数据

时间:2012-06-17 08:44:03

标签: c# wpf serial-port

我的问题是:如何使用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应用程序的例子。

1 个答案:

答案 0 :(得分: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!";
    }
}