Lilás
Lilás

Reputation: 1201

Lua - io.read sends me an echo back when I read from serial port - why?

I am writing a code in Lua to read from a serial port, but when I read I receive an echo back with the code :

print("Dragino Uart Test started\n")
while 1 do
    serialin=io.open("/dev/ttyS0","r")
    print(serialin:read())    --print the data
    serialin:close()
end

When I open minicom to send him some data, I enable local echo than I type "text" and I see :

tteexxtt

Then I need to press enter to see my message in my lua script.

I am using a OpenWRT in a Dragino.

It seems that it is like a prompt command that you type every thing that you see and you need to press enter to send you command.

There is any other way to read and write to/from a serial port?

Can somebody help me please? Thank you so much!

Upvotes: 2

Views: 3185

Answers (2)

Zuendi
Zuendi

Reputation: 149

I don know if this is still an issue to someone but maybe this helps a few people. Like lhf said :read(1) is a gread way of doing this. I had a few problems with :read("*a") though. In my opinion the easiest way of doing this is to append the answer piece by piece like:

rserial=io.open("/dev/ttyS0",'r')
lines = ""
repeat
    local line=rserial:read(1)
    if string.sub(line, 0, 3) == "OED" then  --OED is here the stream ending. This can vary
            EOD = true
            rserial:close()
    elseif line then
            lines = lines .. line 
    end
until EOD == true
print (lines)

Upvotes: 0

lhf
lhf

Reputation: 72312

The read method with no arguments reads a full line. That's why you need to press enter at the end of the text. Try reading one byte at a time with :read(1) or all of it with :read("*a").

Upvotes: 1

Related Questions