Skip to content

Commit c8de037

Browse files
committed
Add button strobe example
1 parent 4b09a5e commit c8de037

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

examples/button-strobe.toit

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import lightbug.devices as devices
2+
import lightbug.services as services
3+
import lightbug.messages as messages
4+
import log
5+
6+
// A simple application waits for button press messages, and changes the strobe based on them
7+
main:
8+
// Setup the Toit logger with the INFO log level
9+
log.set-default (log.default.with-level log.INFO-LEVEL)
10+
11+
// This example is setup to work with the RH2 device
12+
device := devices.RtkHandheld2
13+
14+
// Setup the comms service, which allows communication with the Lightbug device
15+
comms := services.Comms --device=device
16+
17+
// Draw a new page with instructions, and to replace any existing page
18+
latch := comms.send (messages.TextPage.to-msg
19+
--page-id=3001
20+
--page-title="Strobe Example"
21+
--line2="Press the buttons"
22+
--line3="to change the strobe"
23+
--redraw-type=2 // FullRedraw
24+
)
25+
--now=true
26+
--withLatch=true
27+
--preSend=(:: print "💬 Sending instruction page to device")
28+
--postSend=(:: print "💬 Instruction page sent")
29+
--onAck=(:: print "✅ Instruction page ACKed")
30+
--onNack=(:: print "❌ Instruction page NACKed")
31+
--onError=(:: print "❌ Instruction page error")
32+
33+
// Subscribe to button presses
34+
if not ( comms.send (messages.ButtonPress.subscribe-msg) --now=true
35+
--preSend=(:: print "💬 Sending button press subscribe")
36+
--onAck=(:: print "✅ Subscription ACKed")
37+
--onNack=(:: if it.msg-status != null: log.warn "Button not yet subscribed, state: $(it.msg-status)" else: log.warn "Button not yet subscribed" )
38+
--timeout=(Duration --s=5)
39+
).get:
40+
throw "📟❌ Failed to subscribe to button press events"
41+
42+
// Open an inbox to receive button press messages (and all other messages)
43+
inbox := comms.inbox "button-strobe"
44+
while true:
45+
msg := inbox.receive
46+
e := catch --trace:
47+
if msg.type == messages.ButtonPress.MT:
48+
log.info "Received button press: $msg"
49+
buttonData := messages.ButtonPress.from-data msg.data
50+
if buttonData.duration >= 1000:
51+
device.strobe.set false false false
52+
else:
53+
if buttonData.button-id == 1:
54+
device.strobe.set true false false
55+
else if buttonData.button-id == 0:
56+
device.strobe.set false true false
57+
else if buttonData.button-id == 2:
58+
device.strobe.set false false true
59+
else:
60+
log.info "Received message: $msg"
61+
if e != null:
62+
log.error "Error processing message: $e"
63+
continue

0 commit comments

Comments
 (0)