Wednesday, March 18, 2015

Using HotPaw Basic with a LightBlue Bean Bluetooth LE device

HotPaw Basic 1.7.1 for iOS now includes direct support for communication with the LightBlue Bean.

This example HotPaw Basic program below lets you scan for Bluetooth LE devices, select a Bean, connect to it, blink the LED blue, read scratch bank 3, and read the temperature. Note that 1 or 2 second waits between all Bluetooth commands can be helpful or necessary (depending on your device model and how busy it is, etc.)

100 rem
102 print "starting scan for Beans"
120 fn bean.init()
140 fn sleep(1)
160 fn bean.list()
180 b$ = fn bean.selected()
190 print b$
192 if len(b$) < 20 then print "no bean selected" : end
200 fn bean.connect(1,b$)
210 for i = 1 to 20 : rem wait for bean to connect
212   if fn bean.connect(1) > 0 then exit for
214   fn sleep(0.5)
216 next i
220 print fn bean.name(1)
230 fn bean.led(1,0,0,1) :rem blink blue
246 fn bean.temp() :rem start temperature read
260 fn sleep(1)
270 fn bean.led(1,0,0,0) :rem off
280 fn sleep(1) : rem wait
300 fn bean.rdsc(1,3,0) :rem start scratch read
310 fn sleep(1)
320 s$ = fn bean.rdsc(1,3,1) :rem as a string
322 print len(s$),s$
340 s$ = fn bean.rdsc(1,3,16) :rem as a hex string
342 print len(s$),s$
374 print fn bean.temp()
950 fn sleep(1)
960 fn btle(9) :rem disconnect bluetooth devices
970 print "done"
990 end

Combine this with the MQTT sample app (from in an earlier post in this blog), and you can have your Bean send messages over the internet, using an iOS device as the relay to a broker.

The Bean serial protocol is also supported, see HotPaw Basic's built-in documentation for details. But don't expect a data rate much higher than 2400 baud (due to restrictions involving iOS built-in power saving and WiFi/BLE antenna sharing modes, etc.), so make sure your app sleeps a bit between sending small chunks of serial data.