Lua脚本 - 收集数据并保存到文件中

我正在编写Lua脚本。

我要编写的是...收集数据并将其保存到特定文件中。

_情况_:

有两个传感器,当它们识别到前面的物体时,传感器的值会增加。

我想要每100毫秒保存一次传感器值的数据以及时间格式为“2013-04-25 10:30:004”。

这里是我的代码。

===========================================================

require("TIMER")
require("TIMESTAMP")
require("ANALOG_IN")

function OnExit()
    print("Exit code...do something")
end

function main()

    timer = "TIMER"
    analogsensor_1 = "AIR_1"
    analogsensor_2 = "AIR_2"

    while true do
        valueOfSensor_1 = ANALOG_IN.readAnalogIn(analogsensor_1);
        valueOfSensor_2 = ANALOG_IN.readAnalogIn(analogsensor_2);

        write(colltection_of_data.txt)
        go(print(valueOfSensor_1), 0.1)     //每100ms打印一次传感器值
        print(time)
        go(print(valueOfSensor_2), 0.1)
        print(time)
    end
    TIMER.sleep(timer,500)

end

print("start main")
main()

================================================================

我知道这不是完整的代码。如何将数据保存到特定文件中?如何显示像那样的时间格式?

预先感谢您!

点赞
用户1847592
用户1847592

抱歉,无法处理小数秒

-- 打开文件
local file = assert(io.open('collection_of_data.txt','wb'))

-- 写入文件
local dt = os.date'*t'
local time_string =
   dt.year..'-'..('0'..dt.month):sub(-2)..'-'..('0'..dt.day):sub(-2)..' '..
   ('0'..dt.hour):sub(-2)..':'..('0'..dt.min):sub(-2)..':'..('0'..dt.sec):sub(-2)
file:write(valueOfSensor_1, '\n', time_string, '\n')

-- 关闭文件
file:close()
2013-04-25 13:29:35
用户2198692
用户2198692

获取日期和时间,您需要调用:

local timestr = os.date(“%Y-%m-%d %H:%M:%S”)

现在要将其保存到文件中,您需要打开文件

local filehandle = io.open(filename [,mode]) - 手册

要输出所需数据,请使用

local filehandle = io.open(“Log.txt”,“w +”)
filehandle:write(timestr,“ - Sensor1:“,tostring(valueOfSensor1),“\ n”)

当然,您只需打开文件一次,然后每隔x(毫秒)发出写入命令。完成后:

filehandle:close()

附言:请尽可能使用locals。这比globals快得多(local analogSensor_1而不仅仅是analogSensor_1

2013-04-25 13:32:05