-- -- Example to read from Quasar Temp Logger. -- -- This uses luars232 to send to the com port. -- -- The serial port is buffered. -- Send the command and wait for PIC to return information. -- -- Use a simple timeout counter to establish when the PIC has dried up. -- rs232 = require( "luars232" ) -- Linux -- port_name = "/dev/ttyS0" -- Windows port_name = "COM1" port_name = "COM3" local out = io.stderr lastPort = nil for cnt = 0,255 do port_name = "COM"..cnt -- print( port_name ) local e, p = rs232.open(port_name) if e == rs232.RS232_ERR_NOERROR then -- handle error out:write(string.format("Found serial port '%s', error: '%s'\n", port_name, rs232.error_tostring(e))) assert(p:close() == rs232.RS232_ERR_NOERROR) lastPort = port_name end end if lastPort then port_name = "COM3" -- assume PIC plugged into last port found port_name = lastPort else print( "no port found ... ") end -- open port local e, p = rs232.open(port_name) if e ~= rs232.RS232_ERR_NOERROR then -- handle error out:write(string.format("can't open serial port '%s', error: '%s'\n", port_name, rs232.error_tostring(e))) return end -- set port settings assert(p:set_baud_rate(rs232.RS232_BAUD_2400) == rs232.RS232_ERR_NOERROR) assert(p:set_data_bits(rs232.RS232_DATA_8) == rs232.RS232_ERR_NOERROR) assert(p:set_parity(rs232.RS232_PARITY_NONE) == rs232.RS232_ERR_NOERROR) assert(p:set_stop_bits(rs232.RS232_STOP_1) == rs232.RS232_ERR_NOERROR) assert(p:set_flow_control(rs232.RS232_FLOW_OFF) == rs232.RS232_ERR_NOERROR) out:write(string.format("OK, port open with values '%s'\n", tostring(p))) print(string.format("OK, port open with values '%s'\n", tostring(p))) -- read with timeout local read_len = 1000 -- read one byte -- local timeout = 100 -- in miliseconds local timeout = 100 -- in miliseconds -- use the read time out to allow the PIC to send response. local err, data_read, size = p:read(read_len, timeout) assert(e == rs232.RS232_ERR_NOERROR) -- print( "===", err, size ) -- print( data_read ) dataBuff = data_read -- set buffer and time out local read_len = 10000 -- read one byte -- local timeout = 100 -- in miliseconds local timeout = 5000 -- in miliseconds finished = 1 silenceCount = 0 dataBuff = "" while silenceCount < 5 do err, data_read, size = p:read(read_len, timeout) assert(e == rs232.RS232_ERR_NOERROR) -- print( "===", err, size ) print( data_read ) -- print( "+" ) if size > 1 then dataBuff = dataBuff .. data_read print("++++", dataBuff ) finished = false finished = dataBuff:len() < 200 finished = false while not finished do -- -- look for a line nl, crlf, rest = string.match(dataBuff, "(%C+)(%c+)(.+)" ) if crlf then print( "===>", nl , string.byte(crlf,1), string.byte(crlf,2) ) dataBuff = rest else finished = true end end else silenceCount = silenceCount + 1 end end assert(p:close() == rs232.RS232_ERR_NOERROR)