C# 串口数据接收问题

C# 串口数据接收问题,c#,serial-port,C#,Serial Port,我想从串口读取数据,但不知道怎么做 我正在使用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(9

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

我正在使用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;
}
正如您所见,一切都很简单:按下按钮后,设备将“向下”或“向上”发送到串行端口。 我想从我的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();
        }
    }
}
按下按钮后,没有任何变化,我的文本框仍然是空的


有什么问题吗?

端口在recordButton\u Click功能中关闭。因为DataReceived是异步调用的,所以不会发生任何事情。使SerialPort成为变量类成员,并删除端口。从recordButton\u单击关闭行

您可以在其他位置关闭端口,例如,当表单关闭时

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

可能重复的