e-tipsmemo

ごった煮

C# serialport ReadExisting

急に作りたくなったもののためのデバッグのために
UARTでパソコンに情報を送信しているが
それを可視化したほうが分かりやすかったので寄り道。

フォームアプリケーションが
楽なのでC#を使用。
2.0あたりで適当に使ってから久しぶりに使ったきがする。

\r\nで通信を区切っているがReadLineだとエラーが出るので
ReadExistingを使う。


COMポートの列挙(comboBoxで選べるように)

private void Form1_Load(object sender, EventArgs e)
{
    string[] ports = SerialPort.GetPortNames();

    foreach (var item in ports)
    {
        comboBox1.Items.Add(item);
    }

    comboBox1.SelectedIndex = 1;
}

データの受信インベント
区切り文字(delim=\r\n or \n)があるときは必ず(?)末尾っぽいので
出力してバッファーを空にする。

private string buffer;

private void DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    if (serialPort1.IsOpen == false)
    {
        return;
    }

    try {
        buffer += serialPort1.ReadExisting();
                
        if (buffer.IndexOf(delim) >= 0)
        {
            Debug.WriteLine(buffer);
            buffer = string.Empty;
            Debug.WriteLine("---------------");
        }
    }
    catch (Exception ex) {
        MessageBox.Show(ex.Message);
    }

    if (buffer.Length > 1024)
    {
        buffer = string.Empty;
    }
}

区切り文字なくてもバッファーが長くなると困るので適当にリフレッシュ。
(ココらへんは適当仕様)

あとは受信できた一行なんとかする。