This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
max9076's profile picture

start 30m timer, then stop by using local event?

Started by max9076, 15 August 2014 - 12:28 PM
max9076 #1
Posted 15 August 2014 - 02:28 PM
Hello, I hope I can get some help here, because I think I don't understand that event thing…

So, my code is

local myTimer = os.startTimer(5)
while true do
local event,timerID = os.pullEvent("timer")
if timerID == myTimer then
rs.setOutput("front", true)
end
break
end
end
	
local event, redstone = os.pullEvent()
if redstone == rs.getInput("left") then
rs.setOutput("front", false)
end

I want to start a timer, waiting 30 minutes.
Then it emits a redstone signal to forward.
At this point, I want it to sleep (but not sleep()),
till I press a button, which emits another redstone signal on the left.
And then, the timer should start again.

And… I don't really understand that "break".

Greetings
theoriginalbit #2
Posted 15 August 2014 - 02:40 PM
The break will leave the loop, however where you have it positioned it will break immediately after a timer even has finished, even if it is not yours.

Is there a specific reason you cannot just use sleep, if your code is literally as simple as this then using a sleep could be simpler.

A problem you will encounter is the fact that there is no value returned from the redstone event therefore when you press a button your comparison of redstone == rs.getInput("left") will be trying to check nil against a boolean value. Instead you'd want to do the following code.


--# infinitely loop
while true do
  --# setup the timer
  local timer = os.startTimer(1800) --# 1800 is 30 minutes in seconds

  --# wait until the timer has completed
  repeat
    local event, param = os.pullEvent("timer")
  until param == timer --# was it our timer that finished

  --# the timer has finished, set the redstone output on the front
  rs.setOutput("front", true)

  --# wait for the button to be pressed
  repeat
    os.pullEvent("redstone") --# wait for a redstone state change
  until rs.getInput("left") --# was the change in redstone on the left?

  --# turn off the output on the front
  rs.setOutput("front", false)

  --# nothing more to do, begin again
end

do note however that the process used in the above code to wait for the timer to finish is exactly how the sleep function works, therefore the above code could be simplified to the following


while true do
  sleep(1800) --# wait 30 minutes
  rs.setOutput("front", true)
  repeat
    os.pullEvent("redstone")
  until rs.getInput("left")
  rs.setOutput("front", false)
end
max9076 #3
Posted 15 August 2014 - 03:08 PM
Okay.
Thank you!