如何从 R 中的串口读取数据 [英] How to Read Data from Serial Port in R

查看:18
本文介绍了如何从 R 中的串口读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从串口绘制实时数据.我认为 R 将是完成这项工作的好工具.我在尝试从串行端口(COM4)读取数据时磕磕绊绊.我已经验证数据是通过 terra term 进入的(并在尝试 R 之前关闭会话),但我似乎无法在 R 中得到任何东西.

I'm wanting to plot live data from the serial port. I figured R would be a good tool for the job. I'm stumbling on trying to read data from the serial port (COM4). I've verified the data is coming in through terra term (and close the session before trying R), but I can't seem to get anything in R.

我检查了几个地方,包括这些线程:如何在 Windows 上调用使用 scan() 的脚本?如何包含交互式在要从命令行运行的脚本中输入

I've checked a few places, including these threads: How to invoke script that uses scan() on Windows? How to include interactive input in script to be run from the command line

我还在 R 论坛上找到了这个旧帖子:https://stat.ethz.ch/pipermail/r-help/2005-September/078929.html

I've also found this old thread on the R forum: https://stat.ethz.ch/pipermail/r-help/2005-September/078929.html

这些已经让我走到了这一步,但我似乎无法真正从串行端口将任何数据输入 R.

These have gotten me this far, but I can't seem to actually get any data into R from the serial port.

此时我可以使用 VBA 在 excel 中流式传输数据,但我想在 R 中进行,以便更好地实时绘制和过滤数据.

At this point I can stream in the data in excel using VBA, but I'd like to do it in R for some nicer live plotting and filtering of the data.

感谢到目前为止的帮助.我只是在编写此编辑时让它工作,所以这里是代码:

Thanks for the help so far. I just got it working while writing up this edit, so here's the code:

#
# Reset environment
#
rm(list = ls())         # Remove environemnent variables
graphics.off()          # Close any open graphics

#
# Libraries
#
library(serial)

#
# Script
#

con <- serialConnection(name = "test_con",
                        port = "COM11",
                        mode = "115200,n,8,1",
                        buffering = "none",
                        newline = 1,
                        translation = "cr")

open(con)

stopTime <- Sys.time() + 2
foo <- ""
textSize <- 0
while(Sys.time() < stopTime)
{
    newText <- read.serialConnection(con)
    if(0 < nchar(newText))
    {
        foo <- paste(foo, newText)
    }
}

cat("
", foo, "
")

close(con)

foo 最终成为一个长字符串,其中包含我想要的新行:

foo ends up being a long string with new lines the way I want them:

3181, -53120, -15296, 2,  
3211, -53088, -15328, 2,  
3241, -53248, -15456, 1,  
3271, -53216, -15424, 2,  
3301, -53184, -15488, 2,  
3331, -53344, -15360, 1,  
3361, -53440, -15264, 1,

再次感谢大家的帮助!

推荐答案

我正在使用 serial-package (这里) 在 CRAN 上可用.这是为了完全满足您的需要而开发的.读取和发送数据表格并连接到 RS232 等.我确实推荐这个,因为mode.exe"似乎不适用于虚拟 COM 端口.见 NPort-Server 等.

i am working with the serial-package (here) available on CRAN. This was developed to do exactly that what you need. Reading and sending data form and to RS232 etc. connections. I do really recommend this, because "mode.exe" seems not to work for virtual COM-ports. See NPort-Server etc.

这篇关于如何从 R 中的串口读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆