Skip to content

Commit 2d86d1f

Browse files
committed
Simplify fire_alarm solution
1 parent e15d0d7 commit 2d86d1f

File tree

1 file changed

+36
-46
lines changed

1 file changed

+36
-46
lines changed

exercises/fire_alarm/solution/solution.js

Lines changed: 36 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -7,62 +7,52 @@ board.on('ready', function () {
77
var btn = new five.Button(5)
88
var thermo = new five.Sensor('A0')
99

10-
var temp = null
1110
var threshold = 50
12-
var wasReset = false
11+
var isOnFire = false
12+
var isReset = false
1313

14-
btn.on('press', function () {
15-
if (temp <= threshold) return
16-
noFire()
17-
wasReset = true
18-
})
19-
20-
thermo.on('change', function () {
21-
// Convert to celsius (TMP36)
22-
temp = ((this.value * 0.004882814) - 0.5) * 100
23-
24-
if (wasReset && temp <= threshold) {
25-
wasReset = false
26-
}
14+
var sirenInterval = null
2715

28-
if (wasReset && temp > threshold) {
29-
return
30-
}
16+
// Sound the alarm
17+
function panic () {
18+
if (isOnFire) return
19+
isOnFire = true
3120

32-
if (temp <= threshold) {
33-
noFire()
34-
} else {
35-
fire()
36-
}
37-
})
38-
39-
var blazing = false
40-
41-
function fire () {
42-
if (blazing) return
4321
led.strobe(1000)
44-
siren()
45-
blazing = true
22+
piezo.tone(five.Piezo.Notes.c, 750)
23+
sirenInterval = setInterval(function () {
24+
piezo.tone(five.Piezo.Notes.c, 750)
25+
}, 1000)
4626
}
4727

48-
function noFire () {
49-
if (!blazing) return
28+
// Silence the things
29+
function calm () {
30+
if (!isOnFire) return
31+
isOnFire = false
32+
5033
led.stop().off()
51-
stopSiren()
52-
blazing = false
34+
clearInterval(sirenInterval)
35+
piezo.noTone()
5336
}
5437

55-
var sirenTimeout = null
38+
// The reset button
39+
btn.on('press', function () {
40+
if (!isOnFire) return
41+
isReset = true
42+
calm()
43+
})
5644

57-
function siren () {
58-
sirenTimeout = setTimeout(function () {
59-
piezo.tone(five.Piezo.Notes.c, 750)
60-
siren()
61-
}, 1000)
62-
}
45+
// Watch the temp
46+
thermo.on('change', function () {
47+
// Convert to celsius (TMP36)
48+
var temp = ((this.value * 0.004882814) - 0.5) * 100
49+
50+
if (!isReset && temp > threshold) {
51+
panic()
52+
} else {
53+
calm()
54+
isReset = false // clear the reset flag when temp drops below threshold
55+
}
56+
})
6357

64-
function stopSiren () {
65-
clearTimeout(sirenTimeout)
66-
piezo.noTone()
67-
}
6858
})

0 commit comments

Comments
 (0)