[英]Strange behaviour when communicating over serial from VS WPF to Arduino
[英]Strange behavior on getting serial outputs from arduino
我制作了一個 Arduino 腳本,用於在按下按鈕時打印按鍵:
#include <Keypad.h>
//Buttons
const byte ROWS = 2;
const byte COLS = 2;
char keys[ROWS][COLS] = {
{'1','2'},
{'3','4'}
};
byte rowPins[ROWS] = {A0, A1};
byte colPins[COLS] = {30, 31};
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
void setup() {
Serial.begin(9600);
keypad.addEventListener(keypadEvent);
}
void loop() {
char key = keypad.getKey();
}
void keypadEvent(KeypadEvent key){
switch (keypad.getState()){
case PRESSED:
Serial.println(key);
break;
default:
break;
}
}
然后,我制作了一個 C# 代碼,用於在調試控制台中打印它(在進一步操作之前進行測試):
using System;
using System.Diagnostics;
using System.IO.Ports;
namespace ConsoleApplication1
{
class Program
{
public static void Main()
{
SerialPort SP = new SerialPort("COM3");
SP.BaudRate = 9600;
SP.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
SP.Open();
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
SP.Close();
}
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort SP = (SerialPort)sender;
string msg = SP.ReadExisting();
Debug.Print($"Data Received: {msg}");
}
}
}
使用 Arduino 的串行監視器時,我得到了良好的行為:
但是當使用我的控制台應用程序時,我有時會得到空行:
關於如何改進它的任何想法?
Jasc24 讓我上路了。 SerialPort.ReadExisting() 讀取一個可能未完成的流,並且 SerialDataReceivedEventHandler 可以為一行觸發多次。
我的解決方法如下:
class Program
{
static string line = string.Empty;
public static void Main()
{
SerialPort SP = new SerialPort("COM3");
SP.BaudRate = 9600;
SP.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
SP.Open();
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
SP.Close();
}
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort SP = (SerialPort)sender;
line = $"{line}{SP.ReadExisting()}";
if (line.Contains(Environment.NewLine))
{
line = line.Replace(Environment.NewLine, string.Empty);
Debug.Print($"Data Received: {line}");
line = string.Empty;
}
}
}
等待 EOL 字符以確保我在打印之前得到了所有行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.