如何从lua中的串口读取 [英] How to read from a serial port in lua

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

问题描述

我是 lua 新手,我正在尝试从端口 ttyACM0 接收数据,我可以通过以下方式写入端口:

I'm new to lua and I'm trying to receive data from the port, ttyACM0, I can write to the port by:

wserial = io.open("/dev/ttyACM0","w")
wserial:write("hellloooo")
wserial:flush()

我认为因为我可以像写入文件一样写入它,所以我可以像读取文件一样读取它.但是当我尝试阅读它(使用下面的代码)时,我最终陷入了无限循环.

I thought since I can write to it in the same way as I would write to a file that I could read it in the same way as I would read a file. But when I try to read it (using the code below) I just end up in an infinite loop.

rserial=io.open("/dev/ttyACM0","r")
while chaine==nil do
  chaine=rserial:read()
  rserial:flush()
end
print(chaine)

所以我的问题是我做错了什么,我如何从端口读取,ttyACM0?

So my question is what am I doing wrong, how do I read from the port, ttyACM0?

推荐答案

这里有两种行缓冲:一种在 C 库中,你可以避免使用 :read(1) 就像评论中提到的@Advert,以及终端驱动程序本身中的另一个.您可以使用 stty 命令行实用程序 (stty -F/dev/ttyACM0 -icanon) 或例如禁用终端驱动程序中的输入行缓冲.使用 luaposix(未经测试的代码):

There are two kinds of line buffering going on here: one in the C library, which you can avoid using :read(1) like @Advert mentioned in the comments, and another one in the terminal driver itself. You can disable input line buffering in the terminal driver using the stty command line utility (stty -F /dev/ttyACM0 -icanon) or e.g. using luaposix (untested code):

local p = require( "posix" )
local rserial = assert( io.open( "/dev/ttyACM0", "r" ) )
local fd = assert( p.fileno( rserial ) )

local function table_copy( t )
  local copy = {}
  for k,v in pairs( t ) do
    if type( v ) == "table" then
      copy[ k ] = table_copy( v )
    else
      copy[ k ] = v
    end
  end
  return copy
end

-- get current settings
local saved_tcattr = assert( p.tcgetattr( fd ) )
local raw_tcattr = table_copy( saved_tcattr )
-- clear ICANON bits from local flags using Lua 5.2 bit32 module
raw_tcattr.lflag = bit32.band( raw_tcattr.lflag, bit32.bnot( p.ICANON ) )

-- apply modified settings
assert( p.tcsetattr( fd, p.TCSANOW, raw_tcattr ) )
local c = rserial:read( 1 )
print( c )
-- restore default settings afterwards
p.tcsetattr( fd, p.TCSANOW, saved_tcattr )
rserial:close()

还有一个专门的C模块用于处理Lua中的串口,以及最新的未发布版本LuaSocket 具有处理串行端口的代码(但在默认版本中被禁用).

There is also a specialized C module for handling serial ports in Lua, and the latest unreleased version of LuaSocket has code for handling serial ports (but it's disabled in default builds).

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

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