0
votes

I have Openwrt router with Arduino connected via USB FTDI adapter. Serial port is /dev/ttyUSB0

Arduino code prints some data:

First part of data printed with delay via command print(), for example:

Serial.begin(9600);
Serial.print(var1);
delay(1000);
Serial.print(var2);
delay(1000);
Serial.print(var3);
delay(1000);

And second part printed with println() command:

Serial.println("");
Serial.println(var4);
Serial.println(var5);
Serial.println(var6);

So when I open Serial port in terminal I can see something like this:

1

then timeout in 1 sec, then

1 2

next timeout. and then

1 2 3

last timeout and

1 2 3
4
5
6

It works in Terminal program and in console in OpenWRT, for example screen /dev/ttyUSB0

I need make a Lua script that will read Serial port and print the data in the same way. I have a simple script, but it doesn't work as expected.

rserial=io.open("/dev/ttyUSB0","r")
while true do
chain = nil
  while chain==nil do
    chain=rserial:read();
    print(chain)
  end
end

it shows all data at once. it doesn't show first 3 vars one by one with delays. Seems it is because of rserial:read() - it will read until it receives a newline character. It stated in similar question: How to read from a serial port in lua

I tried to run this command as was advised there:

stty -F /dev/ttyUSB0 -icanon

but it doesn't help and I don't understand why. Is it the way to fix this behavior via stty? or I definitely need to use another Serial libs for Lua script? All of these libs seems pretty outdated for now and I don't want to use outdated stuff..

1

1 Answers

0
votes

From the Lua Reference Manual:

When called without formats, it uses a default format that reads the next line (see below).

A new line is anything in the buffer until the next newline character.

So as long as you don't send a newline character Lua will wait one as it has been told by calling read()

Once a newline character is received you will be prompted any other character in that line.

Terminal programs usually update every byte to show what they receive in "real-time".

So if you want to have the same behaviour you may not use read() without any arguments.

Use read(1) to read every single byte without waiting for anything else.