-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ポートを変数クラスのメンバーにし、port.Close行をrecordButton_Clickから削除します。

フォームを閉じたときなど、別の場所でポートを閉じることができます。

また、textBox.Textは任意のスレッドコンテキストで呼び出されるため、port_DataReceived関数内で直接変更しないでください。Dispatcher.BeginInvokeを使用して、このアクションをメインアプリケーションスレッドにリダイレクトします。

于 2012-06-17T08:54:06.347 に答える