从串口读取换行返回第一个值

Reading to newline from serial port returning first value

我正在尝试从连接了 Arduino 和操纵杆的串口读取数据。

当尝试打印接收到的数据以检查我是否收到它时,它继续打印出连接时的相同值。

我正在以这种格式从串口发送数据:Xaxis:yAxis:switchBool

这是我在 WPF 应用程序中的 C# 代码

public partial class MainWindow : Window {

  public Timer loopTimer;
  string comport = "COM7";
  SerialPort sp;

  public MainWindow() {
    InitializeComponent();
    SetTimer();
    OpenPort();
  }

  private void SetTimer() {
    //Setup the timer
    loopTimer = new Timer(500);
    // Hook up the Elapsed event for the timer. 
    loopTimer.Elapsed += TryRead;
    loopTimer.AutoReset = true;
    loopTimer.Enabled = false;
  }

  public void OpenPort() {
    sp = new SerialPort();
    try {
      string portName = comport;
      sp.PortName = portName;
      sp.BaudRate = 9600;
      sp.Open();
      Debug.WriteLine("Connected");
      loopTimer.Enabled = true;
    }
    catch (Exception) {
      MessageBox.Show("Please give a valid port number or check your connection");
      loopTimer.Enabled = false;
    }
  }

  public void TryRead(object sender, EventArgs e) {
    string s = sp.ReadLine();
    Debug.WriteLine(s);
    Debug.WriteLine("-");
  }
} 

这是我的 arduino 代码:

int xPin = A1;
int yPin = A0;
int swPin = A2;
float deadzone = .05;

void setup() {
  Serial.begin(9600);
  pinMode(swPin, INPUT);
}

void loop() {
  float xVal =  (((analogRead(xPin) + 1) / 1023.) * 2) -1;
  if (xVal < deadzone && xVal > -deadzone ) {
    xVal = 0; 
  }

  float yVal =  (((analogRead(yPin) + 1) / 1023.) * 2) -1;
  if (yVal < deadzone && yVal > -deadzone ) {
    yVal = 0; 
  }

  int swVal = analogRead(swPin);
  bool switchDown;

  if (swVal == 0) {
    switchDown = true;
  } else {
    switchDown = false;
  }
   
  Serial.println( String(xVal) + ":" + String(yVal) + ":" + switchDown);
} 

这是一个示例,说明在移动摇杆时,Arduino 的串行监视器中的数据应该是什么样子:

-1.00:0.70:0
-0.80:0.50:0
-0.70:0.60:0

运行 我在上面的 C# 代码并且没有移动拇指杆我每次阅读时只会得到 0.00:0.00:0.00,如果我在开始之前移动它我只会收到任何值。

我不会按间隔读取,而是在新数据到达总线时读取。下面是一个如何做到这一点的例子。

SerialPort Port= new SerialPort("Com7");
Port.DataReceived+=OnSerialRecieve;
private void OnSerialRecieve(object sender, SerialDataReceivedEventArgs e)
{
    if ((sender as SerialPort).IsOpen)
    {
        string DataRecieved=(sender as SerialPort).ReadExisting();
    }
}

从那里您可以根据需要将其拆分。否则,如果您知道您期望的确切数据量,您可以起诉 SerialPort.ReadByte 以准确读取您需要的字节数。