簡體   English   中英

python 串行 readline() 與 C# 串行 ReadLine()

[英]python serial readline() vs C# serial ReadLine()

我正在嘗試從我的設備讀取串行輸入,並使用 pyserial 使其在 Python 中工作,例如

import serial
port = serial.Serial(port='COM1', baudrate=19200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=False, rtscts=False, dsrdtr=False)

while 1:
    N = port.in_waiting
    
    if N>4:
        msg = port.readline(N)
        print(list(msg))

我正在嘗試在 C# 中實現相同的代碼,但它似乎不太有效,例如

port = new SerialPort(COM1);
port.BaudRate = baudRate;
port.DataBits = 8;
port.Parity = Parity.None;
port.StopBits = StopBits.One;
port.ReadTimeout = SerialPort.InfiniteTimeout;
port.Handshake = Handshake.None;
port.RtsEnable = false;
port.DtrEnable = false;
port.DataReceived += new SerialDataReceivedEventHandler(DataReceived);

void DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    
    int N = port.BytesToRead;
    if (N > 4)
    {
         string line = port.ReadLine();

    }
}

我能夠在 C# 中使用 port.Read() 正確讀取內容,但是 ReadLine 似乎不能正常工作——它似乎無法找到行尾字符 ("\ n")? 程序只是凍結。 但是我不確定為什么它與 pyserial.ReadLine() 一起工作,它也尋求相同的字符(並且沒有超時工作)。 據我所知,端口設置的 rest 是相同的。

謝謝!

因為DataReceived事件指示數據已通過端口接收,數據已被讀取,您應該調用SerialPort.ReadExisting來獲取它。

void DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    var data = port.ReadExisting();
}

這個事件不保證它的數據是單行的,如果你想要類似pySerial的方式,你不應該使用這個事件,直接使用ReadLine:

 port.DataReceived += new SerialDataReceivedEventHandler(DataReceived);
while(true)
{
    int N = port.BytesToRead;
    if (N > 4)
    {
         string line = port.ReadLine();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM