我正致力于编写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) //print value of sensor every 100ms
print(time)
go(print(valueOfSensor_2), 0.1)
print(time)
end
TIMER.sleep(timer,500)
end
print("start main")
main()
================================================================
我知道这不是完整的代码。如何将数据保存到某个文件中? 我该如何显示这样的时间格式?
提前谢谢!
答案 0 :(得分:4)
要获得致电的日期和时间:
local timestr = os.date("%Y-%m-%d %H:%M:%S")
现在要将其保存到文件中,您需要打开文件
local filehandle = io.open(filename[, mode])
- Manual
要输出所需数据,请使用
local filehandle = io.open("Log.txt", "w+")
filehandle:write(timestr, " - Sensor1: ", tostring(valueOfSensor1), "\n")
当然,您只打开一次文件,然后每隔x(毫秒)发出一次写入命令。完成后:
filehandle:close()
P.S。请尽可能使用当地人。它比全局变量(local analogSensor_1
而不仅仅是analogSensor_1
)
答案 1 :(得分:1)
抱歉,没有小数秒
-- Open file
local file = assert(io.open('collection_of_data.txt','wb'))
-- Write to file
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')
-- Close file
file:close()