我正在使用 raspberry pi 和 arduino 开发一个项目。我正在树莓派上编写一个 GO 程序,以每秒 115200 的波特率从 Arduino 接收 UART 数据。树莓派读取 UART 数据,将其保存到文件中(根据 file1
或 file2
等的值),然后将文件发送到 ftp 服务器。
由于上传到服务器可能需要一些时间,具体取决于网络,我想使用 go 并发,这样 UART 读取和保存到文件就不会中断。以下是我尝试应用的伪代码(骨架)。我在代码中的想法是文件路径将按顺序缓冲在 channel 中,并以相同的顺序执行上传。我做得对吗?有没有更好的方法来解决这个问题?
package main
import "strings"
func SendFile(filePath string) {
}
// based on the value of the data, SaveToFile saves the data to either file1, file2 or file3
func SaveToFile(uartData []string) filePath string {
return filePath
}
func main() {
ch := make(chan string, 1000)
//uartInit initialization goes here
uart := uartInit()
//infinite loop for reading UART...
for {
buf := 1024 // UART buffer
data := uart.Read(buf)
uartData = strings.Split(string(buf), " ")
//channel receives filepath
ch <- SaveToFile(uartData)
//channel sends filepath
go SendFile(<-ch)
}
}
最佳答案
您正在向 channel 写入一个字符串,然后将其读回。 sendFile() 在不同的 goroutine 中运行,但在您使用它的方式中不需要 channel 。你可以简单地做
fname:= SaveToFile(uartData)
go SendFile(fname)
但是,我不认为这是你想要做的。
相反,您应该有一个 goroutine,您可以在其中从 UART 读取数据,并写入缓冲 channel 。监听该 channel 的是另一个将数据 block 写入文件的 goroutine。准备好发送时,创建第三个 goroutine 来发送文件。
关于go - Go 中的缓冲 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57488619/