Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Peripheral setup
- local modemSide = "bottom"
- local speakerSide = "top"
- local lightSide = "front"
- local thresholdPct = 3 -- Set your threshold here (percent, 0-100)
- local flickerTime = 0.5 -- seconds for lamp flicker
- local alarmRepeat = 2 -- seconds between alarm beats
- local speaker = peripheral.wrap(speakerSide)
- if not speaker then error("Speaker not found on top!") end
- rednet.open(modemSide)
- redstone.setOutput(lightSide, false)
- local alarmActive = false
- local lastFlicker = os.clock()
- local lampOn = false
- local lastAlarmBeat = -1
- local lastPct = nil
- term.clear()
- term.setCursorPos(1,1)
- print("Battery alarm script running!")
- term.setCursorPos(1,2)
- io.write("Battery: ")
- while true do
- local tickTimer = os.startTimer(0.1)
- local accPct = nil
- local event
- repeat
- event = { os.pullEvent() }
- if event[1] == "rednet_message"
- and event[4] == "generator_status"
- and type(event[3]) == "table"
- and type(event[3].accPct) == "number"
- then
- accPct = event[3].accPct
- end
- until event[1] == "timer" or accPct
- -- Display and refresh battery percentage on line 2
- if accPct then
- -- Avoid flicker: only redraw if changed or at first
- if lastPct == nil or math.abs(accPct - lastPct) > 0.01 then
- term.setCursorPos(9,2)
- io.write(string.format("%6.2f%% ", accPct))
- lastPct = accPct
- end
- end
- if not accPct then goto continue end
- if accPct < thresholdPct then
- if not alarmActive then
- term.setCursorPos(1,3)
- print("ALARM: Battery below threshold!")
- alarmActive = true
- lampOn = false
- lastFlicker = os.clock()
- lastAlarmBeat = -1
- end
- -- Flicker the lamp
- if os.clock() - lastFlicker > flickerTime then
- lampOn = not lampOn
- redstone.setOutput(lightSide, lampOn)
- lastFlicker = os.clock()
- end
- -- Synced alarm using in-game os.time()
- local now = os.time()
- local beat = math.floor(now * 50 / alarmRepeat)
- if beat ~= lastAlarmBeat then
- for i = 1, 40 do
- speaker.playNote("bass", 3, 8)
- end
- lastAlarmBeat = beat
- end
- else
- if alarmActive then
- term.setCursorPos(1,3)
- print("Battery restored. ")
- alarmActive = false
- redstone.setOutput(lightSide, false)
- end
- end
- ::continue::
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement