使用While循環不斷地從串列埠讀取資料
透過串口與感測器或裝置互動時,常常需要這樣做連續讀取傳入的數據。在這種情況下,問題就出現了 - 如何使用 while 迴圈來實現這一點?
考慮一個用於串行通訊的 Go 程式範例:
<code class="go">package main import ( "fmt" "github.com/tarm/goserial" "time" ) func main() { // ... (code to open the serial port and write data) time.Sleep(time.Second / 2) var buf []byte for { n, err := s.Read(buf) if n > 0 { break } } fmt.Println(string(buf[:n])) // ... (code to close the serial port) }</code>
在此片段中,最初的嘗試建立用於連續閱讀的 while 循環無法按預期工作。與阻塞 Read() 函數不同,串列包的 Read() 方法會立即傳回,即使沒有可用資料也是如此。此行為會導致緩衝區被覆蓋,並且無法捕獲所有傳入資料。
要解決此問題,更可靠的方法是使用 bufio.Reader,它提供緩衝功能。透過使用具有已定義分隔符號的讀取器(例如,「x0a」表示換行符號),可以連續讀取直到遇到分隔符號。
以下是包含此方法的修改後的程式碼片段:
<code class="go">package main import ( "bufio" "fmt" "github.com/tarm/goserial" ) func main() { // ... (code to open the serial port and write data) // Create a bufio.Reader with a defined delimiter reader := bufio.NewReader(s) // Continuously read data until the delimiter is encountered reply, err := reader.ReadBytes('\x0a') // Print the received data fmt.Println(string(reply)) // ... (code to close the serial port) }</code>
透過合併此更改,程式現在可以連續可靠地讀取傳入數據,無論數據流速率如何。
以上是Go中如何使用While迴圈實現串口資料的連續讀取?的詳細內容。更多資訊請關注PHP中文網其他相關文章!