Home

BL600 smartBASIC Module

image

Contents

1. To use UWTerminal follow the steps below Note that the screen shots may differ slightly as it is a continually evolving Windows application 1 Switch on the development board if applicable 2 Start the UWTerminal application on your PC to access the opening screen Figure 3 eager Ya Terma viz tarno BASIC Conky Abma oom l lorire one Ooveded be Lan Teche whaa waranty You oe wetlow se check ow webbots Ar the Laven Tie eens A Chptased EITHER because socept u oot epecdedin fie command ine TF of iest one cormasdt ino open hac Deen 1pected veh en creat peoretoa Tow os lah fee epp r ator aed bapan they sakira te pate a thaiad ba wet prg OO EPI a toroord he opten Ofte comewre re acom sa Figure 3 UWTerminal opening screen 3 Click Accept to open the configuration screen Tewrwnel BASIC Corky Abo o Cancel Da tim i f T Uml aH Cornmard Dopo Cang Bysdiate IHAN 48 3 Now Al P wR Come Langh M Tex Socket Paip hene Sing Bits 1 Line T evea Fara eo Date lites 2 Homishebng CTSATIS w Tree Leg FAIL corea batts n Tarra Wirciow Figure 4 UWTerminal Configuration screen 4 Enter the COM port that you have used to connect the development board The other default parameters should be Baudrate 9600 Parity None Stop Bits 1 Data Bits 8 Handshaking CTS RTS Americas 1 800 492 2320 Option 2 13 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless su
2. Given that the outgoing data is notified to the client the tx fifo characteristic has a Client Configuration Characteristic CCCD which must be set to 0x0001 to allow the module to send any data waiting to be sent in the transmit ring buffer While the CCCD value is not set for notifications writes by the smart BASIC application result in data being buffered If the buffer is full the appropriate write routine indicates how many bytes actually got absorbed by the driver In the background the transmit ring buffer is emptied with one or more indicate or notify messages to the client When the last bytes from the ring buffer are sent EVVSPTXEMPTY is thrown to the smartBASIC application so that it can write more data if it chooses When GATT Client sends data to the module by writing into the rx fifo characteristic the managing driver will immediately save the data in the receive ring buffer if there is any space If there is no space in the ring buffer data is discarded After the ring buffer is updated event EVVSPRX is thrown to the smartBASIC runtime engine so that an application can read and process the data Similarly given that ModemOut is notified to the client the ModemOut characteristic has a Client Configuration Characteristic CCCD which must be set to 0x0001 By default in a connection the RTS bit in ModemOut Is set to 1 so that the VSP driver assumes there is buffer space in the peer to send data The RTS flag is affecte
3. teen TEE TE TTE TETE TEE n dE W acral 7 eovslmio 206 Tae uale Sc lno 20o vy actual T yeno Olo actual 7 oysIni o 0l actual Sysintro 2018 acevUal A sysinmo Z0 13 actual Ye sysinro Z0e BLETXPOWERSET is an extension function BleConfigDcDc SUBROUTINE This routine is used to configure the DC to DC converter to one of 3 states OFF ON or AUTOMATIC Note Until a future revision when the chipset vendor has fixed a hardware Issue at the silicon level this function will not function as stated and any nWewsState value will be interpreted as OFF BLECONFIGDCDC nNewState Returns Arguments nNewState Interactive Command Americas 1 800 492 2320 Option 2 None byVal nNewState AS INTEGER Configure the internal DC to DC converter as follows 0 OFF 2 AUTO Any other value ON NO Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth 207 Laird Technologies smart BASIC User Manual BleContaqDebDe 2 Set for automatic operation BLECONFIGDCDC is an extension function Advertising Functions This section describes all the advertising related routines An advertisement consists of a packet of information with a header identifying it as one of 4 types along with an optional payload that consists of multiple advertising records referred to as AD in the rest of this manual Each AD record consists of
4. COMMAND This is a command that is successful one time as it writes an IEEE MAC address to non volatile memory This address is then used instead of the random static MAC address that comes preprogrammed in the module Notes If the module has an invalid licence then this address will not be visible If the address OOOOO0000000 is written then it will be treated as invalid and prevent a new address from being entered AT MAC 12 hex digits Returns nOO r or n01 192A r Where the error code 192A is NVO_NVWORM_EXISTS meaning an IEEE mac address already exists which can be read using the command AT 24 Arguments aa A string delimited by volatile memory which shall be a valid 12 hex digit mac address that is written to non This is an Interactive Mode command and MUST be terminated by a carriage return for It to be processed Note The module self reboots if the write is successful Subsequent invocations of this command generate an error Interactive Command YES Examples AT MAC 008098010203 AT MAC is an extension command Americas 1 800 492 2320 Option 2 47 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual AT BLX COMMAND This command is used to stop all radio activity adverts or connections when in interactive mode It is particularly useful when t
5. Expression Lists Expression lists are used for outputting data principally with the PRINT and the SPRINT command Two types of Expression lists are allowed arithmetic and string Multiple valid Expression lists may be concatenated with a comma or a semicolon to form a complex Expression list The use of a comma forces a TAB character between the Expression lists it separates and a semicolon generates no output The latter results in the output of two expressions being concatenated without any white space Numeric Expression Lists Numeric variables are formatted in the following form lt type base gt arithexpr lt seoarator gt Americas 1 800 492 2320 Option 2 70 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Where Type Must be INTEGER for integer variables base Integers can be forced to print in decimal octal binary or hexadecimal by prefixing with D O B or H respectively For example INTEGER h somevar will result in the content of somevar being output as a hexadecimal string Arithexpr A valid arithmetic or logical expression Separator One of the characters or which have the following meaning Insert a tab before the next variable Print the next variable without a space String Expression Lists String variables are formatted in the following form
6. FUNCTION HandlerBleMsg BYVAL nMsgid BYVAL nCtx AS INTEGER SELECT mnMsqid CASE 19 PRINTE VAn Power Paul Warning metx mv ReadPwrSuppl yMv PRINT n Supply voltage ic gt Readewrsupol yMy gt my CASE ELSE ignore this message ENDSELECT EM DE UNC i aansnaansaaaassaaass558555555555585 55555555555 5555 555555 555555555555552555 55 Handler to service button 0 pressed aoasnaaaaaasssaass5555552555555555558555555555555 5555 55555555555555555555 55 FUNCTION HndirBtnOPr A gt tLe err Americas 1 800 492 2320 Option 2 354 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output SETPWRSUPPLYTHRESHMV is an extension function Americas 1 800 492 2320 Option 2 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth 355 Laird Technologies smart BASIC User Manual 8 EVENTS amp MESSAGES smart BASIC is designed to be event driven which makes it suitable for embedded platforms where it is normal to wait for something to happen and then respond To ensure that access to variables and resources ends up in race conditions the event handling is done synchronously meaning the smart BASIC runtime engine has to process a WAITEVENT statement for any events or messages to be processed This guarantees that
7. jovedigr es Vai FOR a 2 DOWNTO 1 PRINT Hello NEXT jcuauiian eam alt POR a l TO 4 Suuiile 2 PRINT hello NEXT Expected Output Americas 1 800 492 2320 Option 2 61 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual HelloHello HelloHello HelloHello FOR NEXT is a core function IF THEN ELSEIF ELSE ENDIF The IF statement construct allows a block of code to be processed depending on the evaluation of a condition expression If the statement is true equates to non zero then the following block of application is processed until an ENDIF ELSE or ELSEIF command is reached Each ELSEIF allows an alternate statement block of application to be executed if that conditional expression is true and any preceding conditional expressions were untrue Multiple ELSEIF commands may be added but only the statement block immediately following the first true conditional expression encountered is processed within each IF command The final block of statements is of the form ELSE and is optional IF arithexor_ 7 THEN statement block A ENDIF IF arithexor_ 7 THEN statement block A ELSE statement block B ENDIF IF arithexor_ 7 THEN statement block A ELSEIF arithexor_2 THEN statement block B ELSE statement block C ENDIF Statement block A B C A valid set of zero or more program state
8. lt type minchar gt strexor lt separator gt Type Must be STRING for string variables The type must be followed by a Tull stop to delineate it from the width field that follows Minchar An optional parameter which specifies the number of characters to be printed for a string variable or expression If necessary leading spaces are filled with spaces strexpr A valid string or string expression Separator One of the characters or which have the following meaning Insert a tab before the next variable Print the next variable without a space Interactive Command YES Example Print sb See in BL600CodeSnippets zip PRINT Hello ia DIME a 100 PRINT amp PRINT sala es ye Oise TUN e E OO TAa PUNE Aig Ocea ae TECER Ce O0 TAT PERITE SIO Ena a TTE ER R OO Expected Output Hello 100 In Hex 0x00000064 im Ogtal 00000000144 it Binary 00000000000000000000000001100100 PRINT is a core function Americas 1 800 492 2320 Option 2 71 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual SPRINT The SPRINT statement directs output to a string variable which may be the result of multiple comma or semicolon separated arithmetic or string expressions It is very useful for creating strings with formatted data SPRINT stringvar exoriist Arguments Stringvar A pre decl
9. 603 Flash File System Data Segment Deleted Space 604 Flash File System FAT Segment Total Space 605 Flash File System FAT Segment Free Space 606 Flash File System FAT Segment Deleted Space 631 NvRecord Memory Store Segment Total Space 632 NvRecord Memory Store Segment Free Space 633 NvRecord Memory Store Segment Deleted Space 1000 1999 See SYSINFO function definition 2000 2999 See SYSINFO Q function definition Any other number currently returns the manufacturer s name For ATi4 the TT in the response is the type of address as follows 00 Public IEEE format address 01 Random static address default as shipped 02 Random Private Resolvable used with bonded devices not currently available 03 Random Private Non Resolvable used for reconnections not currently available Please refer to the Bluetooth specification for a further description of the types Americas 1 800 492 2320 Option 2 33 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual This is an Interactive mode command and must be terminated by a carriage return for it to be processed Interactive Command Yes Example MME ak 10 Po 00 AT I 4 10 4 Cri D SAO 0731B0 AT i is a core command The information returned by this Interactive command can also be useful from within a running application and so a built in function calle
10. FUNCTION This function is used to initialise a context for AES encryption and decription using the mode key and initialisation vector supplied The modes that are catered for is EBC and CBC with a block size of 128 bits AESSETKEYIV mode blockSize key initVector Returns INTEGER Will be 0x0000 if the context was created successfully Otherwise an appropriate resultcode will be returned which will convery the reason it failed Arguments mode BYVAL mode AS INTEGER This shall be as follows 0x100 for EBC mode 0x101 for EBC mode but data is XORed with same initVector everytime 0x200 for CBC mode blockSize BYVAL blockSize AS INTEGER Must always be set to16 which is the size in bytes key BYREF key AS STRING This string specifies the key to use for encryption and decryption and MUST be exactly 16 bytes long initVector BYREF initVector AS STRING If mode is 0x101 or 0x200 then this string MUST be supplied and it shall be 16 bytes long It is left to the caller to ensure a sensible value is supplied For example providing a string where all bytes is O is going to be of no value Interactive Command NO Example AesSetKeylIv sb See in BL6OO00CodeSnippets zip DEME aah eV Se e125 Dit vise Cre ate context for EBC mode 128 bit keys 00 01 02 03 04 0506 07 06 09 0A 0B 0C OD OEN OET initVector EBC does not require initialisation vector re Aesoeukeyly Ox100 16 keys init Vectrors IF rc 0 THEN PRINT
11. FUNCTION HandlerGatteTout cHndl AS INTEGER PRINE nhVGATLTCTOUM conndancile chnel ENDE UNG 1 ff mae SSS Main equivalent fff SS ONEVENT EVBLEMSG CALL HndlrBleMsg OnEvent EVGATTCTOUT call heard WeaG aire Ole re OnStareup WA EIIE on i Americas 1 800 492 2320 Option 2 268 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Laird Technologies smart BASIC User Manual Expected Output EVGATTCTOUT connhanc le 123 BleGattcOpen FUNCTION This function is used to initialise the GATT Client functionality for immediate use so that appropriate buffers for caching GATT responses are created in the heap memory About 300 bytes of RAM is required by the GATT Client manager and given that a majority of BL600 use cases will not utilise it the sacrifice of 300 bytes which is nearly 15 of the available memory is not worth the permament allocation of memory There are various buffers that need to be created that are needed for scanning a remote GATT table which are of fixed size There is however one buffer which can be configured by the smartBASIC apps developer and that is the ring buffer that is used to store incoming notifiable and indicatable characteristics At the time of writing this user manual the default minimum size is 64 unless a bigger one is desired and in that case the input parameter to this function specifies that size A maximum of
12. SUBROUTINE This subroutine stops one of the built in timers so that it will not generate a timeout event TIMERCANCEL number Arguments number byVal number AS INTEGER The number of the timer O to N where N can be determined by submitting the command AT 2003 or at runtime returned via SYSINFO 2003 If the value is not valid then a runtime error will be thrown with code INVALID_TIMER Interactive Command NO Related Commands ONEVENT TIMERCANCEL TIMERRUNNING Example TimerCancel sb See in BL600CodeSnippets zip DIM i x i 0 x 1 x is HandlerTimerO s return value Americas 1 800 492 2320 Option 2 116 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Will switch to 0 when timerO has expired so that the application can STO PUNCTION HandlerTimer0 PRINT nTimer 0 has expired starting again IF i 4 THEN PRINT nCancelling Timer 0 TimerCancel 0 PRINT Tamer OUr oan Va Eames x 0 ENDIF i it l BNDEPUNCG x ONEVENT EVTMRO CALL HandlerTimer0O Timerstare 07800 1 PRINT Wasting for Taimer 0 Should cum gt times WALTEVENT Expected Output TIMERCANCEL Is a core subroutine GetTickCount FUNCTION There is a 31 bit free running counter that increments every 1 millisecond The resolution of this counter in microseconds can be determined by submitting the command AT 2004 or at ru
13. The target string which cannot be a const string length byVal length AS INTEGER The number of leftmost characters that are returned before being dropped from the target string Note string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Interactive Command NO Example StrSplitLeft sb See in BL600CodeSnippets zip DIM Origo oero tr TI ao Americas 1 800 492 2320 Option 2 99 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRIME Str o plir lero Or oaa cog Yas PRIIT orio en Expected Output 123 45678 STRSPLITLEFTS is a core function STRSUM This function identifies the substring starting from a specified offset and specified length and then does an arithmetic sum of all the unsigned bytes in that substring and then finally adds the signed initial value supplied For example if the string is 01 02 03 04 05 and offset is 1 and length is 2 and initial value is 1000 then the output will be 1000 2 3 1005 STRSUM string nindex nBytes initVal Function Returns INTEGER The result of the arithmetic sum operation over the bytes in the substring If nlndex or nBytes are negative then the initVal will be returned Exceptions Local Stack
14. commit reports to GATT table adRpt is empty rc BleAdvRptsCommit adRpt scRpts POPILA kertoa re 0 adders 200 0 0 BNDSUB SUB Ve loseConmecunens rc BleDisconnect conHnd1 rc BleAdvertStop ENDSUB FUNCTION Hides levisg BYVAL nMsgIld BYVAL m rx conHndl nCtx ENDFUNC 1 Americas 1 800 492 2320 Option 2 264 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual FUNCTION HandlerCharDesc BYVAL hChar AS INTEGER BYVAL hDesc AS INTEGER DIM Bnstene nuud a a Ori Se y d IF hChar hMyChar THEN re BleCharbescRead h har hbese 0 20 duid as IE fc 0 THEN PRINT nRead 20 bytes from index ortser am new Char value PRINT n os New Descriptor Data Striexizes an PRINT ees hengrn strlen as PREM eee sDesceripton UUiD We shiguerssolenen iaty velthie EXITFUNGC O E TOE PRINT nCou ld nort access rhe ould ENDIF Filo ky PEINT nlhis 1s fOr some other chertacteristic BENDI E ENDEUNC a install a handler for writes to characceristic values ONE VEN EVCHARDESC CALL HandlerCharbDesc ONEVENT EVBLEMSG CALL HndlrBleMsg OnStarctup PRINT nWrite to the User Descriptor with UUID 0x2999 wait for events and messages WALTEVENT CloseConnections Paw PS sit hile a Expected Output BLECHARDESCREAD is an extension function GATT Client Functions Th
15. function HandlerNotifyBuf as integer print WEVNOTIEYBUP Event endfunc 0 need to progress the WAITEVENT fSSSSS SSS SSS SSS SSS SSS SSS SSS SSS SSS SSS SSS SSS SSS SSS SSS SSS SS SSS SSS SSS SSS SSS SS SSS SSS Main equivalent SSS SSS SS SSS SSS SS SS SS SSS SSS SS SSS SSS SS SSS SSS SS SS SS SSS SSS SS SSS SSS SSS SSS SSS SSS SSS ONEVENT EVBLEMSG CALL HndlrBleMsg Onmvent EVNOTIFY YBUF call HandlerNocuifyBur TE OnSCartup O THEN PRINT nAdvertising and Gatt Client is open n ELSE PRINT Yi nralilure Onewartue ENDIF WALTEVENT SUS EAS NE cde aialope on Americas 1 800 492 2320 Option 2 305 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output BLEGATTCWRITECMD is an extension function BleGattcNotifyRead FUNCTION A Gatt Server has the ability to notify or indicate the value attribute of a characteristic when enabled via the Client Characeristic Configuration Descriptor CCCD This means data will arrive from a Gatt Server at any time and so has to be managed so that it can synchronised with the smartBASIC runtime engine Data arriving via a notification does not require Gatt acknowledgements however indications require them This Gatt Client manager saves data arriving via a notification in the same ring buffer for later extraction using the command BleGattcNotifyRead and for indica
16. nDstldx byVal nDstidx AS INTEGER This is the zero based bit index into the string attr treated as a bit array where the new fragment of data bits is written If the string attr is not long enough to accommodate the index plus the length of the fragment it is extended If the new length exceeds the maximum allowable length of an attribute see SYSINFO 2013 this function fails srcBitArr byVal srcBitArr AS INTEGER This contains the source data bits which is qualified by the nSrcldx and nBitLen arguments that follow nSrclax byVal nSrcidx AS INTEGER This is the zero based bit index into the bit array contained in srcBitArr trom where the data bits will be copied No data Is copied if this index is negative or greater than 32 nBitLen byVal nBitlLen AS INTEGER This species the number of bits from offset nSrcldx to be copied into the destination bit array represented by the string attr It will be clipped to the number of bits left to copy after the index nSrcldx Interactive Command NO Example BleEncodeBits sb See in BL600CodeSnippets zip DIM atiro to DA boo ML TOnOOUCI I rc BleEncodeBits attr 20 bA 7 5 Sess Miele ieee er een roe to eg emer Expected Output a OO0 00 A0 01 BLEENCODEBITS Is an extension function Americas 1 800 492 2320 Option 2 320 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual
17. nEBC context created successfully rls ya Americas 1 800 492 2320 Option 2 162 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT nFailed to create EBC context ANB ee Ceeake context for EBC mode with XOR 128 bit keys 00 01 02 0204 05 06 07 03809 GA 0B OC 0b 0b 0m iiieeVecrous fr VOlev Os br Os Var O07 bb OO Van Oe BE Ol We VO rc AesSetKeylv 0x101 16 key initVectorS IF rc 0 THEN PRINT nEBC XOR context created successfully Blok PRINT nFailed to create EBC XOR context ENDI E Create context for CBC mode 128 bit keyo C0 0 02 02 04 05 0607 08 09 CA OBE Ce 0b 0m OET imi vechoro ah OI er OS Fe VOSS O07 bb OO RE OER br ODA kr OR rce AesSetKeylv 0x200 16 key initVector S IF rc 0 THEN PRINT mCBC context created successfully BLSE PRINT nFailed to create CBC context ENDIF Expected Output AESSETKEYIV is a core language function AesEncrypt FUNCTION This function is used to encrypt a string up to 16 bytes long using the context that was precreated using the most recent call of the function AesSetKeylv For all modes AesSetKeylV is called only once which means in CBC mode the cyclic data is kept in the context object that was created by AesSetKeylV On the BL600 which has AES 128 encryption hardware assist the function has been timed to take roughly 125 micro
18. smart BASIC User Manual Terminal BASIC Config About CTS OSR CCOM RB RTS DTR BRI Figure 10 Interactive command access UWTerminal supports a range of interactive commands to interact directly with the module The following ones are typical AT Returns 00 if the module Is working correctly AT 3 Shows the revision of module firmware Check to see that it is the latest version AT 13 Shows the hash value of the smartBASIC build AT 4 Shows the MAC address of the module AT DIR Lists all of the applications loaded on the module AT DEL filename Deletes an application from the module AT RUN filename Runs an application that is already loaded on the module Please be aware that if a filename does not contain any spaces it is possible to launch an application by just entering the filename as the command The next chapter lists all of the Interactive commands First check to see what is loaded on the module by typing AT DIR and Enter at dir 06 factory 00 If the module has not been used before then you should not see any lines starting with the two digit 06 sequence Americas 1 800 492 2320 Option 2 17 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Your First smartBASIC Application Create Hello World App Let s sta
19. Arguments None This is an Interactive Mode command and MUST be terminated by a carriage return for it to be processed Interactive Command YES Examples AT FCL AT FCL is a core command Americas 1 800 492 2320 Option 2 41 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Read Variable COMMAND When an application encounters a STOP BPnnn or END statement it falls into the Interactive mode of operation and does not discard any global variables created by the application This allows them to be referenced in Interactive mode var lt index gt Returns Displays the value of the variable if it had been created by the application If the variable is an array then the element index MUST be specified using the n syntax If the variable exists and it is a simple type then the response to this command is n08 tnnnnnn r nOO r If the variable is a string type then the response is n08 t Hello World r nOO r If the variable does not exist then the response to this command is nO1 tE023 r Where n linefeed t horizontal tab and r carriage return Note If the optional type prefix is present the output value when It is an integer constant is displayed in that base For example h var returns nO8 tH nnnnnn r nOO r Arguments Var lt nf gt Any valid variable wi
20. Attribute Decoding Functions Data in a Characteristic is stored in a Value attribute a byte array Multibyte Characteristic Descriptors content are stored similarly Those bytes are manipulated in smartBASIC applications using STRING variables Attibute data is stored in little endian format This section describes decoding functions that allow attribute strings to be read from smaller bytewise subfields more efficiently than the generic STRXXXX functions that are made available in s martBASIC Please note that CCCD and SCCD Descriptors are special cases as they are defined as having just 2 bytes which are treated as 16 bit integers mapped to INTEGER variables in smartBASIC BleDecodeS8 FUNCTION This function reads a single byte in a string at a specified offset into a 32bit integer variable with sign extension If the offset points beyond the end of the string then this function fails and returns zero BLEDECODESS attr nData nlndex Returns INTEGER the number of bytes extracted from the attribute string Can be less than the size expected if the nindex parameter is positioned towards the end of the string Arguments attr byRef atir AS STRING This references the attribute string from which the function reads nData byRef nData AS INTEGER This references an integer to be updated with the 8 bit data from attr after sign extension nindex byVal nindex AS INTEGER This is the zero based index into the string attr from wh
21. ENDIF WALTEVENT PRINT in cae ayy er E Expected Output BLEGATTCFINDCHAR is an extension function Americas 1 800 492 2320 Option 2 290 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleGattcFindDesc FUNCTION This function facilitates a quick and efficient way of locating the details of a descriptor if the uuid is known along with the uuid of the service and the uuid of the characteristic containing it and the results will be delivered in a EVFINDDESC event message If the Gatt server table has multiple instances of the same service characteristic descriptor combination then this function will work because in addition to the uuid handles to be searched for it also accepts instance parameters which are indexed from 0 which means the 2 instance of a descriptor in the 4 instance of a characteristic with the same uuid in the 3 instance of a service with the same uuid will be located with index values 1 3 and 2 respectively Given that the results are returned in an event message a handler must be registered for the EVFINDDESC event Depending on the size of the remote GATT server table and the connection interval the search of the characteristic may take many 100s of milliseconds and while this is in progress it is sate to do other non Gatt related operations like for example servicing sensors and displays or any of th
22. FUNCTION This function is used to determine the number of integer items held in the circular buffer CIRCBUFITEMS circHandle nitems Returns INTEGER a result code The typical value is OxO000 indicating a successful operation If 0x5102 is returned it implies the buffer was empty so nothing was read Arguments circHandle byRef circHandle AS INTEGER This identities the circular buffer which needs to be queried nitems byRef n tems AS INTEGER This returns the total items waiting to be read in the circular buffer Americas 1 800 492 2320 Option 2 124 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Interactive Command NO Example CircBufItems sb See in BL600CodeSnippets zip DIM rc circHandle i nItems re CircBufCreate 4 circHandle IF re 0 THEN PRINT nThe circular buffer was not created n ELSE PRINT nThe circular buffer was created successfully n ENDIF FOR i 1 TO 5 re CircBufOverwrite circHandle 1 LE ze 05103 THEN PRINT nOldest value was discarded to write i ELSEIF ze 1 0 THEN PRINT neatled TO write inTO the Circular buffrer BENDI E rc CircBufItems circHandle nItems IF rec 0 THEN PRINTE An nitems items in the circular Duffer BNDL E NIET Expected Output CIRCBUFITEMS is an extension function Serial Communications Routines In keeping with the event
23. It is advised that this be called once at the beginning of your application and not changed again within the application unless all PWM outputs are deconfigured and then re enabled after this function is called The PWM output is generated using 32 bit hardware timers The timers are clocked by a 1MHz clock source A PWM signal has a frequency and a duty cycle property the frequency is set using this function and is defined by the nMaxPeriodus parameter For a given nMaxPeriodus value given that the timer is clocked using a 1MHz source the frequency of the generated signal will be 1000000 divided by nMaxPeriodus Hence if nMinFreqHz is more than that 1000000 nMaxPeriodus this function will fail with a non zero value Americas 1 800 492 2320 Option 2 179 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual The nMaxPeriodus can also be viewed as defining the resolution of the PWN output in the sense that the duty cycle can be varied from O to nMaxPeriodus The duty cycle of the PWM signal is modified using the GpioWrite command For example a period of 1000 generates an output frequency of 1KHz a period of 500 a frequency of 2Khz etc On exit the function will return with the actual frequency in the nMinFreqHz parameter GPIOCONFIGPWM nMinFreqHz nMaxPeriodus Returns INTEGER a result code The most typical value is OxO000
24. Local Stack Frame Overflow Arguments string byRef string AS STRING The string from which the character is to be extracted nindex byVal nindex AS INTEGER The position of the character within the string zero based see example Americas 1 800 492 2320 Option 2 88 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Note string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Interactive Command NO Example StrGetChar sb See in BL600CodeSnippets zip DIM sS sS Hello ARI BE eS n PRINT StrGetChr se 0 gt gt ASCII value for H yn PRINT StrGetChr ss 1 gt ASCII value tore An PRINT SerGerehn s os OO aS errors in PRINT StrGetehr sS 6 gt error an Expected Output ASCII value for H ASCII value for e Srror cL tor STRGETCHR is a core function STRSETBLOCK FUNCTION STRSETBLOCK allows a specitied number of characters within a string to be filled or overwritten with a single character The fill character starting position and the length of the block are specified STRSETBLOCK string nChr nindex nBlocklen Function Returns INTEGER Represents command execution status O If the block is successfully upda
25. Ox000C 0x2803 Properties Value Handle Value UUID3 Ox000D Value UUID3 Value 1 to 512 bytes OxOOOE Ox2902 Value Descriptor 1 CCCD OxOOOF Ox2903 Value Descriptor 2 SCCD 0x0010 0x2904 Value presentation format data Descriptor 3 Ox00111 0Ox2906 Value valid range Descriptor 4 Range A colour highlighted example of a GATT Server table is shown above which shows there are 3 services at handles 0x0001 0x0008 and OxOOOB because there are 3 rows where the Type 0x2803 and all rows up to the next instance of a row with Type 0x2800 or 2801 belong to that service Americas 1 800 492 2320 Option 2 266 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Laird Technologies smart BASIC User Manual In each group of rows for a service you can see one or more Characteristics where Type 0x2803 For example the service beginning at handle Ox0008 has one characteristic which contains 2 rows identified by handles 0x0009 and OxO00A and the actual value for the characteristic starting at Ox0009 is in the row identified by OxOOO0A Likewise each characteristic starts with a row with Type 0x2803 and all rows following it up to a row with type 0x2800 2801 2803 are considered belonging to that characteristic For example see characteristic at row with handle 0x0004 which has the mandatory value row and then 2 descriptors The Bluetooth specification allows for multiple instances of
26. PRINT s Expected Output 123456789 36 09 STRSHIFTLEFT is a core function STRCMP FUNCTION Compares two string variables STRCMP string1 string2 Returns INTEGER A value indicating the comparison result O if string exactly matches string2 the comparison is case sensitive 1 if the ASCII value of string7 is greater than string2 1 if the ASCII value of string7 is less than string2 Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments string 1 byRef string AS STRING The first string to be compared string2 byRef string2 AS STRING The second string to be compared Americas 1 800 492 2320 Option 2 92 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Note string1and string2 cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Interactive Command NO Example StrCmp sb See in BL600CodeSnippets zip DIM Io oo s1 S hello e25 or ko PRIM Er O ello eZ a PINE Siete eZ Ss Aedes 5 ar PE THEA CE o els Sils js ia Expected Output STRCMP is a core function STRHEXIZE FUNCTION This function is used to convert a string variable into a string which contains all the bytes in the input string converte
27. gpiobindevent 1 16 1 Simds Gout ranean low Ooms holo Dur ton O to event 1 rc gpiobindevent 2 17 0 Apindo opio transi eon Alon on stole sibucron to event 2 rc gpiobindevent 3 17 1 Dimes h1O trans telon oy ven cio 6 bUr on 2 to event 3 onevent evgpiochanO call BtnOrel detects when button 0 is released and calls the function onevent evgpiochanl call BtnOpress detects when button 0 is pressed and calls the FUNCION Americas 1 800 492 2320 Option 2 69 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual onevent evgpiochan2 call Btnirel detects when button 1 is released and calls the function onevent evgpiochan3 call Btnipress detects when button 1 is pressed and calls the PING TE deta PRINT nWaiting for an event n WAITEVENT Wied is tor an event tO OCCUE PRINT nGot here because evgpiochan2 happened Expected Output ONEVENT is a core function Miscellaneous Commands PRINT The PRINT statement directs output to an output channel which may be the result of multiple comma or semicolon separated arithmetic or string expressions The output channel is a UART interface in most platforms PRINT exprlist Arguments exprlist An expression list which defines the data to be printed consisting of comma or semicolon separated arithmetic or string expressions Formatting with PRINT
28. nhandle nAhndl eles print nFailed to read attribute endif endiunc S2 SS SSSSSSSS SSS SSS SSeS S SS SSS SSS SSS S SS SSeS SSS Main equivalent ff a a SSS 5533352335235 S255 S 22 5S SSSS S525 SS SSS S gt S252 SSS SS S S S ONEVENT EVBLEMSG CALL HndlrBleMsg OnEvent EVATTRREAD call HandlerAttrRead IF OnStartup 0 THEN PRINT nAdvertising and Gatt Client is open n BLSE PRINT Ana la e Onea e bys ENDTE WALTEVENT URINE ol ICING gs Americas 1 800 492 2320 Option 2 298 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Laird Technologies smart BASIC User Manual Expected Output BLEGATTCREAD and BLEGATTREADDATA are extension functions BleGattcWrite FUNCTION If the handle for an attribute is known then this function is used to write into an attribute starting at offset O The acknowledgement will be returned via a EVATTRWRITE event message Given that the success or failure of this write operation is returned in an event message a handler must be registered for the EVATTRWRITE event Depending on the connection interval the write to the attribute may take many 100s of milliseconds and while this is in progress it is sate to do other non Gatt related operations like for example servicing sensors and displays or any of the onboard peripherals EVATTRWRITE event message This event message WILL be thrown if BleGa
29. then within a function or a subroutine that global variable cannot be accessed Variable Class smart BASIC supports two generic classes of variables Simple Numeric variables There are currently two types of simple variables INTEGER a signed 32 bit variable which also has the alias LONG and ULONG an unsigned 32 bit variable Simple variables are scalar and can be used within arithmetic expressions as described later Complex Non numeric variables There is currently only one type STRING STRING is an object of concatenated byte characters of any length up to a maximum of 65280 bytes but for plattorms with limited memory it is further limited and that value can be obtained by submitting the AT 1004 command when in Interactive mode and using the SYSINFO 1004 function from within an application For example in the BLE module the limit is 512 bytes since it is always the largest data length for any attribute Complex variables can be used in expressions which are dedicated for that type of variable In the current implementation of smart BASIC the only general purpose operator that can be used with strings Is the operator which is used to concatenate strings Example DimEx2 sb See in BL600CodeSnippets zip DIM 1S as STRING DIM aS as STRING aS Laird iS siclol ss Rocks Here we are concatenating the two strings PENCEN Expected Output LairdRocks Note To preserve memory smart
30. 1 for the characteristic value attribute and more as appropriate For example if the Characteristic s property specified is notifiable then a single CCCD attribute will exist too Please note that in reality in the GATT table when a Characteristic is registered there are actually a minimum of 2 attribute handles one for the Characteristic Declaration and the other for the Value However there is no need for the smartBASIC apps developer to ever access it so it is not exposed Access is not required because the Characteristic was created by the application developer and so shall already know its content which never changes once created BLECHARCOMMIT hService attr charHandle Returns INTEGER a result code The typical value is OxO000 indicating a successful operation Arguments Americas 1 800 492 2320 Option 2 253 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual AService attr CharHandle byVal hService AS INTEGER This is the handle of the service that this Characteristic shall belong to which in turn was created using the function BleSvcCommit byRef attr AS STRING This string contains the initial value of the Value attribute in the Characteristic The content of this string is copied into the GATT table and so the variable can be reused after this function returns byRef charHandle AS INTEGER Th
31. 1 800 492 2320 Option 2 145 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual This subroutine is used to close a 12C port which had been opened with I2COPEN This routine is safe to call if it is already closed I2CCLOSE handle Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments handle byVal handle AS INTEGER This is the handle value that was returned when I2COPEN was called which identifies the I2C interface to close Interactive Command No Related Commands I2COPEN I2CWRITEREAD I2CWRITEREG8 I2CWRITEREG16 I2CWRITEREG32 IZ CREADREG8 I2CREADREG16 I2CREADREG32 Example I2cClose sb See in BL600CodeSnippets zip DIM handle DIM rco rco cCOpen 100000 0 handle TF gzel 0 THEN PRINT anFailed to open I2C interface with error code T ITNTEGER h rc ELSE PRINT nI2C open success nHandle is handle ENDIF I2cClose handle close the port TeC oee Manca iy no tiem come dong lie aan I2CCLOSE is a core subroutine I2cWriteREG8 SUBROUTINE Note For firmware releases older than 1 2 54 4 there is an issue where some 12C slaves are not able to drive the ACK down to a low enough voltage level for the module to recognise it as an ACK This is a result of a bug in the BL600 s I2C driver which results in the SDA line not being released by the module This has
32. 1 THEN PRINT n n Disconnected from client EXITFUNG Q ELSEIF nMsgID 0 THEN PRINT n Connected to client ADS ENDFUNC 1 OE i i i a i e i iM handler to service button 0 pressed Fe EBUNGLION HndileBenUPr AS INTEGER CloseConnections BNDEUNG I Americas 1 800 492 2320 Option 2 201 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Client has written to writeable descriptor essossesesssse ses oss se SS SS FUNCTION HndlrGharbesc BYVAL charHandle BYVAL hDesc AS INTEGER IF charHandle hMyChar THEN PRINT An Char Handle Y eharHamdile PRINT nee Description Index bese PRINT nThe new descriptor value is then read using the function BleCharDescRead ELSE PRINT nTthies Ls tor some other characteristic ENDINE ENDFUNC 1 ONEVENT EVBLEMSG CALL HndlrBleMsg ONEVENT EVCHARDESC CALL HndlrCharDesc ONE VENT EVGPTOCHANT CALL HndileBenvrr OnSrabeup PRINT nWrite to the User Descriptor with UUID 0x2999 PRINT n Press button 0 to exit n WALTEVENT ERTES soley je aLighe a 3 6 EVVSPRX This event is thrown when the Virtual Serial Port service is open and data has arrived from the peer EVVSPTXEMPTY This event is thrown when the Virtual Serial Port service is open and the last block of data in the transmit buffer is sent via a notify or indicate See VSP Virtual Serial Port E
33. 10 4 mmeoce 1234 10 1234 x 10710 will fail because exponent too large Encode 10000 0 10000 x 10 0 will fail because mantissa too large Expected Output Success Failed to encode to SFLOAT Failed to encode to SFLOAT BLEENCODESFLOAT is an extension function Americas 1 800 492 2320 Option 2 317 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleEncodeTIMESTAMP FUNCTION This function overwrites a 7 byte string into the string at a specified offset If the string is not long enough it is extended with the new extended block uninitialized and then the byte specified is overwritten The 7 byte string consists of a byte each for century year month day hour minute and second If year month Is zero it is taken as not noted year and all the other fields are set zero not noted For example 5 May 2013 10 31 24 will be represented as 14 OD 05 05 0A 1F 18 If the nindex is such that the new string length exceeds the maximum attribute length this function fails The maximum length of an attribute as implemented can be obtained using the function SYSINFO n where n is 2013 The Bluetooth specification allows a length between 1 and 512 Note When the attr string variable is updated the two byte year field is converted into a 16 bit integer Hence 14 0D gets converted to DD 07 BLEE
34. 188 EVBLE ADY TIMEOUT orcrirnriiirinninirininiiseni 190 EOE YG esnia E EE E 191 Americas 1 800 492 2320 Option 2 359 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth BB EIS Toana E E OR 191 EVCHARCC CD Ree ent et Cnn en ten Aa 196 EVCHARDES C xnonaaneunereaadamancrnssyaasubaiosastuneeyaale 200 rh Cc stetentete cctecincesta nner tatters are toot suse 196 EVCHARSC Oa estes ach eceace ta semsertyetansiategnantaterslauascnee 198 EVCHARVA C oino eE R rO 194 EVD C Nee E AEA 193 EVNOTIFY BUF ce scesractrstoecigaoey evoecanmasrorduenanee cence 202 EVN PR a N ne reed ynenjin rouse ue 202 BE IP II meiner 202 EE ONG AE A P ae T A T 50 EEN E E EE 189 ET D E EE E EEE 188 PORS NEA E a E E 60 FONCTION eae E E SE EEE 188 GE PIG GOUT stemextanpoveuadenenenteectarnedeanoccaviese 117 GE TTIGKSINGE saiscmexsaienesounionenintossenenednaenatiacneies 118 GPIOUNBINDEVENT cpssrtabesene tenes coypsaaezuasiawnntense 184 POVRE e 181 PECO E ES 145 IZGREADREG J6 renons 150 IZC READ REG BZ veccniccnectiniasnnasasenndenmaastinwenseasseinnes 153 IZCREADREGSB 000cccccccceeeeeeeeeeeeeeeeeee eae 148 IZCWRITEREAD cece cc cceeeeeceeceeeeeeeeeeees 154 ZO WRITEREGN G incvcssctevenmescttnavennoienadateiiunnnndenin 149 IZCWRITEREG32 cece cceeeeeeeeeeeeeeeee anaes 152 IZG WRITE RE GS rasacricscenssnncedacntensengntussnncnateaconss 146 IF THEN ELSEIF ELSE ENDIF 62
35. 2048 bytes is allowed but that can result in unreliable operation as the smartBASIC runtime engine will be starved of memory very quickly Use SYSINFO 2019 to obtain the actual default size and SYSINFO 2020 to obtain the maximum allowed The same information can be obtained in interactive mode using the commands AT 2019 and 2020 respectively Note that when the ring buffer for the notifiable and indicatable characteristics is full then any new messages will get discarded and depending on the flags parameter the indicates will or will not get confirmed This function is safe to call when the gatt client manager is already open however in that case the parameters are ignored and existing values are retained and any existing gattc client operations are not interrupted It is recommended that this function NOT be called when in a connection BLEGATTCOPEN nNotifyBufLen nFlags Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation Arguments nNotifyBufLen byVal nNotifyBufLen AS INTEGER This is the size of the ring buffer used for incoming notifiable and indicatable characterstic data Set to O to use the default size nFlags byVal nFlags AS INTEGER Bit O Set to 1 to disable automatic indication confirmations if buffer is full then the Handle Value Confirmation will only be sent when BleGattcNotifyRead is called to read the ring buffer Bit 1 31 Reserved for future use and must be set to O
36. 2320 Option 2 236 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BLESVCREGDEVINFO FUNCTION Returns Arguments mantName modelNum serialNum hwkRev swRev sysldg regDataList pnpld Interactive Command Eae manfName modelNum serialNum hwRev swRev sysid regDataList pnpld INTEGER a result code The typical value is 0x0000 indicating a successful operation byVal manfName AS STRING The device manufacturer Can be set empty to omit submission byVal mode Num AS STRING The device model number Can be set empty to omit submission byVal seria Vum AS STRING The device serial number Can be set empty to omit submission byVal hwRev AS STRING The device hardware revision string Can be set empty to omit submission byVal swRev AS STRING The device software revision string Can be set empty to omit submission byVal sys d AS STRING The device system ID as defined in the specifications Can be set empty to omit Submission Otherwise it shall be a string exactly 8 octets long where Byte 0 4 Manufacturer Identifier Byte 5 7 Organisationally Unique Identifier For the special case of the string being exactly 1 character long and containing the system ID is created from the MAC address if and only if an IEEE public address is set If the address is the random static varie
37. 4 re BleBncodell gt o attr 0x4645 4 PRINT VattrS ovens ings Expected Output attrS ABCDEF BLEENCODE24 is an extension function BleEncode32 FUNCTION This function overwrites four bytes in a string at a specified offset If the string is not long enough then it is extended with the new extended block uninitialized and then the bytes specified are overwritten If the nindex is such that the new string length exceeds the maximum attribute length this function fails The maximum attribute length can be obtained using the function SYSINFO n where n is 2013 The Bluetooth specification allows a length between 1 and 512 BLEENCODE32 attr nData nindex Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation Arguments attr byRef attr AS STRING This argument is the string that will be written to an attribute nData byVal nData AS INTEGER The four bytes of this integer is saved The rest is ignored nindex byVal nindex AS INTEGER This is the zero based index into the string attr where the new fragment of data Is written If the string attr is not long enough to accommodate the index plus the length Americas 1 800 492 2320 Option 2 313 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual of the fragment it is extended If the extended length exceeds the maximum
38. 492 2320 Option 2 291 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual runtime engine containing the results A non zero return value implies an EVFINDDESC message will NOT be thrown Arguments connHnal byVal connHnal AS INTEGER This is the connection handle as returned in the on connect event for the connection on which the remote Gatt Server can be accessed This will have been returned in the EVBLEMSG event message with msgld 0 and msgCtx will have been the connection handle svcUuHnal byVal svcUuHnal AS INTEGER Set this to the service uuid handle which will have been generated either by BleHandleUuid16 or BleHandleUuid128 or BleHandleUuidSibling svclax byVal svcidx AS INTEGER This is the instance of the service to look for with the uuid handle svcUuidHndl where 0 is the first instance 1 is the second etc charUuHnal byVal charUuHnal AS INTEGER Set this to the characteristic uuid handle which will have been generated either by BleHandleUuid16 or BleHandleUuid128 or BleHandleUuidSibling charldx byVal charldx AS INTEGER This is the instance of the characteristic to look for with the uuid handle charUuidHndl where 0 is the first instance 1 is the second etc descUuHnal byVal descUuHnal AS INTEGER Set this to the descriptor uuid handle which will have been generated either by BleHandleUuid16 or BleHandleUuid
39. 6 packets will appear little endian format hence reverse order and you will NOT see 7 bytes but a bit in the packet somewhere which specifies it to be public or random Events and Messages EVBLE_ADV_TIMEOUT This event is thrown when adverts that are started using BleAdvertStart time out Usage is as per the example below oxeiisile 45 Ede chy sme olin So See cla EECC c niote 219 DIM peerAddrs Americas 1 800 492 2320 Option 2 190 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual handler tco service an advert timeout FUNCTION HndlrBleAdvTimOut PRINT nAdvert stopped via timeout j Dogtisag i could Use Systemotakesee 0 te switch ork Switch off the system requires a power cycle to recover re SystemStateSet 0 ENDFUNC 0 fSigerce eichveiccs j ce plehoveteorato O LOU 00070 IF BleAdvertStart 0 peerAddr 100 2000 0 0 THEN PRINT nAdvertisement Successful ELSE PRINT n nAdvertisement not successful ENDIE ONE VENT EVBLE ADV TIMEOUT CANL HndlrBleAdvTimOut WALTEVENT Expected Output Advert Started Advert stopped via timeout EVBLEMSG The BLE subsystem is capable of informing a smart BASIC application when a significant BL
40. 80 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual ONEVENT EVMSGAPP CALL HandlerMsgApp re SendMsgApp 100 200 WALTEVENT Expected Output Td 100 Ctx 200 SENDMSGAPP is a core function Arithmetic Routines ABS FUNCTION Returns the absolute value of its INTEGER argument ABS var Returns INTEGER Absolute value of var Exceptions Local Stack Frame Underflow Local Stack Frame Overflow If the value of var is Ox80000000 decimal 2 147 483 648 then an exception is thrown as the absolute value for that value causes an overtlow as 33 bits are required to convey the value Arguments var byValvar AS INTEGER The variable whose absolute value is required Interactive Command No Example ABS sb See in BL600CodeSnippets zip DIM s1 as INTEGER SZ as INTEGER SiN EE PRINT S RAB e ig ee oS 2 Expected Output e Z 4 ABS is a core language function Americas 1 800 492 2320 Option 2 81 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual MAX FUNCTION Returns the maximum of two integer values MAX var1 var2 Returns INTEGER The returned variable is the arithmetically larger of var7 and varZ2 Exceptions Local Stack Frame Undertlow Local Stack Frame Overflow Argumen
41. 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual FTELL FUNCTION This function is used determine the current Tile position in the open file specified by the handle It will be a value from O to N where N is the size of the file FTELL fileHandle curPosition Returns INTEGER The total number of bytes read trom the file specified by the handle Will be O if an invalid handle is supplied Arguments fileHandle BYVAL fileHandle AS INTEGER The handle of a file for which the total size is to be returned curPosition BYREF curPosition AS INTEGER This will be updated with the current file position for the file specified by the fileHandle Interactive Command NO See the full and detailed example in the FOPEN section FTELL is a core language function FSEEK FUNCTION This function is used to move the file pointer of the open Tile specified by the handle supplied The offset is relative to the beginning of the file or the current position or the end of the Tile which is specified by the whence parameter FSEEK fileHandle offset whence Returns INTEGER Will be O if successful Arguments fileHandle BYVAL fileHandle AS INTEGER The handle of a file for which the Tile pointer is to be moved offset BYVAL offset AS INTEGER This is the offset relative to the position defined by the whence parameter whence BYVAL whence AS INTEGER This parameter specifies from
42. Americas 1 800 492 2320 Option 2 35 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Returns If the filename does not exists the AT RUN will respond with an error response starting with a 01 and a hex value describing the type of error When the application aborts or if the application reaches its end a deferred nOO r response is sent If the compiled file was generated with a non matching language hash then it will not run with an error value of 0707 or 070C Arguments filename String_constant The name of the file to be run The maximum length of filename is 24 characters and should not include the following characters lt gt This is an Interactive mode command and must be terminated by a carriage return for it to be processed Note Debugging is disabled when using AT RUN hence all BP nnnn statements are inactive To run an application with debugging active use AT DBG If any variables exist from a previous run they are destroyed before the specified application Is serviced Note The application filename can also be invoked by entering the name if it does not contain any spaces Interactive Command YES Examples AT RUN NewApp or NewApp AT RUN is a core command AT DBG COMMAND AT DBG runs a precompiled application that is stored in the flash file system In contrast t
43. An application can have multiple lt WaitEvent gt statements waitevent when program is run it waits here until an event is detected When this application is launched and appropriate buttons are pressed and released the output is as follows 3 INTERACTIVE MODE COMMANDS Interactive mode commands allow a host processor or terminal emulator to interrogate and control the operation of a smart BASIC based module Many of these emulate the functionality of AT commands Others add extra functionality for controlling the filing system and compilation process Syntax Unlike commands for AT modems a space character must be inserted between AT the command and subsequent parameters This allows the smart BASIC tokeniser to efficiently distinguish between AT commands and other tokens or variables starting with the letters at Example AT I 3 Americas 1 800 492 2320 Option 2 31 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual The response to every Interactive mode command has the following form lt linefeed character gt response text lt carriage return gt This format simplities the parsing within the host processor The response may be one or multiple lines Where more than one line is returned the last line has one of the following formats lt lf gt 00 lt cr gt for a successful outcome or lt lf gt 01 lt
44. BASIC only allocates memory to string variables when they are first used and not when they are allocated If too many variables and strings are declared in Americas 1 800 492 2320 Option 2 53 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual a limited memory environment it is possible to run out of memory at run time If this occurs an ERROR is generated and the module will return to Interactive Mode The point at which this happens depends on the free memory so will vary between different modules This return to Interactive Mode is NOT desirable for unattended embedded systems To prevent this every application MUST have an ONERAOR handler which is described later in this user manual Note Unlike in the C programming language strings are not null terminated Arrays Variables can be created as arrays of single dimensions their size number of elements must be explicitly Stated when they are first declared using the nomenclature x or x after the variable name e g DIM array 10 AS STRING DIM array2 10 AS STRING Example ArraysExl sb See in BL600CodeSnippets zip DIM nCmds AS INTEGER DIM siCmds 20 AS STRING declare an array as a string with 20 elements Not recommended because we are only using 7 elements as you will see below Setting the values for 7 of the elements Sweme sa O ESTA
45. BSa E E E AE ETN 83 MA a nen ta lenoeeerautusotnavercteeayooincnes 82 MID se E 84 VIIN a e EE A TE 82 Notepad cece eeeeeceeeetttteeeeeeeeeenenes 18 ONERROR caroctiresrnnantsseeutontinteorosta tiennciaoieuananbiioseotaedtepnes 66 ONEVENT rre e Seed auoins 68 ONFATALERROR catacavesutucnsainssicetinsistvaeanicsbintianatnnits 67 PRINT ON S E ie seunepsde E EE 70 RAND ar A E T E 110 PAINE Kaori ecyesohioenecatsinnsdesmunaadatonnecnacddeantanns vets 111 BAIN SEE Desens tesniea ercetutevanencurn pet enteunsavestreanieiane 111 RESETE o ecetauvineney nein teucoteeinar 108 RESETEAS TERROR oiessniscniscitanncuntnnsesaoovaniocatimensneads 77 RESUME er E S EE 44 RIGHT E eE E T 85 SELECT CASE CASE ELSE ENDSELECT 64 SENDIVISGAPP wcsssscunutssscaterwsconmaasuantmnacpondeiotecndnes 80 BPG SE P E 159 DPIOPEN senscnsosniaetcctnddgtstobusiensnesaginsnscshesauadinooes 156 SPIRE D snnzcncndoiectccandugentotssneninesagdnemaachoreundenboes 161 SPIRE AD VV RINE wainteccsissscrenantatcaaamsascansentenacsnass 160 Laird Technologies smart BASIC User Manual DV IRIE eae EEA estaniabiavenniete 160 ERIT a E EEE T2 EO a EE tan A eae AE S 73 RCIP T 92 STRDEESCAPE scsesecosicaiicveentsvareinoeenengaiencehaueme 97 STRDEHEXIZE scicscsniceroensceresntpasientewseupecsrseiuense 94 STRESCAPEG 000cccccceceeeseeeseeeeeeeeeeeeeaneeeeees 96 STRAIN enor ainen E 90 SIRGET CHR iceosercs iei ei ie 88 SIRAHEXZ BIN acter cent aerate esteceetsc
46. BleCharCommit hHtsSvc attr hHtsMeas 0 THEN Americas 1 800 492 2320 Option 2 254 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT AnCharacteri stic Committed ELSE PRINT nFailed ENDIF the characteristic will now be visible in the GATT table and is refrenced by hHtsMeas for subsequent calls Expected Output Characteristic Commited BLECHARCOMMIT is an extension function BleCharValueRead FUNCTION This function reads the current content of a characteristic identified by a composite handle that was previously returned by the function BleCharCommit In most cases a read will be performed when a GATT client writes to a characteristic value attribute The write event is presented asynchronously to the smartBASIC application in the form of EVCHARVAL event and so this function will most often be accessed from the handler that services that event BLECHARVALUEREAD charHandle attr Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation Arguments charHanale byVal charHandle AS INTEGER This is the handle to the characteristic whose value must be read which was returned when BleCharCommit was called attr byRef attr AS STRING This string variable contains the new value from the characteristic Interactive Command NO Example BleCh
47. Defining the arglist The arguments of the function may be any valid variable type i e INTEGER or STRING Americas 1 800 492 2320 Option 2 188 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Each argument can be individually specified to be passed either as byVal or byRef By default simple variables INTEGER are passed byVal and complex variables STRING are passed byRef However this default behaviour can be varied by using the SET directive SET 1 0 Default Simple arguments are BYVAL SET 1 1 Default Simple arguments are BYREF SET 2 0 Default Complex arguments are BYVAL SET 2 1 Default Complex arguments are BYREF Interactive Command NO ENDFUNC This statement marks the end of a function declaration Every function must include an ENDFUNC statement as it instructs the compiler that here is no more code for the routine ENDFUNC arithemetic_expression_or_string_expression This statement marks the end of a block of statements belonging to a function It also marks the end of scope on any variables declared within that block ENDFUNC must be used to provide a return value through the use of a simple or complex expression FUNCTION doThis byRef s as string AS STRING S S World ENDFUNC S world FUNCTION doThis byRef v as integer AS INTEGER v v 100 ENDFUNC v 3 EXITFUNC This sta
48. EA E EE EA E 3 CONTENT oee E E spec eb temenlseren wekeanendeeenpeeines 4 eU ONC ON e a ett etsencn ene eieaauateecsev anueenueacieaiad saneqeussoiesae casi aueacieeeeeieneeetee 6 Why Do We Need smart carcass reac pecs RE T 6 WAYNE ADC ONS a E A T E E 7 What does a BLE Module Contain vsssecaves srucacassrnquecheredevadeaueuandsteiesibatecsmedsawosadsetucuacseudasedetuiunad iawoaseduiceneeoneecnsiaueweids 7 smart BASIC ESSENtialS owsrcacanperseecirosesanconadencacusntmnsdencwdacennnooscesmesannccsasonasendenaeanseos aauanteoecuusedansaeaannncleeruansanstunaauseasescenaed 8 Developing with smart BASIC cevessicscsagosatadversaveseneuchesancacraneswoausduvenctafeisinteieunaotsdessantaideiicialedotmshstaveanvareacuasvdetaeckesareans s 9 SHIGE BASIC Operating MOES zeresiciiian niren nE ENE irae a EON E EE EATA OA 9 TTS OAPI ON a E T E E E E O A OE E 10 Non v oE MEMO Y a AE E T E E T EE A AATAS 11 Using the Modules Flash File 5 V5 ON raat eaccteste setae scecevon sence cstactiuesScsdchanesasstoneads nee gecasvantwacdepeceinecuesaccde aeouacseoateatense 11 2 MSU IAC Aae eestor isa te erentr wees dase E E E 12 FCI SVS S raa EE eicpogusnmten achat A aie ofp stanrm avin E E E cluattoncanitopmnaeduntosseutoamnaaton 12 OPV INE TNES UP cessen EE EEEE R AAEE E EEEE AE EA ARESE 12 YT PN P E E AE I E E EE A E E A E E AEA T 12 Your First smart BASIC APpPliCatiOny cvsscsassapsasvacvesesusatenudussvesacoansanesnoadieancupeapvadwacvansdnsavoansapedipeaesactadedweaTeaodus
49. Example Arithmetic sb DIM sumi bated one Z bitl 2 Americas 1 800 492 2320 Option 2 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth See in BL600CodeSnippets zip Ti Laird Technologies smart BASIC User Manual abe 3 DIM volume height area height 5 area 20 Sam lose ae lean 2 volume height aread Piin enoun oam Prine nvolume volame a Expected Output Arithmetic operators can be unitary or binary A unitary operator acts on a variable or constant which follows it whereas a binary operator acts on the two entities on either side Operators in an expression observe a precedence which is used to evaluate the final result using reverse polish notation An explicit precedence order can be forced by using and in the usual manner The following is the order of precedence within operators Unitary operators have the highest precedence logical NOT bit complement 2 negative negate the variable or number multiplies it by 1 positive make positive multiplies it by 1 Precedence then devolves to the binary operators in the following order Multiply Divide Modulus Addition Subtraction lt lt Arithmetic Shift Left gt gt Arithmetic Shift Right lt Less Than results in a O or 1 value in the expression lt Less Than Or Equal results in a O or 1
50. ExtractIntToken sentences intValue PRUs Vania Vane Dyte iy oyl en oo tay cline DO tknlen ExtractStrToken sentenceS tokenS PRG woe Choices kegs le aen Seni aes oke UNTIL tknlen Expected Output ExtractIntToken is a core function Americas 1 800 492 2320 Option 2 104 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Table Routines Tables provide associative array or in other words lookup type functionality within smart BASIC programs They are typically used to allow lookup features to be implemented efficiently so that for example parsers can be implemented Tables are one dimensional string variables which are configured by using the TABLEINIT command Tables should not be confused with Arrays Tables provide the ability to perform pattern matching in a highly optimised manner As a general rule use tables where you want to perform efficient pattern matching and arrays where you want to automate setup strings or send data using looping variables TABLEINIT FUNCTION TABLEINIT initialises a string variable so that it can be used for storage of multiple TLV tokens allowing a lookup table to be created TLV Tag Length Value TABLEINIT string Returns INTEGER Indicates success of command 0 Successful initialisation lt gt 0 Failure Exceptions Local Stack Frame Underflow Local
51. FWR is a core command AT FWRH COMMAND AT FWRH writes a string to a Tile that has previously been opened for writing using AT FOW The group of commands AT FOW AT FWR AT FWRH and AT FCL are typically used for downloading Tiles to the Americas 1 800 492 2320 Option 2 40 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual module s flash filing system For example web pages x 509 certificates or BLE data AT FWRH string Returns If the string is successfully written AT FWRH will respond with nOO r Arguments string string_constant A string that is appended to a previously opened file Only hexadecimal characters are allowed and the string Is first converted to binary and then appended to the file This is an Interactive Mode command and MUST be terminated by a carriage return for it to be processed Interactive Command YES Examples AT FWRH FE900002250DEDBEEF AT FWRH 000102 Invalid example AT FWRH hello world because not a valid hex string AT FWRH is a core command AT FCL COMMAND AT FCL closes a file that has previously been opened for writing using AT FOW The group of commands AT FOW AT FWR AT FWRH and AT FCL are typically used tor downloading files to the module s flash filing system AT FCL Returns If the filename exists AT FCL responds with nOO r
52. Frame Underflow Local Stack Frame Overflow Arguments string byRef string AS STRING String that contains the unsigned bytes which need to be arithmetically added nindex byVal nindex AS INTEGER Index of first byte into the string nBytes ByVal nBytes AS INTEGER Number of bytes to process initVal ByVal initVal AS INTEGER Initial value of the sum Note string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Interactive Command NO Example StrSum sb See in BL600CodeSnippets zip DIM s sS 0aA lt PR We Sie uml oa Ons Oye tae d MAE SG S423 14 6040 PRINT tr o umne 0p Sy AL a Ue aay 74879776513 60 10 Prr oer uno a4 le iO nt ain 60 100 Americas 1 800 492 2320 Option 2 100 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output ee 307 317 160 STRSUM is a core function STRXOR This function identifies the substring starting from a specified offset and specified length and then does an arithmetic exclusive or XOR of all the unsigned bytes in that substring and then finally XORs the signed initial value supplied For example if the string is 01 02 03 04 05 and offset is 1 and length is 2 and initial value is 1000 then th
53. GETTICKCOUNT and it is used to calculate the time elapsed since that update Interactive Command No Related Commands GETTICKCOUNT Example GetTickSince sb See in BL600CodeSnippets zip DIM startTick clapseMs x x 1 startTick GetTickCount DO PRINT sco lt x og X X 2 PRINT cee a UNTIL x 32768 elapseMs GetTickSince startTick PRINT n nthe Do Until loop took elapsemMS T msec to process Americas 1 800 492 2320 Option 2 118 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output GETTICKCOUNT is a core subroutine Circular Buffer Management Functions It is a common requirement in applications that deal with communications to require circular buffers that can act as first in first out queues or to create a stack that can store data in a push pop manner This section describes functions that allow these to be created so that they can be expedited as fast as possible without the speed penalty inherited in any interpreted language The basic entity that is managed is the INTEGER variable in smartBASIC Hence be aware that for a buffer size of N 4 times N is the memory that will be taken from the internal heap These buffers are referenced using handles provided at creation time CircBufCreate FUNCTION This function is used to create a circular buffer with a maximum c
54. IF nMsgID 1 THEN PRINT n n Disconnected EXITEUNC 0 ELSEIF nMsgID 0 THEN PRINT n Connected so scan remote Gatt Table for first service PRINT n and a characeristic scan will be initiated in the event re BleDiscServiceFirst conHndl 0 0 IF rc 0 THEN wait for start and end handles for first primary service WALILTEVENT PRIN m nSecan for Gdesecritore With uuid OxDEAD uHndl BleHandleUuidl6 OxDEAD re BleDrschbescrirsre conhndl ubndl ecValArtr IF rec 0 THEN HandlerDescDisc will exit with 0 when operation is complete WAITEVENT mus 1122334455667 168 99AABBCCDDEEFEOO PRIM i nseam for service with cu tom ouid uus uus StrDehexizes uus uHndl BleHandleUuid128 uu he BleDLscDescrLrsr Conknell pind cYyalarer IF rc 0 THEN HandlerDescDisc will exit with 0 when operation is complete WAITEVENT ENDIF BNDILE ENDIF CloseConnect one END IRE ENDFUNC 1 FUNCTION Handlervrrimoeve ckndl syveUuicd sHnaLl ennel AS INTEGER Americas 1 800 492 2320 Option 2 283 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT neVDISCPRIMSYVC 3 PRINT Y GHMEOLSY ohm PRIN svecUuad tneeqer sf seveuudd PREN GS Serine SHMC PRINT elindl ehndi IF sHndl 0 THEN PRINT nPrimary Service Scan complete BXITEUNC 0 ELSIE PRINT nGOr first primary Service so
55. INTEGER UUID in the range O to FFFF if value is outside that range it will be ignored so set the value to 1 to have it be ignored Interactive Command NO Example BleAdvAddUuidl6 sb See in BL600CodeSnippets zip DIME NEDE re DIM discovMode discovMode 0 DIM advAppearance advAppearance 1 DIM maxDevName maxDevName 10 rc BleAdvRptInit advRpt discovMode advAppearance maxDevName BatteryService 0x180F J DevicerntoService 0xL80A TP BICAdy Rpr A dauu irdl oady Ppr O0 lon Ox SUA a a OTEN Americas 1 800 492 2320 Option 2 213 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT nuUrD Service List AD acelea BNDLE Only the battery and device information services are included in the advert report Expected Output UULD Service List AD added BLEADVRPTADDUUID16 is an extension function BleAdvRptAddUuid128 FUNCTION This function is used to add a 128 bit UUID service list AD Advertising record to the advert report specified Given that an advert can have a maximum of only 31 bytes it is not possible to have a full UUID list unless there is only one to advertise BLEADVRPTADDUUID 128 advRpt nUuidHandle Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments advRot byRef AdvRot AS STRING The advert report into
56. INTEGER Where to start the position search Note STRPOS does a case sensitive search Note string1and string2 cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then Tirst save it to a temp string variable and then pass it to the function Interactive Command NO Example StrPos sb See in BL600CodeSnippets zip DIM slo S23 slS Are you there s2S there PEN ee el a ole I e aoa a a Tw OCceNise sae DOcmME RON sok m rOs Gore or Os Expected Output In Are you there the word there occurs at position 8 STRPOS is a core function STRSETCHR FUNCTION STRSETCHR allows a single character within a string to be replaced by a specified value STRSETCHR can also be used to append characters to an existing string by filling it up to a defined index If the nindex is larger than the existing string then it is extended The use of STRSETCHR and STRGETCHR in conjunction with a string variable allows an array of bytes to be created and manipulated STRSETCHR string nChr nlndex Returns INTEGER Represents command execution status O Ifthe block is successfully updated 1 If nCAris greater than 255 or less than O 2 If the string length cannot be extended to accommodate n ndex 3 If the resultant string is longer than allowed Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Memory Heap Exhausted Arguments Americ
57. INTEGER the number of bytes extracted from the attribute string Can be less than the size expected if the nindex parameter is positioned towards the end of the string Arguments attr byRef attr AS STRING This references the attribute string from which the function reads nData byRef nData AS INTEGER This references an integer to be updated with the 3 byte data from attr with sign extension nindex byVal nindex AS INTEGER This is the zero based index into the string attr from which data is read If the string attr is not long enough to accommodate the index plus the number of bytes to read this function fails Interactive Command NO Americas 1 800 492 2320 Option 2 325 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Example BleDecodeS24 sb See in BL600CodeSnippets zip DIM ChridanciLle yil syvenanclLle tc DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc DIM acero abero 00 oA o0 A 0425 36387 se 35 DIM uuid uuid 0x1853 rc BleSvcCommit 1 BleHandleUuidl6 uuid svcHandle rc BleCharNew 0x07 BleHandleUuidl16 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle rc BleCharValueRead chrHandle attrS read 3 signed bytes from index 2 rc BleDecodeS24 attr vl1 2 PRINT Andata an Hex Ox INTEGER H yl PRINT V ndata in Decimal ey le me read 3 signed b
58. Local Stack Frame Undertlow Local Stack Frame Overflow String De Escape Error E g chrs after the are not recognized Arguments string byRef string AS STRING The string to be converted in situ If a parsing error occurs a nonfatal error is generated which must be handled or the application will abort Note string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Americas 1 800 492 2320 Option 2 97 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Interactive Command NO Example StrDeescape sb See in BL600CodeSnippets zip DIM ise Ch so HellovecC40norld PAPE Nees ewe Nan rL ana a ae StrDeescape s PRINT sS int Ss ete laem Soe ine Expected Output Hello 40world ibe Hello world KI STRDEESCAPE is a core function STRVALDEC FUNCTION STRVALDEC converts a string of decimal numbers into the corresponding INTEGER signed value All leading whitespaces are ignored and then conversion stops at the first non digit character STRVALDEC string Function Returns INTEGER Represents the decimal value that was contained within string Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments string byRef str
59. Me Uleiere Laure IL PRINT AnTtransmit ring bDulrer Capacity AU e on PRINTE N nNo n bytes waiting in eran at Dur era Vente nroa start GetTickCount DO UNTIL UartiInfo 5 0 Americas 1 800 492 2320 Option 2 133 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT A n ntook GertlickSincei start milliseconds for transmit buffer to be emptied Expected Output UARTINFO is a core subroutine UartWrite FUNCTION This function is used to transmit a string of characters UARTWRITE strMsg Returns INTEGER O to N Actual number of bytes successfully written to the local transmit ring buffer Exceptions Local Stack Frame Undertlow Local Stack Frame Overflow Uart has not been opened using UARTOPEN or auto opened with PRINT statement Arguments strMsg byRef strMsg AS STRING The array of bytes to be sent STRLEN strMsg bytes are written to the local transmit ring buffer If STRLEN strMsg and the return value are not the same this implies the transmit buffer did not have enough space to accommodate the data If the return value does not match the length of the original string then use STRSHIFTLEFT function to drop the data from the string so that subsequent calls to this function only retries with data which was not placed in the output ring buffer Interactive Command No Note strMsg ca
60. OD OE OF inii Vec Cor AFON Er OS PR O05 bE O07 RR OS BP VOR Er 0D FR OR rc AesSetKeylv 0x200 16 key initVectorS IF rc 0 THEN PRINT nCBC context created successfully ELSE PRINT nFailed to create EBC context BNDI EF encrypt some data ihWeiwas SOs eZ 8334353 6o7sCoUSA BSC sb ae or inDataS StrDehexizeS inDataS re AesEncrypt inData s c 0 IF rc 0 THEN PRUNE OE ot OK Pid oe PRINT nFailed to encrypt ENDIF PRINT Anina 7 ster mesciezeo aim Deas PRINT mMeurDeata etre ze es 0 f encrypt same data again rce AesEncrypt inData s c 1 IF rc 0 THEN PRINT bine yi OK BLOE PRINT nFailed to encrypt ENDIF PRIN 2 ninDeate ai so Siete 265 junbewac Americas 1 800 492 2320 Option 2 165 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRI Mowe Data skrrne lt i wes eo tl ecrypt same data again re AesEncrypt inDatas c 2 IF rc 0 THEN PRINT neneryor OK ELSE PRINT nFailed to encrypt ENDIF PRINT A ninData 7 Strhne ize I nDa Lady PRINT nowkData gt tre ues oo e Rereate context for CBC mode 128 bit kKevyo OG 01 02 03 042 05 06 07 08 09 0A 0B CC 0b Or Or ipeveccoro EP Ol ER O PROS Fr 07 PE 0S Pr 0B FE OD Fr OR rc AesSetKeylv 0x200 16 key initVectors IF rc 0 THEN PRINT nCBC context created success
61. Option 2 271 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Arguments connHandle byVal nConnHandle AS INTEGER This is the connection handle as returned in the on connect event for the connection on which the remote Gatt Server can be accessed This will have been returned in the EVBLEMSG event message with msgld 0 and msgCtx will have been the connection handle startAttrHandle byVal startAttrHandle AS INTEGER This is the attribute handle from where the scan for primary services will be started and you can typically set it to O to ensure that the entire remote Gatt Server is scanned uuidHandle byVal uuidHandle AS INTEGER Set this to O if you want to scan for any service otherwise this value will have been generated either by BleHandleUuid16 or BleHandleUuid128 or BleHandleUuidSibling BLEDISCSERVICENEXT connHandle Calling this assumes that BleDiscServiceFirst has been called at least once to set up the internal primary services scanning state machine Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation and it means an EVDISCPRIMSVC event message WILL be thrown by the smartBASIC runtime engine containing the results A non zero return value implies an EVDISCPRIMSVC message will NOT be thrown Arguments connHandle byVal nConnHandle AS INTEGER This is the connection h
62. Parameters characteristic of the GAP service Range is between 7500 and 4000000 microseconds rounded to the nearest 1250 microseconds This must be smaller than nMaxConniInterval nMaxConninterval byVal nMaxConninterval AS INTEGER The preferred maximum connection interval updates the Peripheral Preferred Connection Parameters characteristic of the GAP service Range is between 7500 Americas 1 800 492 2320 Option 2 234 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual nSupervisionTimeout nSlavelatency and 4000000 microseconds rounded to the nearest 1250 microseconds This must be larger than nMinConninterval byVal nSupervisionTimeout AS INTEGER The preferred link supervision timeout and updates the Peripheral Preferred Connection Parameters characteristic of the GAP service Range is between 100000 to 32000000 microseconds rounded to the nearest 10000 microseconds byVal nS avelatency AS INTEGER The preferred slave latency is the number of communication intervals that a slave may ignore without losing the connection and updates the Peripheral Preferred Connection Parameters characteristic of the GAP service This value must be smaller than nSupervisionTimeout nMaxConniInterval 1 i e nSlaveLatency lt nSupervisionTimeout nNMaxConniInterval 1 Interactive Command NO Example BleGapSv
63. Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments nTxPower byVal n7xPower AS INTEGER Specifies the new transmit power in dBm units to be used for all subsequent tx packets The actual value is determined by scanning through the following values 4 O 4 8 12 16 20 30 55 such that the highest value in the table which Is less than the desired value is selected unless the desired value is less than 55 and in that case 55 will be set Interactive Command NO Americas 1 800 492 2320 Option 2 206 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Example BIMO dip do 1000 PRINT PRINT dp 8 PRINT dp 2 PRINT dp kg PRINT dp 25 PRINT dp 45 YC PRINT nT dp 1000 PEINE me AE rc uA m re uA EX ae ON aves ie UA alll re WA eG HOIS BleTxPwrWhilePairing sb See BleTxPwrWhilePairing dp ee power while pairing desired BleTxPwrWhilePairing dp power while pairing desired BleTxPwrWhilePairing dp power while pairing desired BleTxPwrwWhilePairing dp power while pairing desired BleTxPwrwWhilePairing dp power while pairing desired BleTxPwrwWhilePairing dp power while pairing desired BleTxPwrWhilePairing dp power while pairing desired Expected Output im BL6OO0O0CodeSnippets zip
64. S2 5 5 S5 IF BleCharNew 0x22 charUuid mdVal mdCccd 0 0 THEN PRINT nNew Characteristic created BLSE PRINT nFailed ENDIF Expected Output New Characteristic created BLECHARNEW is an extension function BleCharDescUserDesc FUNCTION This function adds an optional User Description Descriptor to a Characteristic and can only be called after BleCharNew has started the process of describing a new Characteristic The BT 4 0 specification describes the User Description Descriptor as a UTF 8 string of variable size that is a textual description of the characteristic value It further stipulates that this attribute is optionally writable and so a metadata argument exists to configure it to be so The metadata automatically updates the Writable Auxilliaries properties flag for the Characteristic This is why that flag bit is NOT specified for the nCharProps argument to the BleCharNew function BLECHARDESCUSERDESC userDesc mdUser Returns INTEGER a result code The typical value is OxO000 indicating a successful operation Americas 1 800 492 2320 Option 2 248 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Arguments userDesc byRef userDesc AS STRING The user description string to initiliase the Descriptor with If the length of the string exceeds the maximum length of an
65. See the virtual serial port service section for more details This facility allows the current autorun application to be replaced with a new one VARNING If this function is called from within autorun and the SIO7 input is high then it will get erased and a fresh download of the application is required which can be facilitated over the air ERASEFILESYSTEM nArg Returns INTEGER Indicates success of command O Successful erasure but you will not see it as the module will reboot lt gt 0 Failure Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments nArg byVal nArg AS INTEGER This is for future use and MUST always be set to 1 Any other value will result in a failure Example EraseFileSystem sb See in BL600CodeSnippets zip DIM re re EraseFileSystem 1234 IP rel O THEN PRINT nFailed to erase file system because incorrect parameter ENDIF Americas 1 800 492 2320 Option 2 109 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Toru SO 7 Ss slow re EraseFileSystem 1 IF rc 0 THEN PRINT nFailed to erase file system because SIO7 is low ENDIF Expected Output Failed to erase file system because incorrect parameter Failed to erase file system because SIO7 is low 00 ERASEFILESYSTEM is an extension function Random Number Generation Routines
66. Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual determine the size of the fille flen filelen handle Prine Winer e her tlen bytes hong get the current position in the file should be 0 re ftell handle fpos prine Sn urren position le Toes read the first 11 bytes from the file frlen fread handle data S 11 Crip Anata from mile ms cakes get the current position in the file should be 11 ce tLelivhnandle Tpos Perne Curent DOSE MON wie Epos reposition the file pointer to 6 so that we can read 5 bytes again re fseek handle 6 0 get the current position in the file re ftell handle fpos read 5 bytes frien fread handle data S 5 print abata rom mille us 2 Ys datas LOC METOM tO wine Start of 91s rc fseek handle 19 0 fread Until a w 1s encountered w ascii 0x77 frlen freaduntil handle dataS 0x77 32 Crime Rata irom ile mses gt cates finally close the file which on exit will set the handle to 0 fclose handle ELSE print nFailed to open file fname ENDIF FOPEN is a core language function FCLOSE FUNCTION This function is used to close a file previously opened with FOPEN It takes a handle parameter as a reference and will on exit set that handle to O which signifies an invalid file handle Americas 1 800 492 2320 Op
67. The lack of requirement for a central register is important to understand in the sense that if a custom service or characteristic needs to be created the developer can use any publicly available UUID sometimes also known as GUID generation utility These utilities use entropy from the real world to generate a 128 bit random number that has an extremely low probability to be the same as that generated by someone else at the same time or in the past or future As an example at the time of writing this document the following website http Awww guidgenerator com online quid generator aspx offers an immediate UUID generation service although it uses the term GUID From the GUID Generator website Americas 1 800 492 2320 Option 2 228 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual How unique is a GUID 128 bits is big enough and the generation algorithm is unique enough that if 1 000 000 000 GUIDs per second were generated for 1 year the probability of a duplicate would be only 50 Or if every human on Earth generated 600 000 000 GUIDs there would only be a 50 orobability of a duplicate This extremely low probability of generating the same UUID is why there is no need for a central register maintained by the Bluetooth SIG for custom UUIDs Please note that Laird does not warrant or guarantee that the UUID generated by this
68. This report is for use with advertisement packets BLEADVRPTINIT advRpt nFlagsAD nAdvAppearance nMaxDevName Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments advRot byRef advRot AS STRING This will contain an advertisement report nFlagsAD byVal nFlagsAD AS INTEGER Specifies the flags AD bits where bit O is set for limited discoverability and bit 1 is set for general discoverability Bit 2 will be forced to 1 and bits 3 amp 4 will be forced to O Bits 3 to 7 are reserved for future use by the BT SIG and must be set to O Note If a whitelist is enabled in the BleAdvertStart function then both Limited and General Discoverability flags MUST be 0 as per the BT 4 0 specification Volume 3 Sections 9 2 3 2 and 9 2 4 2 Americas 1 800 492 2320 Option 2 211 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual nAdvAppearance byVal nAdvAppearance AS INTEGER Determines whether the appearance advert should be added or omitted as follows O Omit appearance advert 1 Add appearance advert as specified in the GAP service which is supplied via the BleGapSvclnit function nMaxDevName byVal nMaxDevName AS INTEGER The n leftmost characters of the device name specified in The GAP service If this value is set to O then the device name will not be included In
69. UART then it will be in a closed state If a PRINT statement is encountered which results in output then the UART is automatically opened using default comms paramaters Americas 1 800 492 2320 Option 2 10 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Other Applications can be loaded into the BASIC module and run under the control of an external host processor using the AT RUN command The flash memory supports the storage of multiple applications Note that the storage space is module dependent Check the individual module data sheet Non Volatile Memory All smartBASIC modules contain user accessible flash memory The quantity of memory varies between modules check the relevant datasheet The flash memory is available for three purposes File Storage Files which are not applications can also be stored in flash memory certificates for example X 501 The most common non application files are data files for application Application Storage Storage of user applications and the AT RUN command is used to select which application runs Non volatile records Individual blocks of data can be stored in non volatile memory in a flat database where each record consists of a 16 bit user defined ID and data consisting of variable length This is useful for cases where program specific data needs to be preser
70. W gt nReacLen amp Americas 1 800 492 2320 Option 2 155 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual re I2cWriteRead nSlaveAddr stWriteS stRead nReadLen Iie gels 0 THEN PRINT nFailed to WriteRead integer h rc EOE PRINS Anr ee aa rr eaae a a head a a ea aeaa BNDIF I2cClose handle close the port Expected Output I2C open success Write 3435 Read Write 343543 Read 1042D509 Write Read 2B322380ED236921 IZCWRITEREAD is a core function SPI Interface This section describes all the events and routines used to interact with the SPI peripheral available on the plattorm The BL600 module can only be configured as a SPI master The three signal lines are called SCK MOSI and MISO where the first two are outputs and the last is an input A very good introduction to SPI can be found at http en wikipedia org wiki Serial_Peripheral_Interface_Bus and the reader is encouraged to refer to it before using the api described in this section It is possible to configure the interface to operate in any one of the 4 modes defined for the SPI bus which relate to the phase and polarity of the SCK clock line in relation to the data lines MISO and MOSI In addition the clock frequency can be configured from 125 000 to 8000000 and it can be configured so that it shifts data in out most signific
71. When you launch the application using AT RUN the following displays O OO Gy C1 i Go ND fF If you launch the application using AT DBG the following displays Hello World 1 Hello World 2 Hello World 3 21 BREAKPOINT 3333 Americas 1 800 492 2320 Option 2 27 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Having been returned to Interactive mode the command varname can be used to interrogate the value of any of the application variables which are preserved during the break from execution The command varname newvalue can then be used to change the value of a variable if required For example The single step command SO Step Over can then be invoked to step through the next statements individually note the first SO reruns the BP statement When required the command RESUME can be used to resume the run time engine trom the current application position as shown below Hello World 1 Hello World 2 Hello World 3 al BREAKPOINT 3333 I 8 resume Hello World 8 Hello World 9 Hello World 10 Structuring an Application Applications must follow smartBASIC syntax rules However the single pass compiler places some restrictions on how the application needs to be arranged This section explains these rules and suggests a structure for writing applications which should adhere to the event dri
72. a spout etc For a Tull list of these Descriptors online see http developer bluetooth org gatt descriptors Pages DescriptorsHomePage aspx These descriptors are assigned 16 bit UUIDs value 0x29xx and are referenced in some of the smartBASIC API functions if you decide to add those to your characteristic definition To wrap up the loose analogy think of Service as just a carrier bag to hold a group of related Characterisics together where the printing on the carrier bag is a UUID You will find that from a smartBASIC developer s perspective a set of characteristics is what you will need to manage and the concept of Service Is only required at GATT table creation time A GATT table can have many Services each containing one or more Characteristics The differentiation between Services and Characteristics is expedited using an identification number called a UUID Universally Unique Identifier which is a 128 bit 16 byte number Adopted Services or Characteristics have a 16 bit 2 byte shorthand identifier which is just an offset plus a base 128 bit UUID defined and reserved by the Bluetooth SIG and custom Service or Characteristics shall have the full 128 bit UUID The logic behind this is that when you come across a 16 bit UUID it implies that a specification will have been published by the Bluetooth SIG whereas using a 128 bit UUID does NOT require any central authority to maintain a register of those UUIDs or specifications describing them
73. active scans peerAdar byRef peerAdar AS STRING It can be an empty string that is omitted if the advertisement type is not ADV_DIRECT_IND This is only required when nAdvType 1 When not empty a valid address string Is exactly 7 octets long for example OO 1 1 22 33 44 55 66 where the first octet Is the address type and the rest of the 6 octets is the usual MAC address in big endian format so that most significant octet of the address is at offset 1 whether public or random The address type is O for Public 1 for Random Static 2 for Random Private Resolvable and 3 for Random Private Non Resolvable and all other values are illegal nAdvinterval byVal nAdvinterval AS INTEGER The interval between two advertisement events in milliseconds An advertisement event consists of a total of 3 packets being transmitted in the 3 advertising channels The range of this interval is between 20 and 10240 milliseconds nAdvTimeout byVal nAdvTimeout AS INTEGER The time after which the module stops advertising in milliseconds The range of this value is between 0 and 16383000 milliseconds and is rounded up to the nearest 1 seconds 1000ms A value of 0 means disable the timeout but note that if limited advert modes was specified in BleAdvRoptinit then this function will fail When the advert type specified is ADV_DIRECT_IND the timeout is automatically set to 1280 ms as per the Bluetooth Specification WARNING To save power do not mis
74. are the ones that will be read or written to The smartBASIC internal engine also maintains data objects so that it is possible to interact with descriptors associated with the characteristic In a nutshell the table scanning process will reveal characteristic handles as handles of handles and these are then used in other GATT client related smartBASIC functions to interact with the table to for example read write or accept and process incoming notifications and indications This encapsulated approach is to ensure that the least amount of RAM resource is required to implement a GATT Client and given that these procedures operate at soeeds many orders of magnitude slower compared to the speed of the cpu and energy consumption is to be kept as low as possible the response to a command will be delivered asynchnornously as an event for which a handler will have to be specified in the user smartBASIC application The rest of this chapter describes all the GATT Client commands responses and events in detail along with example code demonstrating usage and expected output Events amp Messages The nature of GATT Client operation consists of multiple queries and acting on the responses Due to the connection intervals being vastly slower than the speed of the cpu responses can arrive many 10s of milliseconds after the precudure was triggered which are delivered to an app using an event or message Since these event messages are tightly coupled with
75. attribute then this function will abort with an error result code mdUser byVal mdUser AS INTEGER This is a mandatory metadata that defines the properties of the User Description Descriptor attribute created in the Characteristic and will have been pre created using the help of BleAttrMetadata If the write rights are set to 1 or greater the attribute will be marked as writable and the client will be able to provide a user description that overwrites the one provided in this call Interactive Command NO Example BleCharDescUserDesc sb See in BL600CodeSnippets zip DIM re merascuccess UsrMesco UsSrDesco A deseriprion DIM chanUure 3 charUuid Blebendleuurdic L DIM charMet charMet BleAttrMetaData 1 1 20 0 metaSuccess DIM mdUsrDsc mdUsrDsc BleAttrMerabata l 1 20 0 metasuccess D mo eeoa omc seecu slew ht eile tadaa lel 20 stce V7 CCCD mer adaa shor har initialise char write read enabled accept signed writes indicatable rc BleCharNew 0x4B charUuid charMet 0 mdSccd rc BleCharDescUserDesc usrDesc mdUsrDsc IF rc 0 THEN PRINT nChar created and User Description usrDescS added ELSE PRINT nFailed ENID IL E Expected Output Char created and User Description A description added BLECHARDESCUSERDESC is an extension function BleCharDescPrstnFrmt FUNCTION This function adds an optional Presentation Format Descriptor to a Characteristic and can only be called after B
76. be deprecated in future releases It is recommended to invoke this function with the parameter set to O before calling BleAuthenticate BLESECMNGRBONDREQ nBondReq Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments nBondReg byVal nBondReg AS INTEGER O Disable 1 Enable Interactive Command NO Example BleSecMngrBondReq sb See in BL600CodeSnippets zip IF BleSecMngrBondReg 0 0 THEN PRINT AnBonding dieableo ENDIF Expected Output Bonding disabled BLESECMNGRBONDREQ is an extension function BleAuthenticate FUNCTION This routine is used to induce the device to authenticate the peer This will be deprecated in future firmware BLEAUTHENTICATE nConnCtx Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments nConnCtx byVal nConnCtx AS INTEGER This is the context value provided in the EVBLEMSG 0 message which informed the stack that a connection had been established Interactive Command NO Americas 1 800 492 2320 Option 2 221 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual See example for BleDisconnect H Change rc BleAuthenticate nCtx to PRINT BleAuthenticate nCtx BLEAUTHENTICATE is an extension function GATT Server Functions This s
77. connected Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments txbuflen byVal txbutlen AS INTEGER Set the transmit ring buffer size to this value If set to O a default value is used by the underlying driver and use BleVspInto 2 to determine the size rxbuflen byVal rxbuflen AS INTEGER Set the receive ring buffer size to this value If set to O a default value is used by the underlying driver and use BleVspInto 1 to determine the size nFlags byVal nFlags AS INTEGER This is a bit mask to customise the driver as follows Bit O Set to 1 to try for reliable data transfer This uses INDICATE messages if allowed and there is a choice Some services will only allow NOTIFY and in that case if set to 1 it will be ignored Bit1 31 Reserved for future use Set to O svcUuid byRef svcUuid AS INTEGER On exit this variable is updated with a handle to the service UUID which can then be Subsequently used to advertise the service in an advert report Given that there is no BT SIG adopted Serial Port Service the UUID for the service Is 128 bit so an appropriate Advert Data element can be added to the advert or scan report using the function BleAdvRptAddUuid128 which takes a handle of that type Related Commands BLEVSPINFO BLEVSPCLOSE BLEVSPWRITE BLEVSPREAD BLEVSPFLUSH Example BleVspOpen sb See in BL600CodeSnippets zip DIM VSeRhoes adRpE o addr o VSpovehme tl Americas 1 800 492 2320 Option
78. created using one of the three functions BleHandleUuid16 BledandleUuid128 or BleHandleUuidSibling hService byRef hService AS INTEGER If the Service attribute is created in the GATT table then this will contain a composite handle which references the actual attribute handle This is then subsequently used when adding Characteristics to the GATT table If the function fails to install the Service attribute for any reason this variable will contain O and the returned result code will be non zero Interactive Command NO Example BleServiceNew sb See in BL600CodeSnippets zip DEFINE BCE OERVICET O ECONDARY 0 DEFINE BLE SE RY TCE PRIMARY 1 T Eren E EEEE EEE E E e Aa DIM hles sve composite handle for hts primary service DIM hUUI1GHT hUULTdeT Blehandlevurd gt 0x1803 jj ul Svc UUD Handle IF BleServiceNew EPLET ERVI CETPRIMARY hUuidHT hHtsSvc 0 THEN PRINT nHealth Thermometer Service attribute written to GATT table PRINT nuUID Handle value T NUuidhT PRINT nService Attribute Handle value hHtsSvc ELSE PRINT nService Commit Failed ENDIF DIL lalscie VE composite handle for battery primary service or we could have reused nHtsSvc DIM hUwuidBatt hHUuldBatt BlenHandlevUuid 16 0x1 80F Bate Sve UULD Handle IF BleServiceNew BLE SERVICE PRIMARY hUuidBatt hBatSvc 0 THEN PRINT n nBattery Service attribute written to GATT table PRINT nuulD Handle value huuidBatt PRINT nSe
79. development board DVK BL600 V01 aL j 24 01 2013 Initial yen em Va p KR KKK KKK KKK RK KK KK KK KK KR KK I KK KK IK KK IK KK IK KK KK KK KK KK Kk KK p RR KKK KKK KKK KK KK KK KK I KK KK IK I KK I DS DS I I IK KK IK KK I KK KK KK ok KK KK KK S 7 Definicions KKK KK KKK KK KK KK KK I KK KK IK KK IK KK IK KK IK KK IK KK KK KK KK KK KK T KKK KK KK KKK KK KK KK KK KK KK I KK KK IK I KK I I KK IK KK I KK I KK KK KK KK KK KK DS OF baloney SE p KR KKK KKK KKK KK KK KK KK KK KK I KK KK IK IK I KK I KK KK KK I KK I KK KK KK KK KK KK D J Hime lide So lke Doe sot RRR KKK KKK KKK KK KK KK I KK KK IK KK I KK KK DE DS DE I I KK I KK KK IK KK KK KK KK kK KK J GAG Wells Van aioe Dee laa pom KR KKK KKK KKK KK KK KK I KK KK IK I KK I KK KK IK IK I KK IKK KK E E KK KK KK KK KK kk KK dim ro declare re as integer variable p p EE EEEE KKK KKK KK RK KK VE DE TE I E DE TS WE VE IK I KK F TE I IK KK DE DE E KK IKK KK KK KK KK KK Function anc Subrourcine detinicLons p KR KKK KKK KKK KK KK KK I KK KK IK KK I E DS I E DE DS E IK KK IK KK DE E DES KK KK KK KK Kk KK Americas 1 800 492 2320 Option 2 29 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual function button0release is released gpiowrite 18 0 print Button 0 has been released n the button is released Deine iE DO should nen gorau
80. e ristie with ouil OxbDEAD uHndl BleHandleUuidl6 OxDEAD re Blebpise harktirsr conmmmal unndl sAtrcr eAtrs IF rc 0 THEN HandlerCharDisc will exit with 0 when operation is complete WALTEVENT muS 112733445566 7 8309 ss SBCeDDEEE HOO PRIN Vn nocan rer Service With custom uud o s uus StrDehexizes uus uHndl BleHandleUuidl28 uuS ro Blebiseehartirst conmmal unne sAttu eAttL IF rc 0 THEN HandlerCharDisc will exit with 0 when operation is complete WALTEVENT Americas 1 800 492 2320 Option 2 2 8 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual ANDi ENDIKA ENDIF CloseConnections NDE ENDFUNC 1 EVDIESCPRIMSVC event handler FUNCTION HandlerPrimSvc cHndl svcUuid sHndl e Hnd1 PRINT An EVDISCPRIM VC PRINE cHncoUl chineol PRINT svecUUuid integer h svcUuid PRINT 4 Sshrndil shngil PRINT eHndl eHndl TET KmA 0 Tae PRINT nPrimary Service Scan complete EXITFUNG O BLSE AS INTEGER PRINT nGot first primary Service so scan for ALL characteristics SATTE SHEL eArrtE ebhndl roe BlebiseCharw rest comindl 0 sAnbr eNtrs IF ce 0 THEN PRINT nascan characteristics failed EXITFUNC Q ANDi ENDL endfunc 1 1 Clave in 1 Oey Handler C nar Die eHandel ao urd Prine nEeD OCCHAR Peint e Hnd errdill print
81. free and Laird s Development Kit to test and debug your application For the purpose of this chapter the examples are based upon Laird s BL600 a BLE module However the principles apply to any smartBASIC enabled module Requirements To replicate this example you need the following items A BL600 series development kit UWTerminal application contact Laird for the latest version The UWTerninal must be at least v6 50 Save the application to a suitable directory on your PC Accross compiler application with a name typically formatted as XComo_dddddddd_aaaa_bbbb exe where dddddddd is the first non space eight characters from the response to the AT 0 command and aaaa bbbb is the hexadecimal output to the command AT 13 Note aaaa bbbb is a hash signature of the module so that the correct cross compiler is used to generate the bytecode for download When an application Is launched in the module the hash value is compared against the signature in the run time engine and if there is a mismatch the application is aborted Connecting Things Up The simplest way to power the development board and module is to connect a USB cable to the PC The development board regulates the USB power rail and feeds it to the module Note The current requirement is typically a few mA with peak currents not exceeding 20 mA We recommend connecting to a powered USB hub or a primary USB port UWTerminal UWTerminal is a term
82. frequency to use and can be one of 125000 250000 500000 1000000 2000000 4000000 or 8000000 byVal nCfgFlags AS INTEGER This is a bit mask used to configure the SPI interface All unused bits are allocated as for future use and MUST be set to 0 Used bits are as follows Bit Description O If set then the least significant bit is clocked in out first 1 31 Unused and MUST be set to O byRef nHandle AS INTEGER The handle for this interface will be returned in this variable if it was successfully opened This handle is subsequently used to read write and close the interface Related Commands SPICLOSE SPIREADWRITE SPIWRITE SPIREAD SPIOPEN is a core function On the following page is an example which demonstrates usage of all the SPI related functions for this module Americas 1 800 492 2320 Option 2 157 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual SPI Example Example SpiExample sb See in BL600CodeSnippets zip The SPI slave used here is the Microchip 25A512 See http wwl microchip com downloads en DeviceDoc 22237C pdf DIM we DIM h hnandle DIM rl readlen DINTE waco oo DIM wren FUNG TON Sep ronsearus GpioWrite 13 0 wrS 05 00 rdS _ rc SpiReadWrite wrS rds Gprowrice 13 1 ENDFUNG StrGer hr rds l le a ee ee a a Wait for WR bit in status flag to reset ia or at a
83. high see the PWM Ourpur tO 25S GpioWrite 5 256 256 1024 4 roet coe FRRO CUr rut tO 45236 Kiz GpioWrite 7 4236 Note you can generate a chirp output on sio 7 by starting a timer which expires every 100ms and then in the timer handler call GpioWrite 7 xx and then increment xx by a certain value Expected Output 0000 GPIOWRITE is a Module function GPIO Events EVGPIOCHANn Here n is from O to N where N is platform dependent and an event is generated when a preconfigured digital input transition occurs The number of digital inputs that can auto generate is hardware dependent For the BL600 module N can be 0 1 2 or 3 Use GpioBindEvent to Tgenerate these events EVDETECCHANn Here n is from O to N where N is platform dependent and an event is generated when a precontigured digital input transition occurs The number of digital inputs that can auto generate is hardware dependent For the BL600 module N can only be 0 Use GpioAssignEvent to generate these events GpioBindEvent FUNCTION This routine binds an event to a level transition on a specified special i o line configured as a digital input so that changes in the input line can invoke a handler in smart BASIC user code Americas 1 800 492 2320 Option 2 182 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Note In the BL600 module
84. i chr lt HH chr gt 0x7F HH Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Memory Heap Exhausted Arguments string byRef string AS STRING The string to be converted If a parsing error is encountered a nonfatal error will be generated which needs to be handled otherwise the script will abort Interactive Command NO Americas 1 800 492 2320 Option 2 96 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Note string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Associated Commands STRDEESCAPE Example StrEscape sb See in BL600CodeSnippets zip DIM 3o Eo sS Hello O0world tS StrEscapes sS PRINT Strlem ss s n PRINT StrLen tS n 11 13 STRESCAPES is a core function STRDEESCAPE SUBROUTINE STRDEESCAPE is used to convert an escaped string variable in the same memory space that the string exists in Given all 3 byte escape sequences are reduced to a single byte the result is never longer than the original STRDEESCAPE string Returns None string now contains de escaped characters converted as follows r carriage return n lineteed t horizontal tab HH ascii byte HH Exceptions
85. in Once that list is made at the client end it can throw away the carrier bag Americas 1 800 492 2320 Option 2 230 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Similarly in the module once the GATT table is created and after each Service is fully populated with one or more Characteristics there is no need to keep that carrier bag However as each Characterstic is placed in the carrier bag using the appropriate smartBASIC API function a receipt will be returned and is referred to as a char_handle The developer will then need to keep those handles to be able to read and write and generally interact with that particular characteristic The handle does not care whether the Characteristic is adopted or custom because from then on the firmware managing It behind the scenes in smartBASIC does not care Therefore from the smartBASIC app developer s logical perspective a GATT table looks nothing like the table that is presented in most BLE literature Instead the GATT table is purely and simply just a collection of char_handles that reference the characteristics data containers which have been registered with the underlying GATT table in the BLE stack A particular char_handle is in turn used to make something happen to the referenced characteristic data container using a smartBASIC function
86. indicating a successful operation Arguments nMinFreqHz byRef nMinFreqHz AS INTEGER On entry this variable contains the minimum frequency desired for the PWM output On exit if successful it contains the actual frequency of the PWM output nMaxPeriodus byVal nMaxPeriodus INTEGER This specities the duty cycle resolution and the value to set to get a 100 duty cycle Interactive Command NO Example GpioConfigPWM See in BL600CodeSnippets zip DINES DIM nFregHz nMaxValUs we want a minimum frequency of 500Hz so that we can use a 100Hz low pass filter to create an analogue output which has a 100Hz bandwidth nFreqHz 500 we want a resolution of 1 1000 in the generated analogue output nMaxValUs 1000 PRINT GpioConfigPWM nFregqHz nMaxValUs PRINT AnThe actual frequency Of the PWM output as nfEreghz in IA ow cont cure SIO pin as a PWM curoue PRINT Goroserrunc 2 2 2 3rd parameter is subfunc PWM output Set PWM output to 0 GpioWrite 2 0 j Seu PUM ouEpUE Eo 50s GpioWrite 2 nMaxValUs 2 Set PWM output to 100 GpioWrite 2 nMaxValUs any value gt nMaxValUs will give a 100 duty cycle Set PWM output to 33 333 Set PWM output to 50 GpioWrite 2 nMaxValUs 3 Expected Output O The actual frequency of the PWM output is 1000 O GPIOCONFIGPWM is a Module function Americas 1 800 492 2320 Option 2 180 Laird Technologies Europe 44 162
87. is as follows Register a handler for the EVNOTIFYBUF event message On EVNOTIFYBUF event message Can now send another write command Americas 1 800 492 2320 Option 2 303 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Call BleGattcWriteCmd If BleGattcWrite ok then Wait for EVNOTIFYBUF Returns INTEGER a result code The typical value is 0x0000 indicating a successful read Arguments connHnal byVal connHnal AS INTEGER This is the connection handle as returned in the on connect event for the connection on which the remote Gatt Server can be accessed This will have been returned in the EVBLEMSG event message with msgld 0 and msgCtx will have been the connection handle attrHnal byVal attrHna AS INTEGER The handle for the attribute that is to be written to attrData byRef attrData AS STRING The attribute data to write Interactive Command NO Example BleGattcWriteCmd sb See in BL600CodeSnippets zip a Remote server has 3 prim services with 16 bit uuid First service has one characteristic whose value attribute is at handle 3 and has read write props a U Seieve e Using e e T ee o a aae iin Oe e e j 7 Using Nordic Veb Dongle ae OO DLLME tee eos cinabacll wilshacll sere and HUNGTICN Onsotareupe DIM ror adRots addr seRpir re pileAdvRpelinit adkRpee 2 07 10 if re 0 TH
88. is not 0 byRef nReadlen AS INTEGER On entry this variable contains the number of bytes to be read from the slave and on exit will contain the actual number that were actually read If the entry value is O then the read phase will be skipped Interactive Command No Related Commands IZCOPEN I2CCLOSE I2CWRITEREAD I2CWRITEREG8 I2CWRITEREG16 Example IZCWRITEREG32 IZCREADREGS8 I2CREADREG16 I2 CREADREG32 I2cWriteRead sb See in BL600CodeSnippets zip Please ensure that nSlaveAddr is the slave address of your I2C peripheral IIE tare DIM handle DIM nSlaveAddr DIM stWeites stReadS nReadLen rc I2cOpen 100000 0 handle IE cels 0 THEN PRINT nPatVved to open eO anter ace with error code inteqer bh re ELSE PRINT nI2C open success ENDIE Write 2 bytes and read 0 nSlaveAddr 0x6f stWriteS 34 35 stReadS _ nReadLen 0 re I2cWriteRead nSlaveAddr stWriteS stRead nReadLen IF rc O THEN PRINT nFailed to WriteRead integer h rc ELSE PRINT AA aea S a e a e a a gt Read 7Sieriexives sukReads ENDIF Write 3 bytes and read 4 nSlaveAddr 0x6f stWriteS 34 35 43 stReadS _ nReadhen 4 re I2cWriteRead nSlaveAddr stWriteS stRead nReadLen IE ee 0 THEN PRINT nFailed to WriteRead integer h rc BLSE PRINT Anr te ee raea a N e e ead e e ea aee BENIDE Write 0 bytes and read 8 nslayeAddr 0x6f gt stWrite s W o gtReacd
89. is the integer value to write into the circular buffer Interactive Command NO Example CircBufWrite sb See in BL600CodeSnippets zip PB ae DIM eriweHandike DIM i re CircBufCreate 16 circHandle IF rc 0 then PRINT nThe circular buffer was not created n ES a PRINT nThe circular buffer was created successfully n BNDTs write 3 values into the circular buffer FOR 1 1 TO 3 re CireBuiwriee Cikeas IF re 0 then PRINT nPatvled to write into the circular bufrerin BLSE PRINT i was successtuly veil en to he circular Durer u BNDL E NEAT Americas 1 800 492 2320 Option 2 121 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected output The circular buffer was created successfully 1 was successfuly written to the circular buffer 2 was successfuly written to the circular buffer 3 was successfuly written to the circular buffer CIRCBUFWRITE is an extension function CircBufOverWrite FUNCTION This function is used to write an integer at the head end of the circular buffer and if there is no space available to write then it will return with a failure resultcode but still write into the circular buffer by first discarding the oldest item CIRCBUFOVERWRITE circHandle nData Returns INTEGER An integer result code The most typical value is 0x0000 which indicates a successf
90. is used to erase a string and then Till it with a number of identical characters STRFILL string nChr nCount Returns INTEGER Represents command execution status O If successful 1 If nChris greater than 255 or less than O 2 If the string length cannot be extended due to lack of memory 3 If the resultant string is longer than allowed or nCountis lt 0 STRING string contains the modified string Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Memory Heap Exhausted Arguments string byRef string AS STRING Americas 1 800 492 2320 Option 2 90 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual The target string to be filled nChr byVal nChr AS INTEGER ASCII value of the character to be inserted The value of nChr should be between 0 and 255 inclusive ncount byVal nCount AS INTEGER The number of occurrences of NCArto be added The total number of characters in the resulting string must be less than the maximum allowable string length for that platform Note string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Interactive Command NO Example StrFill sb See in BL600CodeSnippets zip Diltits Senso nel lor PRINT ess TAn PR
91. lines of application which can include nested conditional statement blocks a Var A valid INTEGER variable which can be referenced in the statement block Arithexpr A valid arithmetic or logical expression arithexor7 is enumerated as the starting point for the FOR NEXT loop Arithexpr2 A valid arithmetic or logical expression arithexor2 is enumerated as the finishing point for the FOR NEXT loop Arithexor3 A valid arithmetic or logical expression arithexor3 is enumerated as the step in variable values in processing the FOR NEXT loop If STEP and arithexor3 are omitted then a unity step is assumed Note Arithmetic precedence is as defined in the section Arithmetic Expressions The lines of code comprising the statement block are processed with varstarting with the value calculated or detined by arithexpr1 When the NEXT command is reached and processed the STEP value resulting from arithexor3 is added to varif TO is specified or subtracted from var it DOWNTO is specified The function continues to loop until the variable var contains a value less than or equal to arithexpor2 in the case where TO is specified or greater than or equal to arithexpr2 in the alternative case where DOWNTO is specitied Note In smart BASIC the Statement Block is ALWAYS executed at least once Interactive Command NO Example ForNext sb See in BL600CodeSnippets zip DIM a FOR a 1 TO 2 PRINT Hello NEXT
92. maximum long term encryption key size requirements for subsequent pairings If this function is not called default values are 7 and 16 respectively To ship your end product to a country with an export restriction reduce nMaxKeySize to an appropriate value and ensure it is not modifiable BLESECMNGRKEYSIZES nMinKeysize nMaxKeysize Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments nMinKeysiz byVal nMinKeysiz AS INTEGER The minimum key size The range of this value is from 7 to 16 nMaxKeysize byVal nMaxKeysize AS INTEGER The maximum key size The range of this value is from nMinKeysize to 16 Americas 1 800 492 2320 Option 2 225 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Interactive Command NO Example BleSecMngrKeySizes sb See in BL600CodeSnippets zip PRINT BleSecMngrKeySizes 8 15 Expected Output Osi BLESECMNGRKEYSIZES is an extension function BleSecMngrloCap FUNCTION This function sets the user I O capability for subsequent pairings and is used to determine if the pairing is authenticated or not This is related to Simple Secure Pairing as described in the following whitepapers https Awww bluetooth org docman handlers DownloadDoc ashx doc_id 86174 https Awww bluetooth org docman handlers DownloadDoc ashx doc_id 861 73 I
93. message This event message WILL be thrown if either BleDiscServiceFirst or BleDiscServiceNext returns a success The message contains 4 INTEGER parameters Connection Handle Service Uuid Handle Start Handle of the service in the Gatt Table End Handle for the service If no more services were discovered because the end of the table was reached then all parameters will contain O apart trom the Connection Handle BLEDISCSERVICEFIRST connHandle startAttrHandle uuidHandle A typical pseudo code for discovering primary services involves first calling BleDiscServiceFirst then waiting for the EVDISCPRIMSVC event message and depending on the information returned in that message calling BleDiscServiceNext which in turn will result in another EVDISCPRIMSVC event message and typically is as tollows Register a handler for the EVDISCPRIMSVC event message On EVDISCPRIMSVC event message If Start End Handle 0 then scan is complete Else Process information then call BleDiscServiceNext if BleDiscServiceNext not OK then scan complete Call BleDiscServiceFirst If BleDiscServiceFirst ok then Wait for EVDISCPRIMSVC Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation and it means an EVDISCPRIMSVC event message WILL be thrown by the smartBASIC runtime engine containing the results A non zero return value implies an EVDISCPRIMSVC message will NOT be thrown Americas 1 800 492 2320
94. mn ana endfunc 1 function oule wom Opie sc is pressed Govowrr te le 1 print Button 0 has been pressed n the button is pressed this tunction Ls called an LED OMOT these lines are printed this tunction is called A ebicas LEDO ON these lines are printed print LED 0 will light while the button is pressed n endrunce 1 function buttonlrelease is released qolowrite 19 0 print Button 1 has been released n the button is released Prin LED ie should mew gO out nan endiume 1 UMC EO mmole monilpace ss is pressed gpiowrite 19 1 this tuncctLon Ls called eurn TED yest these lines are printed this function is called turns LED 1 on when the button 0 to the UART when when the button 0 to the UART when when the button 1 to the UART when when the button 1 print Button 1 has been pressed n these lines are printed to the UART when the button is pressed Prine LED Twill light whale Ene Dutton 1S pressed An endfunc 1 p KR KKK KKK KKK RK KR KK KK KK DE DE E I KK I KK KK IK I KK IK I KK I DE DE DE E DE IK KK KK KK Kk kK Kk J 7 Handler definicions KR KKK KKK KKK RK KK KK I KK KK IK KK I KK KK IK IK I IK I KK IKK KK KK KK KK KK kK p KR KKK KKK KKK KK KR KK IK KK KK I KK I KK KK I KK IK I KK I KK KK IK KK I KK KK kK kK Kk BOG alene FO Main anc p RR KKK KKK KK KK KR KK I KK KK I E E I KK I KK I I I KK IK KK I KR KK KK KK K
95. msgld 0 and msgCtx will have been the connection handle Americas 1 800 492 2320 Option 2 300 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual attrHnal byVal attrHnal AS INTEGER The handle for the attribute that is to be written to attrData byRef attrData AS STRING The attribute data to write Interactive Command NO Example BleGattcWrite sb See in BL6O00CodeSnippets zip ie Remote server has 3 prim services with 16 bit uuid First service has one characteristic whose value attribute is at handle 3 and has read write props lle fF Seive Cieecinec Messing Eee eC oLa ee Sule Linvolsecl sig _ Cloeialllicis Sidi using Nordic Usb Dongle PC10000 DIM seep eres oinebatoll wilsholl ere and PUNECTITCN Se OnsbanEeue paier ER e so secldlcka orm Ss Lqoln re BilleAdvRpEIni tb adRpes 2 07 10 IE e 0 THEN 3 re BleSeankoe ln SsecReEs ENDIF IF rc 0 THEN rc BleAdvRptsCommit adRpt scRpt ENDIF ie ee 0 THEN re BleAGvertStarte O0Faddro 50 070 ENDIF open the gatt client with default notify indicate ring buffer size IF rc 0 THEN re BleGattcOpen 0 0 ENDIF BNDE UNG wise SUB Glose ocnnecrioms rc BleDisconnect conHnd1 rc BleAdvertStop BAS UB FUNCTION HrndalrBleMsg BYVAL nMsgid BYVAL nCcEx DIM uHndA conHndl nCtx IF nMsgID 1 THE
96. notifiable rc BleCharNew 0x12 BleHandleUuidl16 1 BleAttrMetaData 1 0 20 0 rc mdCccd 0 COMME Char initialised above vith interval value hi to service hMyChar rc BleCharCommit hSvc attrs hMyChar rc BleScanRptInit scRpt Add 1 service handle to scan report re sloNwNorNCcluUmLolls e aoe lniiswe e commit reports to GATT table adRptS is empty rc BleAdvRptsCommit adRpt scRpts rc BleAdvertStart 0 addr 50 0 0 ENDEUNC re FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx comnlindl mcex IF nMsgID 1 THEN PRINT n n Disconnected from client EXT TEUNC 0 ELSEIF nMsgID 0 THEN PRINT n Connected to client DNDI E ENDEUMC wi EE i CCCD Gescrietor written handler EE FUNCTION HndlrCharcecd BYVAL charHandle BYVAL nval AS INTEGER DIM values Americas 1 800 492 2320 Option 2 259 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual IF charHandle hMyChar THEN PRINT nCeCD Vel enval IP nyal THEN PRINT Notifications have been enabled by client valueS hello IF BleCharValueNotify hnMyChar value 0 THEN PRINT nPatled to notify new value INTEGER A rc BLSE PRINT nsuccesstul notification of mew value EXITFUNG O BNDIE Bilis Ey PRINT Notifications have been disabled by client ENDLE E TOE PRINT AnThis is for Some other Characteristic BND ENDFUNC
97. or any more that arrive but less than 20 will be forced onwards when that timer expires BLEVSPUARTBRIDGE Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments None Interactive Command No Related Commands BLEVSPOPEN BLEVSPCLOSE BLEVSPINFO BLEVSPWRITE BLEVSPFLUSH Example BleVSpUartBridge sb See in BL6O00CodeSnippets zip DIM conHndl SUB OnStartup DIM tee loarclilL 2S Selyoes a a aE re BleVvSpOpen 126 128 0 andl rc BleScanRptInit scRpt rc BleAdvRptAddUuidl128 scRpts hndl1 rc BleAdvRptsCommit adRpt scRpts rC BleAdvertStarce 0 addrs 20 300000 0 rc GpioBindEvent 1 16 1 Channel bind to low transietom som EPO pam io PRINT nDevice name is BleGetDeviceNameS n oo Vai Seinicl me some text nPress burton Owe exit n re BleVSpWrite tx ENDSUB SUB CloseConnections DMRS Americas 1 800 492 2320 Option 2 349 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual rc BleDisconnect conHndl rc BleAdvertStop BleVspClose IB She FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx conHndl nCtx IF nMsgID 1 THEN PRINT nDisconnected from client EXP r Sune 70 SNID IL IE ENDEUNG Si FUNCTION HnellreBtcn0Pr AS INTEGER just exit and stop waiting for events ENDFUNC 0 FUNCTION HandlerBridge AS INTEGER transfer data betwee
98. or more statements to be processed until a condition becomes true DO statement block UNTIL arithmetic expr Statement block A valid set of program statements Typically several lines of application Arithmetic expression A valid arithmetic or logical expression Arithmetic precedence is defined in the section Arithmetic Expressions For DO UNTIL if the arithmetic expression evaluates to zero then the statement block is executed again Care should be taken to ensure this does not result in infinite loops Interactive Command NO Example DoUntil sb See in BL600CodeSnippets zip DIM a AS INTEGER don t really need to supply AS INTEGER a 1 DO a atl PRINT amp UNTIL a 10 loop will end when A gets to the value 10 Americas 1 800 492 2320 Option 2 59 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output 2345678910 DO UNTIL is a core function DO DOWHILE This DO DOWHILE construct allows a block of one or more statements to be processed while the expression in the DOWHILE statement evaluates to a true condition DO statement block DOWHILE arithmetic exor Statement block A valid set of program statements Typically several lines of application Arithmetic expression A valid arithmetic or logical expression Arithmetic precedence is defined in the se
99. precedence is as defined in the section Arithmetic Expressions All WHILE commands must be terminated with an ENDWHILE statement Interactive Command NO Example While sb See in BL600CodeSnippets zip DEI ia n 0 now print Hello ten times WEEE ASLO PRINT Y Hello Y pn n n 1l ENDWHILE Expected Output Hello 0 Hello 1 Hello 2 Hello 3 Hello 4 Hello 5 Hello 6 Hello 7 Hello 8 Hello 9 WHILE is a core function Americas 1 800 492 2320 Option 2 63 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual SELECT CASE CASE ELSE ENDSELECT SELECT Is a conditional command that uses the value of an arithmetic expression to pass execution to one of a number of blocks of statements which are identified by an appropriate CASE nnn statement where nnn is an integer constant After completion of the code which is marked by a CASE nnn or CASE ELSE statement execution of the application moves to the line following the ENDSELECT command In a sense it is a more efficient implementation of an IF block with many ELSEIF statements An initial block of code can be included after the SELECT statement This is always processed When the first CASE statement Is encountered execution moves to the CASE statement corresponding to the computed value of the arithmetic expression in the SELECT command After selection of t
100. relative to the beginning or current position or from the end of the file and function FTELL is provided to obtain the current position as an offset from the beginning of the file FOPEN filename mode Returns INTEGER A non zero Integer representing an opaque handle to the Tile that was opened If the file failed to open like for example because the mode specified writing to the file which is not allowed on certain platforms then the returned value will be O Arguments filename BYREF filename AS STRING This string specifies the name of the file to open mode BYVAL mode AS STRING Must always be set to r This string specifies the mode the file should be opened and for this module as only reading is allowed must always be specified as r Interactive Command NO Example FilelIo sb See in BL600CodeSnippets zip i First download a file into the module by submitting the following commands manually wait for a 00 response after each command ie Ve at fow myfile dat atriwe Hello a arti World a at twe Vas 1S something IA at fwr in a file which we can read le attfcl iy You can check you have the file in the file system by submitting the command AT DIR and you should see myfile dat listed Fie DIM handle tnames then triken datas toos cc fnames myfile dat handle fopen fname r IF handle O THEN Americas 1 800 492 2320 Option 2 168 Laird
101. representing the shorthand UUID and can be zero which is an invalid UUID handle if nUuidHandle is an invalid handle in the first place Arguments nUuidHandle byVal nUuidHanadle AS INTEGER A handle that was previously created using either BleHandleUui16 or BleHandleUuid1280 nUuid16 byVal nUuid76 AS INTEGER A UUID value in the range 0 t0 65535 which will be treated as an offset into the 128 bit base UUID referenced by nUuidHandle Interactive Command NO Example BleHandleUuidSibling sb See in BL600CodeSnippets zip DIM uuid AlalUibakelks NUU nUuid2 will have the same base uuid as hUuidl create a custom uuid for my ble widget uuid ced9d9l366924a1 728 d56827 647 62524 uuid StrDehexizes uuids hUuicdil BlefancleUuridil28 uurid IF hUuidl 0 THEN PRINT nFailed to create a handle ELSE PRIND Hendhe for custom Vuid is Pr integers in sina T BUU di ae ENDIF hUuidl now references an object which points to a base uuid ced9000066924a1287d56f 2747622b2a note O s in byte position 2 3 and an offset 0xd913 hUuid2 BleHandleUuidSibling hUuidl 0x1234 IF AUuid2 0 THEN PRINT nFailed to create a handle BLSE PRINT handles torm euse omn sto ling Uad e a na e ae a ae a Uur 4 y IEND IL IE Americas 1 800 492 2320 Option 2 240 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manua
102. result code The most typical value is OxO000 which indicates a successful operation If 0x5102 is returned it implies the buffer was empty so nothing was read Arguments circHanadle byRef circHandle AS INTEGER This identities the circular buffer to read from nData byRef Data AS INTEGER This is the integer value to read from the circular buffer Interactive Command NO Example CircBufRead sb See in BL600CodeSnippets zip DIM re CLrceHancLle L nDarca rc CircBufCreate 4 circHandle Le ze O TREN PRINT nThe circular buffer was not created BLSE PRINT nThe circular buffer was created successfully n PUNE Oe Neel ale snes 4 ENDI E EOR DESEO rc CircBufOverwrite circHandle i IF re 0x5103 THEN PRINT mOldest value was discarded to write si n ELSELF re 1 0 THEN PRINTE AnFrailed TO write Gano the circular butter ELSE Americas 1 800 492 2320 Option 2 123 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Ie see er ee ENDILE NEXT read 4 values from the circular butter PRINT nReading n TORE E ace el re CircBufRead circHandle nData IF rec 0x5102 THEN PRINT The buffer was empty ELSEIF rec l O THEN BRINI Paved to read from che circular butter SIs PRINT nData n ENDIF NEXT Expected Output CIRCBUFREAD is an extension function CircBufltems
103. scan for ALL characteristics sAttr sHndl eAttr eHndl re BlebDisccCharrirste conknd 0 sAbtr eAbiic LE pG l O THEN PRINT nScan characteristics failed BXITEUNC 0 ENDIF ENDIF endfunc PUMICE LOM Mandler harbi c Chncdly clus cecop bya teu sas mse ger joigubiay ola DISC OCAR el Ditmte VCH mcdi na print chUusd inreqer h cUuid print H Props T OCProp Pring valhndil 7 nval Drink leveVuad pr Uan IF hVal 0 THEN PRINT nCharacteristic Scan complete EXITPUNC Q ELSE PRINT AnGot first characteristic service at handle hval PRINT msSecan tor ALE Desce cValAttr hVal rc BleDiscDescFirst conHndl 0 cValAttr LE re O THEN PRINT nScan descriptors failed Ee reuUnC 40 ENDIF ENDIF endfunc 1 Poeton Handler Deas curs e1 cibimciuly ec Uuarc aiimniclil eee Ta aer Prine Y meV CDE C1 print chndil i chndil Print T dscuuid integer N cUuad print dscehmel gt indl IF hndl O THEN PRINT nDescriptor Scan complete EXITFUNC O BLSE rc BleDiscDescNext cHndl IP cc l O THEN PRINCE SAn De Cri peor scan abore Americas 1 800 492 2320 Option 2 284 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual ET PUNG 30 ENDL ENDIF endrune 1 ONEVENT EVBLEMSG Onknvenc HYVDISCPRIMS VC OnEvent EVDISCCHAR Onkivenu EVDESCDE SC HndlrBleMsg HandlerPrimSvc H
104. smart BASIC will never need the complexity of locking variables and objects There are many subsystems which generate events and messages as follows Timer events which generate timer expiry events and are described here Messages thrown from within the user s BASIC application as described here Events related to the UART interface as described here GPIO input level change events as described here BLE events and messages as described here Generic Characteristics events and messages as described here 9 MODULE CONFIGURATION There are many features of the module that cannot be moditied programmatically which relate to interactive mode operation or alter the behaviour of the smartBASIC runtime engine These configuration objects are stored in non volatile flash and are retained until the flash file system is erased via AT amp F or AT amp F 1 To write to these objects which are identified by a positive integer number the module must be in interactive mode and the command AT CFG must be used which is described in detail here To read current values of these objects use the command AT CFG described here Predefined configuration objects are as listed under details of the AT CFG command Americas 1 800 492 2320 Option 2 356 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual 10 MISCELLANEOUS Bluetooth R
105. tab gt hex number lt tab gt optional verbose explanation lt cr gt for failure Note Inthe case of the 01 response the lt tab gt optional_verbose_explanation will be missing in resource constrained platforms like the BL600 modules The verbose explanation is a constant string and since there are over 1000 error codes these verbose strings can occupy more than 10 kilobytes of flash memory The hex number in the response is the error result code consisting of two digits which can be used to help investigate the problem causing the failure Rather than provide a list of all the error codes in this manual you can use UWTerminal to obtain a verbose description of an error when it is not provided on a platform To get the verbose description click on the BASIC tab in UWTerminal and if the error value is hhhh enter the command ER Oxhhhh and note the Ox prefix to hhhh This is illustrated in Figure 14 Oo mu UwTerminal v6 22 Terminal BASIC Config About CTS DSR DCM RI GENERIC FAIL COMMAND Tx 3971 Rx 2428 Figure 14 Optional verbose explanation You can also obtain a verbose description of an error by highlighting the error value right clicking and selecting Lookup Selected ErrorCode in the Terminal window If you get the text UNKNOWN RESULT CODE OxHHHH please contact Laird for the latest version of UWterminal AT AT is an Interactive mode command It must be ter
106. the default data if the record does not exist Interactive Command NO Example NvRecordGetEx sb See in BL600CodeSnippets zip DIM r PRINT NvyRecordGerEx 007 rs default bytes read PRINT va ies Expected Output 7 bytes read default NVRECORDGETEX is a module function Americas 1 800 492 2320 Option 2 174 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual NvRecordSet FUNCTION NVRECORDSET writes a value to a user record in non volatile memory NVRECORDSET recnum strvar Returns INTEGER Returns the number of bytes written If an invalid record number is specified then 1 is returned There are a limited number of user records which can be written to depending on the specific module Exceptions Local Stack Frame Undertlow Local Stack Frame Overflow Arguments recnum byVal recnum AS INTEGER The record number that is to be read in the range 7 to n where n depends on the specific module strvar byRef strvar AS STRING The string variable that will contain the data to be written to the record WARNING You should minimise the number of writes Each time a record is changed empty flash is used up The flash filing system does not overwrite previously used locations Eventually there will be no more free memory and an automatic defragmentation will occur This operation takes much long
107. the same service or characteristics or descriptors and they are differentiated by the unique handle Hence when a handle is known there is no ambiguity Each GATT Server table will allocate the handle numbers the only stipulation being that they be in ascending order gaps are allowed This is important to understand because two devices containing the same services and characteristic and in EXACTLY the same order may NOT allocate the same handle values especially if one device increments handles by 1 and another with some other arbitrary random value The specification DOES however stipulate that once the handle values are allocated they be fixed for all subsequent connections unless the device exposes a GATT Service which allows for indications to the client that the handle order has changed and thus force it to flush it s cache and rescan the GATT table When a connection is first established there is no prior knowledge as to which services exist and of their handles so the GATT protocol which is used to interact with GATT servers provides procedures that allow for the GATT table to be scanned so that the client can ascertain which services are offered This section describes smartBASIC functions which encapsulate and manage those procedures to enable a smartBASIC application to map the table These helper functions have been written to help gather the handles of all the rows which contain the value type for appropriate characteristics as those
108. them with AT DEL testl HelloWorld Note All responses to interactive commands are of the format nNN tOptionalText1 tOptionalText2 r where MWis always a two digit number and t is the tab character and is terminated by r This format has been provided to assist with developing host algorithms that can parse these responses in a stateless fashion The NN will always allow the host to attach meaning to any response from the module Autorun One of the major features of a smartBASIC module is its ability to launch an application autonomously when power is applied To demonstrate this we will use the same HelloWorld example An autorun application is identical to any other BASIC application except for its name which must be called autorun Whenever a smart BASIC module is powered up it checks its nAutoRUN input line see the BL600 module pinout and if it is asserted at Ov it looks for and executes the autorun application In the BL600 development kit the nAutoRUN input pin of the module is connected to the DTR output pin of the USB to UART chip This means the DTR checkbox in UWTerminal can be used to affect the state of that pin on the BL600 module The DTR checkbox is always selected by default in asserted state which translates to a Ov at the nAutoRUN input of the module This means if an autorun application exists in the module s file system it is automatically launched on power up Tesminal Script Co
109. type minchar gt strexor lt separator gt Type Must be STRING for string variables The type must be followed by a full stop to delineate it from the width field that follows minchar An optional parameter which specifies the number of characters to be printed for a string variable or expression If necessary leading spaces are filled with spaces strexpr A valid string or string expression separator One of the characters or which have the following meaning Americas 1 800 492 2320 Option 2 72 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Insert tab before next variable f Print next variable without a space Interactive Command YES Example SPrint sb See in BL600CodeSnippets zip DIM a sS a 100 Note SPRINT replaces the content of s with exprlist each time it is used SPRINT sS a So Mow Contains 100 PRINT Antroo An SPRINT s INTEGER H a Se NON lt comuains oF PIB INE Ss oF sore SERINT kso INTECER Oa VSS Mow Contains 44 PRENET vn SPRINT fso INTECER B a J So NON contains 1100100 PRINT ss via Expected Output 100 00000064 00000000144 00000000000000000000000001100100 SPRINT is a core function STOP STOP is used within an application to stop it running so that the device falls back into Interactive Command line mode STOP It is normall
110. used as parameters If it accepts them as references rather than as values This subtle difference is described further in the next section Subroutines A subroutine does not generate a return value and is generally used as the only command on a line Like a function it may affect the value of variables used as parameters if it accepts them as references rather than values For example STRSHIFTLEFT string num This brings us to the definition of the different forms an argument can take both for a function and a subroutine When a function is defined its arguments are also defined in the form of how they are passed either as byVal or byRef Passing Aruments as byVal If an argument Is passed as byVal then the function or subroutine only sees a copy of the value While it is able to change the copy of the variable upon exit all changes are lost Passing Arguments as byRef If an argument is passed as byRef then the function or subroutine can modify the variable and upon exit the variable that was passed to the routine contains the new value To understand look at the smart BASIC subroutine STRSHIFTLEFT It takes a string and shifts the characters to the left by a specitied number of places STRSHIFTLEFT string num Americas 1 800 492 2320 Option 2 49 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual It is u
111. website or any other utility is unique It is left to the judgement of the developer whether to use it or not Note If the developer does intend to create custom Services and or Characteristics then it is recommended that a single UUID is generated and be used from then on as a 128 bit 16 byte company developer unique base along with a 16 bit 2 byte offset in the same manner as the Bluetooth SIG This will then allow up to 65536 custom services and characteristics to be created with the added advantage that it will be easier to maintain a list of 16 bit integers The main reason for avoiding more than one long UUID is to keep RAM usage down given that 16 bytes of RAM is used to store a long UUID SmartBASIC functions have been provided to manage these custom 2 byte UUIDs along with their 16 byte base UUIDs In this document when a Service or Characteristic is described as adopted it implies that the Bluetooth SIG has published a specification which defines that Service or Characteristic and there is a requirement that any device claiming to support them SHALL have approval to prove that the functionality has been tested and verified to behave as per that specification Currently there is no requirement for custom Service and or Characteristics to have any approval By definition interoperability is restricted to just the provider and implementer A Service is an abstraction of some collectivised functionality which if broken down
112. will scan for a characteristic with a particular uuid the handle of which must be supplied and is generated by using either BleHandleUuid16 or BleHandleUuid128 If instead it is known that a gatt table has a specific service and a specific characteristic then a more efficient method for locating details of that characteristic is to use the function BleGattcFindChar which is described later While the scan Is in progress and waiting for the next piece of data from a Gatt server the module will enter low power state as the WAITEVENT statement is used as normal to wait for events and messages Americas 1 800 492 2320 Option 2 275 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Depending on the size of the remote GATT server table and the connection interval the scan of all characteristics may take many 100s of milliseconds and while this is in progress it is safe to do other non Gatt related operations like for example servicing sensors and displays or any of the onboard peripherals Note Itis not currently possible to scan for characteristics in included services This will be a future enhancement EVDISCCHAR event message This event message WILL be thrown if either BleDiscCharFirst or BleDiscCharNext returns a success The message contains 5 INTEGER parameters Connection Handle Characteristic Uuid Hand
113. 008 i Womleeie one iene PRINT arse ase Os lt s 010 SYSINFO 0x8010 Code memory page size from FICR Expected Output For BL600 svyeince 1000 13154895336 Syeiniio 2003 8 Syeinto UZEL 1024 SYSINFO is a core language function SYSINFO FUNCTION Returns an informational string value depending on the value of varld argument SYSINFO varld Returns STRING Value of information corresponding to integer ID requested Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments varld byValvarld AS INTEGER An integer ID which is used to determine which information is to be returned as described below 4 The Bluetooth address of the module It is seven bytes long First byte is OO for IEEE public address and 01 for random public address Next six bytes are the address 14 A random public address unique to this module May be the same value as in 4 above unless AT MAC was used to set an IEEE mac address It is seven bytes long First byte is OO for IEEE public address and 01 for random public address Next six bytes are the address Interactive Command No Example SysInfo sb See in BL600CodeSnippets zip PRINT novsinros 4 C YSINFOS 4 i Biccice se Cit module PRIUT Anoye In o n 4 Sv Sires 4 publ e random address PRINT ANS yS Ino O Wo SY SINFOS 0 Americas 1 800 492 2320 Option 2 79 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless suppo
114. 1 ONEVENT EVBLEMSG CALL HndlrBleMsg ONEVENT A 2VCHARCCED CALL Ane lreiareecd LE Onetartup O THEN re BleCharValueRead hMyChar ats PRINT nChareacteristic Value ears PRINT Mnrou Can connecti and Weise to Ene C OCD charactericric PRINT nThe BL600 will then notify your device of a new characteristic value n ELSE PRINT Anfali lure OnStartcup ENDIF WALTEVENT ro BleDisconnect conina rc BleAdvertStop PRINT REI EIN o Expected Output BLECHARVALUENOTIFY is an extension function Americas 1 800 492 2320 Option 2 260 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleCharValuelndicate FUNCTION If there is BLE connection this function is used to write new data into the VALUE attribute of a Characteristic so that it can be sent as an indication to the GATT client The characteristic is identified by a composite handle returned by the function BleCharCommit An indication results in an acknowledgement from the client and that will be presented to the smartBASIC application as the EVCHARHVC event BLECHARVALUEINDICATE charHandle attr Returns INTEGER a result code The typical value is OxO000 indicating a successful operation Arguments charHandle byVal charHandle AS INTEGER This is the handle to the characteristic whose value must be updated which was returned when BleCharCommi
115. 128 or BleHandleUuidSibling desclax byVal descldx AS INTEGER This is the instance of the descriptor to look for with the uuid handle charUuidHndl where O is the first instance 1 is the second etc Interactive Command NO Example BleGattcFindDesc sb See in BL600CodeSnippets zip jel Remote server has 5 prim services with 16 bit uuid and 3 with 128 bit uuids 3 of the 16 bit uuid are the same value OxDEAD and 2 of the 128 bit uuids are also the same 112233445566778899AABBCCDDEEFF ae py Seiove ieee vec Using BileGeisucWolmiine Desc Ssulo Linvolmecl im CO Seiiiicio Sick j ising Nordic Ush Dongle PeLv 00d BIM reoeo Colma Unmne uade solo ele ailax lt FUNG TRON VOnstaceue DIM ro alot r adde oo Rp re pileAdvRpEIntt adRpts 2 Oa 0 IF rc 0 THEN rc BleScanRptInit scRpt ENDIF IF rc 0 THEN rc BleAdvRptsCommit adRpts scRpt ENDIF te rc 0 THEN re BleAdvertStart 0 adadrs 50 0 0 ENDIF lopen the gatt client with default notify indicate ring buffer size IF rc 0 THEN re BleGattcOpen 0 0 ENDIF BIDEN yee Americas 1 800 492 2320 Option 2 292 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual SUB Closet onneerions rc BleDisconnect conHnd1 rc BleAdvertStop ENDSUB PUNCTION HndirBleMsg BYVAL nMsgid BYVAL MOX DIM uus unnd unnd uUnndD conkneall nCTtT
116. 2 170 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual FREADUNTIL fileHandle data matchByte maxReadLen Returns INTEGER The actual number of bytes read from the file Will be O if read from end ot file is attempted Arguments fileHandle BYVAL fileHandle AS INTEGER The handle of the file to be read from data BYREF data AS STRING The data read from file is returned in this string matchByte BYVAL matchByte AS INTEGER Read until this matching byte is encountered or the max number of bytes are read Whichever condition is asserted first maxReadLen BYVAL maxReadLen AS INTEGER The max number of bytes to read from the file Interactive Command NO See the full and detailed example in the FOPEN section FREADUNTIL is a core language function FILELEN FUNCTION This function is used determine the total size of the file in bytes FILELEN fileHandle Returns INTEGER The total number of bytes read from the file specified by the handle Will be O if an invalid handle is supplied Arguments fileHandle BYVAL fileHandle AS INTEGER The handle of a file for which the total size is to be returned Interactive Command NO See the full and detailed example in the FOPEN section FILELEN is a core language function Americas 1 800 492 2320 Option 2 171 Laird Technologies Europe 44 1628 858 940 Hong Kong
117. 2 262 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT nFavlure OnStartup ENDIF WALTEVENT rc BleDisconnect conHnd1L rc BleAdvertStop PRINT 4 ollprciie al atop nT Expected Output BLECHARVALUEINDICATE is an extension function BleCharDescRead FUNCTION This function reads the current content of a writable Characteristic Descriptor identified by the two parameters supplied in the EVCHARDESC event message after a Gatt Client writes to It In most cases a local read will be performed when a GATT client writes to a characteristic descriptor attribute The write event will be presented asynchronously to the smartBASIC application in the form of an EVCHARDESC event and so this function will most often be accessed trom the handler that services that event BLECHARDESCREAD charHandle nDescHandle nOffset nLength nDescUuidHandle attr Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation Arguments charHandle byVal charHandle AS INTEGER This is the handle to the characteristic whose descriptor must be read which was returned when BleCharCommit was called and will have been supplied in the EVCHARDESC event message nDescHandle byVal nDescHandle AS INTEGER This is an index into an opaque array of descriptor handles inside the charHandle and will have been suppl
118. 2 342 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Close VSP if already open le Blevspiniro 0 0 THEN BleVSpClose ENDIF Open VSP IF BleVSpOpen 128 128 0 vspSvcHndl 0 THEN PRINT nVSP service opened ELSE PRINT nFailed TEIN IDPS 2 Expected Output VSP service opened BLEVSPOPEN is an extension function BleVSpClose SUBROUTINE This subroutine closes the managed virtual serial port which had been opened with BLEVSPOPEN This routine is safe to call if it is already closed When this subroutine is invoked both receive and transmit buffers are flushed If there is data in either buffer when the port is closed it will be lost BLEVSPCLOSE Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments None Interactive Command No Related Commands BLEVSPINFO BLEVSPOPEN BLEVSPWRITE BLEVSPREAD BLEVSPFLUSH Use the iOS BL600 Serial app and connect to your BL600 to test this sample app Example BleVspClose sb See in BL600CodeSnippets zip DEM E te eek ole r a aR E ac Glise aad nandler when VSP tx buffer is empty FUNCTION HandlerVSpTxEmpty AS INTEGER PRINT n nVise tx butrer empty BleVspClose ENDFUNC 0 PRINT nDevice name is BleGekDeviceNames Open the VSP advertise me Blevspopen 123 128 0 Pnad re BleSc
119. 2 byte values have special meaning Ox0O7FFFFFF NaN Not a Number Ox08000000 NRes Not at this resolution Ox0O7FFFFFE INFINITY Ox08000002 INFINITY Ox08000001 Reserved for future use Americas 1 800 492 2320 Option 2 314 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual nExponent byVal nExponent AS INTEGER This value must be in the range 128 to 127 or the function fails nindex byVal nindex AS INTEGER This is the zero based index into the string attr where the new fragment of data Is written If the string attr is not long enough to accommodate the index plus the length of the fragment it is extended If the extended length exceeds the maximum allowable length of an attribute see SYSINFO 2013 this function fails Interactive Command NO Example BleEncodeFloat sb See in BL600CodeSnippets zip DEM ice DON eieieies 2 she ce Sa NY J wWeilmen 1234567 x 10 54 as FLOAT to index 2 PRINT BleEncoderLOAT attrs 123456 54 0 jjweite 1234567 x 10 1000 as BLOAT to andex 2 and 1 will fail bpecause the exponent is too large it has to be lt 127 IF BleEncodeFLOAT attr 1234567 1000 2 0 THEN PRINT nFailed to encode to FLOAT ENDIF fwrite VLOOOU0UO x LOU as PLOAN tco inde 2 and ae wil ral because the mantissa is too large it has to be lt 8388600 iF BlekncoderLOAT attics 10000000 0 2 1
120. 20 Option 2 150 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual I2ZCREADREG16 nSlaveAddr nRegAddr nRegValue Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments nSlaveAdar byVal nSlaveAdar AS INTEGER This is the address of the slave in range O to 127 nRegAdar byVal nRegAddr AS INTEGER This is the 8 bit start register address in the addressed slave in range 0 to 255 nkegValue byRef nRegValue AS INTEGER The 16 bit value trom two registers in the addressed slave will be returned in this variable Interactive Command No Related Commands I2COPEN I2CCLOSE I2CWRITEREAD I2CWRITEREG8 I2CWRITEREG16 IZCWRITEREG32 IZCREADREGS8 I2CREADREG16 I2CREADREG3S2 Example I2cReadRegl16 sb See in BL600CodeSnippets zip xPlease ensure that nSlaveAddr is the slave address of your I2C peripheral DIM rc handle nSlaveAddr nRegAddr nRegVal Open I2C Peripheral rc I2cOpen 100000 0 handle IE ease 0O THEN PRINT nFailed to open I2C interface with error code INTEGER H rc ELSE PRINT nI2C open success Bit Read value from address 0x34 nSlaveAddr 0x6of nRegAddr 0x34 re I 2cReadRegl6 nSlaveAddr nRegAddr nRegVal ip re O THEN PRINT nFailed to Read from slave register INTEGER H rc ELSE PRINT nValue read from register is nRegVal ENDIF I2c
121. 320 Option 2 39 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual AT FOW filename Returns If the filename is valid AT FOW responds with nOO r Arguments filename String_constant The name of the file to be opened The maximum length of filename is 24 characters and should not include the following characters lt gt This is an Interactive Mode command and MUST be terminated by a carriage return for it to be processed Interactive Command YES Examples AT FOW myapp AT FOW is a core command AT FWR COMMAND AT FWR writes a string to a file that has previously been opened for writing using AT FOW The group of commands AT FOW AT FWR AT FWRH and AT FCL are typically used for downloading Tiles to the module s flash filing system For example web pages x 509 certificates or BLE data AT FWR string Returns If the string is successfully written AT FWR will respond with nOO r Arguments string string_constant A string that is appended to a previously opened file Any NN or r or n characters present within the string are de escaped before they are written to the file This is an Interactive Mode command and MUST be terminated by a carriage return for it to be processed Interactive Command YES Examples AT FWR nhelloworld r AT FWR 00 01 02 AT
122. 55 5 ONEVENT EVBLEMSG CALL HndlrBleMsg OnEvent EVATTRWRITE call HandlerAttrWrite OnE vento EVATTRNOTTEY call HandlerAttrNotify IF OnStartup 0 THEN PRINT nAdvertising and Gatt Client is open n ELSE PRINT nPatlure On o tartup ENDIF WALTEVENT PRINT DELI EIN Expected Output BLEGATTCNOTIFYREAD is an extension function Americas 1 800 492 2320 Option 2 309 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Laird Technologies smart BASIC User Manual Attribute Encoding Functions Data for Characteristics are stored in Value attributes arrays of bytes Multibyte Characteristic Descriptors content is stored similarly Those bytes are manipulated in smart BASIC applications using STRING variables The Bluetooth specification stipulates that multibyte data entities are stored communicated in little endian format and so all data manipulation is done similarly Little endian means that a multibyte data entity will be stored so that lowest significant byte is position at the lowest memory address and likewise when transported the lowest byte will get on the wire first This section describes all the encoding functions which allow those strings to be written to in smaller bytewise subfields in a more efficient manner compared to the generic STRXXXX functions that are made available in smart BASIC Note CCCD and SCCD Descriptors are special cases the
123. 600CodeSnippets zip DEM tae BUNGTTON Shinde acai PRINT A nDaca has arriver ENDFUNC 1 remain blocked in WAILTEVENT FUNCTION Btn0Pressed UartClose ENDFUNC 0 re GPLOBindEvent 0 16 1 M BO BDUETONO ONEVENT EVUARTRX CALL HndlrUartRx ONEVENT EVGPIOCHANO CALL BtnOPressed UartClose Since Uart port is already open we must close it before opening it again with different settings Open Compor Sse Eaat PCD end R are iipurs re UartOpen 9600 0 0 CN81H Open as DOE no parity O databits etorb ee eto tes o a aroa IF cels 0 THEN PRINT nFailed to open UART interface with error code INTEGER H re ELSE PRINT nUART open success LNB IE E PRINT oPress Dubeon0 to exit this applicationn WAITEVENT wait for rx events PRINT nE LETO Expected Output Americas 1 800 492 2320 Option 2 129 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual UARTOPEN is a core function UartClose FUNCTION This subroutine is used to close a uart port which had been opened with UARTOPEN If after the uart is closed a print statement is encountered the uart will be automatically re opened at the default rate 9600N81 so that the data generated by the PRINT statement is sent This routine will throw an exception if the uart is already closed so if you are not sure then it is best to call it
124. 600CodeSnippets zip DIM v v 0 initial the value just in case the key does not exist PRINT NvCfigkKeyGet 100 v PRN ne vy Expected Output O S303 1 NVCFGKEYGET is a module function NvCfgKeySet FUNCTION NVCFGKEYSET writes a value to a pre existing configuration key See AT CFG for a complete list of configuration keys If a key does not exist calling this function will not create a new one The set of configuration keys are created at firmware build time If you wish to create a database of non volatile configuration keys for your own application use the NvRecordSet Get commands NVCFGKEYSET keyld va ue Returns INTEGER An integer result code The most typical value is 0x0000 which indicates a successful operation Exceptions Americas 1 800 492 2320 Option 2 176 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Local Stack Frame Underflow Local Stack Frame Overflow Arguments keyld byVal keyld AS INTEGER The configuration key that is to be read in the range 1 to n where n depends on the specific module and the full list is described for the AT CFG command value byVal value AS INTEGER If the configuration key keyld exists then it is updated with the new value WARNING You should minimise the number of writes as each time a record is changed empty flash is used up The flas
125. 73 Input Output Interface ROUTINES cccccccccccccccccccceceeeceeeeeeeeeeeeeeeeeeseeeeeeseeeeeeeseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeesss 177 ESI ROUINO esnin E E E E A A E E E A 187 6 BLE Extensions BUIN ROUTES cerroensis E aN 190 MAC AOAIE SS sisaria eonia T S S S 190 Events and IV 5S SS aie ciesac cscs ences cccigs esate EE E 190 Miscellaneous FUNCTIONS saiiewsxnsaddauvccesesctonndavesndusasvaibeddbasicantaneuaead dauadsaneaedousabetaealaaat due ddeaitedeeansaaeaedauvansdasabsensdvesadatee 205 PORT ST SIN TUN 11S a cca see vars cesctescetassin os cease ba vena ae oases E ae acca past E EA O A T TEE 208 Connec Hon FUNCHONS sesira aR ante eins itvomn og nc eran tharans E EEE E EEA 219 Security Manager Functions ssessesssesresresseesersresresseesresrresesseosresrroreoseosresreoresseoseesreereoseoseeoreeresseoseesreereeseeseesnee 224 GATIS OO E O E T E E E AEN 228 GATT Clem FUNGOS senise E EAE E A 265 AtibDUte Encoding FUNCIONS sseroeinernn Toes EEN E AE E O T 310 Atrib te Decoding FUNCIONS sa cacaaanscecacanctamaaaaabanataeanacosnadanseieesatsaunasinadaadstuntacaapendeas RA EAE aiia 321 Painne BOndmMe FUNCTION SicccettcecccuntasceesatnencnpieseceatesntecapennrceaseSnceeuieiueeectegate nesesrcactasint seeeastecettenmehuneneceatainemneeantces 335 Virtual Serial Port Service Managed test when dongle and application availbable cccccccssssseeeeeeeeeeeeees 338 7 Other Extension Built in ROUTINES cccccc
126. 8 382 Americas 1 800 492 2320 Option 2 2 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual REVISION HISTORY 1 0 1 1 50 0r3 1 Feb 2013 Initial Release Production Release 3 Apr 2013 Incorporate review comments for JG 15 Apr 2013 24 Apr 2013 Engineering release Esei Engineering release with custom service capability 8 May 2013 12 Jun 2013 53 Engineering release with Virtual Serial Service capability 29 Jun 2013 26 Jul 2013 Production Release 2 99 Engineering release with PWM amp FREQUENCY output 1 2 55 8 8 Aug 2013 Engineering release with VSP Uart Bridging Engineering release with AT CFG command 1 2 55 12 1 3 57 0 12 Aug 2013 29 Aug 2013 Engineering release with sysinfo Engineering release with UartCloseEx 1 4 59 0 1 5 62 0 12 Sep 2013 19 Dec 2013 4 Jan 2014 Engineering release v1 4 59 0 Production release v1 5 62 0 Softdevice 6 0 0 1 5 65 0 24 Feb 2014 Engineering release v1 5 65 0 Softdevice 6 0 0 1 5 66 0 28 Mar 2014 Production release v1 5 66 0 Softdevice 6 0 0 Americas 1 800 492 2320 Option 2 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth 3 Laird Technologies smart BASIC User Manual CONTENTS REVISION HISTO Y oeann anA EE EEEE TEE EE EE EA AAEE ES E EEE
127. 8 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual GpioRead FUNCTION This routine reads the value from a SIO special purpose I O pin The module datasheet will contain a pinout table which will mention SIO Special I O pins and the number designated for that special I O pin corresponds to the nSigNum argument GPIOREAD nSigNum Returns INTEGER the value from the signal If the signal number is invalid then it will return value O For digital pins the value will be O or 1 For ADC pins it will be a value in the range 0 to M where M is the max value based on the bit resolution of the analogue to digital converter Arguments nsigNum byVal nSigNum INTEGER The signal number as stated in the pinout table of the module Interactive Command NO Example GpioRead sb See in BL6O00CodeSnippets zip DIM Signal Signal GpioRead 3 PRINT signal Expected Output GPIOREAD is a Module function GpioWrite SUBROUTINE This routine writes a new value to the GPIO pin If the pin number is invalid nothing happens If the GPIO pin has been configured as a PWM output then the nNewValue specifies a value in the range O to N where N is the max PWM value that will generate a 100 duty cycle output that is a constant high signal and N is a value that is configure using the function GpioConfigP WMO If the GPIO pin has been configured as a FREQUENCY out
128. 8 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Interactive Command NO Example BleEncode8 amp sb See in BL600CodeSnippets zip DIME DIM attics attrs Laird PRINT natero arrrs Remember 4 bytes are used to store an integer on the BL600 WLES VC so wadex 2 ih well be ignored rc BleEncode8 attrS 0x11143 2 p w TAr co index 0 rc BleEncodes artro 0x41 0 write B to index 1 rc BleEncodes attrS 0x42 1 j fwcice TD to index 3 rc BleEncodes artro 0x44 3 j weite 7 to index 7 attr will be extended rc BleEncodes attrS 0x6o 7 7 PRIMI Y narccrceS now Yr attreS Expected Output attrS Laird attrS now ABCDd 00 00g BLEENCODES Is an extension function BleEncode16 FUNCTION This function overwrites two bytes in a string at a specified offset If the string is not long enough then it is extended with the new extended block uninitialized and then the bytes specitied are overwritten If the nindex is such that the new string length exceeds the maximum attribute length this function fails The maximum attribute length can be obtained using the function SYSINFO n where n is 2013 The Bluetooth specification allows a length between 1 and 512 BLEENCODE16 attr nData nlndex Returns INTEGER a result code The typical value is OxO000 indicating a successful operation Arguments attr b
129. 803 for characteristics Basically a table should be scanned trom top to bottom and the specification stipulates that the 16 bit handle field SHALL contain values in the range 1 to 65535 and SHALL be in ascending order and gaps are allowed When scanning if a row is encountered with the value 0x2800 or 0x2801 in the Type column then it SHALL be understood as the start of a primary or secondary service which in turn SHALL contain at least one charactestic or one included service which have Type 0x2803 and Ox2802 respectively When a row with Type 0x2803 a characteristic is encountered then the next row shall contain the value for that characteristic and then after that there may be O or more descriptors This means each characteristic shall consist of at least 2 rows in the table and if descriptors exist for that characteristic then a single row per descriptor Ox0002 Ox2803 Properties Value Handle Value UUID1 Characteristic 1 Start Ox0003 Value UVID1 Value 1 to 512 bytes Actual data 0x0004 0x2803 Properties Value Handle Value UUID2 Characteristic 2 Start 0x0005 Value UUID2 Value 1 to 512 bytes Actual data 0x0006 0x2902 Value 0x0007 0x2903 Value Descriptor 1 CCCD Descriptor 2 SCCD Characteristic 1 Start Actual data Ox2803 Properties Value Handle Value UUID3 Value UUID3 Value 1 to 512 bytes Ox0009 Ox000A Id Jv iv JL Characteristic 3 Start Actual data
130. AADCUDE Data at location Ux01s0 is DEADBEEF Data at location 0x0184 is BAADCODEFFFFFFFF SpiClose SUBROUTINE This subroutine is used to close a SPI port which had been opened with SPIOPEN This routine is safe to call if it is already closed SPICLOSE handle Exceptions Local Stack Frame Underflow Americas 1 800 492 2320 Option 2 159 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Local Stack Frame Overflow Arguments handle byVal handle AS INTEGER This is the handle value that was returned when SPIOPEN was called which identifies the SPI interface to close Interactive Command No Related Commands SPICLOSE SPIREADWARITE SPIWRITE SPIREAD Example See SpiExample sb SPICLOSE is a core subroutine SpiReadWrite FUNCTION This function is used to write data to a SPI slave and at the same time read the same number of bytes back Every 8 clock pulses result in one byte being written and one being read Note a handle parameter is NOT required as this function is used to interact with the main interface In the future a new version of this function will be made available if more than one SPI interface is made available SPIREADWRITE stWrite stRead Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Returns INTEGER a result code The typical value is 0x0000
131. Adverts Started New Connection 2915 Connection 2915 Closed 0x19 EVCHARVAL This event is thrown when a characteristic has been written to by a remote GATT client It comes with three parametera which are the characteristic handle that was returned when the characteristic was registered using the function BleCharCommit the Offset and Length of the data from the characteristic value Example EvCharVal sb See in BL600CodeSnippets zip DIM hiMy Chiat We aes Connal DUNC ROh On sik cist tien DIM Te UaSve a En gt siclvots eiclcles SRE siowies aa Americas 1 800 492 2320 Option 2 194 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual commit service rc BleSvcCommit 1 BleHandleUuidl 0x18EE hnSvc initialise char write read enabled accept signed writes rc BleCharNew 0x0A BleHandleUuidl16 1 BleAttrMetaData 1 1 20 0 rc 0 0 J Commits char initialised above with initial value hi to service hSvc rc BleCharCommit hSvc attrs hMyChar rc BleScanRptInit scRpt Add 1 service handle to scan report V7 eC Plean Ror hoduutalG sehobe aane a a n l commit reports to GATT table adRpt is empty rc BleAdvRptsCommit adRpt scRpts rc BleAdvertStart 0 addrS 20 300000 0 BNDPUNC re SUB CloseConnections rc BleDisconnect conHnd1 rc BleAdvertStop ENDSUB PUNGTION tin
132. Allowed but not recommended practice as there is a at end of name DIM temp6 AS STRING Allowed but not recommended practice as no at end of name DIM ab azador 3 INTEGER variables and 1 STRING variable print We will now print each varaible on screen n print Cemp tenp TeijosS tenplo tenpo memos al a2 acs ad Since the variables have not been instantiated they hold default values The comma inserts a TAB Expected Output We will now print each varaible on screen O 0 0 0 CO Americas 1 800 492 2320 Option 2 52 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Variable Scope The scope of a variable defines where it can be used within an application Local Variable The most restricted scope These are used within functions or subroutines and are only valid within the function or subroutine They are declared within the function or subroutine Global Variable Any variables not declared in the body of a subroutine or a function and are valid from the place they are declared within an application Global Variables remain in scope at the end of an application which allows the user or host processor to interrogate and modity them using the and commands respectively As soon as a new application is run they are discarded Note Ifa local variable has the same name as a global variable
133. Andata am Hex Ux INTEGER A vl PRINT Y ndata in Decimal ey et a read unsigned byte from index 6 rc BleDecodeU8 attr v1 6 PRINT Andata in Hex O0 INTEGER Hall Ranh ee Waele ac in Decimal ety Ie aa Expected Output BLEDECODEU8 is an extension function BleDecodeS16 FUNCTION This function reads two bytes in a string at a specified offset into a 32bit integer variable with sign extension If the offset points beyond the end of the string then this function fails BLEDECODES16 attr nData nindex Returns INTEGER the number of bytes extracted from the attribute string Can be less than the size expected if the nindex parameter is positioned towards the end of the string Arguments attr byRef atir AS STRING This references the attribute string from which the function reads nData byRef nData AS INTEGER This references an integer to be updated with the 2 byte data from attr after sign extension nindex byVal nindex AS INTEGER This is the zero based index into the string attr from which data Is read If the string attr is not long enough to accommodate the index plus the number of bytes to read this function fails Interactive Command NO Example BleDecodeS16 sb See in BL600CodeSnippets zip DIM ehrhende vi sychandle re DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc DUM atheros eireao 00 Ol 0203 0485 Vaio 87 a3 389 DIEM Sb bel Ss OSO rc BleSvcCommit 1 BleHandleUuidl6
134. Assuming there is a connection and indicate has been enabled then a value indication is expedited as follows Li indicate a value for characteristic 2 in service I This handler is called when there is a EVCHARHVC message FUNCTION HandlerCharHvec BYVAL hChar AS INTEGER AS INTEGER IF hChar hCharl2 THEN PRINT Svcl Char2 indicate has been confirmed EN Dale ENDEUNC enable characteristic value indicacion contem hnandler Onkvene EVCHARHVE CALG handle nehachve attrS somevalue rc BleCharValueIndicate hCharl2 attr The rest of this section details all the smartBASIC functions that help create that framework Events amp Messages Americas 1 800 492 2320 Option 2 233 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual See also Events amp Messages for the messages that are thrown to the application which are related to the generic characteristics API The relevant messages are those that start with EVCHARxxx BleGapSvcinit FUNCTION This function updates the GAP service which is mandatory for all approved devices to expose with the information provided If it is not called before adverts are started default values are exposed Given this is a mandatory service unlike other services which need to be registered this one must only be initialised as the underlying BLE stack unconditionally registers it when s
135. C0 THEN PRINT nFailed to encode to FLOAT ENDIF Expected Output 0 Failed to encode to FLOAT Failed to encode to FLOAT BLEENCODEFLOAT is an extension function BleEncodeSFLOATEX FUNCTION This function overwrites two bytes in a string at a specified offset as short 16 bit float value If the string is not long enough it is extended with the extended block uninitialized Then the bytes are overwritten If the nindex is such that the new string length exceeds the maximum attribute length this function fails The maximum attribute length can be obtained using the function SYSINFO n where n is 2013 The Bluetooth specification allows a length between 1 and 512 BLEENCODESFLOATEX attr nData nindex Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation Arguments Americas 1 800 492 2320 Option 2 315 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual attr byRef attr AS STRING This argument is the string that will be written to an attribute nData byVal nData AS INTEGER The 32 bit value is converted into a 2 byte IEEE 11073 16 bit SFLOAT consisting of a 12 bit signed mantissa and a 4 bit signed exponent This means a signed 32 bit value always fits in such a FLOAT enitity but there will be a loss in significance to 12 from 32 nindex byVal nindex AS INTEGER This is the
136. CALL HndirTmro ONEVENT EVUARTRX CALC EANd rU tR PRINT nWhat is your name n WALTEVENT Americas 1 800 492 2320 Option 2 136 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output What is your name David Your Name is David UARTREAD is a core subroutine UartReadN FUNCTION This function is used to read the content of the receive buffer and append it to the string variable supplied but it ensures that the string is not longer than nMaxLen UARTREADN strMsg nMaxLen Returns INTEGER Oto N The total length of the string variable not just what got appended This means the caller does not need to call strlen function to determine how many bytes in the string that need to be processed Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Uart has not been opened using UARTOPENxxx Arguments strMsg byRef strMsg AS STRING The content of the receive buffer will get appended to this string nMaxLen byval nMaxlen AS INTEGER The output string strMsg will never be longer than this value If a value less than 1 is specified it will be clipped to 1 and if gt that OxFFFF it will be clipped to OxFFFF Interactive Command No Note strMsg cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it
137. CHARHVC charHandle See example that is provided for EVCHARCCCD EVCHARCCCD This event is thrown when the client writes to the CCCD descriptor of a characteristic It comes with two parameters the first is the characteristic handle returned when the characteristic was registered with BleCharCommit and the second is the new 16 bit value in the updated CCCD attribute Example BEvCharCecd so See in BEe00Codesnippets zip DIM NMyChar ro alor C Oia hme FUNCTION OnStartup DIM re hoyo me tdouecee or aE ae ado ada e aE Americas 1 800 492 2320 Option 2 196 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual ait eo hw DIM svcUuid svcUuid 0xI8EE DIM CGharUurd 3 charUurad BlenHandlevuuidils6 1 DIM charMet charMet BleAttrMetaData 1 1 20 0 metaSuccess DIM hSvcUuid hSvcUuid Blentandlevuidls6 svcUuid DIM mdeecde macCced sbleArrriicradara i i 2 0 16 J CCCD metadata for char Commit Sve with handle ASveuuad Fe BlesveCconmit 1L bSoveclnid hove initialise char write read enabled accept signed writes indicatable rc BleCharNew 0x6A charUuid charMet mdCccd 0 commit Char initialised above with initial value hi to service rc BleCharCommit hSvc attrs hMyChar re PilescankoOr Init SCRpES Add 1 service handle to scan report POEP LeNeh ROCA UU elle Sesioe
138. Chari 2 handles tor chacacrcerLsrcLie l of Seryice 2 DIM NUCO handles for uuid of Service 1 DIM HUNdo I handles for ouid Gf Service 2 DIM hUitaCiIIT S77 handles Ffor uuid or C hara teris iie lin services DIM hUltdel2 77 handles for Wad of characteristic 2 in Scervice l DIM AUNI Ia handles for uuid of characteristic lim Service Register Service 1 hUuidSl1 BleHandleUuidl6 0x180D Pee ble oveC Om me gt hi ol CHE TMAR E lease Reqister Characteristic l in Service il mdAttr BleAttrMetadata BLE ATTR ACCESS OPEN BLE ATTR ACCESS TORE O OT mdCccd BLE CHAR METADATA ATTR NOT PRESENT mdSccd BLE CHAR METADATA ATTR NOT PRESENT chProp BLE CHART PROPERTIES READ BERT CHAR PROPERTIES WRITE hUuidC1l1l BleHandleUuidl6 0x2A37 re BleCharlew cheroo NUurd ik mdai ma ecd masece re BleCharComnre shhrs hrs hChari j 7 Register Characteristic 2 an Service i mdAttr BleAttrMetadata BLE ATIR ACCESS OPEN BLE ATTR ACCESS OPEN 10 0 rc MAC CCE Pletrervevedava BTE alin Cero OEN BTE TATIR TAC En OREN 27 0 Ee mdSccd BLE CHAR METADATA ATTR NOT PRESENT chProp BELE WC aba TPROPER MIES EN DAL C 2 ue hUuidCl12 BleHandleUuidl6 0x2A39 me BleCharNew cheroo hUumdCiZ2 mdArcir mdCccd mdsccd attrs 00 00 ro BleCharcoml b nSve dukro meharZ l Register Service 2 can now reuse the service handle hUuidS2 BleHandleUuidl6 0x1856 fee gt hea Ve Conner B TER ER CETER INAR a seiUU
139. Close handle close the port Expected Output a I2C open success Value read from register is 16912 IZCREADREG16 is a core function Americas 1 800 492 2320 Option 2 151 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual I2cWriteREG32 SUBROUTINE Note For firmware releases older than 1 2 54 4 there is an issue where some 2C slaves are not able to drive the ACK down to a low enough voltage level for the module to recognise it as an ACK This is a result of a bug in the BL600 s I2C driver which results in the SDA line not being released by the module This has been corrected in release 1 2 54 4 and the firmware is available as a uart download on request You should upgrade the firmware if you have an I2C slave not responding to the correct slave address This function is used to write a 32 bit value to 4 registers inside a slave and the first register is identified by an 8 bit register address supplied Note a handle parameter is NOT required as this function is used to interact with the main interface In the future a new version of this function will be made available if more than one 2C interface is made available most likely made available by bit bashing gpio I2CWRITEREG32 nSlaveAddr nRegAddr nRegValue Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments nSlaveA
140. Command No Related Commands I2COPEN I2CCLOSE I2CWRITEREAD I2CWRITEREG8 I2CWRITEREG16 IZCWRITEREG32 IZCREADREGS8 I2CREADREG16 I2CREADREGS2 Example I2cReadREG32 sb See in BL600CodeSnippets zip Americas 1 800 492 2320 Option 2 153 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Please ensure that nSlaveAddr is the slave address of your I2C peripheral DIM handle DIM nSlaveAddr nRegAddr nRegVal DIM rc re 1ZcOpen 100000 0 handle IF cols 0 THEN PRINT nFailed to open I2C interface with error code INTEGER h rc ELSE PRINT niZze open success ENDILE Read value from address 0x56 nSlaveAddr Ox6f nRegAddr 0x56 rc I 2cReadReg32 nSlaveAddr nRegAddr nRegVal IF ace O THEN PRINT nFailed to read from slave register ELSE PRINT nValue read from register is nRegVal ENDIE I2cClose handle close the port Expected Output I2C open success Value read from register is 1108410076 IZCREADREG16 is a core function I2cWriteRead SUBROUTINE Note For firmware releases older than 1 2 54 4 there is an issue where some 12C slaves are not able to drive the ACK down to a low enough voltage level for the module to recognise it as an ACK This is a result of a bug in the BL600 s I2C driver which results in the SDA line not being released by the module T
141. E module to stop advertising BLEADVERTSTOP Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments None Interactive Command NO Example BleAdvertStop sb See in BL6O00CodeSnippets zip DIM addr addr o DIMENGE HUNGAONE EC e O O PRINT nAdvert stopped via timeout PRU nat imo ENDFUNC 0 FUNCTION BtnOPress IF BleAdvertStop 0 THEN PRINT nAdvertising Stopped BSE Americas 1 800 492 2320 Option 2 210 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT n nAdvertising failed to stop ENDIF ASIEN Aout canis awiave Bee al BKNDFUNC TO iP BleAdvVercstart Opaddrs 25 60000 0 0 THEN PRINT V nAdverts Starced Press button 0 vo Stop n Pili PRINT n nAdvertisement not successful ENDIF me Goreosereume 0 1 2 ro Gorobrndh yen 0 16 15 ONEVENT TE Ve Od TAD TEINE OUT RCA LETE B r A EmO ONEVENT EVGPIOCHANO CALL BtnOPress WAT TEVENT Expected Output Adverts Started Press button 0 to stop Advertising Stopped ip I me BY al sa BLEADVERTSTOP is an extension function BleAdvRptlinit FUNCTION This function is used to create and initialise an advert report with a minimal set of ADs advertising records and store it the string specified It will not be advertised until BLEADVRPTSCOMMIT is called
142. E related event has occurred and it does so by throwing this message as opposed to an EVENT which is akin to an interrupt and has no context or queue associated with it The message contains two parameters The first parameter to be called msgID subsequently identifies what event was triggered and the second parameter to be called msgCtx subsequently conveys some context data associated with that event The s martBASIC application will have to register a handler function which takes two integer arguments to be able to receive and process this message Note The messaging subsystem unlike the event subsystem has a queue associated with it and unless that queue is Tull will pend all messages until they are handled Only messages that have handlers associated with them will get inserted into the queue This is to prevent messages that will not get handled trom filling that queue The list of triggers and associated context parameter follows A connection has been established and msgCtx is the connection handle A disconnection event and msgCtx identifies the handle Immediate Alert Service Alert The 2 parameter contains new alert level Link Loss Alert The 2 parameter contains new alert level A BLE Service Error The 2 parameter contains the error code Thermometer Client Characteristic Descriptor value has changed Indication enable state and msgCtx contains new value O for disabled 1 for enabled UW eIwWIN gt O Am
143. ED BLE HCI SCO INTERVAL REJECTED BLE HCI SCO AIR MODE REJECTED BLE HCI STATUS CODE INVALID LMP PARAMETERS BLE HCI STATUS CODE UNSPECIFIED ERROR BLE HCI UNSUPPORTED LMP PARM VALUE BLE HCI ROLE CHANGE NOT ALLOWED BLE HCI STATUS CODE LMP RESPONSE TIMEOUT BLE HCI LMP ERROR TRANSACTION COLLISION BLE HCI STATUS CODE LMP PDU NOT ALLOWED BLE HCI ENCRYPTION MODE NOT ALLOWED BLE HCI LINK KEY CAN NOT BE CHANGED BLE HCI REQUESTED QOS NOT SUPPORTED BLE HCI INSTANT PASSED BLE HCI PAIRING WITH UNIT KEY UNSUPPORTED BLE HCI DIFFERENT TRANSACTION COLLISION Americas 1 800 492 2320 Option 2 357 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth 0x00 0x01 0x02 0x03 Ox04 0x05 0x06 0x07 0x08 0x09 OxO0A OxO0B 0x0C OxOD Ox0F OxOF Ox10 0x11 0x12 0x13 0x14 0x15 0x16 xL 0x18 0x19 0x1A Ox1B JXIC Ox1lD Ox1E Ox1F 0x20 Ox21 0x22 UX 23 0x24 0x25 0x26 0x27 0x28 0x29 0x2A Laird Technologies smart BASIC User Manual BLE HCI QOS UNACCEPTABLE PARAMETER Ox2C BLE HCI QOS REJECTED Ox2D BLE HC I CHANNEL CLASS il FICATION UNSUPPORTED Ox2E BLE HCL INSUFFICIENT SECURITY Ox2F BLE HCI PARAMETER OUT OF MANDATORY RANGE 0x30 BLE HCI ROLE SWITCH PENDING 0x32 BLE HCI RESERVED SLOT VIOLATION 0x34 BLE HCI ROLE SWITCH FAILED 0x35 BLE HCI EXTENDED INQUIRY RESP TOO LARGE 0x36 BLE HCI SSP_NOT SUPPORTED BY HOST Ox BLE HCI HOST BUS
144. EG16 I2CREADREG32 Example I2cWriteReg8 sb See in BL600CodeSnippets zip xPlease ensure that nSlaveAddr is the slave address of your I2C peripheral DIM rc handle nSlaveAddr nRegAddr nRegVal I Open 12C Peripheral rc I2cOpen 100000 0 handle IFP ccls O THEN PRINT nFailed to open I2C interface with error code INTEGER H rc ELSE PRINT nI2C open success EADIE Write nRegVal to register nRegAddr nSlaveAddr 0xef mnRegAddr 23 nRegVal 0x63 re I2cWriteReg8 nSlaveAddr nRegAddr nRegVal IFP ee O THEN PRINT A nFfailed to Write to slave register gt INTEGER H rc ELSE PRINT n nReqVval gt written Ssuccesstully to register nRegAddr ENDL I2cClose handle close the port Expected Output M eee I2C open success 99 written successfully to register 23 IZCWRITEREG8 is a core function Americas 1 800 492 2320 Option 2 147 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual I2cReadREG8 SUBROUTINE Note For firmware releases older than 1 2 54 4 there is an issue where some 2C slaves are not able to drive the ACK down to a low enough voltage level for the module to recognise it as an ACK This is a result of a bug in the BL600 s I2C driver which results in the SDA line not being released by the module This has been corrected in release 1 2 54 4 and the firmwa
145. EGER H nADTag is Wo Sitbnexizes ADvals ELSE PRINT Y nError reading AD gt INTEGER Hre LNB IE IE Will fail because there are only 2 AD elements rc BleGetADbyIndex 2 fullADS nADTag ADval IF rc 0 THEN Americas 1 800 492 2320 Option 2 216 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT nlhard AD element with tag 0x INTEGER A nADlag is Wo StrHexLzes ADvals ELSE PROM AAR ror reading AD T TECER iro TS NIB HIE IE Expected Output BLEGETADBYINDEX is an extension function BleGetADbyTag FUNCTION This function is used to extract a copy of the first advertising data AD element that has the tag byte specitied trom a string which is assumed to contain the data portion of an advert report Incoming or outgoing If multiple instances of that AD tag type are suspected then use the function BleGetADbylndex to extract Please not that if the last AD element is malformed then it will be treated as not existing For example it will be malformed if the length byte for that AD element suggests that more data bytes are required than actually exist in the report string BLEGETADBYTAG rptData nADtag ADval Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments rotData byREF sotData AS STRING This parameter is a string tha
146. EN re BleSeankpe Inte SCReES ENDIF IF rc 0 THEN rc BleAdvRptsCommit adRpt s scRpt ENDIF if re 0 TREN re pleAdvertstarce O7addrs 50 0 0 a open the gatt client with default notify indicate ring buffer size IF rc 0 THEN re BleGattcOpen 0 0 ENDIF ENDERUN CEE SUB Closee onmecri ems rc BleDisconnect conHnd1 rc BleAdvertStop INVES Uns Americas 1 800 492 2320 Option 2 304 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx DIM uHndA conHndl nCtx IF nMsgID 1 THEN PRINT n n Disconnected EXITFUNC Q ELSEIF nMsgID 0 THEN PRINT n Connected so write to attribute handle 3 atHndl 3 aro VO O72 0s 04 rc BleGattcWriteCmd conHndl atHndl at IF rc 0 THEN WALITEVENT BENIDE PRINT n write again to attribute handle 3 atHndl 3 deo 05 06 07 Oe rc BleGattcWriteCmd conHndl atHndl atS IF rc 0 THEN WALILTEVENT ENDL PRINT An write aga n to aren bute handle 3 atHndl 3 atS 09 0A 0B 0C rc BleGattcWriteCmd conHndl atHndl at IF rc 0 THEN WALTEVENT AND tS PRINT nwrite to attribute handle 300 which does not exist atHndl 300 rc BleGattcWriteCmd conHndl atHndl at IF rc 0 THEN PRINT nEven when the attribute does not exist an event will occur WALTEVENT END CleseConmeceions ENDIF ENBDE UNG 1
147. ER This is the connection handle as returned in the on connect event for the connection on which the remote Gatt Server can be accessed This will have been returned in the EVBLEMSG event message with msgld 0 and msgCtx will have been the connection handle attrHnal byRef attrHnal AS INTEGER The handle for the attribute that was read is returned in this variable Will be the same as the one supplied in BleGattcRead but supplied here so that the code can be stateless offset byRef offset AS INTEGER The offset into the attribute data that was read is returned in this variable Will be the Americas 1 800 492 2320 Option 2 296 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual same as the one supplied in BleGattcRead but supplied here so that the code can be stateless attrData byRef attrData AS STRING The attribute data which was read is supplied in this parameter Interactive Command NO Example BleGattcRead sb See in BL600CodeSnippets zip a Remote server has 3 prim services with 16 bit uuid First service has one characteristic whose value attribute is at handle 3 and has read write props fi O Denner serene 1G il Caere lone euo a oel a Ope ml leper j 7 srg Nordic Uch Dongle C1 00Ge Dil Macro eon Glee And nOr e a A PUNETICN POnseaneue DIM ror adROC cldciacrens Ckpibe re BleAdvepeInit adkp
148. ESENCRYPT is a core language function AesDecrypt FUNCTION This function is used to decrypt a string of exactly 16 bytes using the context that was precreated using the most recent call of the function AesSetKeylv Americas 1 800 492 2320 Option 2 164 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual For all modes AesSetKeylV is called only once which means in CBC mode the cyclic data is kept in the context object that was created by AesSetKeylV On the BL600 which does not have AES 128 decryption hardware assist the function has been timed to take roughly 570 microseconds AESDECRYPT inData outData Returns INTEGER Will be 0x0000 if the data was decrypted successfully Otherwise an appropriate resultcode will be returned which will convey the reason it failed ALWAYS check this Arguments inData BYREF inData AS STRING This string MUST be eactly 16 bytes long and should contain the data to decrypt outData BYREF outData AS STRING On exit if the function was successful then this string will contain the decrypted plaintext data If unsuccessful then string will be O bytes long Interactive Command NO Example AesDecrypt sb See in BL600CodeSnippets zip DIM keys initvector gt DIM anbara o oUr Data e a oi DINERS Create context for CBC mode 128 bit keyS 00 01 02 03 04 05 06 07 08 09 0A OB OC
149. Event FUNCTION This routine unbinds the runtime engine event from a level transition bound using GpioBindEvent GPIOUNBINDEVENT n ventNum Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments nEventNum byVal nEventNum INTEGER The GPIO event number in the range of 0 N which will be disabled so that it no longer generates run time events in smart BASIC Interactive Command NO Example GpioUnbindEvent sb See in BL600CodeSnippets zip FUNCTION BtnOPress PRINT nnel lo ENDE UNG i FUNCTION TmrOTimedOut PRINT nNothing happened ENDFUNC 0 PRIN CproBIindEvent 0 Vo Vi ONEVENT EVGPIOCHANO CALL BtnOPress ONEVENT EVTMRO CALL TmrOTimedOut PRINT GpioUnbindEvent 0 n PRINT Press butcon On TimersScart 0 8000 0 WAL TEVEN Expected Output GPIOUNBINDEVENT is a Module function Americas 1 800 492 2320 Option 2 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth 184 Laird Technologies smart BASIC User Manual GpioAssignEvent FUNCTION This routine assigns an event to a level transition on a specified special I O line configured as a digital input Changes in the input line can invoke a handler in smart BASIC user code Note In the BL600 this function results in around 4uA of continuous current consumption from the power supply It is impossible to
150. Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments string byRef string AS STRING The string to be converted in situ If a parsing error occurs a nonfatal error is generated which must be handled or the application aborts Note string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Interactive Command NO Americas 1 800 492 2320 Option 2 94 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Example StrDehexizeS sb See in BL600CodeSnippets zip DIMMs ou sco 204A 7A BRINETE Yndie cdarcas oss PRN AA a De ne n ae A e Dea aaa ss AAW Etoo ar First nom mex digiti s 4041he1l104243 PRINT n s Dehexized StrDehexizeS sS Expected Output Hex data 40414243 Dehexized GABC 4041hel104243 Dehexized A STRDEHEXIZE is a core function STRHEX2BIN This function is used to convert up to 2 hexadecimal characters at an offset in the input string into an integer value in the range O to 255 STRHEX2BIN string offset Function Returns INTEGER A value in the range O to 255 which corresponds to the up to 2 hex characters at the specified offset in the input string Exceptions Local Stack Frame Underflow
151. F nVal amp 0x02 THEN PRINT nIndications have been enabled by client valueS hello IF BleCharValueIndicate hMyChar values 0 THEN PRINT nFailed to indicate new value BENDI E ELSE PRINT nIndications have been disabled by client ENDIF BLSE PRINT nihis 2S for some other characteristic BENDI E ENDEUIC a ONEVENT EVBLEMSG CALL HndlrBleMsg ONEVENT EVCHARHVC CALL PndlrCharHyc ONE VENT 22 VCHARCCED T CALC Hndilreharcecd ONEVENT EVGPIOCHAN CALL HndleBenvrr IF OnStartup 0 THEN re BleCharValueRead hMyChar at PRINT neheracteristie Valie ears PRINT Vnrou can write bo Ene CCCD characterise c Y PRINT nThe BL6OO will then indicate a new characteristic value n PRINT nPress button 0 to exit ELSE PRINT nrailure OnsStartup ENDIF WAL TEVENT PRINTE ENG on EVCHARSCCD This event is thrown when the client writes to the SCCD descriptor of a characteristic It comes with two parameters the first is the characteristic handle that was returned when the characteristic was registered using the function BleCharCommitQand the second is the new 16 bit value in the updated SCCD attribute The SCCD is used to manage broadcasts of characteristic values Example EvCharSccd sb See in BL600CodeSnippets zip Americas 1 800 492 2320 Option 2 198 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Man
152. FUNC arithemetic_expression_or_string_expression A function MUST be defined before the first instance of its being called It is good practice to define subroutines and functions at the beginning of an application immediately after variable declarations A typical example of a function block would be FUNCTION somename argl AS INTEGER arg2 AS STRING AS INTEGER DIM S AS INTEGER S argl IF argl 0 THEN EXITFUNC arg1 2 ENDIF ENDFUNC argl 4 Defining the routine name The function name can be any valid name that is not already in use The return variable is always passed as byVal and shall be of type varType Return values are defined within zero or more optional EXITFUNC statements and ENDFUNC is used to mark the end of the block of statements belonging to the function Defining the return value The variable type AS varType for the function may be explicitly stated as one of INTEGER or STRING prior to the routine name If it is omitted then the type is derived in the same manner as in the DIM statement for declaring variables Hence if function name ends with the character then the type will be a STRING Otherwise it is an INTEGER Since functions return a value when used they must appear on the right hand side of an expression statement or within a index for a variable This is because the value has to be used up so that the underlying expression evaluation stack does not have orphaned values left on it
153. Free Space Americas 1 800 492 2320 Option 2 T1 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual 603 Flash File System Data Segment Deleted Space 611 Flash File System FAT Segment Total Space 612 Flash File System FAT Segment Free Space 613 Flash File System FAT Segment Deleted Space 631 NvRecord Memory Store Segment Total Space 632 NvRecord Memory Store Segment Free Space 633 NvRecord Memory Store Segment Deleted Space 1000 BASIC compiler HASH value as a 32 bit decimal value 1001 How RAND generates values O for PRNG and 1 for hardware assist 1002 Minimum baudrate 1003 Maximum baudrate 1004 Maximum STRING size 1005 Will be 1 for run time only implementation 3 for compiler included 2000 Reset Reason 8 Self Reset due to Flash Erase 9 ATZ 10 Self Reset due to smart BASIC app invoking function RESET 2002 Timer resolution in microseconds 2003 Number of timers available in a smart BASIC Application 2004 Tick timer resolution in microseconds 2005 LMP Version number for BT 4 0 spec 2006 LMP Sub Version number 2007 Chipset Company ID allocated by BT SIG 2008 Returns the current TX power setting see also 2018 2009 Number of devices in trusted device database 2010 Number of devices in trusted device database with IRK 2011 Number of devices in trusted device database with CSRK 2012 Max number of devices that can be stor
154. GER Valid range 0 to 255 The format specifies how the data in the Value attribute is structured A list of valid values for this argument is found at http developer bluetooth org gatt Pages FormatTypes aspx and the enumeration is described in the BT 4 0 spec section 3 3 3 5 2 At the time of writing the enumeration list is as follows 0x00 RFU 0x01 boolean 0x02 2bit 0x03 nibble 0x04 uint8 0x05 uint12 0x06 uint16 0x07 uint24 0x08 uint32 0x09 uint48 Ox0A uint64 OxOB uint128 OxOC sint8 OxOD sint12 OxOE sint16 OxOF sint24 0x10 sint32 0x11 sint48 0x12 sint64 0x13 sint128 0x14 float32 0x15 float64 0x16 SFLOAT 0x17 FLOAT 0x18 duint16 0x19 utf8s 0x1A utf16s Ox1B struct Ox1C OxFF RFU nExponent byVal nExponent AS INTEGER Valid range 128 to 127 This value is used with integer data types given by the enumeration in nFormat to further quality the value so that the actual value Is actual value Characteristic Value 10 to the power of nExponent nUnit byVal nUnit AS INTEGER Valid range 0 to 65535 This value is a 16 bit UUID used as an enumeration to specify the units which are listed in the Assigned Numbers document published by the Bluetooth SIG found at http developer bluetooth org gatt units Pages default aspx nNameSpace byVal nNameSpace AS INTEGER Valid range O to 255 The value identifies the organization defined in the Assigned Numbers document published by the Bluetooth SIG found at https developer blue
155. GETCTS VARTGETDCD UARTGETRI UARTSETDTR UARTSETRTS UARTSETDCD UARTSETRI VARTBREAK UARTFLUSH Example UartReadMatch sb See in BL600CodeSnippets zip DIM ee ycres vet char stro ret 1 PUNncrion return value char 13 ASCII decimal value for carriage return stro yYour Mame as Sere TAn iMac character a5 ot found NExteungg PUNCT LON Ancliaviairrks lt TimerSstart 0 10 0 j Pillow time for data to roach rx butter EN DEUNG oi BUNGE ION tind Termin rc UartReadMatch stro char PRINT Vn sers IF rc 0 THEN h StroetChr SerZ gt o Char 19 7 linsert Teha the match Character PRINT stieZs Seren nMerch character nob found hiring recet sirZs ret 0 SE PRINT n n nNow type something without the letter a n strS You sent reset strs char 97 ASCII decimal value for a ret 1 ENDIF EN DRUNG cer ONEVENT EVTMRO CALL Andi Imro ONEVENT EVUARTRX CALL HndlrUartRx PRINT nWhat is your name n VAT rei Americas 1 800 492 2320 Option 2 139 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output UARTREADMATCH is a core subroutine UartFlush SUBROUTINE This subroutine is used to flush either or both receive and transmit ring buffers This is useful when for example you have a character terminated messaging system and the peer sends a very long me
156. Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual UartRead FUNCTION This function is used to read the content of the receive buffer and append it to the string variable supplied UARTREAD strMsg Returns INTEGER O to N The total length of the string variable not just what got appended This means the caller does not need to call strlen function to determine how many bytes in the string that need to be processed Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Uart has not been opened using UARTOPENxxx Arguments strMsg byRef strMsg AS STRING The content of the receive buffer will get appended to this string Interactive Command No Note strMsg cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Related Commands UARTOPEN UARTINFO UARTCLOSE UARTWRITE VARTREADMATCH UARTGETDSR UARTGETCTS UARTGETDCD UARTGETRI UARTSETDTR UARTSETRTS UARTSETDCD UARTSETRI UARTBREAK UARTFLUSH Example UartRead sb See in BL600CodeSnippets zip DIM Mae ys Pr Lengt sei stEeS Your name ins a HUNGMLONMEMCO RE kaim r otarre 07 r000 Allow enough time for data to reach rx buffer ENDFUNC 1 PUNCT TO bimcile iimic0 strLength UartRead str PRINT Yne strs ENDFUNC 0 ONEVENT EVTMRO
157. I A smartBASIC run time engine Program accessible flash memory which contains a robust flash file system exposing a conventional file system and a database for storing user configuration data Voltage regulators and brown out detectors Americas 1 800 492 2320 Option 2 T Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual For simple end devices these modules can completely replace an embedded processing system The following block diagram Figure 1 illustrates the structure of the BLE smartBASIC module trom a hardware perspective on the left and a firmware software perspective on the right 44 connection pads User smarfBASIC Application Example App 256K Flash 16K RAM ARM Cortex MO smartBASIC smartBASIC run time engine provides safe access to BLE stack drivers and non vol stores 2 2 A A n G N cc lt 5 Q BLE Radio Internal on Figure 1 BLE smart BASIC module block diagram Bluetooth Low Energy Stack smartBASIC Essentials smartBASIC is based upon the BASIC language It has been designed to be highly efficient in terms of memory use making it ideal for low cost embedded systems with limited RAM and code memory The core language which is common throughout all smartBASIC implementations provides the standard functionality of any program such as Variables
158. ID 1 THEN PRINT n n Disconnected from client EXITFUNG Q ELSEIF nMsgID 0 THEN PRINT n Connected to client ENDIE ENDEUNC 1 EE V7 CCD descriptor written mandler BF MMMM MMMM MMMM FUNCTION HndlrCharcCccd BYVAL charHandle BYVAL nVal DIM values IF charHandle hMyChar THEN PRIA MCC EDEN o e nvak LE nVal THEN PRINT Indications have been enabled by client valueS hello rc BleCharValueIndicate hMyChar value S IF rc 0 THEN PRINT nFailed to indicate new value INTEGER H rc Pili Fi PRINT nSuccessful indication of new value EXITFUNG 1 ENDIF Peli E PRINT Indications have been disabled by client EN ae E DoE PRINT AnThis a6 tom some other Characteristic ENDIF ENDEUNC 555 5555555555555 55555555555 Indication Acknowledgement Handler 5 55555555 55555555555 FUNCTION Hndlreenrhve BYVAL charnandie IF charHandle hMyChar THEN PRINT ninot confirmation Of recent indication ETSE PRINT n nGOr Confirmacion Of come other indication gt charHandilc BNE ENDFUNC 0 ONEVENT EVBLEMSG CALL HndlrBleMsg ONE VENT 2 VCHARCCeED CALL inc hue Nare ONEVENT EVCHARHVC CALL Hndlerchrave TF On tarrcup 0 THEN re BleCharValueRead hMyChar at PRINT nCharacteristic value sats PRINT mYou can connecti and write to the CCCD characte ristic PRINT AnThe BEGOO will then indicate a new characteristic valuen ES E Americas 1 800 492 2320 Option
159. INT Strpali ss 64 7 7 no eo ee o Marl PRINT StrPill sS 23 7 Expected Output hello 7 CACECECECICE STRFILL is a core function STRSHIFTLEFT SUBROUTINE STRSHIFTLEFT shifts the characters of a string to the left by a specified number of characters and drops the leftmost characters It is a useful subroutine to have when managing a stream of incoming data as Tor example a UART I2C or SPI and a string variable is used as a cache and the oldest N characters need to be dropped STRSHIFTLEFT string numChars Exceptions Local Stack Frame Undertlow Local Stack Frame Overflow Arguments string byRef string AS STRING The string to be shifted left Americas 1 800 492 2320 Option 2 91 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual numChrs byVal numChrs AS INTEGER The number of characters that the string is shifted to the left If numCArs is greater than the length of the string then the returned string will be empty Note string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Interactive Command NO Example StrShiftLeft sb See in BL600CodeSnippets zip DIM So yes 173456739 PRU se io Stroherelereiso 4 drop leftmost 4 characters
160. Interactive mode either RESUME can be used to continue execution or the Interactive mode command SO can be used to step through the next statements Note The next state is the BP statement itself hence multiple SO commands may need to be issued Arguments nnnn A constant integer identifier for each breakpoint in the range O to 65535 The integers should normally be unique to allow the breakpoint to be determined but this is the responsibility of the programmer There is no limit to the number of breakpoints that can be inserted into an application other than ensuring that the maximum size of the compiled code does not exceed the 64 Kword limit Note Itis helpful to make the integer identifiers relevant to the program structure to help the debugging process A useful tip is to set them to the program line Interactive Command NO Example BP sb See in BL600CodeSnippets zip PRINT hello BP 1234 PRINT Wows kel PRINT Lared PRINT Rocks BP 156 E PRINT Ghe PRINT worlo Expected Output Depending on what order you use the commands SO and RESUME Americas 1 800 492 2320 Option 2 14 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BP is a core function 5 CORE LANGUAGE BUILT IN ROUTINES Core Language built in routines are present in every implementation of smart BASIC The
161. K kK KK re Gou secuerunce le iy 2 octa stole Burvon Oas a digital in vich a weak pull up resistor ro p e eun a oet Siol Potton I ae a dga a wa a weak pull up resistor Ler Geloseenune le 2 0 7sees srole TEDO tas a digital our be Golosertrume 19 2 0 sets siol LEDI was a digital our re gpiobindevent 0 16 0 6inds a Golo Exansition high to an event siol burccon re gpiobindevent 1 16 1 s1iol6 burcon 0 be gpiobindevent 2 17 0 s1017 burcon 1 roe gpiobindevent 3 17 1 Dimas a gplo Lransition low to an event Ond a Gore e ranen on haon o an evenr pind a Golo tranc ition low tO an event Americas 1 800 492 2320 Option 2 30 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Laird Technologies smart BASIC User Manual SLO burccon 1 onevent evgpiochan0 call button0release detects when button 0 is released and Calls the Tunction onevent evgpiochanl call buttonOpress detects when button 0 is pressed and calls the function onevent evgpiochan2 call buttonlrelease detects when button 1 is released and Callo tthe runcreion onevent evgpiochan3 call buttonlpress detects when button 1 is pressed and calls the une eion Prime Ready to begn button and LED tect an these lines are printed to the UART when the program is run Prope Please press button Eor bution 2 ann Wait for a synchronous event
162. Laird gt BL600 smartBASIC Module User Manual Release 1 5 66 0 global solutions local support Americas 1 800 492 2320 Option 2 Europe 44 1628 858 940 Hong Kong 852 2923 0610 www lairdtech com wireless smart BASIC User Manual 2013 Laird Technologies All Rights Reserved No part of this document may be photocopied reproduced stored in a retrieval system or transmitted in any form or by any means whether electronic mechanical or otherwise without the prior written permission of Laird Technologies No warranty of accuracy is given concerning the contents of the information contained in this publication To the extent permitted by law no liability including liability to any person by reason of negligence will be accepted by Laird Technologies its subsidiaries or employees for any direct or indirect loss or damage caused by omissions from or inaccuracies in this document Laird Technologies reserves the right to change details in this publication without notice Windows is a trademark and Microsoft MS DOS and Windows NT are registered trademarks of Microsoft Corporation BLUETOOTH is a trademark owned by Bluetooth SIG Inc U S A and licensed to Laird Technologies and its subsidiaries Other product and company names herein may be the trademarks of their respective owners Laird Technologies Saturn House Mercury Park Wooburn Green Bucks HP10 OHH UK Tel 44 0 1628 858 940 Fax 44 0 1628 52
163. Latency AS INTEGER The number of connection interval polls that the peripheral may ignore This times the connection interval shall not be greater than the link supervision timeout Note Slave latency is a mechanism that reduces power usage In a peripheral device and maintains short latency Generally a slave reduces power usage by setting the largest connection interval possible This means the latency is equivalent to that connection interval To mitigate this the peripheral can greatly reduce the connection interval and then have a non zero slave latency For example a keyboard could set the connection interval to 1000 msec and slave latency to O In this case key presses are reported to the central device once per second a poor user experience Instead the connection interval can be set to e g 50 msec and slave latency to 19 If there are no key presses the power use Is the same as before because 19 1 50 equals 1000 When a key is pressed the peripheral knows that the central device will poll within 50 msec so it can send that keypress with a latency of 50 msec A connection interval of 50 and slave latency of 19 means the slave Is allowed to NOT acknowledge a poll for up to 19 poll messages from the central device Interactive Command NO Example BleSetCurConnParms sb See in BL600CodeSnippets zip DIMERS DIM addr addrs FUNCTION HandlerBleMsg BYVAL nMsgId AS INTEGER BYVAL nCtx AS INTEGER AS INTEGER Am
164. Local Stack Frame Overflow Arguments string byRef string AS STRING The string to be converted into hex characters offset byVal offset AS INTEGER This is the offset from where up to 2 hex characters will be converted into a binary number Interactive Command NO Note string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Associated Commands STRHEXIZE Americas 1 800 492 2320 Option 2 95 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Example StrHex2Bin sb See in BL600CodeSnippets zip DIM ss so 0102020405 PEINT Serlex2bian so 4 nm s 4C61697264 PRINT Serle x2eamiso 2 as Expected Output 3 97 STRHEX2BIN is a core function STRESCAPE FUNCTION STRESCAPE is used to convert a string variable into a string which contains only printable characters using a 2 or 3 byte sequence of escape characters using the NN format STRESCAPE string Returns STRING A printable version of string which means at best the returned string is of the same length and at worst not more than three times the length of the input string The following input characters are escaped as follows carriage return r linefeed n horizontal tab t
165. N PRINT n n Disconnected Ee LTEUNG 30 ELSEIF nMsgID 0 THEN PRINT n Connected so write to attibute handle 3 atHndl 3 ato O1 02 03 04 rc BleGattcWrite conHndl atHndl ats IF rc 0 THEN Americas 1 800 492 2320 Option 2 301 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual WALTEVENT ENDIF PRINT nwrite to attibute handle 300 which does not exist atHndl 300 rc BleGattcWrite conHndl atHndl at IF rc 0 THEN WALTEVENT BND CloseConnections ENDIE ENDFUNC 1 function HandlerAttrWwrite cHndl aHndl nots as integer dinm TOSE Vanco ar Print O nEVATITRWE IIE Y print eae Hnd e enad Print Vatterhndil abmadil print Statie Faneeqer in nots if nSts 0 then print nALtribute write OK else Dent miele d to write attribute endif endfunc 0 aseessaasss255555 5555555555559 5555555595555 55555555555555555555 Main equivalent asaasssssss25 5555555555555 55555 5555555955555 555555555 55555555555 ONEVENT EVBLEMSG CALL HndlrBleMsg OnEvent EVATTRWRITE call HandlerAttrWrite IF OnStartup 0 THEN PRINT nAdvertising and Gatt Client is Openin BLSE PRINT nFailure OnStartup END LE WALILTEVENT PRENT AP NESIC a ay Americas 1 800 492 2320 Option 2 302 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com blueto
166. N HndlrBleMsg BYVAL nMsgId BYVAL nCtx conHndl nCtx IF nMsgID 1 THEN PRINT n n Disconnected ED ELEUNC 0 ELSEIF nMsgID 0 THEN PRINT An Connected so enable notification for Ghar with Cecd at 167 atHndl 16 at S 01 00 rc BleGattcWrite conHndl atHndl ats IF rc 0 THEN WALILTEVENT END PRIN m enable indication for char with cecd art 19 atHndl 19 acs 0Z2 00 rc BleGattcWrite conHndl atHndl ats IF rc 0 THEN WALTEVENT END IE ENIDI E EES at f unction HandlerArtErWrice Chmdl aknndl nots as Integer dim nOret r rANdi ae Leine T TAnEVA TETP eE Prints endl Sn CHA Drink ate r Hnd gt andl print status integer h nots if nSts 0 then print nAttribute write OK else print nFailed to write attribute endif endfunc 0 Americas 1 800 492 2320 Option 2 308 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual fLunetion HandlerArcerNorinry as integer dim ennd P aushacll seisieS clecel Print nh VALTRNOU TRY laren rc BleGattcNotifyRead cHndl aHndl att dscd print n BleGattcNotifyRead if rc 0 then Print chidl i Ond Print aeerhnicl atimel Pene ata s Strtew 7eS ais print discarded dsed else orint fem kod witiviy Integer N ace endif endfunc 1 j Main equivalent sossessessesesassasesssssssssssesssess sess sasesssesesssss
167. NCODETIMESTAMP attr timestamp nlndex Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation Arguments attr byRef atir AS STRING This argument is the string that is written to an attribute timestamp3 byRef timestamp AS STRING This is an exactly 7 byte string as described above For example 5 May 2013 10 31 24 is entered 14 0D 05 05 0A 1F 18 nindex byVal nindex AS INTEGER This is the zero based index into the string attr where the new fragment of data Is written If the string attr is not long enough to accommodate the index plus the length of the fragment it is extended If the new length exceeds the maximum allowable length of an attribute see SYSINFO 2013 this function fails Interactive Command NO Example BleEncodeTimestamp sb See in BL600CodeSnippets zip DIMT o hss DIME ao O write the timestamp lt 5 May 2013 10 31 24 gt peo V4 VOD 05 05 Of Ie PRINT BleEncodeTimestamp attrs tsS 0 Expected Output BLEENCODETIMESTAMP is an extension function Americas 1 800 492 2320 Option 2 318 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleEncodeSTRING FUNCTION This function overwrites a substring at a specified offset with data from another substring of a string If the destination string is not long enough it is extended with the ne
168. NG the current device name in the local GATT table It is the same as that supplied in BleGapSvcinit if the nameWritable parameter was 0 otherwise it can be different EVBLEMSG event is thrown with msgid 21 when the GATT client writes a new value Arguments None Interactive Command NO Example BleGetDeviceNameS sb See in BL600CodeSnippets zip DIM ae dvelimes umeViaeeoleapoeiecs MiunConmilne MaC onn mir onno pTO SL PRINT n DevName BleGetDeviceNames Changing device name manually dvcNmesS My BL600 nmeWrtble 0 apprnce 768 MinCconmint SOOO MaxConniInt 1000000 ConnSupTO 4000000 sL 0 re BleGapSvcInit dvcNmeS nmeWrtble apprnce MinConniInt MaxConnInt ConnSupToO sL PRINT n New DevName BleGetDeviceNameS Expected Output DevName LAIRD BL600 New DevName My BL60O0 BLEGETDEVICENAMES is an extension function BleSvcRegDevinfo FUNCTION This function is used to register the Device Information service with the GATT server The Device Information service contains nine characteristics as listed at the following website http developer bluetooth org gatt services Pages ServiceViewer aspx u org bluetooth service device_intorm ation xml The firmware revision string will always be set to BL600 vW X Y Z where W X Y Z are as per the revision information which is returned to the command AT 4 Americas 1 800 492
169. Ono ar up O THEN DIM atS re BleCharValueRead hMyChar ats PRINT nCharacteristic value attribute T afo TAn Connect to BLCOO and send a new value n EGOE PRINT nfarlure Onotartup ENID IL E ONEVENT EVCHARVAL CALL HndlrChar ONEVENT EVBLEMSG CALL HndlrBleMsg WALTEVENT PPLINT YNE ICIN a S Americas 1 800 492 2320 Option 2 256 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output Characteristic value attribute Hi Connect to BL600 and send a new value New characteristic value Laird ip ages Sal eae BLECHARVALUEREAD is an extension function BleCharValueWrite Note For firmware versions prior to 1 4 X Y the module must be in a connection for this function to work FUNCTION This function writes new data into the VALUE attribute of a Characteristic which is in turn identified by a composite handle returned by the function BleCharCommit BLECHARVALUEWRITE charHandle attr Returns INTEGER a result code The typical value is OxO000 indicating a successful operation Arguments charHandle byVal charHandle AS INTEGER This is the handle to the characteristic whose value must be updated which was returned when BleCharCommit was called attr byRef attr AS STRING String variable contains new value to write to the characteristic Interactive Command NO Exa
170. Or SEn e il Se a ie Sweme sii bs oO ee Semel cipol oes 0 hae Sie mesa eke 50 3 ih re Semele S ems s04 lh ares Secmes 16 Aran wet nCmds 6 Print the 7 elements above in order DIM i AS INTEGER fom a O te mnam step erint Sel maelan next Expected Output ATS0 1 ATS512 4 ATS501 ATS502 1 ATS503 1 ATS504 1 AT amp W Americas 1 800 492 2320 Option 2 54 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual General Comments on Variables Variable Names begin with A to Z or _ and then can have any combination of A to Z 0 to 9 and Note Variable names are not case sensitive for example test and 7ES7 are the same variable smart BASIC is a strongly typed language and so if the compiler encounters an incorrect variable type then the compilation will fail Declaring Variables Variables are normally declared individually at the start of an application or within a function or subroutine DIM Strings AS STRING DIM strla the at the end of the name implies a string so AS STRING not necessary DIM templ AS INTEGER DIM alarmstate Owe wae eee Pie mame simp bles san aeee so AS INTEGER not necessary DIM array 10 A gt STRING Constants Numeric Constants Numeric Constants can be defined in decimal hexadecimal octal or
171. Q rc GPIOBindE vent 0 16 1 PRINT AnPre e BULON Oto exi te Enis aopoltcabven m ONEVENT EVUARTRX CALE HidivUarers ONEVENT EVGPIOCHANO CALL BtnOPressed WAILTEVENT wait for rx tx and modem status events EE E BE aad ciel alc fees Americas 1 800 492 2320 Option 2 126 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output Note If you type unknown commands an E007 error displays in UwTerminal Example EVUARTTXEMPTY sb See in BL600CodeSnippets zip EOIN CIP WOIN Ishoe J elWeaeie ii A PRINT AnT buffrer vs empty ENDFUNC 0O ONEVENT EVUARTTXEMPTY CALL HndlrUartTxEty PRINDE niSend thio Vile svar ts WALTEVENT Expected Output send this via nart Tx buffer is empty UartOpen Note Until further notice the parity parameter shall not be changed when using this function Function This function is used to open the main default uart peripheral using the parameters specified If the uart is already open then this function will fail If this function is used to alter the communications parameters like say the baudrate and the application exits to interactive mode then those settings will be inherited by the interactive mode parser Hence this is the only way to alter the communications parameters for Interactive mode While the uart is open if a BREAK is sent to the mo
172. Random numbers are either generated using pseudo random number generator algorithms or using thermal noise or equivalent in hardware The routines listed in this section provide the developer with the capability of generating random numbers The Interactive Mode command AT I 1001 or at runtime SYSINFO 1001 will return 1 if the system generates random numbers using hardware noise or O if a pseudo random number generator RAND FUNCTION The RAND function returns a random 32 bit integer Use the command AT I 1001 or from within an application the function SYSINFO 1001 to determine whether the random number is pseudo random or generated in hardware via a thermal noise generator If 1001 returns O then it is pseudo random and 1 if generated using hardware RAND Returns INTEGER A 32 bit integer Exceptions Local Stack Frame Undertlow Local Stack Frame Overflow Arguments None Depending on the platform the RAND function can be seeded using the RANDSEED function to seed the pseudo random number generator If used RANDSEED must be called before using RAND If the platform has a hardware Random Number Generator then RANDSEED has no effect Interactive Command NO Associated Commands RANDSEED Example RAND sb See in BL6o00CodeSnippets zip PRINT nRandomenumber 1s T RAND Americas 1 800 492 2320 Option 2 110 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech
173. SG event message with msgld 0 and msgCtx will have been the connection handle Interactive Command NO Example BleDiscDescFirst Next sb See in BL600CodeSnippets zip a Remote server has 1 prim service with 16 bit uuid and 1 characteristics waren Contains 8 descriptors that are j 5 Woes are 6 bit wand are 128 bit 3 of the 16 bit uuid are the same value OxDEAD and 2 of the 128 bit uuids are also the same 112233445566778899AABBCCDDEEFF ii O Seiever Cree e USsbne Ee a a To eD e suo e ia Ooeicwiog sci A sing Norde Usb Dond e P 10000 DIM o onn an una de SA er a Ae Nalar Americas 1 800 492 2320 Option 2 282 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual j Initialise and anstantiace service Characteristic Start adverts PUD Gir G hs Oi ichiate Wo DIM me eclcizs ecleies Seloirs Ee BileAdvRpE Inte acdRote 2 07 10 IF rc 0 THEN rc BleScanRptInit scRpt ENDIF IF rc 0 THEN rc BleAdvRptsCommit adRpt s scRpt ENDIF te re 0 THEN 2 rec BleAdvertStare 0 addr5 50 0 0 2 ENDIF open the gatt client with default notify indicate ring buffer size IF rc 0 THEN re BleGattcOpen 0 0 ENDIF ENDEUNG re SUB Closet onnecriens rc BleDisconnect conHnd1 rc BleAdvertStop BND SUB PUNCELON HndilrBleMsg BYVAL nMsgld BYVAL MCX DIM uus CconHndl mCr x
174. SIC User Manual UartCloseEx FUNCTION This function is used to close a uart port which had been opened with UARTOPEN depending on the flag mask in the input parameter Please see UartClose for more details Note For firmware versions older than 1 3 57 3 there is a bug which means that if the rx amp tx buffers are not empty an internal pointer is still set to NULL when it should This results in unpredictable behaviour Workaround Use UartInto 6 to check if the buffers are empty and then call UartCloseRx 1 UARTCLOSEEX nFlags Returns INTEGER An integer result code The most typical value is 0x0000 which indicates a successful operation If 0x5231 is returned it implies one of the buffers was not empty so not closed Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments nFlags byVal nFlags AS INTEGER If Bit O is set then only close if both rx and tx buffers are empty Setting this bit to O has the same effect as UartClose routine Bits 1 to 31 are for future use and must be set to 0 Interactive Command No Related Commands UARTOPEN UARTINFO UARTWRITE UARTREAD UARTREADMATCH UARTGETCTS UARTGETDCD UARTGETRI UARTSETDTR UARTSETRTS UARTSETDCD UARTSETRI VARTBREAK UARTFLUSH Americas 1 800 492 2320 Option 2 131 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Workarou
175. Set Ready Output Input DCD Data Carrier Detect Output Input RI Ring Indicate The lines DCD and RI are marked as Output or Input because it is possible unlike a device like a PC where they are always inputs and modems where they are always outputs to configure the pins to be either so that the device can adopt a DTE Data Terminal Equipment or DCE Data Communications Equipment role Please note that both DCD and RI have to be BOTH outputs or BOTH inputs one cannot be an output and the other an input UART Events In addition to the routines for manipulating the UART interface when data arrives via the receive line it is stored locally in an underlying ring buffer and then an event is generated Similarly when the transmit buffer is emptied events are thrown from the underlying drivers so that user smart BASIC code in handlers can perform user defined actions The following is a detailed list of all events generated by the UART subsystem which can be handled by user code EVUARTRX This event is generated when one or more new characters have arrived and have been stored in the local ring buffer EVUARTTXEMPTY This event is generated when the last character is transferred from the local transmit ring buffer to the hardware shift register Example EVUARTRX sb See in BL600CodeSnippets zip Biv ee PFUNGLLON HidillrUarrkx PRINT nData has arrived r BNDEUNC 1 cemain blocked in WALTEVENT FUNCTION BtnOPressed ENDFUNC
176. Stack Frame Overflow Arguments string byRef string AS STRING String variable to be used for the Table Since it is byRef the compiler will not allow a constant string to be passed as an argument On entry the string can be non empty on exit the string will be empty Interactive Command NO Note string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Associated Commands TABLEADD TABLELOOKUP Example TableInit sb See in BL600CodeSnippets zip DUM Mc Sa bo Helio ASME NEES gh aes oo ele PRINT wae elo eine iS ez a ge A ela eae aia eae oy String now blank after being initialised as a table Americas 1 800 492 2320 Option 2 105 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output TABLEINIT is a core function TABLEADD FUNCTION TABLEADD adds the token specified to the lookup table in the string variable and associates the index specified with it There is no validation to check if nilndex has been duplicated as it is entirely valid that more than one token generate the same ID value TABLEADD string strtok nID Returns INTEGER Indicates success of command O Signities that the token was successfully added 1 Indicates an erro
177. TION HndlrBleMsg BYVAL nMsgId BYVAL nCtx conhnd nCerex IF nMsgIiD 1 THEN PRINT nDisconnected from client EXITFUNG O JEND IL IE ENDFUNC 1 ONEVENT EVVSPRX CALL HandlerVSpRx ONEVENT EVBLEMSG CALL HndlrBleMsg OnStartup Calls first subroutine declared above WALTEVENT CloseConnections Calls second subroutine declared above PR TUTAS ELI Ne Expected Output BLEVSPREAD is an extension subroutine Americas 1 800 492 2320 Option 2 348 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleVSpUartBridge SUBROUTINE This function creates a bridge between the managed Virtual Serial Port Service and the UART when both are open Any data arriving from the VSP is automatically transferred to the UART for forward transmission Any data arriving at the UART is sent over the air It should be called either when data arrives at either end or when either end indicates their transmit buffer is empty The following events are examples EVVSPRX EVUARTRX EVVSPTXEMPTY and EVUARTTXEMPTY Given that data can arrive over the UART a byte at a time a latency timer specified by AT CFG 116 command may be used to optimise the data transfer over the air This tries to ensure that full packets are transmitted over the air Therefore if a single character arrives over UART a latency timer is started If it expires that single character
178. UARTSETRTS UARTSETDCD UARTSETRI VARTBREAK UARTFLUSH Example UartGetCTS sb See in BL600CodeSnippets zip IF UartGetCTS 0 THEN PRINT nCTS line is not asserted PUSEILE TU ar ECETES THEN PRINT nCTS line is asserted ENDIF Expected Output CTS line is not asserted UARTGETCTS is a core subroutine UartSetRTS SUBROUTINE This function is used to set the state of the RTS modem control line When the UART port is closed the RTS line can be configured as an input or an output and can be available for use as a general purpose input output line When the uart port is opened the RTS output is automatically defaulted to the asserted state If flow control was enabled when the port was opened then the RTS output cannot be manipulated as it is owned by the underlying driver UARTSETRTS newState Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Uart has not been opened using UARTOPEN Arguments newState byVal newState AS INTEGER O to deassert and non zero to assert Interactive Command No Americas 1 800 492 2320 Option 2 142 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Related Commands UARTOPEN UARTINFO UARTCLOSE UARTWRITE UARTREAD UARTREADMATCH UARTGETCTS UARTGETDCD UARTGETRI UARTGETDSR UARTSETDTR UARTSETDCD UARTSETRI VARTBREAK UARTFLUSH N
179. UME COMMAND RESUME is used to continue operation of an application from Interactive Mode which had been previously halted Normally this occurs as a result of execution of a STOP or BP statement within the application On execution of RESUME application operation continues at the next statement after the STEP or BP statement If used after a SO command application execution commences at the next statement RESUME Returns If there is nothing to resume e g immediately after reset or if there are no more statements within the application then an error response is sent nO1 tEO29 r This is an Interactive Mode command and MUST be terminated by a carriage return for it to be processed Interactive Command YES Examples RESUME RESUME is a core function ABORT COMMAND Abort is an Interactive Mode command which is used to abandon an application whose execution has halted because It has processed a STOP or BP statement ABORT Returns Abort is an Interactive Mode command which is used to abandon an application whose execution has halted because it had processed a STOP or BP statement If there is nothing to abort then it will return a success 00 response This is an Interactive Mode command and MUST be terminated by a carriage return for it to be processed Americas 1 800 492 2320 Option 2 44 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluet
180. VAL charHandle BYVAL nVval AS INTEGER DIM value IF charHandle hMyChar THEN TEV E ce On Mei PRINT nBroadcasts have been enabled by client BRLSE PRINT nBroadcasts have been disabled by client BN oe ELSE PRINT A nTrhis io for Some other Characteristic ENDIF ENDFUNC 1 ONEVENT EVBLEMSG CALL HndlrBleMsg ONE VENT SE VCHARSCCD CALE Amr O ar oeod ONEVENT EVGPIOCHAN1 CALL HndlrBtnOPr IF OnStartup 0 THEN re BleCharValueRead hMyChar at PRINTE n hetracteristic Value ats PRINT nvVou can write to the gt CD alerioute PRINT n Press button 0 to exit n BLOE PRINTS Varavitine OnStar tup EADAR WAITEVENT EE WINES UO evi E EVCHARDESC This event is thrown when the client writes to writable descriptor of a characteristic which is not a CCCD or SCCD as they are catered for with their own dedicated messages It comes with two parameters the first Is the characteristic handle that was returned when the characteristic was registered using the function BleCharCommit and the second is an index into an opaque array of handles managed inside the characteristic handle Both parameters are supplied as is as the first two parameters to the function BleCharDescRead Example EvCharDesc sb See in BL600CodeSnippets zip DIM HM Char ro abo Conna NOLE Donor Americas 1 800 492 2320 Option 2 200 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com ww
181. WITHOUT_RESPONSE is enabled Bit 3 Set if WRITE is enabled Bit 4 Set if NOTIFY is enabled Bit 5 Set if INDICATE is enabled Bit 6 Set if AUTHENTICATED_SIGNED_WRITE is enabled Bit 7 Set if RELIABLE_WRITE is enabled Bit 15 Set if the characteristic has extended properties Handle for the Value Attribute of the Characteristic is the handle for the value attribute and is the value to store to keep track of important characteristics in a gatt server for later read write operations Included Service Uuid Handle is for future use and will always be O Americas 1 800 492 2320 Option 2 287 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BLEGATTCFINDCHAR connHandle svcUuidHndl svcindex charUuidHndl charlndex A typical pseudo code for finding a characteristic involves calling BleGattcFindChar which in turn will result in the EVFINDCHAR event message and typically is as follows Register a handler for the EVFINDCHAR event message On EVFINDCHAR event message If Char Value Handle 0 then Characteristic not found Else Characteristic has been found Call BleGattcFindChar If BleGattcFindChar ok then Wait for EVFINDCHAR Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation and it means an EVFINDCHAR event message WILL be thrown by the smartBASIC runtime engin
182. Y PAIRING 0x38 BLE HCI CONN REJ DUETO NO SUITABLE CHN FOUND 0x39 BLE HCI CONTROLLER BUSY Ox3A BLE HCI CONN INTERVAL UNACCEPTABLE 0x3B BLE HCI DIRECTED ADVERTISER TIMEOUT 0x3C BLE HCI CONN TERMINATED DUE TO MIC FAILURE 0x3D BLE HCI CONN FAILED TO BE ESTABLISHED 0x3E 11 ACKNOWLEDGEMENTS The following are required acknowledgements to address our use of open source code on the BL600 to implement AES encryption Laird s implementation includes the following files aes c and aes h Copyright c 1998 2008 Brian Gladman Worcester UK All rights reserved LICENSE TERMS The redistribution and use of this software with or without changes is allowed without the payment of fees or royalties providing the following Source code distributions include the above copyright notice this list of conditions and the following disclaimer Binary distributions include the above copyright notice this list of conditions and the following disclaimer in their documentation The name of the copyright holder is not used to endorse products built using this software without specific written permission DISCLAIMER This software is provided as is with no explicit or implied warranties in respect of its properties including but not limited to correctness and or fitness for purpose Issue 09 09 2006 This is an AES implementation that uses only 8 bit byte operations on the cipher state there are options to use 32 bit types if available T
183. a 16 byte string and converts It into a 32 bit integer handle The handle consists of a 16 bit 2 byte offset into a new 128 bit base UUID The base UUID is basically created by taking the 16 byte input string and setting bytes 12 and 13 to zero after extracting those bytes and storing them in the handle object The handle also contains an index into an array of these 16 byte base UUIDs which are managed opaquely in the underlying stack The returned handle shall be treated by the developer as an opaque entity and no further logic shall be based on the bit content However note that a string of zeroes represents an invalid UUID handle Please ensure that you use a 16 byte UUID that has been generated using a random number generator with sufficient entropy to minimise duplication as stated in an earlier section and that the first byte of the array is the most significant byte of the UUID BLEHANDLEUUID 128 stUuid Returns INTEGER A handle representing the shorthand UUID If zero which is an invalid UUID handle there is either no soare RAM memory to save the 16 byte base or more than 253 custom base UUIDs have been registered Arguments stUuid byRef stUuid AS STRING Any 16 byte string that was generated using a UUID generation utility that has enough entropy to ensure that it is random The first byte of the string is the MSB of the UUID that is big endian format Interactive Command NO Example BleHandleUuidl128 sb S
184. a SUB routine which takes no parameters It must not be a function It must exist within the application PRIOR to this ONERROR command being compiled Interactive Command NO Americas 1 800 492 2320 Option 2 66 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Example OnError sb See in BL600CodeSnippets zip DEM eu bc SUB HandlerOnErr IDo thas whem an error Occurs DIM le le GetLastError PRINT Error code Ox le denotes a Divide by zero error m PRINT Let s make b equal 25 instead of 0 n n b 25 ENDS a 100 b 0 ONERROR REDO HandlerOnErr j Calls the HandlerOnber routine After that the error causing statement below is reprocessed c a b Print 6 mow sequadls 7c Expected Output Error code 0x1538 denotes a Divide by zero error Let s make b equal 25 instead of 0 c now equals 4 ONERROR is a core function ONFATALERROR ONFATALERROR is used to redirect program flow to a subroutine that can attempt to modify operation or correct the cause of a fatal error Three different options are provided REDO NEXT and EXIT The GETLASTERROR command should be used In the subroutine to determine the type of error that was generated ONFATALERROR REDO routine On return from the routine the statement that originally caused the error Is reprocessed ONFATALERROR NEXT routi
185. aends 80 Arithmetic ROUES eers ocsscins consumo terns eaineart AAEE ERINA NEEE aAA EEEE 81 SINE ROUTINES sorses sinni orison nirea E A gan IE ENE TOS E AT EEEE EAE EEE EE a 83 UN TR ONS aa E E T E A E E cteroneeieneuteateeuenteteaas 105 Miscellaneous ROUTINES acsensisecd svesanesetceisalseesentsetiesincbaretasuceledsbeddeuaaradstccuasaiaiogennsobedabud S 108 Random Number Generation Routines cccccccsseccccssecccensccccenececseneccceseceseuecesseecessuseceseeecessenecessuaeceteueceesenecs 110 TME ROUTINES vavawantondarwaaceiiantedoadaveaaacieusipaadaeneaanwnaneonedanctavaiadedauadaveioranuadteenddectaaataaosanhdaocdeoasaosidersdiaveeaiabaisendaunesauae 112 Circular Buffer Management FUNCIONS wescsacccetescincncvezscnese cee santencanssatinseeaiesudbacaseuucenseconaacmsenesdnauewaraantaucsssancareansuatnces 119 Serial COMMUNICATIONS ROUTINES cceccccsseccccsecccescceceuececcenececeuseceeeeecesseeceseuseceseueceseuneceseuaesessuecessenecetsuaeeeeees 125 Cryptographic FUNCTIONS orinis ar Eea one tasctuahadsnsuaranetmeesadarenasafakesabed annencaseanradsantarcdeted 162 POT O FONCION en E E E E E E A E 167 Americas 1 800 492 2320 Option 2 4 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Non Volatile Memory Management Routines cccccssssscccccesssececcseseeccesaeusecceseeaeeceeseeaeeeessseneecessaunseessuaaeeeeeas 1
186. ains no parameters Please note that if one notification indication arrives or many like in the case of UART events the same event mask bit is asserted The paradigm being that the smartBASIC application is informed that it needs to go and service the ring buffer using the function BleGattcNotifyRead Americas 1 800 492 2320 Option 2 306 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BLEGATTCNOTIFYREAD connHndl attrHndl attrData discardCount A typical pseudo code for handling and accessing notification indication data is as follows Register a handler for the EVATTRNOTIFY event message On EVATTRNOTIRY event BleGattcNotifyRead to actually get the data Process the data Enable notifications and or indications via CCCD descriptors Returns INTEGER a result code The typical value is 0x0000 indicating data was successful read Arguments connHnal byRef connHndl AS INTEGER On exit this will be the connection handle of the gatt server that sent the notification or indication attrHnal byRef attrHnal AS INTEGER On exit this will be the handle of the characteristic value attribute in the notification or indication attrData byRef attrData AS STRING On exit this will be the data of the characteristic value attribute in the notification or indication It is always from offset O of the source attribute discardedCoun
187. al mdCccd AS INTEGER This is an optional metadata that is used to define the properties of the CCCD Descriptor attribute that will be created in the Characteristic and will have been pre created using the help of the function BleAttrMetadata or set to O if CCCD is not to be created If nCharProps specifies that the Characteristic is notifiable or indicatable and this value contains 0 this function will abort with an appropriate result code mdSccd byVal ma Scca AS INTEGER This is an optional metadata that is used to define the properties of the SCCD Descriptor attribute that will be created in the Characteristic and will have been pre created using the help of the function BleAttrMetadata or set to O if SCCD is not to be created If nCharProps specifies that the Characteristic is broadcastable and this value contains O this function will abort with an appropriate resultcode Interactive Command NO Example BleCharNew sb See in BL600CodeSnippets zip DIIMERE DIM charUuid char luid Plehandleuuidlo J ea a aa e a s OU lp DIN maa maa E EA r Meada e 0720707 re Metadata Lor value artribuLe DIM mdGecd md ced BleAttrMetadata aO 1c Metadata for a CD atiEribute or Characteristic Irae Create a new char M indi ecatable Not Broadcastable so mdCcocd Aas Included Dut not maseed Can be read not written shown in mdVal as well Je SSS 2522 S32 532525 525555 2 25S 5225 2 55 5225S
188. allowable length of an attribute see SYSINFO 2013 this function fails Interactive Command NO Example BleEncode32 sb See in BL600CodeSnippets zip DIM ire DIM Aerio 2 accrceS Lairo fwrite BCDE Eo index 1 re BleEncode32 autre 0x45444 3427 1 weite A to index 0 rc BleEncode8 attrsS 0x41 0 PRINT VAberso abrir s Expected Output attrS ABCDE BLEENCODE32 is an extension function BleEncodeFLOAT FUNCTION This function overwrites four bytes in a string at a specified offset If the string is not long enough it is extended with the new extended block uninitialized and then the byte specified is overwritten If the nindex is such that the new string length exceeds the maximum attribute length this function fails The maximum attribute length can be obtained using the function SYSINFO n where n is 2013 The Bluetooth specification allows a length between 1 and 512 BLEENCODEFLOAT attr nMatissa nExponent nIndex Returns INTEGER a result code The typical value is OxO000 indicating a successful operation Arguments attr byRef atir AS STRING This argument is the string that is written to an attribute nMatissa byVal nMantissa AS INTEGER This value must be in the range 8388600 to 8388600 or the function fails The data is written in little endian so that the least significant byte is at the lower memory address Note that the range Is not 2048 because after encoding the following
189. alue does not match the length of the original string use STRSHIFTLEFT function to drop the data from the string so subsequent calls to this function only retry with data not placed in the output ring buffer Another strategy is to wait for EVVSPTXEMPTY events then resubmit data Interactive Command No Americas 1 800 492 2320 Option 2 345 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Note strMsg cannot be a string constant e g the cat but must be a string variable If you must use a const string first save it to a temp string variable and then pass it to the function Related Commands BLEVSPOPEN BLEVSPCLOSE BLEVSPINFO BLEVSPREAD BLEVSPFLUSH Use the iOS BL600 Serial app and connect to your BL600 to test this sample app Example BleVSpWrite sb See in BL600CodeSnippets zip DIMMExs ec ORo r a dot ac aie gt sinc ne mic nandler when VSP tx buffer is empty FUNCTION HandlerVSpTxEmpty AS INTEGER cnt cntt 1l LE cnt lt 2 TREN txS then this is sent re BleVSpWrite tx PNA E ENDFUNC TO ro BleVspOpen 126 128 0 hnd1 Pe BileScankoulnin sckor ro BleAdvRptAddUuidl128 scRpts hnd1 adRpt re BleAdvRptsCommit adRpt scRpts addrs ec BleAdvertStart 0 addrs 20 300000 0 PRINT nDevice name is BleGetDeviceNames ent 1 txS sene this carca anc
190. alues Each breakpoint statement has the following syntax BP nnnn Americas 1 800 492 2320 Option 2 26 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Where nnnn should be a unique number which is echoed back when the breakpoint is encountered at runtime It is up to the developer to keep all the 77nn6 unique as they are not validated when the source is compiled Breakpoints are ignored if the application is launched using the command AT RUN or name alone This allows the application to be run at full soeed with breaks if required However if the command AT DBG is used to run the application then all of the debugging commands are enabled When the breakpoint is encountered the runtime engine Is halted and the command line interface becomes active At this point the response seen in UWTerminal is in the following form lt linefeed gt 21 BREAKPOINT nnnn lt carriage return gt Where nnnn is the identifier associated with the BP nnnn statement that caused the halt in execution As the nnnn identifier is unique this allows you to locate the breakpoint line in the source code For example if you create an application called test2 sb with the following content Example test2 sb See in BL600CodeSnippets DIM i as integer fore i l co 10 ee nora A Holo Wom lo pane ia if i 3 then Dp 235 55 endif next
191. ample BleEncodeString sb See in BL600CodeSnippets zip DIM ro wabrro tices too Helle World Jiweite Wor trom Hello World to the attribute at index 2 e BplehmeoOdeor rama abilts 2 los 6 3 PRINT attr Expected Output 00 00Wor BLEENCODESTRING is an extension function Americas 1 800 492 2320 Option 2 319 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleEncodeBlITS FUNCTION This function overwrites some bits of a string at a specified bit offset with data from an integer which is treated as a bit array of length 32 If the destination string is not long enough It is extended with the new extended block uninitialized Then the bits specified are overwritten If the nindex is such that the new string length exceeds the maximum attribute length this function fails The maximum length of an attribute as implemented can be obtained using the function SYSINFO n where n is 2013 The Bluetooth specification allows a length between 1 and 512 hence the nDstldx nBitLen cannot be greater than the max attribute length times 8 BleEncodeBITS attr nDstlidx srcBitArr nSrcldx nBitLen Returns INTEGER a result code The typical value is OxO000 indicating a successful operation Arguments attr byRef atir AS STRING This is the string written to an attribute It is treated as a bit array
192. anRptInit scRpt re BleAdvRptAddUuidl128 scRpts hnd1 Americas 1 800 492 2320 Option 2 343 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual adRpt W re BleAdvRptsCommit adRpt scRpts aca ec BleAdvertStart 0 addres 20 300000 0 This message will send when connected to client ExS send this data and will close when sent re BleVSpWrite tx ONEVENT EVVSPTXEMPTY CALL HandlerVSpTxEmpty WALTEVENT SHEN ALE NE EIN e Expected Output BLEVSPCLOSE is an extension subroutine BleVSpInfo FUNCTION This function is used to query information about the virtual serial port such as buffer lengths whether the port Is already open or how many bytes are waiting in the receive buffer to be read BLEVSPINFO infold Returns INTEGER The value associated with the type of uart information requested Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments infold byVal infold AS INTEGER This specities the information type requested as follows if the port is open O Oif closed 1 if open 3 if open and there is a BLE connection and 7 if the transmit fifo characteristic CCCD has been updated by the client to enable notifies or indications 1 Receive ring buffer capacity 2 Transmit ring buffer capacity 3 Number of bytes waiting to be read from receive ring buffer 4 Fre
193. and AT 6 to get information about the file system It respond with the following 10 6 aaaa bbbb cccc Where aaaa is the total size of the file system bbbb is the free space available and cccc is the deleted space From within a smart BASIC application you can get aaaa by calling SYSINFO 601 bbbb by calling SYSINFO 602 and cccc by calling SYSINFO 603 Note After AT amp F 1 is processed because the Tile system manager context is unstable there will be an automatic self reboot AT DEL filename Returns OK If the file does not exist or if it was successfully erased it will respond with nOO r Arguments filename String_constant The name of the file to be deleted The maximum length of filename is 24 characters and should not include the following characters lt gt This is an Interactive Mode command and must be terminated by a carriage return for it to be processed Adding the sign to an AT DEL command can be used to force the deletion of an open file For example use AT DEL filename to delete an application which you have just exited after running It Interactive Command YES Examples AT DEL data AT DEL myapp AT DEL is a core command AT RUN COMMAND AT RUN runs a precompiled application that is stored in the module s flash file system Debugging statements in the application are disabled when it is launched using AT RUN AT RUN filename
194. and conversely if data is written into that characteristic data container by a remote GATT Client then an event is thrown in the form of a message into the smartBASIC runtime engine which will get processed if and only if a handler function has been registered by the apps developer using the ONEVENT statement With this simple model in mind an overview of how the smartBASIC functions are used to register Services and Characteristics is illustrated in the flowchart on the right and sample code follows on the next page Americas 1 800 492 2320 Option 2 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Create a UUID Handle for Service 16 128 BleHandleUuid Commit a PRIMARY or SECONDARY service which returns a service handle BleSvcCommit Create a UUID Handle for Characterisitic 16 128 BleHandleUuid Create a metadata object which defines the permissions for the characteristic value attribute BleAttrMetadata Create a metadata object which Notifiable OR Yes defines the permissions for the Indicatable characteristic CCCD attribute Create a metadata object which defines the permissions for the Broadcastable Yes characteristic SCCD attribute tart the definition of a new characteristic which will be later commited to the GA table in a single transaction Create a metadata object which User Desc defines the permi
195. andle as returned in the on connect event for the connection on which the remote Gatt Server can be accessed This will have been returned in the EVBLEMSG event message with msgld 0 and msgCtx will have been the connection handle Interactive Command NO Example BleDiscServiceFirst Next sb See in BL600CodeSnippets zip Ve Remote server has 5 prim services with 16 bit uuid and 3 with 128 bit uuids 3 of the 16 bit uuid are the same value OxDEAD and 2 of the 128 bit uuids are also the same 112233445566778899AABBCCDDEEFF m A eere ere e a e O a a ve e oe ala O Sng Norde Usb Dongle POCIO000 DIMU rooe Conna und ules UNE MING IN OnStarctup DiMeo mechs secldlckacr ms RoE re BleAdvRpeEInit adRpes 2 07 10 IE e 0 THEN 3 re BleScankoclnit SsecReES 92 gt ENDIF IF rc 0 THEN rc BleAdvRptsCommit adRpt s scRpt ENDIF fe Tre 0 THEN re BleAGgvereStare O0 addrs 50 0 0 ENDIE open the gatt client with default notify indicate ring buffer size Americas 1 800 492 2320 Option 2 2 2 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual IF rc 0 THEN re BleGattcOpen 0 0 ENDIF ENDEUNG ce SUB CloseConnecrnlonms rc BleDisconnect conHnd1 rc BleAdvertStop BNDSUB PONCE ICN HndilrBleMsg BYVAL nMsgid BYVAL MCX DIM uu econhndl mCr x IF nMsgID 1 THEN PRINT n n Di
196. andler returns a zero value then the next statement after WAITEVENT is processed Otherwise WAITEVENT continues to wait for another event WAITEVENT Interactive Command NO UNG Min We tae One PRINT Se rah ENDFUNC 1 FUNCTION Punci PRINT quae ENDEUNC O ONEVENT EVO CALL Func0O ONEVENT EVI CALL Fumel WALTEVENT WEG Cor an event tTO OCGUE PRINT n Got here because EV1 happened WAITEVENT is a core function ONEVENT ONEVENT is used to redirect program flow to a predefined FUNCTION that can respond to a specific event when that event occurs This is commonly an external event such as an I O pin change or a received data packet but can be a software generated event too ONEVENT symbolic_name CALL routine When a particular event is detected program execution is directed to the specified function ONEVENT symbolic_name DISABLE A previously declared ONEVENT for an event is unbound from the specified subroutine This allows for complex applications that need to optimise runtime processing by allowing an alternative to using a SELECT statement Events are detected from within the run time engine in most cases via interrupts and are only processed by an application when a WAITEVENT statement is processed Until the WAITEVENT all events are held in a queue Americas 1 800 492 2320 Option 2 68 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com
197. andlerCharDisc HandlerDescDisc Register base uuids with the underlying stack otherwise the services with the 128bit uuid s will be delivered with a uuid handle FFO00000 UNKNOWN uuid 2733445 566 1380 0 AABBCCDDERE ZOO uud StrreDehexizes uuLids uHndl BleHandleUuidl28 uuid uuidS 1122DFAD5566778899AABBCCDDBEEFOO uuid StrDehexizes uuids uHndl BleHandleUuidl28 uuid IF OnStartup 0 THEN PRINT nAdvertising ELSE PRINT Y nrailure Onewar tue ENDIF WALTEVENT aL OE olny EINen Americas 1 800 492 2320 Option 2 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth and Gatt Client is open n 285 Laird Technologies smart BASIC User Manual Expected Output BLEDISCDESCFIRST and BLEDISCDESCNEXT are both extension functions Americas 1 800 492 2320 Option 2 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth 286 Laird Technologies smart BASIC User Manual BleGattcFindChar FUNCTION This function facilitates a quick and efficient way of locating the details of a characteristic if the uuid is known along with the uuid of the service containing it and the results will be delived in a EVFINDCHAR event message If the Gatt server table has multiple instances of the same service characteristic combination then this function will work because in addition to the u
198. ant bit first or last Note A dedicated SPI Chip Select CS line is not provided and it is up to the developer to dedicate any spare gpio line for that function if more than one SPI slave is connected to the bus The SPI interface in this module assumes that prior to calling SPIREADWRITE SPIREAD or SPIWRITE functions the slave device has been selected via the appropriate gpio line SPI Events The API provided in the module is synchronous and so there is no requirement for events SpiOpen FUNCTION This function is used to open the main SPI peripheral using the parameters specified SPIOPEN nMode nClockHz nCfgFlags nHande Returns INTEGER Indicates success of command Americas 1 800 492 2320 Option 2 156 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Exceptions Arguments nMode nClockHz nCfgFlags nHandle 0 Ox5200 Ox5207 Ox5225 Ox521D Ox522B Opened successfully Driver not found Driver already open Invalid Clock Frequency Requested Driver resource unavailable Invalid mode Local Stack Frame Underflow Local Stack Frame Overflow byVal nMode AS INTEGER This is the mode as in phase and polarity of the clock line that the interface shall operate at Valid values are O to 3 inclusive Mode CPOL CPHA O O O 1 O 1 2 1 O 3 1 1 byVal nClockHz AS INTEGER This is the clock
199. apacity set by the caller Most often it will be used as a first in first out queue CIRCBUFCREATE nltems circHandle Returns INTEGER An integer result code The most typical value is 0x0000 which indicates a successful operation Arguments nitems byVal n tems AS INTEGER This specifies the maximum number of INTEGER values that can be stored in the buffer If there isn t enough free memory in the heap then this function will fail and return an appropriate result code Americas 1 800 492 2320 Option 2 119 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual circHandle byRef circHandle AS INTEGER If the circular buffer is successfully created then this variable will return a handle that should be used to interact with it Interactive Command NO Example CircBufCreate sb See in BL600CodeSnippets zip DIM circhancile circHancdile2 re re CircBurCreate 16 circHandle PRINTO TAn esac IF rcec 0 THEN PRINT nihe circular buffer T circhandle was not created ENID ILE re CircBufCreate 32000 circHandle2 PRING Anin re IF rcec 0 THEN PRINT n gt The circular buffer circHandle2 was not created ENDS Expected Output 20736 gt The circular buffer circHandle2 was not created CIRCBUFCREATE is an extension function CircBufDestroy SUBROUTINE This function is used to destr
200. arValueRead sb See in BL600CodeSnippets zip DMEM TAMA Rar ce O HONGAORA DIM ie Doe ORE eiclaioaor adde a a a ea T commit service rc BleSvcCommit 1 BleHandleUuid1l6 0x18EE hSvc initialise char write read enabled accept signed writes rc BleCharNew 0x0A BleHandleUuidl16 1 BleAttrMetaData 1 1 20 0 rc 0 0 Americas 1 800 492 2320 Option 2 255 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual commit char initialised above with initial value hi tro service hove rc BleCharCommit hSvc attrs hMyChar initialise scan report ro BlecocanRptInit ScCRpES Add 1 service handle to scan report vO E LON Noe NOUS S CRPE lasvwe L l 1 1 il commit reports to GATT table adRpt S is empty rc BleAdvRptsCommit adRpt scRpts rc BleAdVereStart 0 addrs 150 0 0 ENP UNCG re PUNCTILION VHncdlirehac By VAlptohwhincaik B VAL Offset B VAL Len dim ss iF chr ind hMyC Char THEN PRINT n len byte s have been written to char value attribute from offset OFESeCE rc BleCharValueRead hMyChar s PRINT nNew Char Value sS ENDIF rc BleAdvertStop rc BleDisconnect conHndl ENDFUNC O EE SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS J Geetha Ccommmect won wamcile Jee FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtn conHndl nCtn ENDFUNC 1 Le
201. are Queue Full Error Used in ATT as Attribute not found Error Attribute cannot be read or written using read write blob requests Error Encryption key size used is insufficient Error Invalid value size Error Very unlikely error Error Encrypted link required Error Attribute type is not a supported grouping attribute Error Encrypted link required Error Reserved for Future Use range 1 begin Error Reserved for Future Use range 1 end Error Application range begin Error Application range end Error Reserved for Future Use range 2 begin Error Reserved for Future Use range 2 end T Error Reserved for Future Use range 3 begin Error Reserved for Future Use range 3 end D PP PP PPP PP PP PP Pe z D PP PP PPP PP PP PP Pe Common Profile and Service Error Client Characteristic Configuration Descriptor CCCD improperly configured Ox01FE ATT Common Profile and Service Error Procedure Already in Progress Ox01FF ATT Common Profile and Service Error Out Of Range Americas 1 800 492 2320 Option 2 295 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BLEGATTCREAD connHndl attrHndl offset A typical pseudo code for reading the content of an attribute calling BleGattcRead which in turn will result in t
202. ared string variable Exorlist An expression list which defines the data to be printed consisting of comma or semicolon separated arithmetic or string expressions Formatting with SPRINT Expression Lists Expression lists are used for outputting data principally with the PRINT command and the SPRINT command Two types of Expression lists are allowed arithmetic and string Multiple valid Expression lists may be concatenated with a comma or a semicolon to form a complex Expression list The use of a comma forces a TAB character between the Expression lists it separates and a semicolon generates no output The latter results in the output of two expressions being concatenated without any whitespace Numeric Expression Lists Numeric variables are formatted in the following form lt type base gt arithexpr lt seoarator gt Where Type Must be INTEGER for integer variables base Integers can be forced to print in decimal octal binary or hexadecimal by prefixing with D O B or H respectively For example INTEGER h somevar will result in the content of somevar being output as a hexadecimal string Arithexpr A valid arithmetic or logical expression Separator One of the characters or which have the following meaning Insert a tab before the next variable Print the next variable without a space String Expression Lists String variables are formatted in the following form lt
203. as 1 800 492 2320 Option 2 87 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual string byRef string AS STRING The target string nChr byVal nCHr AS INTEGER The character that will overwrite the existing characters nChr must be within the range O and 255 nindex byVal nindex AS INTEGER The position in the string of the character that will be overwritten referenced to a zero index Note string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Interactive Command NO Example StrSetChar sb See in BL600CodeSnippets zip DIM S3 3 ose Hel ilo PRINT Strsetche s5 76470 oA ts Ene AS II decimal Code tor tie char a PRINT Sercerenr so 64 5 SS will loys oS avclec PRINTE Vn ss Expected Output 000 ello e e STRSETCHR is a core function STRGETCHR FUNCTION STRGETCHER is used to return the single character at position nindex within an existing string STRGETCHR string nindex Returns INTEGER The ASCII value of the character at position n index within string where nindex is zero based If nindex is greater than the number of characters in the string or lt 0 then an error value of 1 is returned Exceptions Local Stack Frame Underflow
204. assign a polarity value which detects either level transitions GPIOASSIGNEVENT n ventNum nSigNum nPolarity Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments nEventNum byVal nEventNum NTEGER The GPIO event number in the range of O N which will result in the event EVDETECTCHANn being thrown to the smart BASIC runtime engine Note For BL600 only nEventNum 0 is valid nsigNum byVal nSigNum INTEGER The signal number as stated in the pinout table of the module nPolarity byVal Polarity INTEGER States the transition as follows 0 Low to high transition 1 High to low transition 2 Either a low to high or high to low transition Not available in BL600 Interactive Command NO Example GpioAssignEvent sb See in BL600CodeSnippets zip FUNCTION BEenOrrcess PRINT AnHello ENDFUNC 0 PRINT GpioAssignEvent 0 16 1 Assign event 0 to high low transition on S1oOlG ourccono ONEVENT EVDETECTCHANO CALL BtnOPress When event 0 is detected call Btn0OPress PRINT nPrese button 0 WAL TEVENT Expected Output 0 Press button 0 Hello GPIOASSIGNEVENT is a Module function Americas 1 800 492 2320 Option 2 185 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual GpioUnAssignEvent FUNCTION This routine un
205. assigns the runtime engine event from a level transition assigned using GpioAssignEvent GPIOUNASSIGNEVENT n ventNum Returns INTEGER a result code The most typical value is OxO000 indicating a successful operation Arguments nEventNum byVal nEventNum INTEGER The GPIO event number in the range of 0 N which will be disabled so that it no longer generates run time events in smart BASIC Note For BL600 only nEventNum 0 is valid Interactive Command NO Example GpioUnAssignEvent sb See in BL600CodeSnippets zip FUNCTION BtnOPress PRINT nHello ENDFUNC 1 FUNCTION Imrotimedont PRINT nNothing happened ENDFUNC 0 PRINT GoioAssignEvent 0710 1 An ONEVENT EVDETECTCHANO CALL BtnOPress ONEVENT EVTMRO CALL TmrOTimedOut PRINT GpioUnAssignEvent 0 n PRIN inPress burton Oi TimerStarc 0 8000 0 WALTEVENT Expected Output GPIOUNASSIGNEVENT is a Module function Americas 1 800 492 2320 Option 2 186 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual User Routines As well as providing a comprehensive range of built in functions and subroutines smart BASIC provides the ability for users to write their own which are referred to as user routines as opposed to built in routines These are often used to perform frequently repeated tasks in an application and
206. asssessssssss Main equivalent assesses sasssas ese ssaa sss ssss sss es sas sae ss se se casas ss esas see saseaseessssssss ONEVENT EVBLEMSG CALL HndlrBleMsg CnEvent EVEINDDE Se call HandlerFindDesc Register base uuids with the underlying stack otherwise the services with the 128bit uuid s will be delivered with a uid handle FFO00000 UNKNOWN vurde 1172324455667 ee 99AABBCCEDERFEOO uuid StrDehexizes uuids uHndl BleHandleUuid128 uuid uud 1122DEAD556677898992AABBCCDDBEBEOO uurcds StrDehexizes uurids uHndl BleHandleUuid128 uuid TE On tkartup OC THEN PRINT nAdvertising and Gatt Client is open n ELSE PRINTE ime lime On CaL Lup ENDIF WALTEVENT PR TITA DE Enan Expected Output BLEGATTCFINDDESC is an extension function BleGattcRead BleGattcReadData FUNCTIONS If the handle for an attribute is known then these functions are used to read the content of that attribute from a specified offset in the array of octets in that attribute value Given that the success or failure of this read operation is returned in an event message a handler must be registered for the EVATTRREAD event Americas 1 800 492 2320 Option 2 294 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Depending on the connection interval the read of the attribute may take many 100s of millis
207. attr after sign extension nindex byVal nindex AS INTEGER This is the zero based index into the string attr from which data is read If the string attr is not long enough to accommodate the index plus the number of bytes to read this function fails Interactive Command NO E DIM DIM DIM DIM ample BleDecode32 sb See in BL6o00CodeSnippets zip cChilandike viL svViechancdle we mdVal mdVal BleAttrMetadata 1 1 50 0 rc acero 2 ecibero OO VOI 02 03 04 65 86 87 es eo uuid uuid 0x1853 rc BleSvcCommit 1 BleHandleUuidl6 uuid svcHandle rc BleCharNew 0x07 BleHandleUuidl6 0x2A1C mdVal 0 0 te B leCharcCommit svchandle aketo Chunandle rc BleCharValueRead chrHandle attr re ad 4 signed bytes from index 2 rc BleDecode32 attrS vl1 2 PRINT Y ncarca in Hex 0x INTEGER A vi PRINT YV ndata in Decimal 2 yiz a re ad 4 signed bytes from index 6 rc BleDecode32 attrS vl1 6 PRINT ndata in Hex Ux INTEGER AH wyi PRINT Y andata in Decimal sey IY iat Americas 1 800 492 2320 Option 2 328 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output BLEDECODE32 is an extension function BleDecodeFLOAT FUNCTION This function reads four bytes in a string at a specified offset into a couple of 32bit integer variables The decoding results in two va
208. b SPIWRITE is a core function SpiRead FUNCTION This function is used to read data from a SPI slave Note a handle parameter is NOT required as this function is used to interact with the main interface In the future a new version of this function will be made available if more than one SPI interface is made available SPIREAD stRead nReadLen Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation Arguments stRead bykef stRead AS STRING This string will contain the data that is read trom the slave nkeadLen byVal nReadlen AS INTEGER This specifies the number of bytes to be read from the slave Interactive Command No Related Commands SPICLOSE SPIREADWARITE SPIWRITE SPIREAD Example See SpiExample sb SPIREAD is a core function Americas 1 800 492 2320 Option 2 161 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Cryptographic Functions This section describes cryptographic functions that can be used to encrypt and decrypt data over and above and in addition to any crypting applied at the transport layer In cryptography there are many algorithms which could be symmetric or assymetric Each function described in this section will detail the type and modes catered for AesSetKeylV
209. ba5ea5l167c The UUID of the ModemOut characteristic is 569a2002 b87 490c 92cb 11lba5ea5l167c Note Laird s Base 128bit UUID Is 569aXXXX b87 490c 92cb l1lba5ea5167c where XXXX is a 16 bit offset We recommend to save RAM that you create a 128 bit UUID of your own and manage the 16 bit space accordingly akin to what the Bluetooth SIG does with their 16 bit UUIDs If command AT CFG 112 1 Is used to change the value of the contig key 112 to 1 then Nordic s serial port service is exposed with UUID s as follows The UUID of the service is 6e 400001 b5a3 393 e0a9 e50e24dcca9e The UUID of the rx fifo characteristic is 6e 400002 b5a3 393 e0a9 e50e24dcca9e The UUID of the tx fifo characteristic is 6e400003 b5a3 393 e0a9 e50e24dcca9e Note The first byte in the UUID s above is the most significant byte of the UUID The rx fifo characteristic is for data that comes to the module and the tx fifo characteristic is for data that goes out from the module This means a GATT Client using this service will send data by writing into the rx fifo characteristic and will get data from the module via a value notification The rx fifo characteristic is defined with no authentication or encryption requirements a maximum of 20 bytes value attribute The following properties are enabled WRITE WRITE_NO_RESPONSE The tx fifo characteristic value attribute is with no authentication or encryption req
210. been corrected in release 1 2 54 4 and the firmware is available as a uart download on request You should upgrade the firmware if you have an I2C slave not responding to the correct slave address This function is used to write an 8 bit value to a register inside a slave which is identified by an 8 bit register address Note a handle parameter is NOT required as this function is used to interact with the main interface In the future a new version of this function will be made available if more than one 2C interface is made available most likely made available by bit bashing gpio Americas 1 800 492 2320 Option 2 146 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Laird Technologies smart BASIC User Manual I2CWRITEREG8 nSlaveAddr nRegAddr nRegValue Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments nSlaveAdar byVal nSlaveAdar AS INTEGER This is the address of the slave in range O to 127 nRegAdar byVal nRegAdadr AS INTEGER This is the 8 bit register address in the addressed slave in range O to 255 nkegValue byVal nRegValue AS INTEGER This is the 8 bit value to written to the register in the addressed slave Please note only the lowest 8 bits of this variable are written Interactive Command No Related Commands I2COPEN I2CCLOSE I2CWRITEREAD I2CWRITEREG8 I2CWRITEREG16 IZCWRITEREG32 IZCREADREGS8 I2CREADR
211. binary using the following nomenclature Decimal D 1234 or 1234 default Hex H 1234 or 0x1234 Octal 0 1234 Binary B 01010101 Note By default all numbers are assumed to be in decimal format The maximum decimal signed constant that can be entered in an application is 2147483647 and the minimum is 2147483648 A hexadecimal constant consists of a string consisting of characters O to 9 and A to F a to f It must be prefixed by the two character token H or h or Ox H 1234 h DEADBEEF 0x1234 An octal constant consists of a string consisting of characters O to 7 It must be prefixed by the two character token O or o 0 1234 0 5643 Americas 1 800 492 2320 Option 2 55 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual A binary constant consists of a string consisting of characters O and 1 It must be prefixed by the two character token B or b B 11011100 b 11101001 A binary constant can consist of 1 to 32 bits and is left padded with Os String Constants A string constant is any sequence of characters starting and ending with the character To embed the character inside a string constant specify it twice Hello World Laird Rocks in this case the string is stored as Laird Rocks Non printable characters and print format instructions can be inserted within a constant string by
212. blown customised terminal emulator for Windows available upon request at no cost See Chapter 2 UWTerminal for information on writing smartBASIC applications using UWTerminal UWTerminal also embeds s martBASIC to automate its own functionality the extension smartBASIC functions facilitate the automation of terminal emulation functionality smartBASIC Operating Modes Any platform running smartBASIC has up to three modes of operation Interactive Mode In this mode commands are sent via a streaming interface which is usually a UART and are executed immediately This is similiar to the behavior of a modem using AT commands Interactive mode can be used by a host processor to directly contigure the module It is also used to manage the download and storage of smart BASIC applications in the flash file system subsequently used in run time mode Application Load Mode This mode is only available if the platform includes the compiler in the firmware image The BLE module has limited firmware space and so compilation is only possible outside the module using a smartBASIC cross compiler provided for free If this feature is available then the platform switches into Load mode when the compile AT CMP command is sent by the host In this mode the relevant application is checked for syntax correctness on a line by line basis tokenised to minimise storage requirements and then stored in a non volatile file system as the compiled applicati
213. bluetooth smart BASIC User Manual Note When WAITEVENT services an event handler if the return value from that routine is non zero then it continues to wait for more events A zero value forces the next statement after WAITEVENT to be processed Arguments Routine The FUNCTION that is called when the event is detected This must be a function which returns an INTEGER and takes no parameters It must not be a SUB routine It must exist within the application PRIOR to this ONEVENT command Symbolic_Name A symbolic event name which is predefined for a specific smart BASIC module Some Symbolic Event Names A partial list of symbolic event names are as follows EVTMRn Timer n has expired see Timer Events EVUARTRX Data has arrived in UART interface EVUARTTXEMPTY The UART TX ring buffer is empty Note Some symbolic names are specific to a particular hardware implementation Interactive Command NO Example OnEvent sb See in BL600CodeSnippets DIMES FUNCTION BenOQpress PRINT nButton 0 has been pressed BNDEUNEG i Will continue waiting for an event FUNCTION Btn rel PRINT nButton 0 released Resume waiting for an event n EN DPEULC wl FUNCTION Btnlpress PRINT nButton 1 has been pressed ENDFUNC 1 FUNCTION Btnlrel PRINT nButton 1 released No more waiting for events n ENDEUNG 6 rc gpiobindevent 0 16 0 Cimndss Golo Ehanore lon Nig on suelo sirron 0 to event 0 re
214. bute string from which the function reads timestamp byRef timestamp AS STRING On exit this is an exact 7 byte string as described above For example 5 May 2013 10 31 24 Is stored as 14 0D 0O5 05 0A 1F 18 nindex byVal nindex AS INTEGER This is the zero based index into the string attr from which data is read If the string attr is not long enough to accommodate the index plus the number of bytes to read this function fails Interactive Command NO Example BleDecodeTimestamp sb See in BL600CodeSnippets zip DIM chphandile 7ilasvCchamdle re sesso DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc Tora May 20L Se be oA DiM atiri ae AOOO 02 Db 07 0505 0A lh ale DIM iad 3 uui 0x18953 rc BleSvcCommit 1 BleHandleUuidl6 uuid svcHandle rc BleCharNew 0x07 BleHandleUuidl6 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle rc BleCharValueRead chrHandle attr cead 7 byte timestamp from the index 3 in the string rc BleDecodeTimestamp attrs tsS 3 PRINT nTimestamp StrHexizeS ts Expected Output Timestamp 140D05050A1F18 BLEENCODETIMESTAMP is an extension function BleDecodeSTRING FUNCTION This function reads a maximum number of bytes from an attribute string at a specified offset into a destination string This function will not fail as the output string can take truncated strings BLEDECODESTRING attr nindex dst nMaxBytes Returns INTEGER the number of bytes e
215. cInit sb See in BL600CodeSnippets zip DIM ae pdvchmes mmeNicriolkeapocnice ManConm Ine MaxConmime Conmelpl sk so dvcNme S Laird TS nmewrtble 0 apprnce 768 MinConniInt 500000 MaxConnint 1000000 ConnSupTO 4000000 sL 0 Device name will not be writable by peer The device will appear as a Generic Thermometer Minimum acceptable connection interval is 0 5 seconds Maximum acceptable connection interval is 1 second Connection supervisory timeout is 4 seconds Slave latency number of conn events that can be missed rc BleGapSvcInit dvcNmeS nmeWrtble apprnce MinConnInt MaxConnInt ConnSupToO sL IF lre THEN PRINT nSuccess ELSE PRINT nFailed ENDIF Expected Output Ose TE IRIN isl ice Print result code as 4 hex digits Success BLEGAPSVCINIT is an extension function Americas 1 800 492 2320 Option 2 235 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleGetDeviceName FUNCTION This function reads the device name characteristic value trom the local gatt table This value is the same as that supplied in BleGapSvcinit if the nameWritable parameter was O otherwise it can be different EVBLEMSG event is thrown with msgid 21 when the GATT client writes a new value and is the best time to call this function BLEGETDEVICENAMES Returns STRI
216. ccessful EN DE WALTEVENT Expected Output When connection made with BL600 Expected Output When no connection made EVDISCON This event is thrown when there is a disconnection It comes with 2 parameters Parameter 1 is the connection handle and Parameter is the reason for the disconnection The reason for example can be 0x08 which signifies a link connection supervision timeout which is used in the Proximity Profile A full list of Bluetooth HCI result codes for the reason of disconnection can be determined in provided in this document here Americas 1 800 492 2320 Option 2 193 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Example EvDiscon sb See in BL600CodeSnippets zip DIM addres lt addrs FUNCTION HndlrBleMsg BYVAL nMsgId AS INTEGER BYVAL nCtx AS INTEGER IF nMsgID 0 THEN PRINT nNew Connection nCtx ENDILE EN DEUNG FUNCTION BtnOPress PRE HA Soules cals wisi ae pra ee BNDEUNG FUNCTION HndlrDiscon BYVAL hConn AS INTEGER BYVAL nRsn AS INTEGER AS INTEGER PRINT aConmecttom hConm Closed 0x nken ENDFUNC 0 ONEVENT EVBLEMSG CALL HndlrBleMsg ONEVENT EVDISCON CALL HndilrDiscon J Secs a a IF BleAdvertStart 0 addrS 100 10000 0 0 THEN PRINT nAdverts Started n BLSE PRINT n nAdvertisement not successful ENDIF WALTEVENT Expected Output
217. cerLndChar contine unes src umad erick IF rc 0 THEN BleDiscCharFirst will exit with O when operation is complete WALILTEVENT ENDIF CloseConneerioene ENOL NEE i Americas 1 800 492 2320 Option 2 239 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual fonction Handlerkind C har cHndl er conp hvala sas ieee t PLeinte GE VEwNDehAR y Dien SCH mel climes Print Props CProo Prints valina n hval an ar T O E O a O IF hVal 0 THEN PR bic NOM find the characteristic ETSE PRINT nFound the characteristic at handle hVal PAREN Nn ve Iob lt 7s Ihe Beh 3 Claicue ile be 7 elkobx ENDIF endfunc 0 faosesese sass sass sass esses 5555555 555 55 SS SS SSS Main equivalent aeessssesssasesesasese sess ese sess sss eS SSS SS 55 5 5 SS SS SSS ONEVENT EVBLEMSG CALL HndlrBleMsg OnEvent EVFINDCHAR call HandlerFindChar Register base uuids with the underlying stack otherwise the services with the 28bit uuid s will be delivered with a uuid handle FFOO0000 UNKNOWN muds 1122334455667 763 S9AABBCCDDEEEEOO wuidS StrDehexizes uuids uHndl BleHandleUuid128 uuid uuc 1122DEAD55667789899PABBCCDDBEBF OO uuid StrDehexizes uuids uHndl BleHandleUuid128 uuid TF On tartup O THEN PRINT nAdvertising and Gatt Client is open n ELSE PRIN nna lure OnStarkup
218. cicec Using BleGanwivewolmi melee sulo aimvolkwecl iim Oe aie siete aein Nordic Usb Dongle Peo Oe Americas 1 800 492 2320 Option 2 288 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual DIM see wene S e ona micharcll aada 54s Ikebe Ie PUM LiCl SOmsieciac ire DIM ro tador ecicics Seles tro BleAdyRotInit adRpts 2 0 10 IF rc 0 THEN rc BleScanRptInit scRpt ENDIF IF rc 0 THEN rc BleAdvRptsCommit adRpt scRpt ENDIF Te re 0 THEN re BleAdvertStart Oaar a 50 0 0 ENDIE ropen the gatt client with default notify indicate ring buffer size IF rc 0 THEN re BleGattcOpen 0 0 ENDIF ENDEUNG eC SUB CloseConnections rc BleDisconnect conHndl rc BleAdvertStop ENDSUB FUNCTION HndilreleMisg BYVAL nMsgid BYVAL nCrex PEM ors aN annae conhnd nC t IF nMsgID 1 THEN PRINT n n Disconnected EXITFUNG 0 ELSEIF nMsgID 0 THEN PRINT n Connected so scan remote Gatt Table for an instance of char uHndS BleHandleUuidl6 OxDEAD ibys VIL 2S SAE SiS 7 Ss SOM NCC IDI a Ea OG uug StrDehexizes uus unce BlenandlevurdI23 uus sIdx 2 cid ly vallencdle vill be 2 re BleGaccerinolChar conme unes sles umea erd IF rc 0 THEN BleDiscCharFirst will exit with 0 when operation is complete WALITEVENT ENDIF sIdx 1 cid 3 does not exist re BleCac
219. cnum byVal recnum AS INTEGER The record number to be read in the range 1 to n where n is the maximum number of records allowed by the specific module strvar byRef strvar AS STRING The string variable that will contain the data read from the record Interactive Command NO Example NvRecordGet sb See in BL600CodeSnippets zip DEM ees PRINT NvRecordGet 100 r bytes read ERINTO mn es Expected Output When no data present in record Americas 1 800 492 2320 Option 2 173 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual O bytes read NVRECORDGET is a module function NvRecordGetEx FUNCTION NVRECORDGETX reads the value of a user record as a string trom non volatile memory and if it does not exist or an error occurred then the specified default string is returned NVRECORDGETEX recnum strvar strdef Returns INTEGER the number of bytes that are read into strvar Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Out of Memory Arguments recnum byVal recnum AS INTEGER The record number that is to be read in the range 7 to n where n is the maximum number of records allowed by the specific module strvar byRef strvar AS STRING The string variable that will contain the data read from the record strder byVal strdef AS STRING The string variable that will supply
220. com www lairdtech com bluetooth smart BASIC User Manual Subroutines and Functions These should be cited here prior to any program references If any of them refer to other subroutines or functions these referred ones should be placed first The golden rule is that nothing on any line of the application should be new Either it should be an inbuilt smartBASIC function or it should have been defined higher up within the application Event and error handlers Normally these reference subroutines so they should be placed here Main program The final part of the application is the main program In many cases this may be as simple as an invocation of one of the user functions or subroutines and then finally the WAITEVENT statement An example of an application btn button ed test sb which monitors button presses and reflects them to leds on the BLE development kit Is as follows p KR KKK KKK KKK KK KK KK I KK DE E DE KK KK I KK DE DEDE DE DS KK DE S KK I DE DS KK IK KK KK KK kK KK kK Waaro Technologies ec 2013 A E E a a E cles eli at E E a r a a qe When UwTerminal downloads the app it will store it as a filenname a I t which consists Of all characters up to the first and excluding 1t tt E To a a lp teeta tla eae cient ciple clung ste atetacty tected fatale aa estes 7 Simple development board button and LED test Tests the functionality of button 0 button 1 LED O and LED 1 on the
221. com www lairdtech com bluetooth smart BASIC User Manual Expected Output Random number is 2088208507 RAND is a core language function RANDEX FUNCTION The RANDEX function returns a random 32 bit positive integer in the range 0 to X where X is the input argument Use the command AT 1001 or from within an application the function SYSINFO 1001 to determine whether the random number is pseudo random or generated in hardware via a thermal noise generator If 1001 returns O then it is pseudo random and 1 if generated using hardware RANDEX maxval Returns INTEGER A 32 bit integer Exceptions Local Stack Frame Undertlow Local Stack Frame Overflow Arguments maxval byVal maxval AS INTEGER The return value will not exceed the absolute value of this variable Depending on the platform the RANDEX function can be seeded using the RANDSEED function to seed the pseudo random number generator If used RANDSEED must be called before using RANDEX If the platform has a hardware Random Number Generator then RANDSEED has no effect Interactive Command NO Associated Commands RANDSEED Example RANDEX sb See in BL600CodeSnippets zip DM 3 4 95 5 010 PRINTE YnRandom mumoer between 0 anc x ls Y RANDEX X Expected Output Random number between 0 and 500 is 193 RAND is a core language function RANDSEED SUBROUTINE On platforms without a hardware random number generator the RANDSEED function sets th
222. ction Arithmetic Expressions For DO DOWHILE if the arithmetic expression evaluates to a non zero value then the statement block is executed again Care should be taken to ensure this does not result in infinite loops Interactive Command NO Example DoWhile sb See in BL600CodeSnippets zip DIM a AS INTEGER don t really need to supply AS INTEGER a 1 DO a atl PRINT amp DOWHILE a lt 10 loop will end when A gets to the value 10 Expected Output Sia 2345678910 DO DOWHILE is a core function FOR NEXT The FOR NEXT composite statement block allows program execution to be controlled by the evaluation of a number of variables Using the tokens TO or DOWNTO determines the order of execution An optional STEP condition allows the conditional function to step at other than unity steps Given the choice of either TO DOWNTO and the optional STEP there are four variants FOR var arithexor TO arithexor2 statement block NEXT FOR var arthexor TO arithexor2 STEP arithexpr3 statement block NEXT Americas 1 800 492 2320 Option 2 60 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual FOR var arthexor DOWNTO arithexor2 statement block NEXT FOR var arithexor DOWNTO arithexor2 STEP arithexpr3 statement block NEXT Statement block A valid set of program statements Typically several
223. d 1 Standard 1 O High 1 Standard Americas 1 800 492 2320 Option 2 178 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Standard 1 High High 1 High Diconnect 1 Standard Disconnect 1 High Standard 1 Disconnect High 1 Disconnect 2 O 3 0 4 0 5 0 6 0 7 0 if nFuncType ANALOG IN O Use Default for system For BL600 10 bit adc and 2 3 scaling 0x13 For BL600 10 bit adc 1 3 scaling 0x11 For BL600 10 bit adc unity scaling Note The internal reference voltage is 1 2V with 1 5 accuracy WARNING This subtunc value is global and once changed will apply to all ADC inputs Interactive Command NO Example GpioSetFunc sb See in BL600CodeSnippets zip PRINT Govoser rune 3 i 2 j Digital In Golo pin 2 weak pull up resistor PRINT GpioSetFunc 4 3 0 Analog In Gpio pin 4 default settings PRINT GpioSetFunc 5 1 0x12 internal pull up on gpio5 and wake from deep sleep when there is transition from high to low Expected Output E GPIOSETFUNC is a Module function GpioConfigPwm FUNCTION This routine configures the PWM Pulse Width Modulation of all output pins when they are set as a PWM output using GpioSetFunc function described above Please note that this is a sticky configuration calling it affects all PWM outputs already configured
224. d SYSINFO cmdld can be used to return exactly the same information and cmdid is the same value as used in the list above AT DIR COMMAND List all application or data files in the module s flash file system AT DIR lt string gt Returns nOo tFILENAME 1 r nOo tFILENAMEZ2 r nOo tFILENAMEn r nOO r If there are no files within the module memory then only nOO r is sent Arguments string string_constant An optional pattern match string If included AT DIR will only return application names which include this string The match string is not case sensitive This is an Interactive Mode command and MUST be terminated by a carriage return for it to be processed Interactive Command YES Examples AT DIR AT DIR new AT DIR is a core command AT DEL COMMAND This command deletes a Tile from the module s flash file system When the Tile is deleted the space it occupied does not get marked as free for use again Americas 1 800 492 2320 Option 2 34 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Eventually after many deletions the file system does not have free space for new files When this happens the module responds with an appropriate error code when a new file write is attempted Use the command AT amp F 1 to completely erase and reformat the file system At any time you can use the comm
225. d by the thresholds of 80 and 120 which means the when opening the VSP port the rxbuffer cannot be less than 128 bytes It is intended that in a future release it will be possible to register a custom service and bind that with the virtual service manager to allow that service to function in the managed environment This allows the application developer to interact with any GATT client implementing a serial port service whether one currently deployed or one that the Bluetooth SIG adopts VSP Configuration Given that VSP operation can happen in command mode the ability to configure it and save the new configuration in non volatile memory is available For example in bridge mode the baudrate of the uart can be specified to something other than the default 9600 Configuration is done using the AT CFG command and refer to the section describing that command for further details The configuration id pertinent to VSP are 100 to 116 inclusive Americas 1 800 492 2320 Option 2 339 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Command amp Bridge Mode Operation Just as the physical UART is used to interact with the module when it is not running a smartBASIC application it is also possible to have limited interaction with the module in interactive mode The limitation applies to NOT being able to launch smartBASIC applications usi
226. d eeleMse BY VAs mMso la BYVAL n rx Combing ime tx IF nMsgID 1 THEN PRINT n n Disconnected from client EXLITEUNG Q ELSEIF nMsgID 0 THEN PRINT n Connected to client ENDILE ENDFUNC 1 fasososssssssasesassasssasesess esas sess ses sss SSS 555 SSS 5 a SS SSS New char value handler feeeeses2 ss 5s S555 SS FUNCTION HandlerCharVal BYVAL charHandle BYVAL offset BYVAL len DIM s IF charHandle hMyChar THEN PRINT n len byte s have been written to char value attribute from Offset Yr OFESEE rc BleCharValueRead hMyChar s PRINT niNew Char value ss ENDIF CloseConnections ENDFUNC 1 ONEVENT EVCHARVAL CALL HandlerCharVal ONEVENT EVBLEMSG CALL HndlrBleMsg Americas 1 800 492 2320 Option 2 195 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual TF Onstarcup 0 THEN re BleCharValueRead hMyChar at PRINT A nValue of the characteristic 19s zar PRINT nSend a new value to write to the characteristic n BLSE PRINT AnFailure Onstartup EN DIE WALTEVENT PRINTANE ei ie NGN Expected Output EVCHARHVC This event is thrown when a value sent via an indication to a client gets acknowledged It comes with one parameter which is the characteristic handle that was returned when the characteristic was registered using the function BleCharCommit Example EV
227. d is to be appended nlag byVal nTag AS INTEGER nTag should be in the range O to FF and is the TAG field for the record stData bykef stData AS STRING This is an octet string which can be O bytes long The maximum length is governed by the space available in AdvRpt a maximum of 31 bytes long Interactive Command NO Example BleAdvRptAppendAD sb See in BL600CodeSnippets zip DIM scnRpt ad acl 0L VO 03 04 PRINT Blescankob ini senkprs IF BleAdvRptAppendAD scnRpt 0x31 ad 0 THEN 6 bytes will be used up in the LepOtrE PRINT nAD with data ad was appended to the advert report ENDIF Expected Output 0 AD with data 01 02 03 04 was appended to the advert report BLEADVRPTAPPENDAD is an extension function BleGetADbyIndex FUNCTION This function is used to extract a copy of the nth zero based advertising data AD element from a string which is assumed to contain the data portion of an advert report incoming or outgoing Please not that if the last AD element is malformed then it will be treated as not existing For example it will be malformed if the length byte for that AD element suggests that more data bytes are required than actually exist in the report string Americas 1 800 492 2320 Option 2 215 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BLEGETADBYINDEX nindex
228. d launch the emulator directly into the terminal screen The four LED type indicators below the tabs display the status of the RS 232 control lines that are inputs to the PC The colors are red green or white White signifies that the serial port is not open Note According to RS 232 convention these are inverted trom the logic levels at the GPIO pin outputs on the module A Ov on the appropriate pin at the module signifies an asserted state CTS Clear to Send Green indicates that the module is ready to receive data DSR Data Set Ready Typically connected to the DTR output of a peripheral DCD Data Carrier Detect RI Ring Indicate If the module is operating correctly and there is no radio activity then CTS should be asserted green while DSR DCD and RI are deasserted red Again note that if all four are white Figure 6 it means that the serial port of the PC has not been opened and the button labelled OpenPort can be used to open the port Americas 1 800 492 2320 Option 2 14 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Terminal BASIC Config About cis DSR pcog AIG RTSiv DTRiv BREAK E LocalE cho Iv LineMode lv Clear OpenPort Figure 6 White lights Note At the time of this manual being written the DSR line on the BL600 Devkit is connected to the SIO25 signal on
229. d to 2 hex characters It will therefore result in a string which is exactly double the length of the original string STRHEXIZE string Returns STRING A printable version of string which contains only hexadecimal characters and exactly double the length of the input string Exceptions Local Stack Frame Undertlow Local Stack Frame Overflow Memory Heap Exhausted Arguments String byRef string AS STRING The string to be converted into hex characters Interactive Command NO Note string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Associated Commands STRHEX2BIN Americas 1 800 492 2320 Option 2 93 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Example StrHexizeS sb See in BL600CodeSnippets zip DIMNE es sS Laird ASC RINDI E Ma ae tS StrHexizes s PRINT Strlentes 2 in PRE eS Might PR trL Len bo ae Expected Output Laird 5 4C61697264 10 STRHEXIZE is a core function STRDEHEXIZE STRDEHEXISE is used to convert a string consisting of hex digits to a binary form The conversion stops at the first non hex digit character encountered STRDEHEXIZE string Function Returns STRING A dehexed version of string
230. dar byVal nSlaveAdar AS INTEGER This is the address of the slave in range O to 127 nRegAdar byVal nRegAdar AS INTEGER This is the 8 bit start register address in the addressed slave in range 0 to 255 nkegValue byVal nRegValue AS INTEGER This is the 32 bit value to be written to the register in the addressed slave Interactive Command No Related Commands IZ2COPEN I2CCLOSE I2CWRITEREAD I2CWRITEREG8 I2CWRITEREG16 IZCWRITEREG32 IZCREADREGS8 I2CREADREG16 I2CREADREG3S2 Example I2cWriteReg32 sb See in BL600CodeSnippets zip Please ensure that nSlaveAddr is the slave address of your I2C peripheral DIM handle DIM nSlaveAddr nRegAddr nRegVal DIM reo re 1Z2cOpen 100000 0 handle IF rel 0 THEN PRINT nFailed to open I2C interface with error code INTEGER h rc ELSE PRINT ni2 wooen succese TINIE IE IE nSlaveAddr Ox6of nRegAddr 0x56 nRegVal 0x4210FEDC re I2cWriteReg32 nSlaveAddr nRegAddr nRegVal IF rc 0 THEN PRINT nFailed to Write to slave register INTEGER H rc ELSE Americas 1 800 492 2320 Option 2 152 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT n nRegVal written successfully to register nRegAddr ENDIF I2cClose handle close the port Expected Output I2C open success 1108410076 written successfully to register 86 IZCWRITEREG32 is a c
231. deSnippets zip DIM ceemnrna il a M Open Vsp and start advertising BE i MMMM SUB Onsite tue DIe hice ex eC ic addr a a aR ms aC hioleo 0 me adde ro BleVopopen 122 128 0 andl rce Bleocankpt Init SCRpU gt rc BleAdvRptAddUuidl128 scRpts hnd1 rc BleAdvRptsCommit adRpt scRpts eC BleAdvertStare 0 addrs 20 300000 0 rc GpioBindEvent 1 16 1 j Cianne ly pind tos low trans netoneon EGPlO pin iG PRINT nDevice name is BleGetDeviceNameS txS nSend me some text I won t get it nTo exit the app press Button 0O n re BlevVSpWrite tx S lak BES OLS SUB CloseConnections DEM tee rc BleDisconnect conHnd1 rc BleAdvertStop BleVspClose BleVspFlush 2 EASA beth OUr ESTS ENDSUB Americas 1 800 492 2320 Option 2 351 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual FUNCTION HandlerVSpRx AS INTEGER BleVspFlush 0 PRINT mRx butter flushed ENDFUNC 1 BUNGCLTLOMN nde Bed OP AS INTEGER stop waiting for events and exit app ENPBUNE 0 FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx CO minnie i mG mx IF nMsgID 1 THEN PRINT nDisconnected from client EXIT TE UNC C EDIE ENDFUNC 1 ONE VENTS EVVSERX CALL HandlerVSpRx ONEVENT EVBLEMSG CALL HndlrBleMsg ONE VENT EVGETOCHANT CALL HndilrBENOPTr OnStartup Calls first subroutine declared above WALTEVENT CloseCon
232. deSvc hService Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation Arguments hService byVal hService AS INTEGER This argument will contain a handle that was previously created using the function BleSvcCommit Interactive Command NO Example BleSvcAddIncludeSvc sb See in BLO00CodeSnippets zip define BCE SERV ECE TO ECONDARY 0 define BEE Polk Teh PRIMARY 1 Ye ee ee dim NBarsvc composite handle for batteru primary service elim ie or we could have reused nHtsSvc dim metaSuccess DIM charMet charMet BleAttrMetaData 1 1 10 1 metaSuccess DIM s sS Hello initial value of char in Battery Service aa ae inves ie ASS econ we VEN Sm Vile SCONDVA E eA ore Ihe ea eO IcUie pin Sele Swe re BleCharNew 3 BleHandleUuidl6 Ox2A1C charMet 0 0 TOS PIEC hoar one tears ves gt oboe ne DIN REE Sie composite handle for hts primary service Pee EIS eC O nmi EERE EEVI ERE MAR B ECR nN eE ox Osho 7 AE Have to add includes before any characteristics are committed PRINT INTEGER bh Blesvenddincludesve hbatsvc BleSvcAddIncludeSvc is an extension function BleAttrMetadata FUNCTION A GATT Table is an array of attributes which are grouped into Characteristics which in turn are further grouped into Services Each attribute consists of a data value which can be anything from 1 to 512 bytes long according to the specification and properties such as read a
233. driven architecture of smart BASIC the serial communications subsystem enables smart BASIC applications to be written which allow communication events to trigger the processing of user smart BASIC code Note that if a handler function returns a non zero value then the WAITEVENT statement is reprocessed otherwise the smart BASIC runtime engine will proceed to process the next statement after the WAITEVENT statement not after the handlers ENDFUNC or EXITFUNC statement Please refer to the detailed description of the WAITEVENT statement for further information UART Universal Asynchronous Receive Transmit This section describes all the events and routines used to interact with the UART peripheral available on the platform Depending on the platform at a minimum the UART will consist of a transmit a receive a CTS Americas 1 800 492 2320 Option 2 125 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Clear To Send and RTS Ready to Send line The CTS and RTS lines are used for hardware handshaking to ensure that buffers do not overrun If there is a need for the following low bandwidth status and control lines found on many peripherals then the user is able to create those using the GPIO lines of the module and interface with those control status lines using smart BASIC code Output DTR Data Terminal Ready Input DSR Data
234. dtech com www lairdtech com bluetooth smart BASIC User Manual A g r vy e er ayd ORE whe ae Cl paper Phi wad nre s q O Pan 2 DAWork BLE DEV_MAI N Uw yScript UwTerminal Target XComp_B1600Med_9 56_5F81 exe UwScript Cross Compiler Cc Laird Technologies 2008 B1l666Med 6 8 19 8 2 4 LANGUAGE HASH E56 5SF81 HARRE Compiling file lt D Work BLE DEU_MAIN UserManual testi sh gt Se eee eee eee eee eed print nHello World n ERROR Line 1 Code 1566 Hit any key to exit Figure 13 Compilation error window Now that the application has been downloaded into the module run it by issuing test1 or AT RUN testi Note smartBASIC commands variables and filenames are not case sensitive smartBASIC treats Test7 test and TEST1 as the same file The screen should display the following results when both forms of the command are entered attrun testl Hello World 00 Testl Hello World 00 You can check the file system on the module by typing AT DIR and pressing Enter you should see 06 test1 00 You have just written and run your first smartBASIC program To make it a little more complex try printing Hello World ten times For this we can use the conditional functions within smartBASIC We also introduce the concept of variables and print formatting Later chapters go into much more detail but this gives a flavor of the way they work Before we do that it s wo
235. dtech com bluetooth smart BASIC User Manual DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc DIN aeree e sort izo O00 OlV02 03 04 8586 87 ceo DIM uuic 3 uuid 0x1853 rc BleSvcCommit 1 BleHandleUuidl6 uuid svcHandle rc BleCharNew 0x07 BleHandleUuidl6 0Ox2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle rc BleCharValueRead chrHandle attr cead 4 bytes FLOAT from index 2 in the string rc BleDecodeFloat attrs mantissa exp 2 PRINT nihe number read as manbicsa x 10 sexp read 4 bytes FLOAT from index 6 in the string rc BleDecodeFloat attrS mantissa exp 6 PRINT nThe number read is mantissa x 10 exp Expected Output The number read is 262914 10 123 The number read is 7 829626 10 119 BLEDECODEFLOAT is an extension function BleDecodeSFLOAT FUNCTION This function reads two bytes in a string at a specified offset into a couple of 32bit integer variables The decoding results in two variables the 12 bit signed maintissa and the 4 bit signed exponent If the offset points beyond the end of the string then this function fails BLEDECODESFLOAT attr nMatissa nExponent nindex Returns INTEGER the number of bytes extracted from the attribute string Can be less than the size expected if the nindex parameter is positioned towards the end of the string Arguments attr byRef attr AS STRING This references the attribute string from which the function reads
236. dule then it will force the module into deep sleep mode as long as BREAK Is asserted As soon as BREAK is deasserted the module will wake up through a reset as if it had been power cycled Americas 1 800 492 2320 Option 2 127 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual UARTOPEN baudrate txbuflen rxbuflen stOptions Returns INTEGER Indicates success of command O 0x5208 0x5209 Ox520A Ox520B Ox520C Ox520D Ox520E Ox520F Ox5210 Opened successfully Invalid baudrate Invalid parity Invalid databits Invalid stopbits Cannot be DTE because DCD and RI cannot be inputs Cannot be DCE because DCD and RI cannot be outputs Invalid flow control request Invalid DTE DCE role request Invalid length of stOptions parameter must be 5 chrs Exceptions Arguments baudrate txbuflen rxbuflen stOptions 0x5211 0x5212 Invalid tx buffer length Invalid rx buffer length Local Stack Frame Underflow Local Stack Frame Overflow byVal baudrate AS INTEGER The baudrate for the uart Note that the higher the baudrate the more power will be drawn from the supply pins AT 1002 or SYSINFO 1002 returns the minimum valid baudrate AT 1003 or SYSINFO 1003 returns the maximum valid baudrate byVal txbutlen AS INTEGER Set the transmit ring buffer size to this value If set to O then a default val
237. e 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual We believe that if wireless connectivity is going to be widely accepted there must be an easier way to manage It smartBASIC was developed and designed to extend a simple BASIC like programming language with all of the tokens that control a wireless connection using modern language programming constructs smartBASIC differs from an object oriented language in that the order of execution is generally the same as the order of the text commands This makes it simpler to construct and understand particularly if you re not using it every day Our other aim in developing smartBASIC from the ground up is to make wireless design of products both simple and similar in look and feel for all platforms To do this we are embedding smartBASIC within our wireless modules along with all of the embedded drivers and protocol stacks that are needed to connect and transfer data A run time engine interprets the customer applications reduced to bytecode that are stored there allowing a complete product design to be implemented without the need for any additional external processing capability Why Write Applications smartBASIC for BLE has been designed to make wireless development quick and simple vastly cutting down time to market There are three good reasons for writing applications in s martBASIC Since the module can a
238. e to it To store application data so that they are non volatile use the functions described in the section Non Volatile Memory Management Routines This means any and all user data Tiles need to be preloaded using the commands AT FOW AT FWR or AT FWRH AT FCL which are described in the section Interactive Mode Commands The utility UwTerminal helps with downloading such Tiles but not strictly required This section describes all the functions that are available to an application to interact with data files in read mode Americas 1 800 492 2320 Option 2 167 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual With the use of READ FTELL and FSEEK downloading configuration files like say digital certificates can be a very useful and convenient way of making an app behave in custom manner from data derived from these data files as demonstrated by the example application listed in the description of FOPEN FOPEN FUNCTION This function is used to open a Tile in mode specified by the mode string parameter When the file Is opened the file pointer is set to O which effectively means that a read operation will happen from the beginning of the file and then after the read the file pointer will be adjusted to offset equal to the size of the read Function FSEEK is provided to move that file pointer to an offset
239. e composite handle for the newly created Characteristic is returned in this argument It is zero if the function fails with a non zero result code This handle is then used as an argument in subsequent function calls to perform read write actions so it is must be placed in a global smartBASIC variable When a significant event occurs as a result of action by a remote client an event message is sent to the application which can be serviced using a handler That message contains a handle field corresponding to this composite characteristic handle Standard procedure is to select on that value to determine which Characteristic the message Is intended for See event messages EVCHARHVC EVCHARVAL EVCHARCCCD EVCHARSCCD EVCHARDESC Interactive Command NO Example BleCharCommit sb See in BL600CodeSnippets zip DEFINE BLE SERVICH SECONDARY O DEFINE BEET OERVICETERIMARY IL Biv Mae DIM aero wsrMeses Usriesco A description DIN GRE swe composite handle for hts primary service DIM mdCharVal mdCharVal BleAttrMetaData 1 1 20 0 rc DIM mdCced mdGccd BleAttrMetadata 1 2 0 rc DIM mdUsrDsc mdUsrDsc BleAttrMetaData 1 1 20 0 rc DIM hHtsMeas composite handle for htsMeas characteristic Create the Measurement Characteristic object add user description descriptor rc BleCharNew 0x2A BleHandleUuidl16 0x2A1C mdCharVal mdCccd 0 rc BleCharDescUserDesc usrDescS mdUsrDsc atiro mele VOOwer Ine 4 IF
240. e containing the results A non zero return value implies an EVFINDCHAR message will NOT be thrown Arguments connHandle byVal nConnHandle AS INTEGER This is the connection handle as returned in the on connect event for the connection on which the remote Gatt Server can be accessed This will have been returned in the EVBLEMSG event message with msgld 0 and msgCtx will have been the connection handle svcUuidHnal byVal svcUuidHnal AS INTEGER Set this to the service uuid handle which will have been generated either by BleHandleUuid16 or BleHandleUuid128 or BleHandleUuidSibling svcindex byVal svcindex AS INTEGER This is the instance of the service to look for with the uuid handle svcUuidHnadl where 0 is the first instance 1 is the second etc charUuidHnal byVal charUuidHnal AS INTEGER Set this to the characteristic uuid handle which will have been generated either by BleHandleUuid16 or BleHandleUuid128 or BleHandleUuidSibling charindex byVal charindex AS INTEGER This is the instance of the characteristic to look for with the uuid handle charUuidHndl where 0 is the first instance 1 is the second etc Interactive Command NO Example BleGattcFindChar sb See in BL600CodeSnippets zip Tei Remote server has 5 prim services with 16 bit ucid and 3 with 128 bit words 3 of the 16 bit uuid are the same value OxDEAD and 2 of the 128 bit uuids are also the same 112233445566778899AABBCCDDEEFF eh i seiwer Cire
241. e on Slave Latency Interactive Command NO See previous example BLEGETCURCONNPAR MS is an extension function Americas 1 800 492 2320 Option 2 223 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Security Manager Functions This section describes routines which manage all aspects of BLE security such as saving retrieving and deleting link keys and creation of those keys using pairing and bonding procedures Events amp Messages The following security manager messages are thrown to the run time engine using the EVBLEMSG message with msgIDs as follows 9 Pairing in progress and display Passkey supplied in msgCtx 10 A new bond has been successfully created 11 Pairing in progress and authentication key requested Type of key is in msgCtx msgCtx is 1 for passkey_type which will be a number in the range O to 999999 and 2 for OOB key which is a 16 byte key To submit a passkey use the function BLESECMNGRPASSKEY BleSecMngrPasskey FUNCTION This function submits a passkey to the underlying stack during a pairing procedure when prompted by the EVBLEMSG with msgld set to 11 See Events amp Messages BLESECMNGRPASSKEY connHandle nPassKey Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments connHandle byVal connHandle AS INTEGER This is the connectio
242. e onboard peripherals Note Itis not currently possible to scan for characteristics in included services This will be a future enhancement EVFINDDESC event message This event message WILL be thrown if BleGattcFindDesc returned a success The message contains 2 INTEGER parameters Connection Handle Handle of the Descriptor If the specified instance of the service characteristic descriptor is not present in the remote Gatt Server Table then all parameters will contain O apart from the Connection Handle Handle of the Descriptor is the handle for the descriptor and is the value to store to keep track of important descriptors in a gatt server for later read write operations for example CCCD s to enable notifications and or indications BLEGATTCFINDDESC connHndl svcUuHndl svcldx charUuHndl charldx descUuHndl descldx A typical pseudo code for finding a descrirptor involves calling BleGattcFindDesc which in turn will result in the EVFINDDESC event message and typically is as follows Register a handler for the EVFINDDESC event message On EVFINDDESC event message If Descriptor Handle 0 then Descriptor not found Else Descriptor has been found Call BleGattcFindDesc If BleGattcFindDesc ok then Wait for EVFINDDESC Returns INTEGER a result code The typical value is OxO000 indicating a successful operation and it means an EVFINDDESC event message WILL be thrown by the smartBASIC Americas 1 800
243. e output will be 1000 2 3 1001 STRXOR string nindex nBytes initVal Function Returns INTEGER The result of the xor operation over the bytes in the substring If nindex or nBytes are negative then the initVal will be returned Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments string byRef string AS STRING String that contains the unsigned bytes which need to be XOR d nindex byVal nindex AS INTEGER Index of first byte into the string nBytes ByVal nBytes AS INTEGER Number of bytes to process initVal ByVal initVal AS INTEGER Initial value of the XOR Note string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Interactive Command NO Example StrXOR sb See in BLO600CodeSnippets zip DIM numbers number OUl734 PRINT OtCrxOR numbers 0 5 0 i KOR TAS AO SiO gt a0 PRINT StexXOR numbers 0 5 10 7 OR Ap 10 50 a oo O PRINT Strxor numbers 0 5 1000 lf ORS 2157497 50 5 52 LUO Americas 1 800 492 2320 Option 2 101 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output ae 62 208 STRXOR is a core function EXTRACTSTRTOKEN This function takes a sentence in the first parameter and extracts
244. e space available in transmit ring buffer Related Commands BLEVSPOPEN BLEVSPCLOSE BLEVSPWRITE BLEVSPREAD BLEVSPFLUSH Americas 1 800 492 2320 Option 2 344 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Example BleVspInfo sb See in BL600CodeSnippets zip DIM AnaL re Close VSP Qk It Ws open BleVSpClose ro BlevspOpen 123 128 0 hndl PRIND A nVop State T Ble VopIni o 0 PRINT nR bDufrer oapocity 1 BleyColmio il PRINT Anr Durrer c oa pae 91 BI eVo opno PRINT mBytes waiting EO be road from rx buffer BlevVSpintro 3 PRINT nrree Space in tx butter BlevVSpinto 4 BleVspClose PRINS Ws Sate Bley soln 0 Expected Output BLEVSPINFO is an extension subroutine BleVSpWrite FUNCTION This function is used to transmit a string of characters from the virtual serial port BLEVSPWRITE strMsg Returns INTEGER O to N Actual number of bytes successfully written to local transmit ring buffer Exceptions Local Stack Frame Undertlow Local Stack Frame Overflow Arguments strMsg byRef strMsg AS STRING The array of bytes to be sent STRLEN strMsg bytes are written to the local transmit ring buffer If STRLEN strMsg and the return value are not the same It implies that the transmit buffer did not have enough space to accommodate the data If the return v
245. e starting point for generating a series of pseudo random integers To reinitialize the generator use 1 as the seed argument Any other value for seed sets the generator to a random starting point RAND retrieves the pseudo random Americas 1 800 492 2320 Option 2 111 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual numbers that are generated It has no effect on platforms with a hardware random number generator RANDSEED seed Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments Seed byVal seed AS INTEGER The starting seed value for the random number generator function RAND Interactive Command No Associated Commands RAND RandSeed 1234 Note Since the BL600 contains a hardware random number generator this subroutine has no effect RANDSEED is a core language subroutine Timer Routines In keeping with the event driven paradigm of smart BASIC the timer subsystem enables smart BASIC applications to be written which allow future events to be generated based on timeouts To make use of this feature up to N timers where N is platform dependent are made available and that many event handlers can be written and then enabled using the ONEVENT statement so that those handlers are automatically invoked The ONEVENT statement is described in detail elsewhere in this manual Brief
246. eUuid128 or BleHandleUuidSibling startAttrHanadle byVal startAttrHandle AS INTEGER This is the attribute handle from where the scan for characteristic will be started and will have been acquired by doing a primary services scan which returns the start and end handles of services endAttrHandle byVal endAttrHandle AS INTEGER This is the end attribute handle for the scan and will have been acquired by doing a primary services scan which returns the start and end handles of services BLEDISCCHARNEXT connHandle Calling this assumes that BleDiscCharFirst has been called at least once to set up the internal characteristics scanning state machine It scans for the next characteristic Returns INTEGER a result code The typical value is OxO000 indicating a successful operation and it means an EVDISCCHAR event message WILL be thrown by the smartBASIC runtime engine containing the results A non zero return value implies an EVDISCCHAR message will NOT be thrown Arguments connHandle byVal nConnHandale AS INTEGER This is the connection handle as returned in the on connect event for the connection on which the remote Gatt Server can be accessed This will have been returned in the EVBLEMSG event message with msgld 0 and msgCtx will have been the connection handle Interactive Command NO Example BleDiscCharFirst Next sb See in BL600CodeSnippets zip oy Remote server has 1 prim service with 16 bit uuid and 8 character
247. eceeseeeeeeseeeeeeseeeceeseeeeeeeeeeeeuseeeneueeeteegeeseeeaseseneageeetsaensees 353 System COR I Uriel Ol ROUTINES etsarss teeters tives r saan sete vee cueses baa E EET ia 353 Miscellaneous ROUTINES cesiaecsccscrcarercsreesecdsnesaisoneevead caiedactaetecuapeercaae2dcivese dd saudsatondeaueros ect sotecvareuseueueiucuevenosadsenie 353 O EVemS amp 1 Los 6 lt n ee ee ee 356 9 Module COM il OEM AOU cet tere E 356 NO PUSS eS US a erect ete AEE A EE teed E E asda een E E A ETA EET EE 357 11 Acknowledgements wisi sinciaicnisitamentdsecnasevanarenivweanenveipnentd inciansudxanwengtciecancatedtimentistasiensinaesaecpiviecancedstiuensivesanibs 358 PEN sr ereawstcteete ae A san dietetanb ease ceca sed egies ua detanedinetaite buna EE E 359 Americas 1 800 492 2320 Option 2 5 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual 1 INTRODUCTION This user manual provides detailed information on Laird Technologies smartBASIC language which is embedded inside the BL600 series Bluetooth Low Energy BLE modules This manual is designed to make handling BLE enabled end products a straightforward process and it includes the following An explanation of the language s core and extension functions Instructions on how to start using the tools A detailed description of all language components and examples of their use The Laird website contains man
248. ech com bluetooth 203 Laird Technologies smart BASIC User Manual PUN PIOl Shinde Nip iy Bud SendData ENDANG EFEUNCTION HMneLlrCharCece BYVAL Charciancldle BYVAL nvVal AS INTEGER DIM value txs IF charHandle hMyChar THEN IF nVal THEN PRINT Notifications have been enabled by client ntfyEnabled 1 txs Heliloe rc BleCharValueNotify hMyChar tx BLSE PRINT nNotifications have been disabled by client ntfyEnabled 0 ENDIF ELSE PRINT nThis is for some other characteristic ENDIF ENDEUNC i ONEVENT EVNODTIPYBUF CALL HndilrNriyeurt ONEVENT EVBLEMSG CALL HndlrBleMsg ONEVENT 2VCHARCCED CALL And brCharc ced IF OnStartup 0 THEN re BleCharValueRead hMyChar ats PRINT mY om Can connect and wr e to the COCD Characterictic PRINT nthe BLCOOO will then send you data until butter is full in ELSE PRINT nfFailure OnStarcup ENDIF WALTEVENT CloseConnections Pen vA NELICO eres Americas 1 800 492 2320 Option 2 204 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Laird Technologies smart BASIC User Manual Expected Output Miscellaneous Functions This section describes all BLE related functions that are not related to advertising connection security manager or GATT BleTxPowerSet FUNCTION This function sets the power of all packets that are transmitted subsequently The actual value is determined by scannin
249. ecified are overwritten If the nindex is such that the new string length exceeds the maximum attribute length this function fails The maximum attribute length can be obtained using the function SYSINFO n where n is 2013 The Bluetooth specification allows a length between 1 and 512 BLEENCODE24 attr nData nindex Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation Arguments attr byRef atir AS STRING This argument is the string that will be written to an attribute nData byVal nData AS INTEGER The three least significant bytes of this integer is saved The rest is ignored Americas 1 800 492 2320 Option 2 312 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual nindex byVal nindex AS INTEGER This is the zero based index into the string attr where the new fragment of data is written If the string attr is not long enough to accommodate the index plus the length of the fragment it is extended If the extended length exceeds the maximum allowable length of an attribute see SYSINFO 2013 this function will Tail Interactive Command NO Example BleEncode24 sb See in BL600CodeSnippets zip DiM ice DIM arcrS 2 arccrceS Lairo J weite TBCD te index rc BleFncode24 attr 0x444342 1 write A to index 0 rc BleEncode8 attrsS 0x41 0 weite EF to index
250. econds and while this is in progress it is sate to do other non Gatt related operations like for example servicing sensors and displays or any of the onboard peripherals BleGattcRead is used to trigger the procedure and BleGattcReadData is used to read the data from the underlying cache when the EVATTRREAD event message Is received with a success status EVATTRREAD event message This event message WILL be thrown if BleGattcRead returns a success The message contains 3 INTEGER parameters Connection Handle Handle of the Attribute Gatt status of the read operation Gatt status of the read operation is one of the following values where O implies the read was successfully expedited and the data can be obtained by calling BlePubGattClientReadData Ox0000 Success 0x0001 Unknown or not applicable status 0x0100 0x0101 0x0102 0x0103 0x0104 0x0105 0x0106 0x0107 0x0108 0x0109 0x010A 0x010B 0x010C 0x010D OxO10E OxO10F 0x0110 0x0111 0x0112 0x017F 0x0180 0x019F 0x0140 Ox01DF 0x01E0 Ox01FC OxO1FD KF Error Invalid Error Code Error Invalid Attribute Handle Error Read not permitted Error Write not permitted Error Used in ATT as Invalid PDU Error Authenticated link required Error Used in ATT as Request Not Supported Error Offset specified was past the end of the attribute Error Used in ATT as Insufficient Authorisation Error Used in ATT as Prep
251. ection describes all functions related to creating and managing services that collectively define a GATT table trom a GATT server role perspective These functions allow the developer to create any Service that has been described and adopted by the Bluetooth SIG or any custom Service that implements some custom unique functionality within resource constraints such as the limited RAM and FLASH memory that is exist in the module A GATT table is a collection of adopted or custom Services which in turn are a collection of adopted or custom Characteristics Although keep in mind that by definition an adopted service cannot contain custom characteristics but the reverse is possible where a custom service can include both adopted and custom characteristics Descriptions of Services and Characteristics are available in the Bluetooth Specification v4 0 or newer and like most specifications are concise and difficult to understand What follows is an attempt to familiarise the reader with those concepts using the perspective of the smartBASIC programming environment To help understand the terms Service and Characteristic better think of a Characteristic as a container or a pot of data where the pot comes with space to store the data and a set of properties that are officially called Descriptors in the BT spec In the pot analogy think of Descriptor as colour of the pot whether it has a lid whether the lid has a lock or whether it has a handle or
252. ed further UARTREADMATCH strMsg chr Returns INTEGER Indicates the presence of the match character in strMsg as follows O data may have been appended to the string but no matching character 1 to N The total length of the string variable up to and including the match chr Note When 0 is returned you can use STRLEN strMsg to determine the length of data stored in the string On some platforms with low amount of RAM resources the underlying code may decide to leave the data in the receive buffer rather than transfer it to the string Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Uart has not been opened using UARTOPEN Arguments strMsg byRef strMsg AS STRING The content of the receive buffer will get appended to this string up to and including the match character Americas 1 800 492 2320 Option 2 138 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual chr byVal chr AS INTEGER The character to match in the receive buffer for example the carriage return character OxOD Interactive Command No Note strMsg cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Related Commands UARTOPEN UARTINFO UARTCLOSE UARTWRITE UARTREAD UARTGETDSR UART
253. ed in trusted device database 2013 Maximum length of a GATT Table attribute in this implementation 2014 Total number of transmission buffers for sending attribute NOTIFIES 2015 Number of transmission buffers for sending attribute NOTIFIES free 2016 Radio activity of the baseband O no activity 1 advertising 2 connected 3 broadcasting and connected 2018 Returns the TX power while pairing in progress see also 2008 2019 Default ring buffer length for notify indicates in gatt client manager see BleGattcOpen function 2020 Maximum ring buffer length for notify indicates in gatt client manager see BleGattcOpen function 2021 Stack tide mark in percent Values near 100 is not good 2022 Stack size 2023 Initial Heap size 0x8000 to 0x81FF Content of FICR register in the Nordic nrf51 chipset In the nrf51 datasheet in the FICR section all the FICR registers are listed in a table with each register identified by an offset so for example to read the Americas 1 800 492 2320 Option 2 78 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Code memory page size which is at offset 0x010 call SYSINFO Ox8010 or in interactive mode use AT Ox8010 Interactive Command No Example SysInfo sb See in BL600CodeSnippets zip PRs ins 7s incon OG e SS ENO OOG BASIC compiler HASH value PRINT anov Info 200s Lesvos unio 2
254. ee in BL600CodeSnippets zip DIM advRptsS advRpts DIMMSOR Oto eop DIM discovMode discovMode 0 DIM advApprnce advApprnce 1 DIM maxDevName maxDevName 10 PRINT BleAdvRptInit advRpt S discovMode advApprnce maxDevName Prati Pile Rou GUm aaa Pee sings Ol Oslo OAV ae lel elu PRINT BlleAdvRersConmmt advyRets CRPE Only the advert report will be updated Expected Output BLEADVRPTSCOMMIT is an extension function Connection Functions This section describes all the connection manager related routines The Bluetooth specification stipulates that a peripheral cannot initiate a connection but can perform disconnections Only Central Role devices are allowed to connect when an appropriate advertising packet is received from a peripheral Events amp Messages See also Events amp Messages for BLE related messages that are thrown to the application when there Is a connection or disconnection The relevant message IDs are 0 1 14 15 16 17 18 and 20 0 There is a connection and the context parameter contains the connection handle 1 There is a disconnection and the context parameter contains the connection handle 14 New connection parameters for connection associated with connection handle 15 Request for new connection parameters failed for connection handle supplied 16 The connection is to a bonded master 17 The bonding has been updated with a new long term key Americas 1 800 492 2320 O
255. ee in BL600CodeSnippets zip DIM uuid eee UU Cie tom create a custom uuid for my ble widget Udo coed9d91 6609244128 7d560f27647602b2a uuidsS StrDehexizes uuids hUuidCustom BleHandleUuidl28 uuids LF hUurdeustom 0 THEN PRINT nFailed to create a handle BLSE PRINT Handle for custom Vuid ms r rnteJer A savumdCustom 2 NUn dC us om ENDIF hUuidCustom now references an object which points to a base uuid ced9d91366924a1287d56f2747622b2a note 0 s in byte position 2 3 and an offset 0xd913 Americas 1 800 492 2320 Option 2 239 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output Handle for custom Uuid is FCOSDGIS 66856685 BLEHANDLEUUID 128 is an extension function BleHandleUuidSibling FUNCTION This function takes an integer in the range O to 65535 along with a UUID handle which had been previously created using BleHandleUuid16 or BleHandleUuid128 to create a new UUID handle This handle references the same 128 base UUID as the one referenced by the UUID handle supplied as the input parameter The returned handle shall be treated by the developer as an opaque entity and no further logic shall be based on the bit content apart trom all O s which represents an invalid UUID handle BLEHANDLEUUIDSIBLING nUuidHandle nUuid16 Returns INTEGER a handle
256. ent is now closed Gatt Client is closed was safe to call when already closed BLEGATTCCLOSE Is an extension subroutine Americas 1 800 492 2320 Option 2 2 0 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleDiscServiceFirst BleDiscServiceNext FUNCTIONS This pair of functions is used to scan the remote Gatt Server for all primary services with the help of the EVDISCPRIMSVC message event and when called a handler for the event message must be registered as the discovered primary service information is passed back in that message A generic or uuid based scan can be initiated The former will scan for all primary services and the latter will scan for a primary service with a particular uuid the handle of which must be supplied and is generated by using either BleHandleUuid16 or BleHandleUuid128 While the scan is in progress and waiting for the next piece of data from a Gatt server the module will enter low power state as the WAITEVENT statement is used as normal to wait for events and messages Depending on the size of the remote GATT server table and the connection interval the scan of all primary may take many 100s of milliseconds and while this is in progress it is safe to do other non Gatt related operations like for example servicing sensors and displays or any of the onboard peripherals EVDISCPRIMSVC event
257. eo 2 07 10 IE ro 0 THEN 3 ro PleSscankotInit scRpi gt ENDIF IF rc 0 THEN rc BleAdvRptsCommit adRpts scRpt ENDIF tf re 0 THEN 2 re BleAdvertStart 0 addrs 50 070 ENDIF lopen Ene gatt client with default notify indicate ring bukter suze IF rc 0 THEN re BleGattcOpen 0 0 ENDIF BNDEUNGy ne SUB CloseConmecenoms rc BleDisconnect conHnd1 rc BleAdvertStop BNDSUB FUNCTION HrndlrBleMsg BYVAL nMsgid BYVAL nCEX DIM uHndA ConHndl nGex IF nMsgID 1 THEN PRINT n n Disconnected EXITFUNG 0 ELSEIF nMsgID 0 THEN PRINT n Connected so read attibute handle 3 atHndl 3 noff 0 rc BleGattcRead conHndl atHndl nOff Americas 1 800 492 2320 Option 2 297 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual IF rc 0 THEN WALTEVENT MND PRINT nread attibute handle 300 which does not exist atHndl 300 noff 0 rc BleGattcRead conHndl atHndl noOff IF rc 0 THEN WALITEVENT END CloseConnections BNDL E ENDEUNG function HandlerAttrkead chndl annd nsts as integer dim norec nAdA print T oEVATIR END T OIE EORR chndil o Ea E l S anmncl print Status integer h nots if nSts 0 then Print nAtEribuLre read Oh rc BleGattcReadData cHnd1l nAhndl nOfst at print nbata Or eHe ze alts Prints Ofiset nOrse pring hen strlen ars print
258. er than normal as a lot of data may need to be re written to a new flash segment This sector erase operation could affect the operation of the radio and result in a connection loss Interactive Command NO Example NvRecordSet sb See in BL600CodeSnippets zip DIM ws r re 2 ws Hel loWorld PRINT NvRecordSet 500 wS bytes written n PRINT NvRecordGetEx 500 r default bytes read n ISON EE ia oes Expected Output 10 bytes written 10 bytes read HelloWorld NVRECORDSET is a module function Americas 1 800 492 2320 Option 2 175 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual NvCfgKeyGet FUNCTION NVCFGKEYGET reads the value of a built in configuration key See AT CFG for a list of configuration keys NVCFGKEYGET keyld va ue Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Exceptions Local Stack Frame Undertlow Local Stack Frame Overflow Arguments keyld byVal keyld AS INTEGER The configuration key that is to be read in the range 1 to n where n depends on the specific module and the full list is described for the AT CFG command value byRef value AS INTEGER The integer variable that will be updated with the value of the configuration key if it exists Interactive Command see AT CFG Example NvCfgKeyGet sb See in BL
259. ericas 1 800 492 2320 Option 2 191 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual 6 Thermometer measurement indication has been acknowledged 7 Blood Pressure Client Characteristic Descriptor value has changed Indication enable state and msgCtx contains new value O for disabled 1 for enabled g Blood Pressure measurement indication has been acknowledged 9 Pairing in progress and display Passkey supplied in msgCtx 10 A new bond has been successfully created 11 Pairing in progress and authentication key requested msgCtx is key type 12 Heart Rate Client Characteristic Descriptor value has changed Notification enable state and msgCtx contains new value O for disabled 1 for enabled 14 Connection parameters update and msgCtx is the conn handle 15 Connection parameters update fail and msgCtx is the conn handle 16 Connected to a bonded master and msgCtx Is the conn handle 17 A new pairing has replaced old key for the connection handle specitied 18 The connection is now encrypted and msgCtx is the conn handle 19 The supply voltage has dropped below that specified in the most recent call of SetPwrSupplyThreshMv and msgCtx is the current voltage in milliVolts 20 The connection is no longer encrypted and msgCtx is the conn handle 21 The device name characteristic in the GAP service of the local gatt table has bee
260. ericas 1 800 492 2320 Option 2 221 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual DIM 1atrvl Sony lO Shak SELECT MMSE CASE OQ BLE EVBLEMSGID CONNECT PRINT n New Connection nCtx re BleGeteurconmearms MCex amery Lb sercvco Slat IF rc 0 THEN PRINT mConm sinker y ae ane ll PRINT nGonn Supervision Tameour sprvto PRINT nConn Slave Latency slat PRINT n nRequest new parameters request connection interval in range 50ms to 75ms and link supervision timeout of 4seconds with a slave latency of 19 be SB leSsereCurconnrarme mer 00C0y 750007 20000007 is ENDIF CASE 1 BLE EVBLEMSEID DISCONNECT PRINT n Disconnected nCtx EXITTEUNC O CASE 14 BLE_EVBLEMSGID CONN PARMS UPDATE re B leGeceCurcommbParms mG ec time ry ls orev O75 aie IF rc 0 THEN PRINTE Vm nconn Interval intryvl PRINT nGonn Supervision Timeout sprvito PRINT nConn Slave Latency slat ENDIF CASE 15 BLE EVBLEMSGID CONN PARMS UPDATE FAIL PRINT n Conn Parm Negotiation FAILED CASE ELSE PRINT nBle Msg nMsgIid ENDSELECT BN Nie ul ONEVENT EVBLEMSG CALL HandlerBleMsg IF BleAdvertStart 0 addrS 25 60000 0 0 THEN PRINT nAdverts Started n PRINT nMake a connection to the BL600 BLOE PRINT n nAdvertisement not successful ENDIF WALTEVENT Expected Output Unsuccesstul Ne
261. es Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual If the value is not valid then a runtime error will be thrown with code INVALID_ TIMER Interval_ms byVal interval AS INTEGER A valid time in milliseconds between 1 and 2 147 493 647 24 8 days Note although the time is specified in milliseconds the resolution of the hardware timer may have more granularity than that Submit the command AT 2002 or at runtime SYSINFO 2002 to determine the actual granularity in microseconds If longer timeouts are required start one of the timers with 1000 and make it repeating and then implement the longer timeout using smart BASIC code If the interval is negative or gt 2 147 493 647 then a runtime error will be thrown with code INVALID_INTERVAL If the recurring argument is set to non zero then the minimum value of the interval is 10ms recurring byVal recurring AS INTEGER Set to O for a once only timer or non O for a recurring timer When the timer expires it will set the corresponding EVTMRn event That is timer number O sets EVTMRO timer number 3 sets EVTMR3 The ONEVENT statement should be used to register handlers that will capture and process these events If the timer is already running calling TIMERSTART will reset it to count down from the new value which may be greater or smaller than the remaining time If either number or interval i
262. es of the parameter are reserved for future use Note In Interactive Mode the command AT BTD can also be used to delete the database BLEBONDMNGRERASE nFutureUse Arguments nFutureUse byVal nFutureUse AS INTEGER This shall be set to O Interactive Command NO Workaround for FW 1 3 57 0 and earlier when there is radio activity Example BleBondMngrErase sb See in BL6OO00CodeSnippets zip DIM TE rc BleAdvertStop BleBondMngrErase 0 For FW 1 4 X Y and newer Example BleBondMngrErase sb See in BL600CodeSnippets zip DIMERS BleBondMngrErase 0 BLEBONDMNGRERASE is an extension function Americas 1 800 492 2320 Option 2 336 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleBondMngrGetlnfo FUNCTION This function retrieves the MAC address and other information from the trusted device database via an index Note Do not rely on a device in the database mapping to a static index New bondings will change the position in the database BLEBONDMNGRGETINFO nIndex addr nExtralnfo Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation Arguments nindex byVal nindex AS INTEGER This is an index in the range O to 1 less than the value returned by SYSINFO 201 2 adar byRef addr AS STRING On exit if nindex points to a valid ent
263. escaping using a Starting V character and two hexadecimal digits Some characters are treated specially and only require a single character after the V character The table below lists the supported characters and the corresponding string 22 or Linefeed n a a Carriage A A1 return Horizontal B 42 Tab x 5C etc Compiler Related Commands and Directives SET The smartBASIC complier converts applications into an internally compiled program on a line by line basis It has strict rules regarding how it interprets commands and variable types In some cases It is useful to modify this default behaviour particularly within user defined functions and subroutines To allow this a special directive is provided SET SET is a special directive which instructs the complier to modify the way that it interprets commands and variable types In normal usage you should never have to modify any of the values SET must be asserted before the source code that it affects or the compiler behaviour will not be altered SET can be used multiple times to change the tokeniser behaviour throughout a compilation Americas 1 800 492 2320 Option 2 56 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual SET commandIiD commandValue Arguments cmdID Command ID and valid range is 0 10000 cmdValue Any valid integer va
264. escriptor and also is the value to store to keep track of important characteristics in a gatt server for later read write operations BLEDISCDESCFIRST connHandle descUuidHandle charValHandle A typical pseudo code for discovering descriptors involves first calling BleDiscDescFirst with information obtained from a characteristics scan and then waiting for the EVDISCDESC event message and depending on the information returned in that message calling BleDiscDescNext which in turn will result in another EVDISCDESC event message and typically is as follows Register a handler for the EVDISCDESC event message On EVDISCDESC event message If Descriptor Handle 0 then scan is complete Else Process information then call BleDiscDescNext if BleDiscDescNext not OK then scan complete Call BleDiscDescFirst information from EVDISCCHAR If BleDiscDescFirst ok then Wait for EVDISCDESC Americas 1 800 492 2320 Option 2 281 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Returns INTEGER a result code The typical value is OxO000 indicating a successful operation and it means an EVDISCDESC event message WILL be thrown by the smartBASIC runtime engine containing the results A non zero return value implies an EVDISCDESC message will NOT be thrown Arguments connHandle byVal nConnHandle AS INTEGER This is the connecti
265. essage calling BleDiscCharNext which in turn will result in another EVDISCCHAR event message and typically is as tollows Register a handler for the EVDISCCHAR event message On EVDISCCHAR event message If Char Value Handle 0 then scan is complete Else Process information then call BleDiscCharNext if BleDiscCharNext not OK then scan complete Americas 1 800 492 2320 Option 2 2 6 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Call BleDiscCharFirst information from EVDISCPRIMSVC If BleDiscCharFirst ok then Wait for EVDISCCHAR Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation and it means an EVDISCCHAR event message WILL be thrown by the smartBASIC runtime engine containing the results A non zero return value implies an EVDISCCHAR message will NOT be thrown Arguments connHandle byVal nConnHandle AS INTEGER This is the connection handle as returned in the on connect event for the connection on which the remote Gatt Server can be accessed This will have been returned in the EVBLEMSG event message with msgld 0 and msgCtx will have been the connection handle charUuldHandle byVal charUuidHandle AS INTEGER Set this to O if you want to scan for any characteristic in the service otherwise this value will have been generated either by BleHandleUuid16 or BleHandl
266. esult Codes There are some operations and events that provide a single byte Bluetooth HCI result code e g the EVDISCON message The meaning of the result code is as per the list reproduced from the Bluetooth Specifications below No guarantee is supplied as to its accuracy Consult the specification for more Result codes in grey are not relevant to Bluetooth Low Energy operation and are unlikely to appear BLE HCI STATUS CODE SUCCESS BLE HCI STATUS CODE UNKNOWN BTLE COMMAND BLE HCI STATUS CODE UNKNOWN CONNECTION IDENTIFIER BLE HCI HARDWARE FAILURE BLE HCI PAGE TIMEOUT BLE HCI AUTHENTICATION FAILURE BLE HCI STATUS CODE PIN OR KEY MISSING BLE HCI MEMORY CAPACITY EXCEEDED BLE HCI CONNECTION TIMEOUT BLE HCI CONNECTION LIMIT EXCEEDED BLE HCI SYNC CONN LIMI TO A DEVICE EXCEEDED BLE HCI ACL COONECTION ALREADY EXISTS BLE HCI STATUS CODE COMMAND DISALLOWED BLE HCI CONN REJECTED DUE TO LIMITED RESOURCES BLE HCI CONN REJECTED DUE TO SECURITY REASONS BLE HCI BLE HCI CONN REJECTED DUE TO BD ADDR BLE HCI CONN ACCEPT TIMEOUT EXCEEDED BLE HCI UNSUPPORTED FEATURE ONPARM VALUE BLE HCI STATUS CODE INVALID BTLE COMMAND PARAMETERS BLE HCI REMOTE USER TERMINATED CONNECTION BLE HCI REMOTE DEV TERMINATION DUE TO LOW RESOURCES BLE HCI REMOTE DEV TERMINATION DUE TO POWER OFF BLE HCI LOCAL HOST TERMINATED CONNECTION BLE HCI REPEATED ATTEMPTS BLE HCI PAIRING NOTALLOWED BLE HCI LMP PDU BLE HCI UNSUPPORTED REMOTE FEATURE BLE HCI SCO OFFSET REJECT
267. eteedieremueteteueuecslewes 314 BIGEENCOGESFLOAT c ccccceccecececeeeeeeeeeereeeaees 316 BIEENCOGESFLOATEX cccceccecececeeeeeeeeeeereeeaees 315 BIGEENCOGESTRING 0 ccccecceeccecececeeeceeeeeeereeeaes 319 BleEncodeTIMESTAMP cccceccecececeeeereeeaees 318 BLESECMNGRKEVYSIZES 219 224 233 267 BLESVCCOMMIT saceontucuceonautadceutcsesaeweniootenanaeses 241 BLESVCREGDEVINFO cccccececceeceeeeeeeeeeaees 236 BleVSpClose n 343 BE SURE VSI eoii EE AAE 351 BO ONTO esis ateceecmndsindenstecememedecossastesteonniceiceas 344 BleVSPOPEN cree eee see tesa se ssscuceieesenscceseeesucocncta cue 342 BIO VSD ROAG rcns a 347 BleVSpUartBridge 00ccccccccccceeeseeeeeeeen 349 BP enarrare carere EARRAN AREENA ER AEE R 74 BREAK cccceccceccceccececececcecececucecucerecereserenerens 65 BB RE cst eset Sine ces nee ee ewes cea ce eee 162 BY Fala states este iets cs oases EE Ei 162 CIRCBUFCREATE 119 162 163 164 168 169 170 171 172 CIRCBUFITEMS ics iciescneastorancaisnatonnhittiteainpatenantnss 124 CIRCBUFOVERWRITE cccce cece eee cena es 122 CIRCBUFREAD ananennnenusrsrrsrrerrsrrsrrerrerren 123 CIRC BUPW RITE sicsccautesoiavenseraseniottererataians 121 EEN L AE E P E E AETA sane 65 UN erea E EA E A EE EEA 51 DO DOWHILE acerca eeeriesacttoascnnsialtetnueeniersa creat 60 1 OP INI eirp a E 59 ENDFUNG ccetcereste crt n erererian iinr ernn E 189 NO UD era AO
268. etookup rs ton Aan PRIN WeblLehookuo es Hello ye n PRINTE Vaclebookup e you a va Expected Output TABLELOOKUP is a core function Miscellaneous Routines This section describes all miscellaneous functions and subroutines RESET SUBROUTINE This routine is used to force a reset of the module RESET nType Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments nType byVal n7ype AS INTEGER This is for future use Set to O Interactive Command NO Americas 1 800 492 2320 Option 2 108 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Laird Technologies smart BASIC User Manual Example RESET sb See in BL600CodeSnippets zip RESET 0 torce a resolt ol the mmecule Expected Output Like when you reset the module using the interactive command ATZ the CTS indicator will momenterally change from green to MF Config About red then back to green CTS OSR DOS AI RISK DIRI RESET is a core subroutine ERASEFILESYSTEM FUNCTION This function is used to erase the flash file system which contains the application that invoked this function if and only if the SIO7 input pin is held high Given that SIO7 is high after erasing the file system the module will reset and reboot into command mode with the virtual serial port service enabled and the module will advertise for a few seconds
269. exe file and then drag and drop it onto your desktop In the dialog box select Create Shortcut 2 Right click the newly created shortcut 3 Select Properties Edit the Target line to add the following commands Figure 8 accept com n baud bbb linemode where nis the COM port that is connected to the dev kit and bbb is the baudrate Shootout Fal Unterm COMS 9600 Target type Application Target location Target Target oct Uw Terminal exe accept com 5 beud 9600 Figure 8 Shortcut properties Starting UWTerminal from this shortcut launches it directly into the terminal screen At any time the status bar on the bottom left Figure 9 shows the comms parameters being used at that time The two counts on the bottom right Tx and Rx display the number of characters transmitted and received The information within denotes the characters sent when you hit ENTER on the keyboard Gn eEeeESESSESESeEeeeeSeSSeeSFSee COMS 9600 N 8 1 cr Tx 5 Rx 20 Figure 9 Terminal screen status bar Using UWTerminal The first thing to do is to check that the module is communicating with UWTerminal To do this follow these steps 1 Check that the CTS light is green DSR DCD and RI should be red 2 Type at 3 Press Enter You should get a OO response Figure 10 Americas 1 800 492 2320 Option 2 16 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth
270. eyond the end of the string this function fails BLEDECODEU8 attr nData nlndex Returns INTEGER the number of bytes extracted from the attribute string Can be less than the size expected if the nindex parameter is positioned towards the end of the string Arguments attr byRef atir AS STRING This references the attribute string from which the function reads nData byRef nData AS INTEGER This references an integer to be updated with the 8 bit data from attr without sign extension nindex byVal nindex AS INTEGER This is the zero based index into the string attr from which data Is read If the string attr is not long enough to accommodate the index plus the number of bytes to read this function fails Interactive Command NO Example BleDecodeU8 sb See in BL600CodeSnippets zip DIM ChrdanciLle vis ychandlhe me DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc DIM pS ssa ciepeo 00 Ol VO2 03 04 85 86 387 o38 89 DIM uuri 3 uuid 0x1853 rc BleSvcCommit 1 BleHandleUuidl6 uuid svcHandle rc BleCharNew 0x07 BlLleHandleUuidl6 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle Americas 1 800 492 2320 Option 2 322 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual rc BleCharValueRead chrHandle attr read unsigned byte from index 2 rc BleDecodeU8 attrS vl1 2 PRINT
271. ffers the usual modern constructs like subroutines functions while if and for loops smartBASIC offers further enhancement which acknowledges the fact that user applications are always in unattended use cases It forces the development of applications that have an event driven structure as opposed to the classical sequential processing for which many BASIC applications were written This means that a typical smartBASIC application source code consists of the following Variable declarations and initialisations Subroutine definitions Event handler routines Startup code The source code ends with a final statement called WAITEVENT which never returns Once the run time engine reaches the WAITEVENT statement it waits for events to happen and when they do the appropriate handlers written by the user are called to service them Why Do We Need smartBASIC Programming languages are mostly designed for arithmetic operations data processing string manipulation and flow control Where a program needs to interact with the outside world like in a BLE device it becomes more complex due to the diversity of different input and output options When wireless connections are involved the complexity increases To compound the problem almost all wireless standards are different requiring a deep knowledge of the specification and silicon implementations in order to make them work Americas 1 800 492 2320 Option 2 6 Laird Technologies Europ
272. fully ETSE PRINT nFailed to create EBC context ENDIF now decrypt the data rc AesDecrypt c 0 outData s IF rc 0 THEN PPI sa Decr yor OK BLSE PRINT nFailed to decrypt ENDANG e E E a TManDete mw E a a 0 PRINT noutData strhexizesS outDatas now decrypt the data rce AesDecrypt c 1 outData s IF rc 0 THEN PRINT ae Westy pE OR BLSE PRINT nFailed to decrypt ENDIF PRINT VninDeate i a r ae a es PRINT neurtDeta strmexizes OuLDaras now decrypt the data rce AesDecrypt c 2 outData s IF rc 0 THEN PRINTE in Decrypt Ok ETSE PRINT nFailed to decrypt ENDL PRIS es ninbeiba w es Sime a ae o 7 PRINT noutData Wo gtrhexizes loutDartas Americas 1 800 492 2320 Option 2 166 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Laird Technologies smart BASIC User Manual Expected Output AESDECRYPT Is a core language function File I O Functions A portion of module s flash memory is dedicated to a file system which is used to store smartBASIC applications and user data Tiles Due to the internal requirement set by the smartBASIC runtime engine because applications are interpreted in situ compiled application files have to be stored entirely in one continguous memory block This means the file system is currently restricted so that it is NOT possible for an application to open a file and then writ
273. further into smaller components would cease to provide the intended behaviour A couple of examples in the BLE domain that have been adopted by the Bluetooth SIG are Blood Pressure Service and Heart Rate Service Each have sub components that map to Characteristics Blood Pressure is detined by a collection of data entities like for example Systolic Pressure Diastolic Pressure Pulse Rate and many more Likewise a Heart Rate service also has a collection which includes entities such as the Pulse Rate and Body Sensor Location A list of all the adopted Services is at http developer bluetooth org gatt services Pages ServicesHome aspx Laird recommends that if you decide to create a custom Service then it is defined and described in a similar fashion so that your goal should be to get the Bluetooth SIG to adopt it for everyone to use in an interoperable manner These Services are also assigned 16 bit UUIDs value 0x18xx and are referenced in some of the smartBASIC API functions described in this section Services as described above are a collection of one or more Characteristics A list of all adopted characteristics is found at http developer bluetooth org gatt characteristics Pages CharacteristicsHome aspx You should note that these descriptors are also assigned 16 bit UUIDs value Ox2Axx and are referenced in some of the API functions described in this section Custom Characteristics will have 128 bit 16 byte UUIDs and API functions a
274. g through the value list 4 0 4 8 12 16 20 30 55 so that the highest value in the list which is less than the desired value is selected unless the desired value is less than 55 and in that case 55 will be set For example setting 1000 will result in 4 3 will result in 4 100 will result in 55 At any time SYSINFO 2008 will return the actual transmit power setting Or when in command mode use the command AT 2008 BLETXPOWERSET nTxPower Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments nTxPower byVal n7xPower AS INTEGER Specifies the new transmit power in dBm units to be used for all subsequent tx packets The actual value is determined by scanning through the following values 4 O 4 8 12 16 20 30 55 such that the highest value in the table which Is less than the desired value is selected unless the desired value is less than 55 and in that case 55 will be set Interactive Command NO Example BleTxPowerSet sb See in BL6O00CodeSnippets zip DIM ro dp dp 1000 rc BleTxPowerSet dp PRIT eke Geiser Wea PRINT nix power desired dp actual T Sycinto 7003 dp 8 rc BleTxPowerSet dp PRE atx pover desired dap Y T actual T oy Info 2003 Americas 1 800 492 2320 Option 2 205 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech co
275. ged virtual serial port service Managed means there Is a driver consisting of transmit and receive ring buffers that isolate the BLE service from the smartBASIC application This in turn provides easy to use API functions Note The driver makes the same assumption that the driver in a PC makes If the on air connection equates to the serial cable there is no assumption that the cable is from the same source as prior to the disconnection This is analogous to the way that a PC cannot detect such in similar cases The module can present a serial port service in the local GATT Table consisting of two mandatory characteristics and two optional characteristics One mandatory characteristic is the TX FIFO and the other is the RX FIFO both consisting of an attribute taking up to 20 bytes Of the optional characteristics one is the Modemin which consists of a single byte and only bit O is used as a CTS type function The other is ModemOut also a single byte which is notifiable only and is used to convey an RTS flag to the client By default configurable via AT CFG 112 Laird s serial port service is exposed with UUID s as Tfollows The UUID of the service is 569a1101 b87 490c 92cbh l1lbab5ea5l1l67c The UUID of the rx fifo characteristic is 569a2001 b87 490c 92cb 1lba5ea5l1l67c The UUID of the tx fifo characteristic is 569a2000 b87 490c 92cb 1lba5ea5167c The UUID of the Modemin characteristic is 569a2003 b87 490c 92cb 11l
276. gle instances of shared Characteristics that are collected in a SECONDARY service This referencing is expedited within the definition of a service using the concept of INCLUDED SERVICE which itself is just an attribute that is grouped with the PRIMARY service definition An Included Service is expedited using the function BleSvcAddIncludeSvc which is described immediately after this function This function now replaces BleSvcCommit and marks the beginning of a service definition in the gatt server table When the last descriptor of the last characteristic has been registered the service definition should be terminated by calling BleServiceCommit BLESERVICENEW nSvcType nUuidHandle hService Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments nSvcType byVal nSvcType AS INTEGER This will be O for a SECONDARY service and 1 for a PRIMARY service and all other values are reserved for future use and will result in this function failing with an appropriate result code Americas 1 800 492 2320 Option 2 241 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual nUuidHandle byVal nUuidHandle AS INTEGER This is a handle to a 16 bit or 128 bit UUID that identities the type of Service function provided by all the Characteristics collected under it It will have been pre
277. gotiation Americas 1 800 492 2320 Option 2 222 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output Successful Negotiation Note First set of parameters will differ depending on your central device BLESETCURCONNPARMS is an extension function BleGetCurConnParms FUNCTION This function gets the current connection parameters for the connection identified by the connection handle Given there are 3 connection parameters the function takes three variables by reference so that the function can return the values in those variables BLEGETCURCONNPARMS nConnHandle nintervalUs nSuprToutUs nSlaveLatency Returns INTEGER a result code The most typical value is OxO000 indicating a successful operation Arguments nConnHandle byVal nConnHandle AS INTEGER Specifies the handle of the connection that needs to have the connection parameters changed nintervalUs byRef n ntervalUs AS INTEGER The current connection interval in microseconds nSuprToutUs byRef nSuprToutUs AS INTEGER The current link supervision timeout in microseconds for the connection nSlaveLatency byRef nS avelatency AS INTEGER This is the current number of connection interval polls that the peripheral may ignore This value multiplied by the connection interval will not be greater than the link Supervision timeout Note See Not
278. gs For example in BLE modules there is a concept of a database of attributes which are just a collection of octets of data up to 512 bytes in length To provide the ability to deal with strings smart BASIC contains a number of commands that can operate on STRING variables LEFT Retrieves the leftmost n characters of a string LEFT string length Function Returns STRING The leftmost length characters of string as a STRING object Exceptions Local Stack Frame Undertlow Local Stack Frame Overflow Memory Heap Exhausted Arguments string byRef string AS STRING The target string which cannot be a const string length byVal length AS INTEGER The number of leftmost characters that are returned If length is larger than the actual length of string then the entire string is returned Notes string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Interactive Command NO Example LEFTS sb See in BL600CodeSnippets zip Americas 1 800 492 2320 Option 2 83 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual DIM newstring DIM s sS Arsenic asec WT Tass 2 Sle iglesias wicukigvers ye Vai Expected Output LEFT is a core la
279. h data is read E g the third bit in the second byte Is index number 10 dstBitArr byRef dstBitArr AS INTEGER This argument references an integer treated as an array of 32 bits into which data is copied Only the written bits are modified nDstldx byVal nDstidx AS INTEGER This is the zero based bit index into the bit array dstBitArr where the data Is written to nMaxBits byVal nMaxBits AS INTEGER This argument specifies the maximum number of bits to read from attr Due to the destination being an integer variable it cannot be greater than 32 Negative values are treated as zero Interactive Command NO Example BleDecodeBits sb See in BL600CodeSnippets zip DIMVchichancdten vl ovcam e re To decors DIM ba ba 0 DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc ABCDEFGHIJ DM eels eis e E ok a7 a ees a DIM mame ssa rel 021853 rc BleSvcCommit 1 BleHandleUuidl6 uuid svcHandle rc BleCharNew 0x07 BleHandleUuidl16 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle rc BleCharValueRead chrHandle attr j eead Max l4 bits Irom index 20 an the string tO index 10 CCc B leDecodeBRITS avtrs 20 ba 10 14 Americas 1 800 492 2320 Option 2 334 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT nbtt artay 7 LNTRGER BY ba read max 14 bits from index 20 in the string to i
280. h filing system does not overwrite previously used locations At some point there will be no more free memory and an automatic defragmentation will occur This operation takes much longer than normal as a lot of data may need to be re written to a new flash segment This sector erase operation could affect the operation of the radio and result in a connection loss Interactive Command NO Example NvCfgKeyGet sb See in BL600CodeSnippets zip DIMEC W aoe WO xo LOY PRINT n NvCfgKeySet 100 w Peo ne Nweimkekey Ger OOT PRINT Y nYalue for 100 is 2r Expected Output O O Value for 100 is 33031 NVCFGKEYSET is a module function Input Output Interface Routines I O and interface commands allow access to the physical interface pins and ports of the smartBASIC modules Most of these commands are applicable to the range of modules However some are dependent on the actual I O availability of each module GpioSetFunc FUNCTION This routine sets the function of the GPIO pin identified by the nSigNum argument The module datasheet contains a pinout table which denotes SIO Special I O pins The number designated for that special I O pin corresponds to the nSigNum argument Americas 1 800 492 2320 Option 2 177 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual GPIOSETFUNC nSigNum nFunction nSubFund Return
281. haracters within a string STRLEN string Returns INTEGER The number of characters within the string Exceptions Local Stack Frame Undertlow Local Stack Frame Overflow Arguments string byRef string AS STRING The target string which cannot be a const string Interactive Command NO Example StrLen sb See in BL600CodeSnippets zip DIM S gt so Helloworla PRINTE TAn eS eves Ser Leno a sovecs Tong Expected Output AA HelloWorld is 10 bytes long STRLEN is a core function STRPOS FUNCTION STRPOS is used to determine the position of the first instance of a string within another string If the string is not found within the target string a value of 1 is returned STRPOS string1 string2 startpos Returns INTEGER Zero indexed position of string2 within string 7 gt 0 If string2 s found within string and specifies the location where found 1 If string2 is not found within string 1 Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments string 1 byRef string AS STRING The target string in which string2 is to be searched for string2 byRef string AS STRING The string that is being searched for within string1 This may be a single character string Americas 1 800 492 2320 Option 2 86 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual startpos byVAL startpos AS
282. hat any signal transitions on these lines prior to this open which may have confused a slave can initialise that slave to a known state The STOP condition should be detected by the slave 1 31 Unused and MUST be set to 0 nHandle byRef nHandle AS INTEGER The handle for this interface will be returned in this variable if it was successfully opened This handle is subsequently used to read write and close the interface Related Commands IZCCLOSE IZCWRITEREAD I2CWRITEREGS8 I2CWRITEREG16 I2CWRITEREG32 IZ CREADREG8 I2CREADREG16 I2CREADREG32 Example I2cOpen sb See in BL600CodeSnippets zip DIM handle DIM ro re 127cOpen 100000 0 handle IFP cels O THEN PRINT AnFailed to open I2C interface with error code T INTEGER Ah ro ELSE PRINT nI2C open success nHandle is handle ENDIF Expected Output I2C open success Handle is 0 I2COPEN is a core function I2cClose SUBROUTINE Note For firmware releases older than 1 2 54 4 there is an issue where some 2C slaves are not able to drive the ACK down to a low enough voltage level for the module to recognise it as an ACK This is a result of a bug in the BL600 s I2C driver which results in the SDA line not being released by the module This has been corrected in release 1 2 54 4 and the firmware is available as a uart download on request You should upgrade the firmware if you have an I2C slave not responding to the correct slave address Americas
283. he EVATTRREAD event message and typically is as follows Register a handler for the EVATTRREAD event message On EVATTREAD event message if Gale ota us 0 chen BleGattcReadData to actually get the data Else Attribute could not be read Call BleGattcRead If BleGattcRead ok then Wait for EVATTRREAD Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation and it means an EVATTRREAD event message WILL be thrown by the smartBASIC runtime engine containing the results A non zero return value implies an EVATTRREAD message will NOT be thrown Arguments connHnal byVal connHnal AS INTEGER This is the connection handle as returned in the on connect event for the connection on which the remote Gatt Server can be accessed This will have been returned in the EVBLEMSG event message with msgld 0 and msgCtx will have been the connection handle attrHnal byVal attrHnal AS INTEGER Set this to the handle of the attribute to read and will be a value in the range 1 to 65535 offset byVal offset AS INTEGER This is the offset from which the data in the attribute is to be read BLEGATTCREADDATA connHndl attrHndl offset attrData This function is used to collect the data trom the underlying cache when the EVATTRREAD event message has a success gatt status code Returns INTEGER a result code The typical value is 0x0000 indicating a successful read Arguments connHnal byVal connHnal AS INTEG
284. he advert report This consists of all the 16 bit service UUIDs that the device supports as a server BLEADVRPTADDUUID 16 advRpt nUuid1 nUuid2 nUuid3 nUuid4 nUuid5 nUuid6 Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments Advkot byRet AdvAot AS STRING The advert report onto which the 16 bit uuids AD record is added Uuid1 byVal uuid1 AS INTEGER UUID in the range O to FFFF if value is outside that range it will be ignored so set the value to 1 to have it be ignored and then all further UUID arguments will also be ignored Uuid2 byVal uuid2 AS INTEGER UUID in the range O to FFFF if value is outside that range it will be ignored so set the value to 1 to have it be ignored and then all further UUID arguments will also be ignored Uuid3 byVal uuid3 AS INTEGER UUID in the range O to FFFF if value is outside that range it will be ignored so set the value to 1 to have it be ignored and then all further UUID arguments will also be ignored Uuid4 byVal uuid4 AS INTEGER UUID in the range O to FFFF if value is outside that range it will be ignored so set the value to 1 to have it be ignored and then all further UUID arguments will also be ignored Uuid5 byVal uuid5 AS INTEGER UUID in the range O to FFFF if value is outside that range it will be ignored so set the value to 1 to have it be ignored and then all further UUID arguments will also be ignored Uuid6 byVal uuid6 AS
285. he appropriate CASE the relevant statement block is executed until a CASE BREAK or ENDSELECT command is encountered If a match is not found then the CASE ELSE statement block is run It is mandatory to include a final CASE ELSE statement as the final CASE in a SELECT operation SELECT arithexor unconditional statement block CASE integerconstA statement block A CASE integerconstB statement block B CASE integerconstc integerconstd integerconste integerconstf statement block C CASE ELSE statement block ENDSELECT Unconditional statement block An optional set of program statements which are always executed Statement block A valid set of zero or more program statements Arithexpr A valid arithmetic or logical expression Arithmetic precedence is as defined in the section Arithmetic Expressions IntegerconstX One or more comma seperated integer constants corresponding to one of the possible values of arithexor which identifies the block that will get processed Interactive Command NO Example SelectCase sb See in BL600CodeSnippets zip DIMERORE a 3 b 4 Use to write multiple commands on one line SELECT ax b CASE 10 c 10 GASH 17 this block will get processed C CASE 4a SG 789 1022 c 1 CASE ELSE c 0 END SE ne i PRINT Americas 1 800 492 2320 Option 2 64 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www laird
286. he combination of mix columns and byte substitution used here is based on that developed by Karl Malbrain His contribution is acknowledged Americas 1 800 492 2320 Option 2 358 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual INDEX POE E EAA AN E 56 ABS E E ES 81 BleDecode32 00 eeeecceccceccecececeecececeueececeaeereeeaees 328 BleDeCOCEBITS ee ce eecceccceccececeeeeeceeeeeeereeeaees 334 BleDeCOdeFLOAT ccceccceccecececeeeeeeeeeeereeeaees 329 BleDecodeS1 6 0 eee eecceecceecceceecececeeeceeeeeereeeaes 323 BleDecodeS24 ooo eee ecccccceccceceececeteeeececeaeeceeeaees 325 BleDecodeSFLOAT cccceccecececeeeceseaeeceeeaees 330 BleDecOdeSTRING cccceccecececeeeececeeeeceesaees 332 BleDecodeTIMESTAMP cccceceeeececeeeereeeaees 331 BLEDECODEU16 0 0 ccc ccc ccccceccceceeeceeeeeeeeeeneen 324 BleDe COde U24 o oo eecececcceceecececesereeeaeereneaees 326 BleDecOde UB ccccccccecceeceeceeceeceeceeees 321 322 BIG ETCOUG IG axteaiwewsacunecsensedus anusnenetiewettundanenendes 311 BleEncode24 o oo e eee ceccceccececececcececeaeececsaeerereaees 312 BleEncode32 ooo eceeccecccececececeecececsucececeaeecereaees 313 BICENCOdES 0 ccc ccecccccceceeecceceecececeueereeeeeereeeases 310 BIGENCOCEBITS 20 0 2 ccceeceeecceceecececeeeecessaeereeeaees 320 BleEncodeFLOAT cuccauctlacoud
287. he virtual serial port is enabled while in interactive mode AT BLX Command Returns nOO r Arguments None This is an Interactive Mode command and MUST be terminated by a carriage return for it to be processed Note The module self reboots so that the bonding manager context is also reset Interactive Command YES Examples AT BLX AT BLX is an extension command Americas 1 800 492 2320 Option 2 48 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual 4 SMARTBASIC COMMANDS smart BASIC contains a wide variety of commands and statements These include a core set of programming commands found in most languages and extension commands that are designed to expose specific functionality of the platform For example Bluetooth Low Energy s GATT GAP and security functions Because smart BASIC is designed to be a very efficient embedded language you must take care of command syntax Syntax smart BASIC commands are classified as one of the following Functions Subroutines Statements Functions A function is a command that generates a return value and Is normally used in an expression For example newstr LEFT o dstring num In other words functions cannot appear on the left side of an assignment statement which has the equals sign However a function may affect the value of variables
288. his has been corrected in release 1 2 54 4 and the firmware is available as a uart download on request You should upgrade the firmware if you have an I2C slave not responding to the correct slave address This function is used to write from O to 255 bytes and then immediately after that read O to 255 bytes in a single transaction from the addressed slave It is a free form function that allows communication with a Slave which has a 10 bit address Note a handle parameter is NOT required as this function is used to interact with the main interface In the future a new version of this function will be made available if more than one I2C interface is made available most likely made available by bit bashing gpio I2CWRITEREAD nSlaveAddr stWrite stRead nReadLen Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Americas 1 800 492 2320 Option 2 154 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Arguments nSlaveAdar stWrite stRead nkeadLen byVal nSlaveAdadr AS INTEGER This is the address of the slave in range O to 127 byRef stWrite AS STRING This string contains the data that must be written first If the length of this string is O then the write phase is bypassed byRef stRead AS STRING This string will be written to with data read trom the slave if and only if nReadLen
289. hovo eles clistica eileen che eie S sland DIM mdCecd maCced BleAterMetadata l 1 7 0 re Commit sve with mame len howe used rce BleSvcCommit 1 BleHandleUuidl6 Ox18EE hSvc initialise char write read enabled rc BleCharNew 0x12 BleHandleUuidl6 1 BleAttrMetaData 1 0 20 0 rc mdCccd 0 Commie char initialised above wira inicial value rc BleCharCommit hSvc attrs hMyChar rc BleScanRptInit scRpt Add 1 service handle to scan report rc BleAdvRptAddUuidl1l6 scRpt hSvc addres 1 1 J CCCD merada Or Char accept signed writes notifiable Ritto service 1nMyChar commit reports to GATY table adkpt gt is empty rc BleAdvRptsCommit adRpt scRpts C BlehdvertiStart 0 addrs 50 0 0 DIS UNG ere SUPR CIPLC COMME CONSA rc BleDisconnect conHnd1 rc BleAdvertStop ENDSUB SUB SendData DIM me Oumt IF ntfyEnabled then PRENES nE Ne oa aro DO txS SomeData rc BleCharValueNotify hMyChar tx S cCount counttl UNTIL r l 0 PRINT n Buffer full PRIN nilotirned count times ENDIF ENDSUB FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx GOmnm llh me tx IF nMsgID 0 THEN PRINT n Connected to client IB iby S Jaded AMSCLD aaa PRINT n Disconnected from client EXITFUNG O NYE ee ENDEUNG Americas 1 800 492 2320 Option 2 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdt
290. ich gt 27 owe j BeGister Charecteristic 1 im Service 2 mdAttr DICAT ETENE aAa aE cia whe CCl oom OVE Sere tke COs om ONE sO nt ae Americas 1 800 492 2320 Option 2 232 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual mA Cea gt lok werMeradawa Phi aia ke Cero Ol Pit Mine Cells OREN 27 0 e mdSccd BLE CHAR METADATA ATTR NOT PRESENT echerop Pi Onan eh Or niin ENOTI EY hUuidC21 BleHandleUuidl6 0x2A54 ro Bla harew chProp NUurd 2i mdArtin md ced mdasece atero TA O0 Oooo gon re BleCharCommit nove artro ANC harl The 2 services are now visible in the gatt table Writes into a characteristic from a remote client is detected and processed as follow j 7 TO deal with writes from a gatt client Into characteristic 1 of Service 1 which has the handle hChar11 This handler is called when there is a EVCHARVAL message FUNCTION HandlerCharVal BYVAL hChar AS INTEGER AS INTEGER DIM artero TEN Dar hCharid THEN rc BleCharValueRead hCharll attrS print Svcl Charl has been writen with attr ENDIE ENDEUNC TI enable characteristic value write handler OnEvent EVCHARVAL call HandlerCharVal WAL TEVENT Assuming there is a connection and notify has been enabled then a value notification is expedited as follows attrS somevalue re BleCharValueNotify hCharl2 attrsS
291. ich the data is read If the string attr is not long enough to accommodate the index plus the number of bytes to read this function fails Interactive Command NO Example BleDecodeS8 sb See in BL600CodeSnippets zip DIM ChridanciLle yil syenanclLle re DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc DIM acte aeee A O0 OT o2 03 04 85 3537 se 35 DIM uuic 3 uuid 0x1853 create random service just for this example rc BleSvcCommit 1 BleHandleUuidl6 uuid svcHandle create char and commit as part of service commited above rc BleCharNew 0x07 BleHandleUuidl16 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle rc BleCharValueRead chrHandle attrS read signed byte from index 2 Americas 1 800 492 2320 Option 2 321 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual rc BleDecodeS8 attrS vl1 2 PRINT V ncarca in Hex Ox gt INTEGER Kyi PRINT ndata in Decimal iO ail a Ga read signed byte from index 6 two s complement of 122 rc BleDecodeS8 attrS vl1 6 PRINT andata aon Hex Ox gt INTHCER Hyl PRINT Y ndata in Decimal g yig n Expected Output BLEDECODESS8 is an extension function BleDecodeU8 FUNCTION This function reads a single byte in a string at a specified offset into a 32bit integer variable without sign extension If the offset points b
292. id the handle of which must be supplied and is generated by using either BleHandleUuid16 or BleHandleUuid128 If instead it is known that a gatt table has a specific service characteristic and a specific descriptor then a more efficient method for locating details of that characteristic is to use the function BleGattcFindDesc which is described later While the scan is in progress and waiting for the next piece of data from a Gatt server the module will enter low power state as the WAITEVENT statement is used as normal to wait for events and messages Depending on the size of the remote GATT server table and the connection interval the scan of all descriptors may take many 100s of milliseconds and while this is in progress it is sate to do other non Gatt related operations like for example servicing sensors and displays or any of the onboard peripherals EVDISCDESC event message This event message WILL be thrown if either BleDissDescFirst or BleDiscDescNext returns a success The message contains 3 INTEGER parameters Connection Handle Descriptor Uuid Handle Handle for the Descriptor in the remote Gatt Table If no more descriptors were discovered because the end of the table was reached then all parameters will contain O apart trom the Connection Handle Descriptor Uuid Handle contains the uuid of the descriptor and supplied as a handle Handle for the Descriptor in the remote Gatt Table is the handle for the d
293. ied as the second parameter in the EVCHARDESC event message nOffset byVal nOffset AS INTEGER This is the offset into the descriptor attribute trom which the data shoud be read and copied into attr Americas 1 800 492 2320 Option 2 263 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual nlength byVal nLength AS INTEGER This is the number of bytes to read from the descriptor attribute from offset nOffset and copied into attr nDescUuidHandle byRef nDescUuidHandle AS INTEGER On exit this will be updated with the uuid handle of the descriptor that got updated attr byRef attr AS STRING On exit this string variable contains the new value from the characteristic descriptor Interactive Command NO Example BleCharDescRead sb See in BL600CodeSnippets zip DIM ce CONME hy har SUB morareup DIMA VO at EE seks adheres acai rc BleSvcCommit 1 BleHandleUuidl 0x18FF hSvc 7 Add one or more characteristics rc BleCharNew 0x0a BLleHandleUuidl6 Ox2AFF BleAttrMetadata 1 1 20 1 rc 0 0 Add a user description DIM Se 2 se You Cam change this rc BleCharDescAdd 0x2999 sS BleAttrMetadata 1 1 20 1 rc commit characteristic arero NO00 A no nial alere re BleCharcCommit Movo attr hMyChar rc BleScanRptInit scRpt Add 1 char handle to scan report rO EILEAN E A Uur dae Seles lawiviCliieiw e
294. if VARTINFO 1 returns a non zero value When this subroutine is invoked the receive and transmit buffers are both flushed If there is any data in either of these buffers when the UART is closed it will be lost This is because the execution of UARTCLOSE takes a very short amount of time while the transfer of data trom the buffers will take much longer In addition please note that when a smart BASIC application completes execution with the UART closed it will automatically be reopened in order to allow continued communication with the module in Interactive Mode using the default communications settings UARTCLOSE Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments None Interactive Command No Related Commands UARTOPEN UARTINFO UARTWRITE UARTREAD UARTREADMATCH UARTGETCTS UARTGETDCD UARTGETRI UARTSETDTR UARTSETRTS UARTSETDCD UARTSETRI VARTBREAK UARTFLUSH Example UartClose sb See in BL6O00CodeSnippets zip UartClose IF UartiInfo 0 0 THEN PRINT nThe Uart port was closed ELSE PRINT A nThe Uart port was Not closed ENDIF he Uareinro 0 1 0 THEN PRINT nand now it is open ENDIF Expected Output ee The Uart port was closed and now it is open UARTCLOSE is a core subroutine Americas 1 800 492 2320 Option 2 130 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BA
295. inal emulation application with additional GUI extensions to allow easy interactions with a smartBAS IC enabled module It is similar to other well known terminal applications such as Hyperterminal As well as a serial interface it can also open a TCP IP connection either as a client or as a server This aspect of UWTerminal is more advanced and is covered in the UWTerminal User s Guide The focus of this chapter is its serial mode In addition to its function as a terminal emulator it also has smartBASIC embedded so you can locally write and run smartBASIC applications This allows you to write smartBASIC applications which use the terminal emulation extensions that enable you to automate the functionality of the terminal emulator It may be possible in the future to add BLE extensions so that when UWTerminal is running on a Windows 8 PC with Bluetooth 4 0 hardware an application that runs on a BLE module also runs in the UwTerminal environment Before starting UWTerminal note the serial port number to which the development kit is connected Americas 1 800 492 2320 Option 2 12 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Note The USB to serial chipset driver on the development kit generates a virtual COM port Check the port by selecting My Computer gt Properties gt Hardware gt Device Manager gt Ports COM amp LPT
296. indicating a successful operation Arguments stWrite byRef stWrite AS STRING This string contains the data that must be written stRead bykef stRead AS STRING While the data in stWrite is being written the slave sends data back and that data is stored in this variable Note that on exit this variable will contain the same number of bytes as stWrite Interactive Command No Related Commands SPICLOSE SPIREADWARITE SPIWRITE SPIREAD Example See SpiExample sb SPIWRITEREAD is a core function SpiWrite FUNCTION This function is used to write data to a SPI slave and any incoming data will be ignored Americas 1 800 492 2320 Option 2 160 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Note a handle parameter is NOT required as this function is used to interact with the main interface In the future a new version of this function will be made available if more than one SPI interface is made available SPIWRITE stWrite Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation Arguments stWrite byRef stWrite AS STRING This string contains the data that must be written Interactive Command No Related Commands SPICLOSE SPIREADWRITE SPIWRITE SPIREAD Example See SpiExample s
297. ines used to interact with the I2C peripheral available on the platform An I2C interface is also known as a Two Wire Interface TWI and has a master slave topology An I2C interface allows multiple masters and slaves to communicate over a shared wired OR type bus consisting of two lines which normally sit at 5 or 3 3v The BL600 module can only be configured as an I2C master with the additional constraint that it be the only master on the bus and only 7 bit slave addressing is supported The two signal lines are called SCL and SDA The former is the clock line which Is always sourced by the master and the latter is a bi directional data line which can be driven by any device on the bus It is essential to remember that pull up resistors on both SCL and SDA lines are not provided in the module and MUST be provided external to the module A very good introduction to I2C can be found at http Awww i2c bus org i2c primer and the reader is encouraged to refer to it before using the api described in this section 12C Events The API provided in the module is synchronous and so there is no requirement for events I2cOpen FUNCTION Note For firmware releases older than 1 2 54 4 there is an issue where some 2C slaves are not able to drive the ACK down to a low enough voltage level for the module to recognise it as an ACK This is a result of a bug in the BL600 s I2C driver which results in the SDA line not being released by the module Thi
298. ing AS STRING The target string If STRVALDEC encounters a non numeric character within the string it will return the value of the digits encountered before the non decimal character Any leading whitespace within the string is ignored Note string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Interactive Command NO Example StrValDec sb See in BL600CodeSnippets zip DIM s9 Se 1234 Americas 1 800 492 2320 Option 2 98 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRIM Vint SGenValbec ss SoSe 284 PRINT Y of tral Dee ss SoSe 2 AT PRIME n tr al Deolen s 2345hello PRIE hone Seiya Deno sS hello ERINE Smite Deo ss Expected Output STRVALDEC is a core function STRSPLITLEFTS FUNCTION STRSPLITLEFT returns a string which consists of the leftmost n characters of a string object and then drops those characters from the input string STRSPLITLEFTS string length Returns STRING The leftmost length characters are returned and then those characters are dropped from the argument list Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Memory Heap Exhausted Arguments string byRef string AS STRING
299. integer and string Arithmetic functions Binary operators Conditionals Looping Functions and subroutines String processing functions Arrays single dimension only O functions Memory management Event handling The language on the various platforms differs by having a sophisticated set of target specific extensions such as BLE for the module described in this manual Americas 1 800 492 2320 Option 2 8 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual These extensions have been implemented as additional program functions that control the wireless connectivity of the module including but not limited to the following Advertising Connecting Security encryption and authentication Power management Wireless status Developing with smartBASIC smartBASIC is one of the simplest embedded environments on which to develop because much of the functionality comes prepackaged The compiler which can be internal or external on a Windows PC compiles source text on a line by line basis into a stream of bytes or bytecode that can be stored to a custom designed flash file system Following that the run time engine interprets the application bytecode in situ from flash To further simplify development Laird provides its own custom developed application called UWTerminal which is a full
300. ion 2 76 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual RESETLASTERROR SUBROUTINE Resets the last error so that calling GETLASTERROR returns a success RESETLASTERROR Exceptions Local Stack Frame Undertlow Local Stack Frame Overflow Arguments None Interactive Command NO Example ResetLastError sb See in BL6o00CodeSnippets zip DIM err err GETLASTERROR RESETLAS TERROR PRINT Y nerror gt lt 2 INTEGER A err Expected Result error 0x00000000 RESETLASTERROR is a core function SYSINFO FUNCTION Returns an informational integer value depending on the value of varld argument SYSINFO varld Returns INTEGER Value of information corresponding to integer ID requested Exceptions Local Stack Frame Undertlow Local Stack Frame Overflow Arguments varld byValvarld AS INTEGER An integer ID which is used to determine which information is to be returned as described below O ID of device for the BL600 module the value will be 0x42460600 3 Version number of Module Firmware For example W X Y Z will be returned as a 32 bit value made up as follows W lt lt 26 X lt lt 20 Y lt lt 6 Z where Y is the Build number and Z is the Sub Build number 33 BASIC core version number 601 Flash File System Data Segment Total Space 602 Flash File System Data Segment
301. ir AS STRING This argument is the string that will be written to an attribute Americas 1 800 492 2320 Option 2 316 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual nMatissa byVal n AS INTEGER This must be in the range 2046 to 2046 or the function fails The data is written in little endian so the least significant byte is at the lower memory address Note that the range Is not 2048 because after encoding the following 2 byte values have special meaning Ox07FF NaN Not a Number Ox0800 NRes Not at this resolution OxO7FE INFINITY Ox0802 INFINITY Ox0801 Reserved for future use nExponent byVal n AS INTEGER This value must be in the range 8 to 7 or the function fails nindex byVal nindex AS INTEGER This is the zero based index into the string attr where the new fragment of data is written If the string attr is not long enough to accommodate the index plus the length of the fragment it is extended If the new length exceeds the maximum allowable length of an attribute see SYSINFO 2013 this function fails Interactive Command NO Example BleEncodeSFloat sb See in BL600CodeSnippets zip DINERS DIME O SUB Encode BYVAL mantissa BYVAL exp IF BleEncodeSFloat attr mantissa exp 2 0 THEN PRINT neetled to encode to SELOATY WLS PRINT nSuccess ENDIF BNDSUB Encode e A 1 1234 x
302. is section describes all functions related to GATT Client capability which enables interaction with GATT servers at the other end of the BLE connection The Bluetooth Specification 4 0 and newer allows for a device to be a GATT server and or GATT Client simultaneously and the fact that a peripheral mode device accepts a connection and in all use cases has a GATT server table does not preclude it from interacting with a GATT table in the central role device which is connected to it Americas 1 800 492 2320 Option 2 265 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual These GATT Client functions allow the developer to discover services characteristics and descriptors read and write to characteristics and descriptors and handle either notifications or indications To interact with a remote GATT server it is important to have a good understanding of how it is constructed and the best way is to see it as a table consisting of many rows and 3 visible columns handle type value and at least one more column which is not visible but the content will affect access to the data column 16 bit Handle Type 16 or 128 bit Value 1 to 512 bytes These rows are grouped into collections called services and characteristics The grouping is achieved by creating a row with Type 0x2800 or 0x2801 for services primary and secondary respectively and Ox2
303. ising with this packet type the timeout is automatically set to 1280 ms When filter policy is enabled the whitelist consisting of all bonded masters is submitted to the underlying stack so that only those bonded masters will result in scan and connection requests being serviced Note nAdvTimeout in the BL600 is rounded up to the nearest 1000 msec BLEADVERTSTART nAdvType peerAddr nAdvinterval nAdvTimeout nFilterPolicy Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation If a Ox6A01 resultcode is received it implies whitelist has been enabled but the Flags AD in the advertising report is set for Limited and or General Discoverability The solution is to resubmit a new advert report which is made up so that the nFlags argument to BleAdvRoptinit function Is O The BT 4 0 spec disallows discoverability when a whitelist is enabled during advertisement see Volume 3 Sections 9 2 3 2 and 9 2 4 2 Americas 1 800 492 2320 Option 2 208 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Arguments nAdvlype byVal nAdv7ypoe AS INTEGER Specifies the advertisement type as follows O ADV_IND invites connection requests 1 ADV_DIRECT_IND invites connection from addressed device 2 ADV_SCAN_IND invites scan request for more advert data 3 ADV _NONCONN_IND will not accept connections
304. istics where Sele Weare Weoebtt and 8 ane 172 it 3 of the 16 bit uuid are the same value OxDEAD and Americas 1 800 492 2320 Option 2 21 1 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual j 2 of the 128 bit uuids are also the same 7127334455667 7 se09AABRBCCDDEEEE m T Sever Cree e eaa Eee e Tee en suo a e ia Oeo e j aeng Norda Usb Dongle PCIOOOO DIMO erie S onm n nade A ee Ar PUNE Lio Orn Seca Wien DIM te Biclkions eiclcies seloirs re BleAdveRpeIni amp adRpts 2 0 10 IF rc 0 THEN rc BleScanRptInit scRpt ENDIF IE ro 0 THEN re BilleAdvReesCommit adRpte scRpeo ENDIF TE re OTEN lt re B leAdgvertstart 07 addro 50 0 0 gt ENDIE fopen the gatt client with default notify indicate ring buffer size IF rc 0 THEN re BleGattcOpen 0 0 ENDIF PHD EUNG ae SUB CloseConnections rc BleDisconnect conHnd1 rc BleAdvertStop ENDBSUB FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx DIM uus conHndl nCtx IF nMsgID 1 THEN PRINT n n Disconnected EX LEE UNC ELSEIF nMsgID 0 THEN PRINT n Connected so scan remote Gatt Table for first service PRINT n and a characeristic scan will be initiated in the event ro BlebuscServyicerirse CoOnHndl 0 0 IF rc 0 THEN wait for start and end handles for first primary service WALITEVENT PRINT n nGean for charac
305. it is stored locally in an underlying ring buffer and then an event is generated Similarly when the transmit buffer is emptied events are thrown from the underlying drivers so that user smart BASIC code in handlers can perform user defined actions The following is a list of events generated by VSP service managed code which can be handled by user code EVVSPRX This event is generated when data has arrived and has been stored in the local ring buffer to be read using BleVSpRead Americas 1 800 492 2320 Option 2 340 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual EVVSPTXEMPTY This event is generated when the last byte is transmitted using the outgoing data characteristic via a notification or indication Use the iOS BL600 Serial app and connect to your BL600 to test this sample app Example VSpEvents sb See in BL600CodeSnippets zip DIEM ISS ee 7 Soot erclajoiS elclcheS Iara Ir handler for data arrival FUNCTION HandlerBleVSpRx AS INTEGER erint the data that arrived DIM n texs n BleVSpRead rx 20 PRINT nr rx9 ENDEUNG i nandler when VSP tx buffer is empty FUNCTION HandlerVSpTxEmpty AS INTEGER IF x 0 THEN re BleVSpWrite tx buffer empty x 1 ENDIF ENDEUNG 1 PRIN nbdevirce meme 1s BleGerbDeviceNnames Open the VSP PRINT a pe Bile SeOpen 23 12807 andl Ini
306. ked resulting in the text lt lt Cross Compiling test1 sb gt gt In this example since the compilation is successful the generated binary file must be downloaded and the AT DEL filename deletes any previous file with the same name that might already be on the module The new Tile is downloaded using the AT FOW AT FWRH and AT FCL commands The strings following AT FWRH consist of the binary data generated by the cross compiler The DONE signifies that the process of compiling and downloading was successfully accomplished There may be a possible failure in this process if the cross compiler cannot be located In this case the following window displays AT I 10 0 B1600Med AT I 10 13 9E56 5F81 fi Grose Compiler AComp BIGUUMSd JE20 ofr el eee Tow found 7I7 2 Please save a copy to the same folder as UwTerminal exe 22 If you cannot locate the file please contact the supplier To fix this issue locate the cross compiler application mentioned in between the brackets and save it to either the folder containing UW 7erminal exe or the folder that contains the smartBASIC application test7 sb A compilation error may be another cause of failure For example if the print statement contains an error in the form of a missing delimiter then the following should display in a separate window Americas 1 800 492 2320 Option 2 21 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lair
307. keys see AT CFG for examples of contig keys 16 Erases the User config keys only Erases all data segments Else Not applicable to current modules If an asterisk is used in place of a number then the module is configured back to the factory default state by erasing all flash file segments This is an Interactive Mode command and MUST be terminated by a carriage return for it to be processed Interactive Command YES AT amp F 1 delete the file system AT amp F 16 delete the user config keys AT amp F delete all data segments AT amp F is a core command AT Zor ATZ Resets the CPU ATZ Returns nOO r Arguments None This is an Interactive Mode command and MUST be terminated by a carriage return for it to be processed Interactive Command YES Examples AT Z AT Z is a core command AT BID COMMAND Deletes the bonded device database from the flash AT BTD Returns nOO r Arguments None This is an Interactive Mode command and MUST be terminated by a carriage return for it to be processed Americas 1 800 492 2320 Option 2 46 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Note The module selt reboots so that the bonding manager context is also reset Interactive Command YES Examples AT BTD AT BTD is an extension command AT MAC 12 hex digit mac address
308. l hUuid2 now references an object which also points to the base uuid ced9000066924a1287d56 2700004762 note O s in byte position 2 3 and has the offset 0x1234 Expected Output Handle Tor custom Uuid Is FCUSD91S 66856605 Handle Tor Custom sibling Uaid 1s FCOSIZ34 7006907390 BLEHANDLEUUIDSIBLING is an extension function BleSvcCommit This function is now deprecated use BleServiceNew amp BleServiceCommt instead BleServiceNew FUNCTION As explained in an earlier section a Service in the context of a GATT table is just a collection of related Characteristics This function is used to intorm the underlying GATT table manager that one or more related characteristics are going to be created and installed in the GATT table and that until the next call of this function they shall be associated with the service handle that it provides upon return of this call Under the hood this call results in a single attribute being installed in the GATT table with a type signifying a PRIMARY or a SECONDARY service The value for this attribute shall be the UUID that will identity this service and in turn have been precreated using one of the functions BleHandleUuid16 BleHandleUuid128 or BleHandleUuidSibling Note that when a GATT Client queries a GATT Server for services over a BLE connection it will only get a list of PRIMARY services SECONDARY services are a mechanism for multiple PRIMARY services to reference sin
309. ld App You must now load the compiled output of this file into the smartBASIC module s File System so that you can run it 1 To manage file downloads right click on any part of the black UWTerminal screen to display the drop down menu Figure 12 CTS DSA DCD S Ald RTS DTR iw BREAE LocalE cho w LineMode Clear ClosePort Compile Load ACompile Load Run ACompile Load ACompile Download Font Run n Automation Batch File Player Figure 12 Right click UWTerminal screen Americas 1 800 492 2320 Option 2 20 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Laird Technologies smart BASIC User Manual 2 Click XCompile Load and navigate to the directory where you ve stored your test7 s6 file Note Do not select Compile Load 3 Click Open In UWTerminal you should see the following display AT I 0 10 0 B1600Med AT I 13 10 13 9E56 5F81 AoLoOee COmELLLOG resell soles AT DEL testi AT FOW testi AT FWRH FE900002250000000000FFFFFFFF569E815FFC10 AT FWRH FB70090054455354312F555743000110CE211000 AT FWRH FB0009000D000A48656C6C6F20576F726C640A00 AT FWRH CC211400A52000000110FD10F510 AT FCL F DOLE 4 Behind the scenes the shortcut uses Interactive Commands to load the file onto the module The first two AT commands are used to identify the module so that the correct cross compiler can be invo
310. le Characteristic Properties Handle for the Value Attribute of the Characteristic Included Service Uuid Handle If no more characteristics were discovered because the end of the table was reached then all parameters will contain O apart trom the Connection Handle Characteristic Uuid Handle contains the uuid of the characteristic and supplied as a handle Characteristic Properties contains the properties of the characteristic and is a bit mask as Tollows Bit O Set if BROADCAST is enabled Bit 1 Set if READ is enabled Bit 2 Set if WRITE_WITHOUT_RESPONSE is enabled Bit 3 Set if WRITE is enabled Bit 4 Set if NOTIFY is enabled Bit 5 Set if INDICATE is enabled Bit 6 Set if AUTHENTICATED_SIGNED_WRITE is enabled Bit 7 Set if RELIABLE_WRITE is enabled Bit 15 Set if the characteristic has extended properties Handle for the Value Attribute of the Characteristic is the handle for the value attribute and is the value to store to keep track of important characteristics in a gatt server for later read write operations Included Service Uuid Handle is for future use and will always be O BLEDISCCHARFIRST connHandle charUuidHandle startAttrHandle endAttrHandle A typical pseudo code for discovering characteristic involves first calling BleDiscCharFirst with information obtained from a primary services scan and then waiting for the EVDISCCHAR event message and depending on the information returned in that m
311. leCharNew has started the process of describing a new Characteristic It adds the descriptor to the gatt table with open read permission and no write access which means a metadata parameter is not required The BT 4 0 specification states that one or more than 1 presentation format descriptor can occur in a Characteristic and that if more than one then an Aggregate Format description shall be included too The book Bluetooth Low Energy The Developer s Handbook by Robin Heydon says on the subject of the Presentation Format Descriptor the following One of the goals for the Generic Attribute Profile was to enable generic clients A generic client is defined as a device that can Americas 1 800 492 2320 Option 2 249 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual read the values of a characteristic and display them to the user without understanding what they mean The most important aspect that denotes if a characteristic can be used by a generic client is the Characteristic Presentation Format descriptor If this exists it s possible for the generic client to display its value and it is safe to read this value BLECHARDESCPRSTNFRMT nFormat nExponent nUnit nNameSpace nNSdesc Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation Arguments nFormat byVal nFormat AS INTE
312. lo 6Hello Hello 8Hello 9Hello 10 Finished CONTINUE is a core function Error Handling Error handling functions are provided to allow program control for instances where exceptions are generated for errors These allow graceful continuation after an error condition is encountered and are recommended for robust operation in an unattended embedded use case scenario In an embedded environment it is recommended to include at least one ONERROR and one ONFATALERROR statement within each application This ensures that if the module is running unattended then it can reset and restart itself without the need for operator intervention ONERROR ONERROR is used to redirect program flow to a handler function that can attempt to modify operation or correct the cause of the error Three different options are provided in conjunction with ONERROR REDO NEXT and EXIT The GETLASTERROR command should be used in the handler routine to determine the type of error that was generated ONERROR REDO routine On return trom the routine the statement that originally caused the error is reprocessed ONERROR NEXT routine On return trom the routine the statement that originally caused the error is Skipped and the following statement is processed ONERROR EXIT If an error is encountered the application will exit and return operation to Interactive Mode Arguments Routine The handler SUB that is called when the error is detected This must be
313. ls simple variables 41 Maximum size of locals complex variables 42 Maximum depth of nested user defined functions and subroutines 43 The size of stack for storing user functions simple variables 44 The size of stack for storing user functions complex variables 45 The size of the message argument queue length 100 Enable Disable Virtual Serial Port Service when in interactive mode Valid values are Ox0000 Disable Ox0001 Enable Ox80nn_ Enable ONLY if Signal Pin nn on module is HIGH OxCOnn Enable ONLY if Signal Pin nn on module is LOW Ox81nn Enable ONLY if Signal Pin nn on module is HIGH and auto bridged to uart when connected OxC1nn Enable ONLY if Signal Pin nn on module is LOW and auto bridged to uart when connected ELSE Disable 101 Virtual Serial Port Service to use INDICATE or NOTIFY to send data to client O Prefer Notify ELSE Prefer Indicate This is a preference and the actual value is forced by the property of the TX characteristic of the service 102 This is the advert interval in milliseconds when advertising for connections in interactive mode and AT Parse mode Valid values are 20 to 10240 milliseconds 103 This is the advert timeout in milliseconds when advertising for connections in interactive mode and AT Parse mode Valid values are 1 to 16383 seconds 104 Inthe virtual serial port service manager data transfer is managed When sending data using NOTIFIES the underlying stack uses transmission buffer
314. lue The parser logic is exactly the same as when in the command mode If you are not sure which alphabet character is a token in its own right then the quickest way to get an answer is to actually try it NOTE any text after either or will be taken as a comment just like the behaviour in the command mode EXTRACTINTTOKEN sentence intValue Function Returns INTEGER The length of the extracted token Will be O of there are no more tokens to extract Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Americas 1 800 492 2320 Option 2 103 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Arguments sentence byRef sentence AS STRING String that contains the sentence containing the tokens to be extracted intValue byRef intValue AS STRING The leftmost set of tokens constituting a legal integer value is extracted from the sentence and will be removed from the sentence Note string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Interactive Command NO Example ExtractIntToken sb See in BL600CodeSnippets zip DIM sentence S DIM intValue bytes DIM tokenS tknlen sentenceS 0x100 is a hex value PRINT nSentence is sentences bytes
315. lue Currently smartBASIC supports the following cmdlDs 1 O 1 2 O 1 3 8 256 4 4 256 5 16 65535 6 16 65535 7 2 65535 8 Z 65535 9 2 32767 10 2 32767 0 1 32 8 1024 1024 32 32 256 256 Default Simple Arguments type for routines O ByVal 1 ByRef Default Complex Arguments type for routines O ByVal 1 ByRef Stack length for Arithmetic expression operands Stack length for Arithmetic expression constants Maximum number of simple global variables per application Maximum number of complex global variables per application Maximum number of simple local variables per routine in an application Maximum number of complex local variables per routine in an application Max array size for simple variables in DIM Max array size for complex variables in DIM Note Unlike other commands SET may not be combined with any other commands on a line Example set 11 change default simple args to byRef set 20 change default complex args to byVal Arithmetic Expressions Arithmetic expressions are a sequence of integer constants variables and operators At runtime the arithmetic expression which is normally the right hand side of an sign is evaluated Where it is set to a variable then the variable takes the value and class of the expression such as INTEGER If the arithmetic expression is invoked in a conditional statement its default type is an INTEGER Variable types should not be mixed
316. ly the usage is select a timer register a handler for it and start it with a timeout value and a flag to specify whether it is recurring or single shot Then when the timeout occurs AND when the application is processing a WAITEVENT statement the handler will be automatically called It is important to understand the significance of the WAITEVENT statement In a nutshell a timer handler callback will NOT happen if the runtime engine does not encounter a WAITEVENT statement Events are synchronous not asynchronous like say interrupts All this is illustrated in the sample code fragment below where timer O is started so that it will recur automatically every 500 milliseconds and timer 1 is a single shot 1000ms later Note as explained in the WAITEVENT section of this manual if a handler function returns a non zero value then the WAITEVENT statement is reprocessed otherwise the smart BASIC runtime engine will proceed to process the next statement after the WAITEVENT statement not after the handlers ENDFUNC or EXITFUNC statement This means that if the WAITEVENT is the very last statement in an application and a timer handler returns a O value then the application will exit the module from Run Mode into Interactive Mode which will be disastrous for unattended operation Americas 1 800 492 2320 Option 2 112 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth
317. m bluetooth smart BASIC User Manual dp 2 rc BleTxPowerSet dp PRINT nT power 2 cesired vido oO acted gt oy Ino 2008 dp 10 re BleTxPowerSet dp PRINTS nitx power desired Tdp M T actual sy sinro 72008 dp 25 ro BleTxPowerSet dp PRINT ntx power destred do e vecrilal gt Svcilaro 7003 dp 45 re BleTxPowerSet dp PRINT AnI power desir d do actual Svycinto 2008 dp 1000 rc BleTxPowerSet dp PRINT nT power desired dp actual T Sysinfo 2008 Expected Output BLETXPOWERSET is an extension function BleTxPwrWhilePairing FUNCTION This function sets the transmit power of all packets that are transmitted while a pairing Is in progress This mode of pairing is referred to as Whsiper Mode Pairing The actual value will be clipped to the transmit power for normal operation which Is set using BleTxPowerSet function The actual value is determined by scanning through the value list 4 0 4 8 12 16 20 30 55 so that the highest value in the list which is less than the desired value is selected unless the desired value is less than 55 and in that case 55 will be set For example setting 1000 will result in 4 3 will result in 4 100 will result in 55 At any time SYSINFO 2018 will return the actual transmit power setting Or when in command mode use the command AT 2018 BLETXPWRWHILEPAIRING nTxPower
318. ments Arithexpr_n A valid arithmetic or logical expression A valid arithmetic or logical expression Arithmetic precedence is as defined in the section Arithmetic Expressions All IF constructions must be terminated with an ENDIF statement Note As the arithmetic expression in an IF statement is making a comparison rather than setting a variable the double operator MUST be used e g IF i 3 THEN SLEEP 200 See the Arithmetic Expressions section for more options Interactive Command NO Example IfThenElse sb See in BL600CodeSnippets zip IDE Tah Americas 1 800 492 2320 Option 2 62 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual n l LE n20 THEN PRINT Laird Rocks vn ENDIF IF n 0 THEN PRINT m 1g 0a ELSEIF n 1 THEN PRANAS sil EGOE BRINT n is not 0 nor 1 ENID IL E Expected Output Laird Rocks H ais 1l IF is a core function WHILE ENDWHILE The WHILE command tests the arithmetic expression that follows it If it equates to non zero then the following block of statements is executed until an ENDWHILE command is reached If it is zero then execution continues after the next ENDWHILE WHILE arithexor statement block ENDWHILE Statement block A valid set of zero or more program statements Arithexpr A valid arithmetic or logical expression Arithmetic
319. millivolts Arguments None Interactive Command NO Example ReadPwrSupplyMv sb See in BL600CodeSnippets zip read and print the supply voltage PRINT nsupoly voltage ts T ReadPwrsupel yi ame Americas 1 800 492 2320 Option 2 353 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output Supply voltage is 3343mV READPWRSUPPLYMV is an extension function SetPwrSupplyThreshMv FUNCTION This function sets a supply voltage threshold If the supply voltage drops below this then the BLE_LEVMSG event is thrown into the run time engine with a MSG ID of BLE_LEVBLEMSGID_POWER_FAILURE_WARNING 19 and the context data will be the current voltage in millivolts Events amp Messages 19 The supply voltage has dropped below the value specified as the argument to this function in the most recent call The context data Is the current reading of the supply voltage in millivolts SETPWRSUPPLYTHRESHMV nThresh Returns INTEGER O if the threshold is successfully set Ox6605 if the value cannot be implemented Arguments None nThreshMv byVal nThresMv AS INTEGER The BLE_EVMSG event is thrown to the engine if the supply voltage drops below this value Valid values are 2100 2300 2500 and 2700 Interactive Command NO Example SetPwrSupplyThreshMv sb See in BL600CodeSnippets zip BNE vate DIM mv
320. minated by a carriage return for it to be processed It performs no action other than to respond with nOO r It exists to emulate the behaviour of a device which is controlled using the AT protocol This is a good command to use to check if the UART has been correctly configured and connected to the host Americas 1 800 492 2320 Option 2 32 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual AT I or ATI Provided to give compatibility with the AT command set of Laird s standard Bluetooth modules ATi num Command Returns n10 tMM tIintormation r nOO r Where n lineteed character Ox0A t horizontal tab character 0x09 MM a number see below Information sting consisting of information requested associated with MM r carriage return character OxOD Arguments num Integer Constant A number in the range O to 65 535 Currently defined numbers are 0 Name of device 3 Version number of Module Firmware 4 MAC address in the form TT AAAAAAAAAAAA 5 Chipset name 6 Flash File System size stats data segment Total Free Deleted 7 Flash File System size stats FAT segment Total Free Deleted 12 Last error code 13 Language hash value 16 NvRecord Memory Store stats Total Free Deleted 33 BASIC core version number 601 Flash File System Data Segment Total Space 602 Flash File System Data Segment Free Space
321. mple BleCharValueWrite sb See in BL600CodeSnippets zip IDLE Iain C Rar ie PUNCTE TONE On Ea TUP DIM ner IS wee 7 elie iwc o arters re commit service rc BleSvcCommit 1 BleHandleUuidl6 Ox18EE hSvc initialise char write read enabled accept signed writes rc BleCharNew 0x4A BleHandleUuidl16 1 BleAttrMetaData 1 1 20 0 rc 0 0 J Commit char initialised above wirch initial value bhi tro service hove rc BleCharCommit hSvc attrs hMyChar PANDEUNC ice Americas 1 800 492 2320 Option 2 257 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Uart Rx handler write input to characteristic SUNG LON SiincilaUeiceron Tameroueare 0 070 ENDFUNC 1 BUNGCTION HinG iret mic O70 DIM tS re UartRead t IF BleCharValueWrite hMyChar t 0 THEN PRINT nNew characteristic value ts ELSE PRINT nFailed to write new characteristic value BENDI E ENDFUNC 0 LE Onsearceuo O THEN DIM atS re BleCharValueRead hMyChar ats PRINT nCharacteristic value attribute arsS nSend a new value n BLOE PRINT nFailure OnStartup ENDIF ONEVENT EVUARTRX CALL HnditeUart Rx ONEVENT EVTMRO CALL Haci eTmeO WALTEVENT PPINT gt rei sane Iii eae Expected Output BLECHARVALUEWRITE is an extension function BleCharValueNotify FUNCTION If there is BLE connection this function
322. n VSP and UART ring buffers BleVspUartBridge BNDEUNG 1 ONEVENT EVVSPRX CALL HandlerBridge ONEVENT EVUARTRX CALL HandlerBridge ONEN SEVVsPlZEMPe RY CALL HandlerBridge ONEVENT EVUARTTXEMPTY CALL HandlerBridge ONEVENT EVBLEMSG CALL HndlrBleMsg ONEVENT EVGPIOCHANL CALG hind lek te OnStartup WALITEVENT CloseConnections V Calls secono subrourcine declareo above 21 SEIN AL Ee gud cise digo ayy vt BLEVSPUARTBRIDGE is an extension subroutine Americas 1 800 492 2320 Option 2 350 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Laird Technologies smart BASIC User Manual BleVSpFlush SUBROUTINE This subroutine flushes either or both receive and transmit ring buffers This is useful when for example you have a character terminated messaging system and the peer sends a very long message filling the input buffer In that case there is no more space for an incoming termination character A flush of the receive buffer is the best approach to recover from that situation BLEVSPFLUSH bitMask Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments bitMask byVal bitMask AS INTEGER Bit O is set to flush the Rx buffer Bit 1 is set to flush the Tx buffer Set both bits to flush both buffers Interactive Command No Related Commands BLEVSPOPEN BLEVSPCLOSE BLEVSPINFO BLEVSPWRITE BLEVSPREAD Example BleVSpFlush sb See in BL600Co
323. n addition the Security Manager Specification in the core 4 0 specification Part H provides a Tull description You will need to be registered with the Bluetooth SIG www bluetooth org to get access to all these documents An authenticated pairing is deemed to be one with less than 1 in a million probability that the pairing was compromised by a MITM Man in the middle security attack The valid user I O capabilities are as described below BLESECMNGRIOCAP nloCap Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments nloCap byVal n oCap AS INTEGER The user I O capability for all subsequent pairings O None also known as Just Works unauthenticated pairing 1 Display with Yes No input capability authenticated pairing 2 Keyboard Only authenticated pairing 3 Display Only authenticated pairing if other end has input cap 4 Keyboard only authenticated pairing Interactive Command NO Example BleSecMngrIoCap sb See in BL600CodeSnippets zip PRINT BleSecMngrloCap 1 Americas 1 800 492 2320 Option 2 226 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output BLESECMNGRIOCAP is an extension function BleSecMngrBondReq FUNCTION This function is used to enable or disable bonding when pairing Note This function will
324. n consists of a command parser and a single line single pass compiler It takes each line of text a series of tokens and does one of the following depending on its content and operating mode Acts on them immediately such as with AT commands lf the build includes the compiler generates a compiled output which is stored and processed at a later time by the run time engine This capability is not present in the BL600 due to flash memory constraint smartBASIC has been designed to work on embedded systems where there is often a very limited amount of RAM To make it efficient you must declare every variable that you intend to use by using the DIM statement The compiler can then allocate the appropriate amount of memory space acer In the following example program we are using the variable i to count how many times we print Hello World smartBASIC allows a couple of different variable types numbers 32 bit signed integers and strings Our program stored in a file called He loWorld sb looks like this Example HelloWorld sb See in BL600CodeSnippets DIM i as integer declare our variable for i l to 10 Perform the print ten times print Hello World n The n forces a new line each time NEXT Americas 1 800 492 2320 Option 2 23 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Some notes rega
325. n handle as received via the EVBLEMSG event with msgld set to O nPassKey byVal nPassKey AS INTEGER This is the passkey to submit to the stack Submit a value outside the range O to 999999 to reject the pairing Interactive Command NO Example BleSecMngrPasskey sb See in BL600CodeSnippets zip DIM rc connHandle DIM addr addro s u FUNCTION HandlerBleMsg BYVAL nMsgid AS INTEGER BYVAL nCtx AS INTEGER AS INTEGER SELECT nMsqid CASE 0 connHandle nCtx PRINT n Ble Connection nCtx CASE 1 PRINT n Disconnected nCtx n EXITFUNC Q CASK Jal PRINT n Auth Key Request type nCtx rc BleSecMngrPassKey connHandle 123456 IF rc 0 THEN key is 123456 Americas 1 800 492 2320 Option 2 224 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT nPasskey 123456 was used BLSE PRINT nResult Code Ox In eger re ENDIF CASH Firs ENDSE LECT ENDEUNCG 1 ONEVENT EVBLEMSG CALL HandlerBleMsg rc BleSecMngrloCap 4 Set i o capability Keyboard Only authenticated pairing LF BleAdvertsccart 0 addres 25 0 0 THEN PRINT nAdverts Started n PRINT nMake a connection to the BL60O BLSE PRINT n nAdvertisement not successful ENDIF WAL TEVENT Expected Output BLESECMNGRPASSKEY is an extension function BleSecMngrKeySizes FUNCTION This function sets minimum and
326. n is possible with the UART device connected to the serial port LocalEcho Enables local echoing of any characters typed at the terminal In default operation this option box should be selected because modules do not reflect back commands entered in the terminal emulator _LineMode Delays transmission of characters entered into UWTerminal until you press Enter Enabling LineMode means that Backspace can be used to correct mistakes We recommend that you select this option Clear Removes all characters from the terminal screen ClosePort Closes the serial port This is useful when a USB to serial adaptor is being used to drive the development board which has been briefly disconnected from the PC OpenPort Re opens the serial port after it has been manually closed Americas 1 800 492 2320 Option 2 15 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Useful Shortcuts There are a number of shortcuts that help soeed up the use of UWTerminal Each time UWTerminal starts it asks you to acknowledge the Accept screen and to enter the COM port details If you are not going to change these you can skip these screens by entering the applicable command line parameters in a shortcut link Follow these steps to create a shortcut to UWTerminal on your desktop 1 Locate and right click the UwTerminal
327. n written by the remote gatt client Note Message ID 13 is reserved for future use An example of how these messages can be used is as follows Example EvBleMsg sb See in BL600CodeSnippets zip DIM addrs addrs DIMERS JE This handler is called when there is a BLE message EESE FUNCTION HndlrBleMsg BYVAL nMsgid AS INTEGER BYVAL nCtx AS INTEGER SELECT nMsgid CASE 0 PRINT nble Connection ncCrx re BleAuthenticate nCtx CASE 1 PRINT nDasconnected ncrex 1 CASE 18 PRINT TAn onne ceon Neex ne Now encrypored CASE 16 PRINT nConnected to a bonded master CASE 17 PRINT nA new pairing has replaced the old key CASE ELSE PRINT nUnknown Ble Msg ENDSELECT ENDFUNC 1 FUNCTION HndlrBlrAdvTimOut PRINT nAdvert stopped via timeout PETOA NE ana Americas 1 800 492 2320 Option 2 192 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BNDEUNG FUNCTION BtnOPress PRINT AE ICIN erry a ENDFUNC 0 PRINT Goreserhume 1o 170x72 PRINT GoroBandevent 0 16 0 ONEVENT EVBLEMSG CALL HndlrBleMsg OUREVEN TERV BEE RAD TIMBOul CALin tind tre lr kav limo ONEVENT EVGPIOCHANO CALL BtnOPress Fi Siceas EON es IF BleAdvertStart 0 addrS 100 10000 0 0 THEN PRINT A nAdverts Started PRINT nPress button 0 to extn ELSE PRINT n nAdvertisement not su
328. nMantissa byRef nMantissa AS INTEGER This is updated with the 12 bit mantissa from the 2 byte object If the nExponent is 0 you MUST check for the following special values OxOO7FFFFF NaN Not a Number 0x00800000 NRes Not at this resolution OxOO7FFFFE INFINITY OxO00800002 INFINITY Ox00800001 Reserved for future use Americas 1 800 492 2320 Option 2 330 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual nExponent byRef nExponent AS INTEGER This is updated with the 4 bit mantissa If it is zero check the nMantissa for special cases as Stated above nindex byVal nindex AS INTEGER This is the zero based index into the string attr from which data is read If the string attr is not long enough to accommodate the index plus the number of bytes to read this function fails Interactive Command NO Example BleDecodeSFloat sb See in BL600CodeSnippets zip DIM chrhandle yl svwchandile re mantissa exp DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc DIM atte e aE A OO Ol 02 02 0485 Veo 87 63 80 DIM uur 3 uuicl 0x1853 rc BleSvcCommit 1 BleHandleUuidl6 uuid svcHandle rc BleCharNew 0x07 BleHandleUuidl16 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle rc BleCharValueRead chrHandle attr Ii read 2 bytes FLOAT from index 2 in the string rc BleDecodeSFloat attr manti
329. nd for FW 1 3 57 0 and earlier Example UartCloseExWA sb See in BL600CodeSnippets zip DIM rel DIME UartClose Eel Uar Open 9600 Or O TCN IET open as DTE at 300 baudrate odd parity AR denaotEs te SeOob hrs ces rise Eloy control Pra e S Tan p Workaround ror bug for firmware versiono older haa AS 23 5 S LE VUarcilniro 6 s0 THEN PRINT nData in at least one buffer Uart Port not closed BLSE rce2 UartClosekx 1 rol Uar Open OoOO 0 TONIE T open as DTE at 300 baudrate odd parity PRINT ihe Uart Port was closed EN Dae For FW 1 3 57 3 and newer Example UartCloseEx sb See in BL600CodeSnippets zip DIM re DIMEC UartClose Eel Uar Open aC OO O O CNI nT lopen as DTE at 300 baudrate odd parity 7 o daea eaa l eooo Cro tes On COMErol PRIM haan IF UartClosekx 1 0 THEN PR VaDabta in art least one burrter Ute Port not closed SE rol UartoOven 9600 0 0 CNS la open as DTE at 300 baudrate odd parity PRINT AnUart Port was closed BNDL E Expected Output Laird Data in at least one buffer Uart Port not closed UARTCLOSEEX is a core function Americas 1 800 492 2320 Option 2 132 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Uartinfo FUNCTION This function is used to query information about the default uart such as buffer lengths
330. nd the GATT table manager will need that before it is added Some attributes have those notes specitied by the BT specification and so the GATT table manager will not need to be provided with any but the rest require it This function helps write that metadata BLEATTRMETADATA nReadRights nWriteRights nMaxDataLen flsVariableLen resCode Returns INTEGER a 32 bit opaque data object to be used in subsequent calls when adding Characteristics to a GATT table Arguments nReadkights byVal nReadkights AS INTEGER This specifies the read rights and shall have one of the following values O No Access 1 Open 2 Encrypted with No Man In The Middle MITM Protection 3 Encrypted with Man In The Middle MITM Protection 4 Signed with No Man In The Middle MITM Protection not available 5 Signed with Man In The Middle MITM Protection not available Americas 1 800 492 2320 Option 2 245 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual nWriteRights NMaxDatalen tls VariableLen resCode Note In early releases of the firmware 4 and 5 are not available byVal nWriteRights AS INTEGER This specifies the write rights and shall have one of the following values No Access Open Encrypted with No Man In The Middle MITM Protection Encrypted with Man In The Middle MITM Protection Signed with N
331. nd write permissions authentication and security Americas 1 800 492 2320 Option 2 244 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual properties When Services and Characteristics are added to a GATT server table multiple attributes with appropriate data and properties get added This function allows a 32 bit integer to be created which is an opaque object which defines those properties and is then submitted along with other information to add the attribute to the GATT table When adding a Service attribute not the whole service in this present context the properties are defined in the BT specification so that it is open for reads without any security requirements but cannot be written and always has the same data content structure This implies that a metadata object does NOT need to be created However when adding Characteristics which consists of a minimum of 2 attributes one similar in function as the aforementioned Service attribute and the other the actual data container then properties for the value attribute must be specified Here properties refers to properties for the attribute not properties for the Characteristic container as a whole These also exist and must be specified but that is done in a different manner as explained later For example the value attribute must be specified for read write pe
332. ndex 10 ba 0x12345678 PRINT ni nbit array INTEGER PUDA rc BleDecodeBITS attr 14000 ba 0 14 PRINT nott array now INTEGER IB ba ba will not have been modified because index 14000 doesn t exist in attrs Expected Output BLEDECODEBITS Is an extension function Pairing Bonding Functions This section describes all functions related to the pairing and bonding manager which manages trusted devices The database stores information like the address of the trusted device along with the security keys At the time of writing this manual a maximum of 4 devices can be stored in the database The command AT 12012 or at runtime SYSINFO 2012 returns the maximum number of devices that can be saved In the database The type of information that can be stored for a trusted device is The MAC address of the trusted device The eDIV and eRAND for the long term key A 16 byte Long Term Key LTK The size of the long term key A flag to indictate if the LTK Is authenticated Man In The Middle MITM protection A 16 byte Indentity Resolving Key IRK A 16 byte Connection Signature Resolving Key CSRK Whisper Mode Pairing BLE provides for simple secure pairing with or without man in the middle attack protection To enhance security while a pairing is in progress the specification has provided for Out of Band pairing where the shared secret information is exchanged by means other than the Bluetooth con
333. ne On return from the routine the statement that originally caused the error is skipped and the following statement is processed ONFATALNERROR EXIT If an error is encountered the application will exit and return the operation to Interactive Mode Please Note At present no fatal errors are thrown in the BL600 module ONFATALERROR is a core function Event Handling An application written for an embedded platform is left unattended and in most cases waits for something to happen in the real world which it detects via an appropriate interface When something happens it needs to react to that event This is unlike sequential processing where the program code order is written in the expectation of a series of preordained events Real world interaction is not like that and so this implementation of smart BASIC has been optimised to force the developer of an application to write applications as a group of handlers used to process events in the order as and when those events occur Americas 1 800 492 2320 Option 2 67 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual This section describes the statements used to detect and manage those events WAITEVENT WAITEVENT is used to wait for an event at which point an event handler is called The event handler must be a function that takes no arguments and returns an INTEGER If the event h
334. nection That mode of pairing Is currently not exposed Laird have provided an additional mechanism for bonding using the standard inbuilt simple secure pairing which is called Whisper Mode pairing In this mode when a pairing is detected to be in progress the transmit power is automatically reduced so that the bubble of influence is reduced and thus a proximity based enhanced security is achieved Americas 1 800 492 2320 Option 2 335 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual To take advantage of this pairing mechanism use the function BleTxPwrWhilePairing to reduce the transmit power for the short duration that the pairing is in progress Tests have shown that setting a power of 55 using BleTxPwrWhilePairing will create a bubble of about 30cm radius outside which pairing will not succeed This will be reduced even further if the BL600 module is in a case which affects radio transmissions BleBondMngrErase Note For firmware versions prior to 1 4 X Y this subroutine has a bug It occurs when the subroutine is called during radio activity Workaround when advertising 1 Stop adverts by calling BleAdvertStop 2 Call BleBondMngrErase 3 Restart adverts using BleAdvertStart SUBROUTINE This subroutine deletes the entire trusted device database if the supplied parameter is 0 Other valu
335. nections Calls second subroutine declared aboye PRTI TS nE Enea Expected Output BLEVSPFLUSH is an extension subroutine Americas 1 800 492 2320 Option 2 352 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Laird Technologies smart BASIC User Manual 7 OTHER EXTENSION BUILT IN ROUTINES This chapter describes non BLE related extension routines that are not part of the core smart BASIC language System Configuration Routines SystemStateSet FUNCTION This function is used to alter the power state of the module as per the input parameter SYSTEMSTATESET nNewState Returns INTEGER a result code The typical value is OxO000 indicating a successful operation Arguments nNewsState byVal nNewState AS INTEGER New state of the module as follows O System OFF Deep Sleep Mode Note You may also enter this state when UART is open and a BREAK condition is asserted Deasserting BREAK makes the module resume through reset i e power cycle Interactive Command NO Example SystemStateSet sb See in BL600CodeSnippets zip Put the module into deep sleep PRINT n SystemStateSet 0 SYSTEMSTATESET is an extension function Miscellaneous Routines ReadPwrSupplyMv FUNCTION This function is used to read the power supply voltage and the value will be returned in millivolts READPWRSUPPLYMV Returns INTEGER the power supply voltage in
336. nfig About CTS OSR DCO AS RTSH DIRI Copy the smartBASIC source file HelloWorld sb to autorun sb and then cross compile and download to the module After it is downloaded enter the AT DIR command and the following displays att dir 06 testl 06 HelloWorld 06 Saucoruns 00 TIP A useful feature of UWTerminal is that the download function strips off the filename extension when it downloads a file into the module file system This means that you can store a number of different autorun applications on your PC by giving them longer more descriptive extension names Americas 1 800 492 2320 Option 2 25 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual For example S autorun HelloWorld By doing this each autorun file on your PC is unique and the list is simpler to manage Note If Windows adds a text extension rename the file to remove it Do not use multiple extensions in filenames such as filename ext1 ext2 The resulting Tiles after being stripped may overwrite other files Clear the UWTerminal screen by clicking the Clear button on the toolbar and then enter the command ATZ to force the module to reset itself You could also click Reset on the development kit to achieve the same outcome Warning If the JLINK debugger is connected to the development kit via the ribbon then the reset button has n
337. ng the AT RUN command If bridge mode is enabled then any incoming VSP data is retransmitted out via the UART Conversely any data arriving via the UART is transmitted out the VSP service This latter functionality provides a cable replacement function Selection of Command or Bridge Mode is done using the nAutorun input signal When nAutorun is low interactive mode is enabled When it is high and bit 8 in the config register 100 accessed by AT CFG 100 is set bridge mode Is selected By default bridge mode is not enabled and the command AT CFG 100 0x8107 should be supplied either over the UART or the on air interactive mode Note If autorun file exists in the file system the bridge mode is always suppressed regardless of the state of the nAutorun input signal The main purpose of interactive mode operation Is to facilitate the download of an autorun smartBASIC application This allows the module to be soldered into an end product without preconfiguration and then the application can be downloaded over the air once the product has been pre tested It is the smartBASIC application that is downloaded over the air NOT the firmware Due to this principle reason for use in production to facilitate multiple programming stations in a locality the transmit power is limited to 12dBm It can be changed by changing the 109 config key using the command AT CFG The default operation of this virtual serial port service is dependent on one of the digi
338. nguage function MID FUNCTION Retrieves a string of characters from an existing string The starting position of the extracted characters and the length of the string are supplied as arguments If pos is positive then the extracted string starts from offset pos If it is negative then the extracted string starts from offset length of string abs pos MID string pos length Returns STRING The length characters starting at offset pos of string Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Memory Heap Exhausted Arguments string byRef string AS STRING The target string which cannot be a const string ae byVal pos AS INTEGER The position of the first character to be extracted The leftmost character position is O see examples length byVal length AS INTEGER The number of characters that are returned If length is larger than the actual length of string then the entire string is returned from the position specified Hence pos 0 length 65535 returns a copy of string Note string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Interactive Command NO Example MID sb See in BL600CodeSnippets zip DIM s sS Arsenic DIM news news MIDS sS 2 4 Americas 1 800 492 2320 Option 2 84 Laird Tech
339. nnot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Related Commands UARTOPEN UARTINFO UARTCLOSE UARTREAD UARTREADMATCH UARTGETDSR UARTGETCTS UARTGETDCD UARTGETRI UARTSETDTR UARTSETRTS UARTSETDCD UARTSETRI VARTBREAK UARTFLUSH Americas 1 800 492 2320 Option 2 134 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Example UartWrite sb See in BL600CodeSnippets zip DIM re ocr a done nd Stra contains a lot of Space SO Chat wa can salisi the condition an the IF stacemengt strs Hello World FUNCTION MAd Uart TEC PRINT nis buffer io now empty ENDFUNC O0 exit from WAITEVENT icc Uena either STES donite SstrS af there isn t enough space in the butter until strs cam be written WHILE done IE We Sivelysia SinieS THEN PRINT re bytes written PRINT instill hae Stren stro re bytes tO Were mn PRE ae Visit tings Shits e 1s tC Sersiisteheoit stro E done 0 BLS PRE string Str ot wriitten sucesso mu lh done 1 ENDIF ENDWHILE ONEVENT EVUARTTXEMPTY CALL HndlrUartTxEty WALTEVENT Expected Output UARTWRITE is a core subroutine Americas 1 800 492 2320 Option 2 135 Laird Technologies Europe 44 1628 858 940
340. nologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT news mn Expected Output Arse abcdef cdefg Hij MID is a core language function RIGHT FUNCTION Retrieves the rightmost n characters from a string RIGHT string len Returns STRING The rightmost segment of length en from string Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Memory Heap Exhausted Arguments string byRef string AS STRING The target string which cannot be a const string length byVal length AS INTEGER The rightmost number of characters that are returned Note string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function If length is larger than the actual length of string then the entire string is returned Interactive Command NO Example RIGHTS sb See in BLO6O00CodeSnippets zip DIM s sS Parse DIM news news RIGHTS sS 4 PRs emewoee i Expected Output RIGHT is a core function Americas 1 800 492 2320 Option 2 85 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual STRLEN FUNCTION STRLEN returns the number of c
341. non volatile configuration key Configuration keys are are comparable to S registers in modems Their values are kept over a power cycle but are deleted if the AT amp F command is used to clear the file system If a configuration key that you need isn t listed below use the functions NvRecordSet and NvRecordGet to set and get these keys respectively The num value syntax is used to set a new value and the num syntax is used to query the current value When the value is read the syntax of the response is 2d Oxhhhhhhhh dddd where Oxhhhhhhhh is an eight hexdigit number which is O padded at the left and dddd is the decimal Signed value AT CFG num value or AT CFG num Returns If the contig key is successfully updated or read the response is nOO r Arguments num Integer Constant The ID of the required configuration key All of the configuration keys are stored as an array of 16 bit words value Integer_constant This is the new value for the configuration key and the syntax allows decimal Americas 1 800 492 2320 Option 2 37 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual octal hexadecimal or binary values This is an Interactive mode command and MUST be terminated by a carriage return for it to be processed The following Configuration Key IDs are defined 40 Maximum size of loca
342. nstant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Americas 1 800 492 2320 Option 2 102 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Interactive Command NO Example ExtractStrToken sb See in BL600CodeSnippets zip DIM sentences tokenS tknlen sentenceS My name is BL600 from ete el PRINT nSentence is sentenceS DO tknlen ExtractStrToken sentenceS tokenS PRINT SY ekokene Wem selene ce jy set tine ems UNTIL tknalen Q Expected Output ExtractStrToken is a core function EXTRACTINTTOKEN This function takes a sentence in the first parameter and extracts the leftmost set of tokens that make an integer number hex or binary or octal or decimal from it and passes it back in the second paremeter The tokens are removed from the sentence The function will return the number of characters extracted from the left side f the sentence This means if O is returned then there are no more tokens in the sentence For example if the sentence is 0x100 is a hex value then the first call of this function will return 256 in the second parameter and the sentence will be adjusted to is a hex value Note that hex value whill result in hex then and then va
343. ntime SYSINFO 2004 This function returns that tree running counter It wraps to O when the counter reaches Ox7FFFFFFF GETTICKCOUNT Returns INTEGER A value in the range O to Ox7FFFFFFF 2 147 483 647 in units of milliseconds Arguments None Interactive Command No Related Commands GETTICKSINCE Example GetTickCount sb See in BL600CodeSnippets zip FUNCTION HandlerTimer0O PRINT n nTimer O has expired ENDFUNC 0 Pei alie valve om Ene CcoUnmberlls ConlickCouned ONE VENTE EVIMRO CA Hawd ler Timex Americas 1 800 492 2320 Option 2 117 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Tamenseare 0 1000 0 PRINT nWasrting for Timer O WALTEVENT PRIINI YAnTrhe value on the counter Ls now VoGetTickCount g Expected Output GETTICKCOUNT is a core subroutine GetTickSince FUNCTION This function returns the time elapsed since the startTick variable was updated with the return value of GETTICKCOUNT It signifies the time in milliseconds If startTick is less than O which is a value that GETTICKCOUNT will never return then a O will be returned GETTICKSINCE startTick Returns INTEGER A value in the range O to 0x7FFFFFFF 2 147 483 647 in units of milliseconds startTickr byVal startTick AS INTEGER This is a variable that was updated using the return value trom
344. nto the string attr from which data is read If the string attr is not long enough to accommodate the index plus the number of bytes to read this function fails Interactive Command NO Example BleDecodeU1l6 sb See in BL600CodeSnippets zip DIM chridanciLle viL sveramea Ley Te DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc EION eoe ee a e a OO Oil A 05 0485 36 87 ee eo DIM Wit des cele 0x1853 Americas 1 800 492 2320 Option 2 324 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual rc BleSvcCommit 1 BleHandleUuidl6 uuid svcHandle rc BleCharNew 0x07 BleHandleUuidl6 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle rc BleCharValueRead chrHandle attr read 2 unsigned bytes from index 2 rc BleDecodeU16 attr vl1 2 PRINT Andata in Hex Ox INTEGER A vl PRINT Vince tae in Decimal Nay EN aa cead 2 unsigned bytes from index 6 rc BleDecodeUl6 attrsS vl1 6 PRINT Andata am Hex 0x7 INTEGER Ho wl PRINT ndata in Decimal g yiz n Expected Output BLEDECODEU16 is an extension function BleDecodeS24 FUNCTION This function reads three bytes in a string at a specified offset into a 32bit integer variable with sign extension If the offset points beyond the end of the string this function fails BLEDECODES24 attr nData nlndex Returns
345. nxevasvax aoeds 18 3 Interactive Mode COMMANAS cccccssececcesseeeceeseeseeeseeeeceesececeesecseneuseceteaecsteaaeeeeseaseeeteageeseseasesersageeetes 31 A SII GPE BPSCCO lie S E E 49 RX APE EA E EEE gu acca PN A E sett eneane anne ean A A N E A EE E A E E 49 POR ON E E E E E E E E E E S 49 SAUDO E aii eA E AE E E E TA 49 Se S ARL E A A T E E A A E A A E E E A E E E A E 50 EPON a E E E E E E AS 50 EAS WOR DSM OMS apcaccassassaeqrsusiortsaventnacanedarsiegaaaitoseseaantcoseaevernbeua saerseetedancsieoesedusacodedanestoaesae E 51 MS TMU ANC este E E E cre stese E A nec ste oo eg E N S dace esas N cc carapace cease ata I A R E T S 51 OIG S E T E E E A E O A EE A A E A A E A T E A O E E 51 CONS e E E E E E E sau soaisouncueessoedassueuannst ot 55 Compiler Related Commands and Directives cccccsssscccccesssececceeseccceceeeececseeeeccesauaeceessueueceesseeaeeeesseuaeeeessagasees 56 A e E E S TO a r A E E OAE E AO EE TOE E 57 CNO aae AEE ENE EA EA EAA E E EEE 59 Enor AnA ereo E AE E E S E 66 Miscellaneous Commands sirsiran eiaeia ea a ENEE Ea A aa a 70 5 Core Language Built in ROUCINGS esisssdecececensttevecustiens vsuwesacetacnteretduuecustdessuvsanincoeceeecetaushdedeewsScneavedawetentes 75 PEU arora acess tence ae cece E A A E E E 75 Mormann ROUNE Sasae N OAOE E AE E AEA AN OAOE 76 Event amp Messaging Routines ccc cacinancesasaedsasstmancenasiiedduanciansenasaedeesnansanenasiien deanasqacenasaiksasnagapeenashentnsmiacnsannsnalsasmeasnc
346. o AT RUN debugging is enabled AT DBG filename Returns If the filename does not exists the AT DBG will respond with an error response When the application aborts or if the application reaches its end a deterred nOO r response is sent Arguments filename String_constant The name of the file to be run The maximum length of filename is 24 characters and should not include the following characters lt gt This is an Interactive mode command and must be terminated by a carriage return for it to be processed Americas 1 800 492 2320 Option 2 36 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Debugging is enabled when using AT DBG which means that all BP nnnn statements are active To launch an application without the debugging capability use AT RUN You do not need to recompile the application but this is at the expense of using more memory to store the application If any variables exist from a previous run they are destroyed before the specified application Is serviced Interactive Command YES Examples AT DBG NewApp AT DBG is a core command AT SET This command has been deprecated please use the new presentation command AT CFG num value instead AT GET This command has been deprecated please use the new command AT CFG num instead AT CFG COMMAND AT CFG Is used to set a
347. o Man lIn The Middle MITM Protection not available Signed with Man lIn The Middle MITM Protection not available Mm BRWN oO Note In early releases of the firmware 4 and 5 are not available byVal nMaxDatalen AS INTEGER This specifies the maximum data length of the VALUE attribute Range is from 1 to 512 bytes according to the BT specification the stack implemented in the module may limit it for early versions At the time of writing the limit is 20 bytes byVal flsVariableLen AS INTEGER Set this to non zero only if you want the attribute to automatically shorten it s length according to the number of bytes written by the client For example if the initial length is 2 and the client writes only 1 byte then if this is O then only the first byte gets updated and the rest remain unchanged If this parameter is set to 1 then when a single byte is written the attribute will shorten it s length to accommodate If the client tries to write more bytes than the initial maximum length then the client will get an error response byRef resCode AS INTEGER This variable will be updated with result code which will be O if a metadata object was successfully returned by this call Any other value implies a metadata object did not get created Interactive Command NO Example DIM mdVal DIM maCceed DIM MESECE DIM rc te ae BleAttrMetadata sb See in BL600CodeSnippets zip metadata for value attribute of Cnha
348. o effect The following output displays World World World World World World World World World World Few 1 amp Ue GW Nh Ff In UWTerminal next clear the screen using the Clear button and then unselect the checkbox labelled DTR so that the nAutoRUN input of the module is not asserted After a reset ATZ or the button the screen remains blank which signifies that the autorun application was NOT invoked automatically The reason for providing this capability suppressing the launching of the autorun application is to ensure that if your autorun application has the WAITEVENT as the last statement This allows you to regain control of the module s command interpreter for further development work Debugging Applications One difference with smartBASIC is that it does not have program labels or line numbers Because it is designed for a single line compilation in a memory constrained embedded environment it is more efficient to work without them Because of the absence of labels smartBASIC provides facilities for debugging an application by inserting breakpoints into the source code prior to compilation and execution Multiple breakpoints can be inserted and each breakpoint can have a unique identifier associated with it These IDs can be used to aid the developer in locating which breakpoint resulted in the break It is up to the programmer to ensure that all IDs are unique The compiler does not check for repeated v
349. ode easier They are included in your application using the include statement which is is described later in this manual As you start to develop more complex applications you may want to use a more fully featured editor such as TextPad trial version downloadable from www textpad com or Notepad free and downloadable from http notepad plus sourcetorge net Tip Laird recommends using TextPad or Notepad because appropriate color syntax highlighting files are available for each build of the firmware which means all tokens recognised by smartBASIC are highlighted in various colors If you use Notepad do the following 1 Copy the file smartBAS C noteoad xm to the Notepad install folder 2 Launch Notepad 3 From the menu select Language gt Define your Language 4 In the new dialog box click Import and select the smartBASIC notepad xml file from the folder you saved it to A confirmation dialog box displays stating that the import was successful Close the User defined Language dialog box and then the Notepad application 6 Reopen Notepad and select Language gt smartBASIC from the menu Th If you use TextPad do the following Americas 1 800 492 2320 Option 2 18 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual ot Eye ae a 9 10 11 12 Copy the smartBASIC Textpad
350. of the random MAC address The exact details and format of how the specification requires this to be managed is not relevant for the purpose of how BLE functionality as exposed in this module and only how various API functions in smartBASIC expect MAC addresses to be provided is detailed here Where a MAC address Is expected as a parameter or provided as a response it will always be a STRING variable This variable SHALL be 7 octets long where the first octet Is the address type and the the rest of the 6 octets is the usual MAC address in big endian format so that most significant octet of the address is at offset 1 whether public or random The address type is O for Public 1 for Random Static 2 for Random Private Resolvable 3 for Random Private Non Resolvable All other values are illegal For example to specity a public address which has the MAC potion as 112233445566 then then STRING variable shall contain 7 octets 00112233445566 and a variable can be initialised using a constant string by escaping as follows DIM addr addr OO 1 1 22 33 44 55 66 Likewise a static random address will be 01C12233445566 upper 2 bits of MAC portion 11 a resolvable random address will be 02412233445566 upper 2 bits of MAC portion 01 and a non resolvable address will be 03112233445566 upper 2 bits of MAC portion 00 Please note The MAC address portion in smartBASIC is always in big endian format If you sniff on air packets the same
351. on This application can then be run at any time and can even be designated as the application to be automatically launched upon power up Run time Mode In Run time mode pre compiled smartBASIC applications are read from program memory and executed in situ trom flash The ability to run the application from flash ensures that as much RAM memory as possible is available to the user application for use as data variables On startup an external GPIO input pin is checked If the state of the input pin is asserted high or low depending on the platform and autorun exists in the file system the device enters directly into Run time mode and the application is automatically launched If that input pin is not asserted then regardless of the existence of the autorun Tile it enters Interactive mode Americas 1 800 492 2320 Option 2 9 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual If the auto run application completes or encounters a STOP or END statement then the module returns to Interactive mode It is therefore possible to write autorun applications that continue to run and control the module s behavior until power down which provides a complete embedded application The modes of the module and transitions are illustrated in Figure 2 autorun input command AT RUN file STOP or END statement or r
352. on handle as returned in the on connect event for the connection on which the remote Gatt Server can be accessed This will have been returned in the EVBLEMSG event message with msgld 0 and msgCtx will have been the connection handle descUuldHandle byVal descUuidHandle AS INTEGER Set this to O if you want to scan for any descriptor in the characteristic otherwise this value will have been generated either by BleHandleUuid16 or BleHandleUuid128 or BleHandleUuidSibling charValHanale byVal charValHandle AS INTEGER This is the value attribute handle of the characteristic on which the descriptor scan is to be performed It will have been acquired from an EVDISCCHAR event BLEDISCDESCNEXT connHandle Calling this assumes that BleDiscCharFirst has been called at least once to set up the internal characteristics scanning state machine and that BleDiscDescFirst has been called at least once to start the descriptor discovery process Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation and it means an EVDISCDESC event message WILL be thrown by the smartBASIC runtime engine containing the results A non zero return value implies an EVDISCDESC message will NOT be thrown Arguments connHandle byVal nConnHanale AS INTEGER This is the connection handle as returned in the on connect event for the connection on which the remote Gatt Server can be accessed This will have been returned in the EVBLEM
353. onnections in interactive mode and UART Bridge mode Valid values are O to 16383 seconds and O disables the timer hence continuous 115 This is used to specify the UART baudrate when Virtual Serial Mode Service is active and UART bridge mode is enabled Valid values are 1200 2400 4800 9600 14400 19200 28800 38400 57600 76800 115200 230400 250000 460800 921600 1000000 If an invalid value is entered then the default value of 9600 is used 116 In VSP UART Bridge mode this value specifies the latency in milliseconds for data arriving via the UART and transfer to VSP and then onward on air This mechanism ensures that the underlying bridging algorithm waits for up to this amount of time before deciding that no more data Is going to arrive to fill a BLE packet and so flushes the data onwards Given that the largest packet size takes 20 bytes if more than 20 bytes arrive then the latency timer is overridden and the data is sent immediately Interactive Command YES AT CFG Is a core command Note These values revert to factory default values if the flash file system is deleted using the AT amp F interactive command AT FOW COMMAND AT FOW opens a file to allow it to be written with raw data The group of commands AT FOW AT FWR AT FWRH and AT FCL are typically used for downloading files to the module s flash Tiling system For example web pages x 509 certificates or BLE data Americas 1 800 492 2
354. ooth smart BASIC User Manual Interactive Command YES Examples Assume the application someapp sb has a STOP statement somewhere which will invoke interactive mode AT RUN someapp ABORT ABORT is a core command AT REN COMMAND Renames an existing file AT REN oldname newname Returns OK if the Tile is successfully renamed Arguments oldname string_constant The name of the file to be renamed Newname _ string_constant The new name for the file The maximum length of filename is 24 characters oldname and newname must contain a valid filename which cannot contain the following seven characters lt gt This is an Interactive Mode command and MUST be terminated by a carriage return for it to be processed Interactive Command YES Examples AT REN oldscript txt newscript txt AT REN is a core command AT amp F COMMAND AT amp F provides facilities for erasing various portions of the module s non volatile memory AT amp F integermask Returns OK if file successfully erased Arguments Integermask Integer corresponding to a bit mask or the character Americas 1 800 492 2320 Option 2 45 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual The mask is an additive integer mask with the following meaning 1 Erases normal file system and system config
355. open success ENDIE Write nRegVal to register nRegAddr nSlaveAddr 0xef nRegAddr 0x34 nRegVal 0x4210 re I2cWriteReg16 nSlaveAddr nRegAddr nRegVal iP re O0 THEN PRINT nFailed to Write to slave register INTEGER H rc ELSE PRINT n nRegVal written successfully to register nRegAddr ENP I2cClose handle close the port Expected Output I2C open success 16912 written successfully to register 52 IZCWRITEREG16 is a core function I2cReadREG16 SUBROUTINE Note For firmware releases older than 1 2 54 4 there is an issue where some 12C slaves are not able to drive the ACK down to a low enough voltage level for the module to recognise it as an ACK This is a result of a bug in the BL600 s I2C driver which results in the SDA line not being released by the module This has been corrected in release 1 2 54 4 and the firmware is available as a uart download on request You should upgrade the firmware if you have an I2C slave not responding to the correct slave address This function is used to read a 16 bit value from two registers inside a slave which is identified by an 8 bit register address Note a handle parameter is NOT required as this function is used to interact with the main interface In the future a new version of this function will be made available if more than one I2C interface is made available most likely made available by bit bashing gpio Americas 1 800 492 23
356. ore function I2cReadREG32 FUNCTION Note For firmware releases older than 1 2 54 4 there is an issue where some 12C slaves are not able to drive the ACK down to a low enough voltage level for the module to recognise it as an ACK This is a result of a bug in the BL600 s I2C driver which results in the SDA line not being released by the module This has been corrected in release 1 2 54 4 and the firmware is available as a uart download on request You should upgrade the firmware if you have an I2C slave not responding to the correct slave address This function is used to read a 32 bit value from four registers inside a slave which is identified by a starting 8 bit register address Note a handle parameter is NOT required as this function is used to interact with the main interface In the future a new version of this function will be made available if more than one I2C interface is made available most likely made available by bit bashing gpio I2CREADREG32 nSlaveAddr nRegAddr nRegValue Exceptions Local Stack Frame Undertlow Local Stack Frame Overflow Arguments nSlaveAdar byVal nSlaveAdar AS INTEGER This is the address of the slave in range O to 127 nRegAdar byVal nRegAdar AS INTEGER This is the 8 bit start register address in the addressed slave in range O to 255 nkegValue byRef nRegValue AS INTEGER The 32 bit value trom four registers in the addressed slave will be returned in this variable Interactive
357. ort services this is the slave latency to be negotiated with the master An adjusted value is used if this value times the value in 106 Is greater than the supervision timeout in 107 109 When in interactive mode and connected for virtual serial port services this is the Tx power used for adverts and connections The main reason for setting a low value is to ensure that in production if smartBASIC applications are downloaded over the air then limited range allows many stations to be used to program devices 110 If Virtual Serial Port Service is enabled in interactive mode see 100 then this specifies the size of the transmit ring buffer in the managed layer sitting above the service characteristic fifo register It must be a value in the range 32 to 256 111 If Virtual Serial Port Service is enabled in interactive mode see 100 then this specifies the size of the receive ring buffer in the managed layer sitting above the service characteristic fifo register It must be a value in the range 32 to 256 112 If set to 1 then the service UUID for the virtual serial port is as per Nordic s implementation and any other value is a per the modified Laird s service See more details of the service definition here 113 This is the advert interval in milliseconds when advertising for connections in interactive mode and UART Bridge mode Valid values are 20 to 10240 milliseconds 114 This is the advert timeout in milliseconds when advertising for c
358. ot exist then the response to this command is nO1 tE023 r If the variable exists but the new value Is missing then the response to this command is nO1 tE26 r Where n linefeed t horizontal tab and r carriage return Arguments Var lt nJ gt The variable whose value is to be changed value A string_constant or integer_constant of appropriate form for the variable This is an Interactive Mode command and MUST be terminated by a carriage return for it to be processed Interactive Command YES Examples after an app exits which had DIM d a global variable called argc iS a core command Americas 1 800 492 2320 Option 2 43 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual SO SO Step Over is used to execute the next line of code in Interactive Mode after a break point has been encountered when an application had been launched using the AT DBG command Use this command after a breakpoint is encountered in an application to process the next statement SO can then be used repeatedly for single line execution SO is normally used as part of the debugging process after examining variables using the Interactive Command and possibly the command to change the value of a variable See also the BP nnnn AT DBG ABORT and RESUME commands for more details to aid debugging SO is a core function RES
359. ote This subroutine is not implemented in the BL600 UARTSETRTS is a core subroutine UartBREAK SUBROUTINE This subroutine is used to assert deassert a BREAK on the transmit output line A BREAK is a condition where the line is in non idle state that is Ov for more than 10 to 13 bit times depending on whether parity has been enabled and the number of stopbits On certain platforms the hardware may not allow this functionality contact Laird to determine if your device has the capability On platforms that do not have this capability this routine has no effect The BL600 module currently does not offer the capability to send a BREAK signal UARTBREAK state Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Uart has not been opened using UARTOPEN Arguments newState byVal newState AS INTEGER O to deassert and non zero to assert Interactive Command No Related Commands UARTOPEN UARTINFO UARTCLOSE UARTWRITE UARTREAD UARTREADMATCH UARTGETCTS UARTGETDCD UARTGETRI UARTGETDSR UARTSETRTS UARTSETDCD UARTFLUSH Note This subroutine is not implemented in the BL600 UARTBREAK is a core subroutine Americas 1 800 492 2320 Option 2 143 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual I2C Also known as Two Wire Interface TWI This section describes all the events and rout
360. oth Laird Technologies smart BASIC User Manual Expected Output BLEGATTCWRITE is an extension function BleGattcWriteCmd FUNCTION If the handle for an attribute is known then this function is used to write into an attribute at offset Owhen no acknowledgment response is expected The signal that the command has actually been transmitted and that the remote link layer has acknowledged is by the EVNOTIFYBUF event Note that the acknowledgement received for the BleGattcWrite command is from the higher level GATT layer not to be confused with the link layer ack in this case All packets are acknowledged at link layer level If a packet fails to get through then that condition will manifest as a connection drop due to the link supervision timeout Given that the transmission and link layer ack of this write operation is indicated in an event message a handler must be registered for the EVNOTIBUF event Depending on the connection interval the write to the attribute may take many 100s of milliseconds and while this is in progress it is sate to do other non Gatt related operations like for example servicing sensors and displays or any of the onboard peripherals EVNOTIFYBUF event This event message WILL be thrown if BleGattcWriteCmd returned a success The message contains no parameters BLEGATTCWRITECMD connHndl attrHndl attrData A typical pseudo code for writing to an attribute which will result in the EVNOTIFYBUF event
361. oy a circular buffer previously created using CircButCreate CIRCBUFDESTROY circHandle Arguments circHandle byRef circHandle AS INTEGER A handle referencing the circular buffer that needs to be deleted On exit an invalid handle value will be returned Interactive Command NO Example CircBufDestroy sb See in BL600CodeSnippets zip DIM ciwehandle circHhHancdle2 re re CircBufCreate 16 circHandle PRINT n sec Le el SO Wa PRINT VanThe circular buffer circhandlie Y was Mok Croaved Americas 1 800 492 2320 Option 2 120 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual ENDILE CirobufbDestroy circHandle PRINT nThe handle value is now circHandle so it has been destroyed Expected Output O The handle value is now 1 so it has been destroyed CIRCBUFDESTROY is an extension function CircBufWrite FUNCTION This function is used to write an integer at the head end of the circular buffer and if there is no space available to write then it will return with a failure resultcode and NOT write the value CIRCBUFWRITE circHandle nData Returns INTEGER An integer result code The most typical value is 0x0000 which indicates a successful operation Arguments circHandle byRef circHandle AS INTEGER This identities the circular buffer to write into nData byVal nData AS INTEGER This
362. pe Otherwise they will have validity throughout the application If a variable is declared within a FUNCTION or SUB and a variable of the same name already exists with global scope then this declaration will take over whilst inside the FUNCTION or SUB However this practice should be avoided DIM Var lt Var lt gt gt Arguments Var A complete variable definition with the syntax varname lt AS type gt Multiple variables can be defined in any order with each definition being separated by a comma Each variable vaf consists of one mandatory element varname and one optional element AS type separated by whitespaces and described as follows Vaname A valid variable name AS type here type is V7EGER or STRING If this element is missing then varname is used to define the type of the variable so that if the name ends with a character then it defaults to a STRING otherwise an N7EGER A variable can be declared as an array although only one dimension is allowed Arrays must always be defined with their size e g array 20 The 20 with round brackets is also allowed The size of an array cannot be changed after it is declared and the maximum size of an array is 256 Interactive Command NO Example DimExl sb See in BL600CodeSnippets zip DIM tempol AS INTEGER DIM temp2 Will be an INTEGER by default DIM temp3 AS STRING DIM temp4 Will be a STRING by default DIM temp5 S AS INTEGER
363. pets zip Diliveorntdmncenl Only 1 global variable because its value is used in more than 1 routine All other variables declared locally inside routine that they are used in More efficient because these local variables only exist in memory when they are being used inside their respective routines ean Open VSp and start advertising ff ee SUB Onscackue DIM rO a hic E cello addr eae wou ade a add rc BleVSpOpen 128 128 0 hnd1 rc BleScanRptInit scRpt rc BleAdvRptAddUuidl128 scRpts hnd1 rc BleAdvRptsCommit adRpt scRpts rC BleAdvertestare 0 addrs 20 300000 0 PRINT nDevice name is BleGetDeviceName S txS nSend me some text nTo exit the app just tell me n re BleVSpWrite txS ENDSUEB Americas 1 800 492 2320 Option 2 347 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual SUB CloseConnections DIM ce rc BleDisconnect conHndl rc BleAdvertStop BleVspClose ENDSWE r VSP Rx buffer event handler eeeessesss sss 2555555555 S55 55 5S ss SS SS FUNCTION HandlerVSpRx AS INTEGER DIM re rxs 5 eS exit rc BleVSpRead rx 20 PRINT nMessage from client rxs T user has typed exit ie Ser roo lt o ce 0 ole haa 1 I Oe 10 BND ENDEUNG 1 5 55555555555 5555555555555555 BLE event handler 5 5555555 55555555555 FUNC
364. pport lairdtech com www lairdtech com bluetooth smart BASIC User Manual Note Comport not Tcp Socket should be selected on the left 5 Select Poll for port to enable a feature that attempts to re open the comport in the event that the devkit is unplugged from the PC causing the virtual comport to disappear 6 In Line Terminator select the characters that are sent when you type ENTER 7 Once these settings are correct click OK to bring up the main terminal screen Getting Around UWTerminal Terminal BASIC Config About CTS DOSAG OCDE RI RT Figure 5 UWTerminal tabs and status lights The following tabs are located at the top of the UWTerminal Terminal Main terminal window Used to communicate with the serial module BASIC smartBASIC window Can be used to run BASIC applications locally without a device connected to the serial port Note You can use any text editor such as notepad for writing your smart BASIC applications However if you use an advanced text editor or word processor you need to take care that non standard formatting characters are not Incorporated into your smartBASIC application Config Configuration window Used to set up various parameters within UWTerminal About Information window that displays when you start UWTerminal It contains command line arguments and information that can facilitate the creation of a shortcut to the application an
365. ption 2 219 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual 18 The connection is encrypted 20 The connection is no longer encrypted BleDisconnect FUNCTION This function causes an existing connection identitied by a handle to be disconnected from the peer When the disconnection is complete a EVBLEMSG message with msgld 1 and context containing the handle will be thrown to the smart BASIC runtime engine BLEDISCONNECT nConnHandle Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments nConnHandle _ byVal nConnHandle AS INTEGER Specifies the handle of the connection that must be disconnected Interactive Command NO Example BleDisconnect sb See in BL6O00CodeSnippets zip DIM addrs addrs DIMERS FUNCTION HndlrBleMsg BYVAL mnMsgqid AS INTEGER BYVAL nCcx AS INTEGER SELECT nMsgid CASE 0 PRINT nNew Connection nCtx re BleAuthenticate nCtx PRINT BleDisconnect nCtx CASE 1 PRINT nDisconnected nee in EXLTEFUNG O ENDSELECT ENDFUNC 1 ONEVENT EVBLEMSG CALL HndlrBleMsg IF BleAdvertStart 0 addrS 100 30000 0 0 THEN PRINT nAdverts Started n BLSE PRINT n nAdvertisement not successful EN DIE WALTEVENT Expected Output Adverts Started New Connection 35800 Disconnected 3580 BLEDISCONNECT is an extension func
366. put then the nNewValue specifies the desired frequency in Hertz in the range 0 to 4000000 Setting a value of O makes the output a constant low value Setting a value greater than 4000000 will clip the output to a 4MHz signal GPIOWRITE nSigNum nNewValue Arguments nsigNum byVal nSigNum INTEGER The signal number as stated in the pinout table of the module nNewValue byVal nNewValue INTEGER The value to be written to the port If the pin is configured as digital then O will clear the pin Americas 1 800 492 2320 Option 2 181 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual and a non zero value will set it If the pin is configured as analogue then the value is written to the pin If the pin is configured as a PWM then this value sets the duty cycle If the pin is configured as a FREQUENCY then this value sets the frequency Interactive Command NO Example GpioWrite sb See in BL600CodeSnippets zip DIM rce dutycycle freghz mink red oeeo pam oaa OUEDUG ano aa alae 1 bo a PRIN Goresetbune i 270 in see sio pin 5 eo PWM output minkreg 300 PRINT Gp oConrr ge WM mamb req 1024 in set max pwm value resolution to 1 1024 ERINE GpLoocemume s 2 2 mr PRINT Goroserwune 7 2 5 nwa J See SiO Pan LO Prequency outpuT GpioWrite 18 0 set pin 1 to low GpioWrite 18 1 set orm ore
367. r if n D gt 255 or lt 0 2 Indicates no memory is available to store token 3 Indicates that the token is too large 4 Indicates the token is empty Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments string byRef string AS STRING A string variable that has been initialised as a table using TABLEINIT strtok byVal strtok AS STRING The string token to be added to the table niD byVal nID AS INTEGER The identifier number that is associated with the token and should be in the range O to 255 Note string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Interactive Command NO Associated Commands TABLEINIT TABLELOOKUP Example TableAdd sb See in BL600CodeSnippets zip DIM eoa PRINT DGaole tai coy an PEIN Vabletdd ts Helio i ma PRINT TableAdd tS everyone 2 n PRIN Tabl Addie eos BOO oe Vat Americas 1 800 492 2320 Option 2 106 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT Tablesadd t o So mAn PRINT t Tokens are stored in TLV format Tag LengthValue Expected Output TABLEADD is a core function TABLELOOKUP FUNCTION TABLELOOKUP searches for the specified token within an existing lookup
368. r not added END LE Expected Output Char created and User Description A description added Presentation Format Descriptor added BLECHARDESCPRSTNFRMT is an extension function Americas 1 800 492 2320 Option 2 251 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleCharDescAdd Note This function has a bug for firmware versions prior to 1 4 X Y FUNCTION This function is used to add any Characteristic Descriptor as long as its UUID is not in the range 0x2900 to Ox2904 inclusive as they are treated specially using dedicated API functions For example 0x2904 is the Presentation Format Descriptor and it is catered for by the API function BleCharDescPrstnFrmt Since this function allows existing future defined Descriptors to be added that may or may not have write access or require security requirements a metadata object must be supplied allowing that to be configured BLECHARDESCADD nUuid16 attr mdDesc Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation Arguments nUuid16 byVal nUuid76 AS INTEGER This is a value in the range 0x2905 to 0x2999 Note This is the actual UUID value NOT the handle The highest value at the time of writing is 0x2908 defined for the Report Reference Descriptor See http developer bluetooth org gatt descriptors Pages Descripto
369. r of milliseconds left for it to expire TIMERRUNNING number Function Returns O if the timer has expired otherwise the time in milliseconds left to expire Arguments number byVal number AS INTEGER The number of the timer O to N where N can be determined by submitting the command AT 2003 or at runtime returned via SYSINFO 2003 If the value is not valid then a runtime error will be thrown with code INVALID_ TIMER Interactive Command No Related Commands ONEVENT TIMERCANCEL Example TimerRunning sb See in BL600CodeSnippets zip SUBS heme TerOmnnn PRUNE Tamer mero Cer bacti tre EBNDSUEB FUNCTION HandlerTimero0O PRINT nTimer 0 has expired PRINT AnTimer l has T TimerRunnino l milliseconds to go BNDEUNC 1 cemain blocked in WAITEVENT FUNCTION HandlerTimerl Americas 1 800 492 2320 Option 2 115 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT nTimer 1 has expired ENDFUNC 0 lezir trom WALLEVENE ONE RROR NEXT HandlerOnErr ONE VEN EVIMRO CALI Handler Tamenc ONE VEN EVEIMRI CALL handler Tame a 1 TIMERSTART 0 500 1 start a 500 millisecond recurring timer PRINT nWaveing for Timer OY TIMERSTART I 200070 I orart a 1000 millisecond tamer PRINT AnWaiting for Timer I WAL TEVENT Expected Output TIMERRUNNING is a core function TimerCancel
370. racteristie metadata tor CCCD accribute ot Characteristic metadata for SCCD attribute OF Characteristic J Crearte the mercadarca torc che value atceiource in tche mela eee ri be and Heart Rate attribute has variable length Vio doles There is always a Value attribute in a characteristic mdVal BleAttrMetadata 17 0 20 0 rc There 15 a CCCD and SCCD im this Characteristic mdCccd BleAttrMetadata 1 2 2 0 rc mdSccd BleAttrMetadata 0 0 2 0 rc Create the Characteristic object Americas 1 800 492 2320 Option 2 246 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual IF BleCharNew 3 BleHandleUuidl16 Ox2A1C mdVal mdCccd mdSccd 0 THEN PRINT nsuccess BLSE PRINT nFailed ENDIF Expected Output BLEATTRMETADATA is an extension function BleCharNew FUNCTION When a Characteristic is to be added to a GATT table multiple attribute objects must be precreated After they are all created successfully they are committed to the GATT table in a single atomic transaction This function is the first function that SHALL be called to start the process of creating those multiple attribute objects It is used to select the Characteristic properties which are distinct and different from attribute properties the UUID to be allocated for it and then up to three metadata objects for the value attribu
371. rc BleDiscServiceNext cHndl IE ce ls 0 THEN PRINT nSean abort EXITFUNC O ENDAS ENDIKA endfunc 1 ONEVENT OnEvent EVDISCPRIMSYC Register base uuids with the underlying stack EVBLEMSG CALL HndlrBleMsg Call HandlerPrimSve otherwise tnae services Wile tche 128bir uuid s will be delivered wich a uuid handle PEF000000 UNKNOWN uuid 1122334455667783 99AABBCCDDEREEOO uuid Se mene sz So uuid uHndl BleHandleUuidl28 uuid uuc 1I22DRAD55667786 0 SAABBCCDDBEREOO uuid SteDehezxLzes uuid uHndl BleHandleUuidl28 uuid IF OnStartup 0 THEN PRINT nAdvertising and Gatt Client is open n BLS PREM nba tlre Ons tact ENID JIL IE WALITEVENT PEINT MANEIO a aS Americas 1 800 492 2320 Option 2 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth 274 Laird Technologies smart BASIC User Manual Expected Output BLEDISCSERVICEFIRST and BLEDISCSERVICENEXT are both extension functions BleDiscCharFirst BleDiscCharNext FUNCTIONS These pair of functions are used to scan the remote Gatt Server for characteristics in a service with the help of the EVDISCCHAR message event and when called a handler for the event message must be registered as the discovered characteristics information is passed back in that message A generic or uuid based scan can be initiated The former will scan for all characteristics and the latter
372. rc BleVSpWrite tx S ONEVENT EVVSPIxXEMPIY CALL HamdlerVsplxbmpry WALTEVENT USE IES ME aise iavepaen 8 Expected Output Device name is LAIRD BL600 ERLANG s BLEVSPWRITE is a extension subroutine Americas 1 800 492 2320 Option 2 346 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleVSpRead FUNCTION This function is used to read the content of the receive buffer and copy it to the string variable supplied BLEVSPREAD strMsg nMaxRead Returns INTEGER Oto N The total length of the string variable This means the caller does not need to call strlen function to determine how many bytes in the string must be processed Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments strMsg byRef strMsg AS STRING The content of the receive buffer is copied to this string nMaxRead byVal nMaxkead AS INTEGER The maximum number of bytes to read Interactive Command No Note strMsg cannot be a string constant e g the cat but must be a string variable and If you must use a const string first save it to a temp string variable and then pass it to the function Related Commands BLEVSPOPEN BLEVSPCLOSE BLEVSPINFO BLEVSPWRITE BLEVSPFLUSH Use the iOS BL600 Serial app and connect to your BL600 to test this sample app Example BleVSpRead sb See in BL600CodeSnip
373. rc DIM Waters 4 skeereo 00 WOlVO2 03 04 8536 387 a8 60 DIM uuric Ue 0x1853 rc BleSvcCommit 1 BleHandleUuidl6 uuid svcHandle rc BleCharNew 0x07 BleHandleUuidl6 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle rc BleCharValueRead chrHandle attr read 3 unsigned bytes from index 2 rc BleDecodeU24 attr S vl1 2 PRINT Andata in Hex Ox INTEGER H yvl PRINT ndata in Decimal eye a read 3 unsigned bytes from index 6 rc BleDecodeU24 attr vl1 6 PRINT ndata In Hex O INTEGER Hl vl PRINT Y ndarcta in Decimal eye sah Expected Output BLEDECODEU 24 is an extension function Americas 1 800 492 2320 Option 2 327 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleDecode32 FUNCTION This function reads four bytes in a string at a specified offset into a 32bit integer variable If the offset points beyond the end of the string this function fails BLEDECODE32 attr nData nindex Returns INTEGER the number of bytes extracted from the attribute string Can be less than the size expected if the nindex parameter is positioned towards the end of the string Arguments attr byRef atir AS STRING This references the attribute string from which the function reads nData byRef nData AS INTEGER This references an integer to be updated with the 3 byte data from
374. rding the previous program Any line that starts with an apostrophe is a comment and is ignored by the compiler from the token onwards In other words the opening line is ignored You can also add a comment to a program line by adding an apostrophe proceeded by a space to start the comment If you have C language experience you can also use the token to indicate that the rest of the line Is a comment The second item of interest is the line feed character n which we ve added after Hello Wor d in the print statement This tells the print command to start a new line If left out the ten Hello World s would have been concatenated together on the screen You can try removing it to see what would happen Compile and download the file He oWorld sb to the module using XCompile Load in UwTerminal and then run the application in the usual way AL RUN helloworld The following output displays If you now change the print statement in the application to jon dhione lee Wowace Vee Vin The n forces a new line each time the following output displays 0 0O sl Oy OT Ss Go RO Americas 1 800 492 2320 Option 2 24 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual If you run AT DIR you will see that both of these programs are now loaded in memory They remain there until you remove
375. re a aa SUB WaitWrite DO Gplewritre 13 0 wrs 05 00 rd S _ rc SpiReadWrite wrS rds GpioWrite 13 1 UNTIE StrGet Chm rd yl ENDSUB SUB EnableWrite GpioWrite 13 0 wrs 06 rd rce SpiWrite wrs GpioWrite 13 1 ENDSUB ei ee ee ee ee re Gorocerrune 13 2 i ensure CS is not enabled GpioWrite 13 1 EnableWrite Americas 1 800 492 2320 Option 2 158 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Laird Technologies smart BASIC User Manual weo 02 01 80 DE AD BE EF BA AD CO DE PRIE A nN e g ros lecarton Ux o05r Striexi zen wre GpioWrite 13 0 rce SpiWrite wrSs GoroWrate 13 1 WaitWrite Fp eal AE E AE TE SEA Se OE A BRIE oe Yee RON APRS EAR PUM IIE IE he RE Pa AE ART een J Read trom Welt ben locacion E E E E E eee E re Pe E OE Te PPE eT aR eo eee Wie OS VO e 00 O10 00 OO 20 0 OO OO Gio rdgs W GpioWrite 13 0 rc SpiReadWrite wrS rd Golowrite 13 1 PRINT mbata ar location Ox0le0 tls Strhexi zesi rds wies 032 01 30 GpioWrite 13 0 rce SpiWrite wrSs rd rc SpiRead rd 4 PRIND AnData at location Ox0l80 ms Criei zeo rds rds rc SpiRead rdS 8 GpioWrite 13 1 PRINT nData at location Ox0 LCA is Y Sirhexrzeo ras SpiClose h Expected Output Writing to location Oxls0 O20180DEADBEEFBAADCODE Data at location Ux0160 is QUO0CUUDEADBPERFR
376. re is available as a uart download on request You should upgrade the firmware if you have an I2C slave not responding to the correct slave address This function is used to read an 8 bit value from a register inside a slave which is identified by an 8 bit register address Note a handle parameter is NOT required as this function is used to interact with the main interface In the future a new version of this function will be made available if more than one 2C interface is made available most likely made available by bit bashing gpio I2CREADREG8 nSlaveAddr nRegAddr nRegValue Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments nSlaveAdar byVal nSlaveAdar AS INTEGER This is the address of the slave in range O to 127 nRegAdar byVal nRegAdadr AS INTEGER This is the 8 bit register address in the addressed slave in range O to 255 nkegValue byRef nRegValue AS INTEGER The 8 bit value from the register in the addressed slave will be returned in this variable Interactive Command No Related Commands I2COPEN I2CCLOSE I2CWRITEREAD I2CWRITEREG8 I2CWRITEREG16 IZCWRITEREG32 IZCREADREGS8 I2ZCREADREG16 I2CREADREGS2 Example I2cReadReg8 sb See in BL600CodeSnippets zip Please ensure that nSlaveAddr is the slave address of your I2C peripheral DIM rc handle nSlaveAddr nRegAddr nRegVal J Open 12C Peripheral rc I2cOpen 100000 0 handle IF ccl 0 THEN PRINT nFailed
377. re provided to handle those too Americas 1 800 492 2320 Option 2 229 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Note If you intend to create a custom Service or Characteristic and adopt the recommendation stated above of a single long 16 byte base UUID so that the service can be identified using a 2 byte UUID then allocate a 16 bit value which Is not going to coincide with any adopted values to minimise contusion Selecting a similar value is possible and legal given that the base UUID is different The recommendation is just for ease of maintenance Finally having prepared a background to Services and Characteristics the rest of this introduction will focus on the specifics of how to create and manage a GATT table from a perspective of the smartBASIC API functions in the module Recall that a Service has been described as a carrier bag that groups related characteristics together and a Characteristic is just a data container pot Therefore a remote GATT Client looking at the Server which is presented in your GATT table sees multiple carrier bags each containing one or more pots of data The GATT Client remote end of the wireless connection needs to see those carrier bags to determine the groupings and once it has identified the pots it will only need to keep a list of references to the pots It is interested
378. re to get handles to all the characteristics that are part of that INCLUDED service This mechanism is provided to allow for a single set of Characteristics to be shared by multiple primary services This is most relevant if a Characteristic is defined so that it can have only one instance in a GATT table but needs to be offered in multiple PRIMARY services Hence a typical implementation where a characteristic is part of many PRIMARY services installs that Characteristic in a SECONDARY service see BleSvcCommit and then uses the function defined in this section to add it to all the PRIMARY services that want to have that characteristic as part of their group It is possible to include a service which is also a PRIMARY or SECONDARY service which in turn can include further PRIMARY or SECONDARY services The only restriction to nested includes is that there cannot be recursion Americas 1 800 492 2320 Option 2 243 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Further note that if a service has INCLUDED services then they shall be installed in the GATT table immediately after a Service is created using BlesvcCommit and before BleCharCommit The BT 4 0 specification mandates that any included service attribute be present before any characteristic attributes within a particular service group declaration BleSvcAddlnclu
379. required Ox0112 ATT Error Reserved for Future Use range 1 begin OxO17F ATT Error Reserved for Future Use range 1 end Ox0180 ATT Error Application range begin OxO19F ATT Error Application range end 0x01A0 ATT Error Reserved for Future Use range 2 begin OxO1DF ATT Error Reserved for Future Use range 2 end 0x01E0 ATT Error Reserved for Future Use range 3 begin OxO1FC ATT Error Reserved for Future Use range 3 end OxO1FD ATT Common Profile and Service Error Client Characteristic Configuration Descriptor CCCD improperly configured OxO1LFE ATT Common Profile and Service Error Procedure Already in Progress OxO1LFF ATT Common Profile and Service Error Out Of Range BLEGATTCWRITE connHndl attrHndl attrData A typical pseudo code for writing to an attribute which will result in the EVATTRWRITE event message and typically is as follows Register a handler for the EVATTRWRITE event message On EVATTWRITE event message Ef Gatt status 0 Then Attribute was written successfully Else Attribute could not be written Call BleGattcWrite If BleGattcWrite ok then Wait for EVATTRWRITE Returns INTEGER a result code The typical value is 0x0000 indicating a successful read Arguments connHnal byVal connHnal AS INTEGER This is the connection handle as returned in the on connect event for the connection on which the remote Gatt Server can be accessed This will have been returned in the EVBLEMSG event message with
380. riables the 24 bit signed mantissa and the 8 bit signed exponent If the offset points beyond the end of the string this function fails BLEDECODEFLOAT attr nMatissa nExponent nindex Returns INTEGER the number of bytes extracted from the attribute string Can be less than the size expected if the nindex parameter is positioned towards the end of the string Arguments attr byRef atir AS STRING This references the attribute string from which the function reads nMantissa byRef nMantissa AS INTEGER This is updated with the 24 bit mantissa trom the 4 byte object If nExponent is 0 you MUST check for the following special values OxOO7FFFFF NaN Not a Number 0x00800000 NRes Not at this resolution OxOO7FFFFE INFINITY Ox00800002 INFINITY 0x00800001 Reserved for future use nExponent byRef nExponent AS INTEGER This is updated with the 8 bit mantissa If it is zero check nMantissa for special cases as Stated above nindex byVal nindex AS INTEGER This is the zero based index into the string attr from which data is read If the string attr is not long enough to accommodate the index plus the number of bytes to read this function fails Interactive Command NO Example BleDecodeFloat sb See in BL600CodeSnippets zip DIM chrhandle wil svcHandle re mantissa exp Americas 1 800 492 2320 Option 2 329 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lair
381. rmission and whether it needs security and authentication to be accessed If the Characteristic is capable of notification and indication the client implicitly must be able to enable or disable that This is done through a Characteristic Descriptor which is also another attribute The attribute will also need to have a metadata supplied when the Characteristic is created and registered in the GATT table This attribute if it exists is called a Client Characteristic Configuration Descriptor or CCCD for short A CCCD always has 2 bytes of data and currently only 2 bits are used as on off settings for notification and indication A Characteristic can also optionally be capable of broadcasting its value data in advertisements For the GATT client to be able to control this there is yet another type of Characteristic Descriptor which also needs a metadata object to be supplied when the Characteristic is created and registered in the GATT table This attribute if it exists is called a Server Characteristic Configuration Descriptor or SCCD for short A SCCD always has 2 bytes of data and currently only 1 bit is used as on off settings for broadcasts Finally if the Characteristic has other Descriptors to quality its behaviour a separate API function is also Supplied to add that to the GATT table and when setting up a metadata object will also need to be supplied In a nutshell think of a metadata object as a note to define how an attribute will behave a
382. rptData nADtag ADval Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments nindex byVAL nindex AS INTEGER This is a zero based index of the AD element that will be copied into the output data parameter ADval rotData byREF sotData AS STRING This parameter is a string that contains concatenated AD elements which will have been either constructed for an outgoing advert or will have been received in a scan depends on module variant nADTag byREF nADTag AS INTEGER When the nth index is found the single byte tag value for that AD element is returned in this paramater ADval byREF ADval AS STRING When the nth index is found the data excluding single byte the tag value for that AD element is returned in this parameter Interactive Command NO Example BleAdvGetADbyIndex sb See in BL600CodeSnippets zip DIM ro adie ad2s FUNA nAra Ava ls AD with length 6 bytes tag OxDD adl o Oo WD II 22 33 44 55 AD with length 7 bytes tag OxDA adZ2s 07 EE Aa BB CC DD EE EE CUMS sols sic Zs PRN a a aes elec eo mele jee a rc BleGetADbyIndex 0 fullADS nADTag ADvalS if ce 0 THEN PRINT oFire AD element with tag 0x INTECER H nADTag 7 is StrHexizeS ADval S ELSE PRENI YnErro reading Ali ss NE Gh Re ie EN DLE rc BleGetADbyIndex 1 fullADS nADTag ADval IP we 0 THEN PRINT nSecond AD element with tag Ox INT
383. rsHomePage aspx for a list of Descriptors defined and adopted by the Bluetooth SIG attr byRef atir AS STRING This is the data that will be saved in the Descriptor s attribute madDesc byVal 7 AS INTEGER This is mandatory metadata that is used to define the properties of the Descriptor attribute that will be created in the Characteristic and will have been pre created using the help of the function BleAttrMetadata If the write rights are set to 1 or greater then the attribute is marked as writable and so the client will be able to modify the attribute value Interactive Command NO Example BleCharDescAdd sb See in BL600CodeSnippets zip DIM rc Metasuccess USrDeScs UsSrDesco A description DIM charUuid charUuid BleHandleUuidl 1 DIM charMet charMet BleAttrMetaData 1 1 20 0 metaSuccess DIM mdUsrDsc mdUsrDsc charMer DIM mdseed gt mdsced echarMer initialise char write read enabled accept signed writes indicatable rc BleCharNew 0x4B charUuid charMet 0 mdSccd rc BleCharDescUserDesc usrDesc mdUsrDsc bpe BleCharDescPrstmrrmc Ox0ER 2 0xZ71A 0x01 0x0000 a fi onclieie ea ee ie Te ea Add the other Descriptor 0x29XX first one Americas 1 800 492 2320 Option 2 252 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual of cesar DIM mdChrDsc mdChrDse BleAttrMetada
384. rt lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output SysInfos 4 O1 FA 84 D7H D9 03 Sysintos 14 OL FA 84 D7H D9 03 Sysiniae 0 SYSINFO is a core language function Event amp Messaging Routines SENDMSGAPP FUNCTION This function is used to send an EVMSGAPP message to your application so that it can be processed by a handler from the WAITEVENT framework It is useful for serialised processing For messages to be processed the following statement must be processed so that a handler is associated with the message ONEVENT EVMSGAPP CALL HandlerMsgApp Where a handler such as the following has been defined prior to the ONEVENT statement as follows FUNCTION HandlerMsgApp BYVAL nMsgId AS INTEGER BYVAL nMsgCtx AS INTEGER AS INTEGER do something with nMsgId and nMsgCtx ENDFUNC 1 SENDMSGAPP msgld msgCtx Returns INTEGER 0000 If successfully sent Exceptions Local Stack Frame Undertlow Local Stack Frame Overflow Arguments msgld byValmsgld AS INTEGER Will be presented to the EVMSGAPP handler in the msgld field msgC tx byValmsgCtx AS INTEGER Will be presented to the EVMSGAPP handler in the msgCtx field Interactive Command NO Example SendMsgApp sb See in BL600CodeSnippets zip DIMER FUNCTION HandlerMsgApp BYVAL nMsgId AS INTEGER BYVAL nMsgCtx AS INTEGER AS INTEGER PRINT Anid nMogid Y Cex nMsgCOtX ENDEUNC i Americas 1 800 492 2320 Option 2
385. rt where every other programming manual starts with a simple program to display Hello World on the screen We use Notepad to write the smartBASIC application To write this sartBASIC application follow these steps 1 Open Notepad 2 Enter the following text print nHello V rl d n 3 Save the Tile with single line test7 s6 Note the following smartBASIC files can have any extension UWTerminal which is used to download an application to the module strips all letters including and after the first when the file is downloaded to the module For example a file called this is my tirst tile sb will be downloaded as this and so will this is my second file sb but that is my other file sb will get downloaded as that This has special significance when you want to manage the special smartBASIC file called autorun which is run automatically on power up It means that you can have files called autorun heart rate sb and autorun blood pressure sb in a single folder and yet ensure that when downloaded they get saved as autorun We recommend always using the extension sb to make it easier to distinguish between smartBASIC files and other files You can also associate this extension with your favorite editor and enable appropriate syntax highlighting You may also encounter files with extension sblib which are library source files provided by Laird to make developing c
386. rth laying out the rules of the application source syntax Americas 1 800 492 2320 Option 2 22 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual smartBASIC Statement Format The format of any line of smartBASIC is defined in the following manner COMMENT COMMAND STATEMENT DIRECTIVE lt COMMENT gt TERMINATOR Anything in is mandatory and anything in lt gt is optional Within each set of or lt gt brackets the character is used to denote a choice of values The various elements of each line are COMMENT A COMMENT token is a or followed by any sequence of characters Any text after the token is ignored by the parser A comment can occupy its own line or be placed at the end of a STATEMENT or COMMAND COMMAND An Interactive command one of the commands that can be executed from Interactive mode STATEMENT A valid BASIC statement s separated by the character if there are more than one statement Note When compiling an application a line can be made of several statements which are separated by the character DIRECTIVE A line starting with the character It is used as an instruction to the parser to modify Its behavior For example DEFINE and INCLUDE TERMINATOR The r character which corresponds to the Enter key on the keyboard The smartBASIC implementatio
387. rvice Attribute Handle value hBatSvc ELSE PRINT nService Commit Failed ENDIF Americas 1 800 492 2320 Option 2 242 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output BLESERVICENEW is an extension function BleServiceCommit This function in the BL600 is a dummy function and does not do anything However for portability to other Laird 4 0 compatible modules always invoke this function after the last descriptor of the last characteristic of a service has been committed to the gatt server BLESERVICECOMMIT hService Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments hService byVal hService AS INTEGER This handle will have been returned from BleServiceNew BleSvcAddIncludeSvc FUNCTION Note This function is currently not available for use on the BL600 This function is used to add a reference to a service within another service This will usually but not necessarily be a SECONDARY service which is virtually identical to a PRIMARY service from the GATT Server perspective and the only difference is that when a GATT client queries a device for all services it does not get any mention of SECONDARY services When a GATT client encounters an INCLUDED SERVICE object when querying a particular service it shall perform a sub procedu
388. ry in the database this variable contains a MAC address exactly 7 bytes long The first byte identifies public or private random address The next 6 bytes are the address nExtrainto byRef nExtralnfo AS INTEGER On exit if nlndex points to a valid entry in the database this variable contains a composite integer value where the lower 16 bits are the eDIV Bit 16 Is set if the IRK Identity Resolving Key exists for the trusted device and bit 17 is set if the CSRK Connection Signing Resolving Key exists for the trusted device Interactive Command NO Example BleBondMngrGetInfo sb See in BL600CodeSnippets zip define BLE INV INDEX 24619 DIM re addrs exinto re BleBondMngrGetInfo 0 addrS exInfo Extract info of device at index 1 IF rc 0 THEN PRINT nMAC address addrs PRINT ninto exilnio ELSE LE TO Phe Ny ENE THEN PRINT ninvaltd index ENDIF Expected Output when valid entry present in database MAC address 00 BC B1 F3x3 AB Into 974537 Expected Output with invalid index Invalid index BLEBONDMNGRGETINFO is an extension function Americas 1 800 492 2320 Option 2 337 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Virtual Serial Port Service Managed test when dongle and application availbable This section describes all the events and routines used to interact with a mana
389. s cead max 20 bytes from index 3 in the string will be truncated rc BleDecodeSTRING attrs 3 decStrs 20 PRINT Ando n decot read max 4 bytes from index 14 in the string nothing at index 14 rc BleDecodeSTRING attrs 14 decStrS 4 PRINT nds decStrs Expected Output dS CDEF dS CDEFGHIJ ds BLEDECODESTRING is an extension function Americas 1 800 492 2320 Option 2 333 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleDecodeBITS FUNCTION This function reads bits from an attribute string at a specified offset treated as a bit array into a destination integer object treated as a bit array of fixed size of 32 This implies a maximum of 32 bits can be read This function will not fail as the output bit array can take truncated bit blocks BLEDECODEBITS attr nSrcidx dstBitArr nDstldx nMaxBits Returns INTEGER the number of bits extracted from the attribute string Can be less than the size expected if the nSrcldx parameter is positioned towards the end of the source string or if nDstldx will not allow more to be copied Arguments attr byRef atir AS STRING This references the attribute string from which to read treated as a bit array Hence a string of 10 bytes will be an array of 80 bits nSrclax byVal nSrcidx AS INTEGER This is the zero based bit index into the string attr from whic
390. s Interactive Command NO Americas 1 800 492 2320 Option 2 269 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Example BleGattcOpen sb See in BL600CodeSnippets zip DIVE ropen the gatt client with default notify indicate ring buffer size rc BleGattcOpen 0 0 IF re 0 THEN PRINT nGatt Client 1s now open ENDIF open the client with default notify indicate ring buffer size again re BleGattcOpen 128 1 IF rc 0 THEN PRINT nGatt Client is still open because already open ENDIF Expected Output Gatt Client is now open Gatt Client is still open because already open BLEGATTCOPEN is an extension function BleGattcClose SUBROUTINE This function is used to close the GATT client manager and is safe to call if it is already closed It is recommended that this function NOT be called when in a connection BLEGATTCCLOSE Arguments None Interactive Command NO Example BleGattcClose sb See in BL6O00CodeSnippets zip DOE Ma ate fopen the gatt client with default notify indicate ring buffer size re BleGattcOpen 0 0 IF rc 0 THEN PRINT nGatt Client is now open ENDIF BleGattcClose PRINT nGatt Client as now closed BleGattcClose PRINT nGatt Client is closed was safe to call when already closed Expected Output Gatt Client is now open Gatt Cli
391. s Arguments nsigNum nFunction nSubFunc INTEGER a result code The most typical value is OxO000 indicating a successful operation byVal nSigNum AS INTEGER The signal number as stated in the pinout table of the module byVal nFunction AS INTEGER Specifies the configuration of the GPIO pin as follows 1 DIGITAL_IN 2 DIGITAL_OUT 3 ANALOG_IN 4 ANALOG_REF not currently available on the BL600 module 5 ANALOG_OUT not available in the BL600 module byVal nSubFunc INTEGER Configures the pin as follows If nFunction DIGITAL_IN Bits 0 3 1 pull down resistor weak 2 pull up resistor weak 3 pull down resistor strong 4 pull up resistor strong Else No pull resistors Bits 4 5 4 When in deep sleep mode awake when this pin is LOW 5 When in deep sleep mode awake when this pin is HIGH Else No effect in deep sleep mode Bits 8 31 Must be Os if nFuncType DIGITAL_OUT Bits 0 3 0 Initial output to LOW 1 Initial output to HIGH 2 Output will be PWM Pulse Width Modulated Output See function GpioContigPW for more configuration The duty cycle is set using function GpioWrite 3 Output will be FREQUENCY The frequency is set using function GpioWrite where O will switch off the output any value in range 1 4000000 will generate an output signal with 50 duty cycle with that frequency Bits 4 6 output drive capacity O O Standar
392. s laisvwe i e commit reports to GATT table adRpt S is empty rc BleAdvRptsCommit adRpt scRpts rc BleAdvertStart 0 addrS 20 300000 0 hMyChar rc GpioBindEvent 1 16 1 Channel I bind to low transition om GClIO pin i gt DiS UNG tere SUB CloseConnections rc BleDisconnect conHnd1 rc BleAdvertStop rc GpioUnbindEvent 1 EBNDSUB BPUNCTION HndlebileMisg BYVAL mMsoqid BYVAL nCrx conHndl nCtx IF nMsgID 1 THEN PRINT n n Disconnected from client EXITFUNG 10 ELSEIF nMsgID 0 THEN PRINT n Connected to client ENDIE ENDEUNC i aenasss2sss28555255555 5555555555555 55 5555555555555 55555555 5555555 5 5 Indication acknowledgement from client handler aonesss2ss555 5555555555555 5 5555555555555 5555555555555 55 555 5555555 555 FUNCTION BHnidilvrCharkvct ByY VAG charkbandle AS INTEGER AS INTEGER IF charHandle hMyChar THEN PRINT nGort Conklrnabilon On recent Indication BLSE PRINT I nGot confirmation Of some other indication T charhandle ENDI IE ENDE UNC nandler to service button 0 pressed Americas 1 800 492 2320 Option 2 197 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Laird Technologies smart BASIC User Manual PUNCTION Hoe lrBen0Pe AS INTEGER CloseConnections ENDEUNG i FUNCTION HndleChareced BYvAl charhandile BYVAL nyval AS INTEGER DIM values IF charHandle hMyChar THEN I
393. s has been corrected in release 1 2 54 4 and the firmware is available as a uart download on request You should upgrade the firmware if you have an I2C slave not responding to the correct slave address This function is used to open the main I2C peripheral using the parameters specified On the BL600 module the SCL signal Pin is on SIO9 and SDA signal pin is SIO8 I2COPEN nClockHz nCfgFlags nHande Returns INTEGER Indicates success of command O Opened successfully 0x5200 Driver not found 0x5207 Driver already open 0x5225 Invalid Clock Frequency Requested 0x521D Driver resource unavailable 0x5226 No free PPI channel 0x5202 Invalid Signal Pins 0x5219 I2C not allowed on pins specified Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Americas 1 800 492 2320 Option 2 144 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Arguments nClockHz byVal nClockHz AS INTEGER This is the clock frequency to use and can be one of 100000 250000 or 400000 nCfgFlags byVal nCfgFlags AS INTEGER This is a bit mask used to configure the I2C interface All unused bits are allocated as for future use and MUST be set to 0 Used bits are as follows Bit Description O If set then a 500 microsecond low pulse will NOT be sent on open This low pulse is used to create a start and stop condition on the bus so t
394. s invalid an Error is thrown Interactive Command No Related Commands ONEVENT TIMERCANCEL Example EVTMRn sb See in BL600CodeSnippets zip SUB HandlerOnErr BRINT YTimer mrerors 3 Gerclasrcorcror ENDSUB FUNCTION HandlerTimerl PRINT nTimer 1 has expired BNDEUNC 1 cemain blocked in WALTEVENYT FUNCTION HandlerTimer2 PRINT nTimer 2 has expired ENDFUNC 0 eie trom WA vane ONERROR NEXT HandleroOnEkrr ONEVENT EVIMRiI CALL HandlerTimer ONEVENT EVIMR Z CALI HandlerTimer2 met Sivek bi Or 10K start a 500 millisecond recurring timer PRINT V nstarteci Timer 0 wich invalid inerval Timers eet deo Wr j seart a 500 millisecond recurring timer PRINT nWartrng for Timer 1 Limeteorar nic LOO 0 oea a OOO mae eond tt ime Americas 1 800 492 2320 Option 2 114 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT Y nWarring tote liners 2 WALTEVENT PRINT nGot here because TIMER 2 expired and Handler returned 0 Expected Output TIMERSTART is a core subroutine TimerRunning FUNCTION This function determines if a timer identified by an index number is still running The command AT 2003 will return the valid range of Timer index numbers It returns O to signify that the timer is not running and a non zero value to signify It is still running and the value is the numbe
395. s of which there are a finite number This specifies the number of transmissons to leave unused when sending a lot of data This allows other services to send notifies without having to wait for them The total number of transmission buffers can be determined by calling SYSINFO 2014 or in interactive mode submitting the command ATi 2014 105 When in interactive mode and connected for virtual serial port services this is the minimum connection interval in milliseconds to be negotiated with the master Valid value is O to 4000 ms and if a value of less than 8 is specified then the minimum value of 7 5 is selected 106 When in interactive mode and connected for virtual serial port services this is the maximum connection interval in milliseconds to be negotiated with the master Valid value is O to 4000 ms and if a value of less the minimum specified in 105 then it is forced to the value in 105 2 ms 107 When in interactive mode and connected for virtual serial port services this is the connection Supervision timeout in milliseconds to be negotiated with the master The valid range is O to 32000 and if the value is less than the value in 106 then a value double that specified in 106 is used Americas 1 800 492 2320 Option 2 38 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual 108 When in interactive mode and connected for virtual serial p
396. s support lairdtech com www lairdtech com bluetooth smart BASIC User Manual in tn in nanan an in fo u oe DO G G nm 7 nm on 1 i om oF J T m i m LE al E r 4 ai 5 La w D L amp J w P in ifs i lo w 6 66 Co A A i i A A a f P i D wo I f PERE ER RRR EERE ERE EERE EERE EERE EERE EERE EEK REE ER REE EEE REE RR EE ee EE Ee Handler definitions I f PERE EERE ERE EE EEE ERE EE EEE EE EEE EEE REE EERE EE EEE EEE REE RE ERE RE ERE ERE EEE EEE EE REE REE rd Uart Inactivity timer handler rd function handlerUVartTimer as integer dim re Close the uart and set up TX RX RIS lines as gpio and for a hi lo transition fon the RE line to be detected if UVartCloseExz 1 0 then re GpioSet Func 21 2 1 TX set high on default rc GpioSet Func 23 2 0 RTS set low by default ro GpioSet Func 27 1 2 FRX Bull high input amp irq on hiZlo transition re GpiocAssignEvent UART GPIO ASSIGN CHANNEL 22 1 if rc 0 then print nGpiocAssignEvent Failed endif endif endfunc 1 ff Delay before uart is opened ff function handlerOpenDelay as integer dim re ree up the level transition detection re GpliocUnAssignEvent UART GPIO ASSIGN CHANNEL Open the uart re UartOpen 9600 0 0 CN81H send an ack character print endfunc 1 Figure 11 Example of a smartBASIC code fragment in TextPad Download Hello Wor
397. schUuid integer h cuid Print Se ropSs Crop print valindl hval Print levevurd a SUI PRINT nCharacteristic Scan complete re BleDiscCharNext conHnd1 PRINT naCharactceristics scan abort IF Aaval Q THEN EXLTFUNG Q BLSE IF re 0 THEN EXLTFUNG Q BNDIE END IE endfunc 1 Main equivalent ONEVENT EVBLEMSG Onkivent 1d VIDINS Gis IMs We OnEvenrt EVDISCCHAR Americas 1 800 492 2320 Option 2 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth CALL HndlrBleMsg call HandlerPrimSvce Call mHanclerCharDise 2 9 as integer Laird Technologies smart BASIC User Manual Expected Output BLEDISCCHARFIRST and BLEDISCCHARNEXT are both extension functions Americas 1 800 492 2320 Option 2 280 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleDiscDescFirst BleDiscDescNext FUNCTIONS These pair of functions are used to scan the remote Gatt Server for descriptors in a characteristic with the help of the EVDISCDESC message event and when called a handler for the event message must be registered as the discovered descriptor information is passed back in that A generic or uuid based scan can be initiated The former will scan for all descriptors and the latter will scan for a descriptor with a particular uu
398. sconnected BXITFUNG 0 ELSEIF nMsgID 0 THEN PRINT n Connected so scan remote Gatt Table for ALL services re BleDiscServiceFirst conHndl 0 0 IF rc 0 THEN HandlerPrimSvc will exit with 0 when operation is complete WALTEVENT PRINT Y nscan for service wath uuid OxDEAD uHndl BleHandleUuidl6 OxDEAD rc BleDiscServiceFirst conHndl 0 uHndl IF rc 0 THEN HandlerPrimSvc will exit with 0 when operation is complete WALTEVENT Mie 1172334455667 1609 AABBCCDDERE LOO PRINT nocan for service with cuc tom uuid uu uu StrDehexizeS uu uHndl BleHandlevuidl 28 uus rc BleDiscServiceFirst conHndl 0 uHndl IF rc 0 THEN HandlerPrimSvc will exit with 0 when operation is complete WALTEVENT BNDIE BND BNDIE CloseConnections ENDIF ENDFUNC 1 aoaasss2as525 5552555555555 5 5555555555555 5 5555555555555 555 55555 55555555555 EVDISCPRIMSVC event handler aenasss25ss5 5555555555552 5 5555555555555 55 555555555555 55 5555555 5555555555 FUNCTION HandlerPrimSvc cHndl svcUuid sHndl eHndl AS INTEGER PRINT A nEVDISCPRIMSVC PRINTE Y CHITCIL W p CRMC PRINTO Sige Uur d A nte dere lay oy Uu d PRS E S lL PRINT TEST IF sHndl 0 THEN Americas 1 800 492 2320 Option 2 2 3 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual ELSE PRINT nScan complete EXLTFUNGE Q
399. se routines provide the basic programming functionality They are augmented with target specific routines for different platforms which are described in the next chapter Result Codes Some of these built in routines are subroutines and some are functions Functions always return a value and tor some of these functions the value returned is a result code indicating success or failure in executing that function A failure may not necessarily result in a run time error see GetLastError and ResetLastError but may lead to an unexpected output Being able to see what causes a failure greatly helps with the debugging process If you declare an integer variable e g rc and set it s value to your function call after the function Is executed you can print rc and see the result code For it to be useful it has to be in Hexadecimal form so prefix your result code variable with INTEGER H when printing it You can also save a bit of memory by printing the return value from the function directly without the use of a variable Example ResultCodes sb See in BL600CodeSnippets zip DIM cB mliremns IC S gt rc CircBufItems cB nI Items PRINT INTEGER oP re PRINT Va g Vy New lane Id Printing return value directly PRINT INTEGER A CircBurlcems cB nitems To remove the leading zeros SPE TNT co INTEGER A CireButltens cs m lees Seroturelere So 4 PRINT sss Now highlight the last 4 characters of the re
400. seconds AESENCRYPT inData outData Returns INTEGER Will be 0x0000 if the data was encrypted successfully Otherwise an appropriate resultcode will be returned which will convey the reason it failed ALWAYS check this Arguments inData BYREF nData AS STRING This string is up to 16 bytes long and should contain the data to encrypt Americas 1 800 492 2320 Option 2 163 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual outData BYREF outData AS STRING On exit if the function was successful then this string will contain the encrypted cypher data If unsuccessful then string will be O bytes long Interactive Command NO Example AesEncrypt sb See in BL600CodeSnippets zip DIM key ini Cie nas DIM inDatas CutDaras DINES Create context for EBC mode 128 bit keyo 00 01 02 03 04 05 06 07 Ue 09 02 08 0G 0b OEN ORS initVector EBC does not require initialisation vector rc AesSetKeylv 0x100 16 key initVector S IF rc 0 THEN PRINT nEBC context created successfully ELSE PRINT nFailed to create EBC context ENDI E imWataso 303132333435363738393A3B3C3D3E3F inDatas StrDehexizes inDatas rce AesEncrypt inDatas outData IF rc 0 THEN PR Winnett ORT Blok PRINT nFailed to encrypt ENDINE PRINT Sh ainara e strea ze anaa ERUNT e no Dara e a re a ze o Daa Expected Output A
401. sed as a command on string which is defined as being passed as byRef This means that when the rotation is complete string is returned with its new value num defines the number of places that the string is shifted and is passed as byVal the original variable num is unchanged by this subroutine Note Throughout the definition of the following commands arguments are explicitly stated as being byVal or byRef Functions as opposed to subroutines always return a value Arguments may be either byVal or byRef In general and by default string arguments are passed byRef The reason for this is twofold It saves valuable memory space because a copy of the string which may be long does not need to be copied to the stack A string copy operation is lengthy in terms of CPU execution time However in some cases the valuables are passed byVal and in that case when the function or subroutine is invoked a constant string in the form string can be passed to It Note For arguments specified as byRef it is not possible to pass a constant value whether number or string Statements Statements do not take arguments but instead take arithmetic or string expression lists The only Statements In smart BASIC are PRINT and SPRINT Exceptions Developing a software application that is error free is virtually an impossible task All functions and Subroutines act on the data that is passed to them and there are occasions when
402. sed by value to a routine any modifications to that variable will not reflect back to the calling routine However if a variable is passed by reference then any changes in the variable will be reflected back to the caller on exit The SUB statement marks the beginning of a block of statements which will consist of the body of a user routine The end of the routine is marked by the ENDSUB statement Americas 1 800 492 2320 Option 2 187 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual ENDSUB This statement ends a block of statements belonging to a subroutine It MUST be included as the last statement of a SUB routine as it instructs the compiler that there is no more code for the SUB routine Note that any variables declared within the subroutine lose their scope once ENDSUB is processed EXITSUB This statement provides an early run time exit trom the subroutine FUNCTION A statement beginning with this token marks the beginning of a block of statements which will consist of the body of a user routine The end of the routine is marked by the ENDFUNC statement A function is a block of statements which constitute a user routine that returns a value A function takes arguments and can return a value of type simple or complex FUNCTION routinename arglist AS vartype EXITFUNC arithemetic_expression_or_string_expression END
403. shing ENDFUNC 0 ONEVENT EVUARTRX CALL HndlxeUareks ONEVENT EVTMRO CALL HndlrTmroO PRINT nasend me some textinn WALTEVENT Expected Output Send me some data baira 6 bytes in the rx buffer O bytes in the rx buffer after flushing Example UartFlushTx sb See in BL600CodeSnippets zip DIM so e gt Hello World DIM pec ro UariWieiibe es Udi Bilas Oro Will flush before all chars have been transmitted PRINT Usatrinro s bytes 1n the tx butter after tilushing Expected Output HO bytes in the tx buffer after flushing UARTFLUSH is a core subroutine UartGetCTS FUNCTION This function is used to read the current state of the CTS modem status input line If the device does not expose a CTS input line then this function will return a value that signifies an asserted line UARTGETCTS Returns INTEGER Indicates the status of the CTS line O CTS line is NOT asserted 1 CTS line is asserted Americas 1 800 492 2320 Option 2 141 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Uart has not been opened using UARTOPEN Arguments None Interactive Command No Related Commands UARTOPEN UARTINFO UARTCLOSE UARTWRITE UARTREAD UARTREADMATCH UARTGETDSR UARTGETDCD UARTGETRI UARTSETDTR
404. smart BASIC User Manual Timer Events EVTMRn Where n 0 to N where N is platform dependent it is generated when timer n expires The number of timers that is N 1 is returned by the command AT 2003 or at runtime by SYSINFO 2003 Example EVTMRn sb See in BL6O00CodeSnippets zip FUNCTION HandlerTimero0O PRINT nTimer 0 has expired ENDEUNG i I remain blocked in WAITEVENT FUNCTION HandlerTimerl1 PRINT nTimer 1 has expired ENDFUNC 0 exit from WAITEVENT ONEVENT EVEMRO CALL HandlerTimerd ONEVENT EVEMRI CALL HandlerTimer Timer cari Or gt 00y I ji stance a 500 millisecond recurring Eimert PRINT T nWarring Tor Timer 0 Tim r tari ik LOCO 0 M Sere a 1000 milli econd timer PRINT ANa Nng for Timer 1 WAITEVENT PRINT nGot here because TIMER 1 expired and handler returned 0 Expected Output TimerStart This subroutine starts one of the built in timers The command AT 2003 will return the number of timers and AT 2002 will return the resolution of the timer in microseconds When the timer expires an appropriate event is generated which can be acted upon by a handler registered using the ONEVENT command TIMERSTART number interval_ms recurring SUBROUTINE Arguments number byVal number AS INTEGER The number of the timer O to N where N can be determined by submitting the command AT 2003 or at runtime returned via SYSINFO 2003 Americas 1 800 492 2320 Option 2 113 Laird Technologi
405. ssa exp 2 PRINT nthe number read is mantissa x 10 exo read 2 bytes FLOAT from index 6 in the string rc BleDecodeSFloat attr mantissa exp 6 PRINT Y nthe number read ws mantissa k O 7 exc Expected Output The number read is 770 x 10 0 The number read is 1926x 10 8 BLEDECODESFLOAT is an extension function BleDecodeTIMESTAMP FUNCTION This function reads 7 bytes from string an offset into an attribute string If the offset plus 7 bytes points beyond the end of the string then this function fails The 7 byte string consists of a byte each for century year month day hour minute and second If year month is zero it is taken as not noted year and all the other fields are set zero not noted For example 5 May 2013 10 31 24 will be represented in the source as DD O7 05 05 0A 1F 18 and the year will be translated into a century and year so that the destination string will be 14 OD 05 05 0A 1 F 18 BLEDECODETIMESTAMP attr timestamp nlndex Americas 1 800 492 2320 Option 2 331 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Returns INTEGER the number of bytes extracted from the attribute string Can be less than the size expected if the nindex parameter is positioned towards the end of the string Arguments attr byRef attr AS STRING This references the attri
406. ssage and the input buffer fills up In that case there is no more space for an incoming termination character and the RTS handshaking line would have been asserted so the message system will stall A flush of the receive buffer is the best approach to recover from that situation Note Execution of UARTFLUSH is much quicker than the time taken to transmit data to from the buffers UARTFLUSH bitMask Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Uart has not been opened using UARTOPEN Arguments bitMask byVal bitMask AS INTEGER This bit mask is used to choose which ring buffer to flush Bit Description O Set to flush the rx buffer 1 Set to flush the tx buffer Set both bits to flush both buffers Interactive Command No Related Commands UARTOPEN UARTINFO UARTCLOSE UARTWRITE UARTREAD UARTREADMATCH UARTGETCTS UARTGETDCD UARTGETRI UARTGETDSR UARTSETRTS UARTSETDCD UARTBREAK UARTFLUSH Example UartrlushRx sb See in BLGO0CodesSniopets zip Americas 1 800 492 2320 Option 2 140 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual EU CAV ON Sein Glee eriaie ins Limetotane 02 0 A low time for data to reach rx buffer ENDFUNC 1 BUNGL TON eine lee limi 0 PRINT Un ano Se bVbes 1m Ene fx bubre a UartElush 0l ea tee OE PRINT Usrrinro o DpDytes in the r lt Duff r after li
407. ssions for the Descriptor User Desc Descriptor BleAttrMetadata Add parameters for creation of User Desc Descriptor BleCharDescUserDesc Section Forma v s Add parameters for creation of Descriptor Presentation Format Descriptor GSCHpIO To BleCharDescPrstnFrmt E Add parameters for creation of other Descriptor BleCharDescAdd Create a metadata object which defines the permissions for the other Descriptor BleAttrMetadata Add other Descriptor Commit the Characteristic to the Gatt ServerTable in single transaction BleCharCommit Sa Save the handle that is returned as it is used to interact with the More characteristic haracteristics More Services 231 Laird Technologies smart BASIC User Manual Example ServicesAndCharacteristics sb See in BL600CodeSnippets zip Register two Services in the GATT Table Service 1 with 2 Characteristics and Ioer e 2 Ween characteristic This amples a bOtal Of 6 Characteristics to manage The characteristic 2 in Service 1 will not be readable or writable but only indicatable The characteristic 1 in Service 2 will not be readable or writable but only notifyable IE DiM ae result code DIM hSvc fo service handle DIM mdAttr Dil mec eed DiM mdsecd DIM eliPa op DIM attr DIM nCharil hanciles tor characrcerLscic 1 of SeryLce 1 DIM nChar21 hnancilles tor charcactcerLlstLe 2 Of Service 1 DIM hn
408. sult code in UwTerminal and select Lookup Selected ErrorCode Americas 1 800 492 2320 Option 2 15 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Terminal BASIC Config About CTS DSR DCDM AB RTS V DTRIV BREAK LocalEcho LineMode Clear ClosePort XCompile XCompile Load XCompile Load Run Lookup Selected ErrorCode Compile Load l Mmanlnarl Expected Output m smartBASIC Error Code 073D gt RUN INV CIRCBUF HANDLE Information Routines GETLASTERROR FUNCTION GETLASTERROR is used to find the value of the most recent error and is most useful in an error handler associated with ONERROR and ONFATALERROR statements which were described in the previous section You can get a verbose error description by printing the error value then highliting it in UwTerminal and selecting Lookup Selected ErrorCode GETLASTERROR Returns INTEGER Last error that was generated Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments None Interactive Command NO Example GetLastError sb See in BL600CodeSnippets zip DIME rove err GETLASTERROR PRINT V nerror Ox INTEGER cence Expected Output If no errors from last application run _ error 0x00000000 GETLASTERROR is a core function Americas 1 800 492 2320 Opt
409. syn file from the firmware upgrade zip file to the Textpad install folder specifically the system subfolder As a one time procedure start TextPad Ensure no documents are currently open From the menu select Configure gt Preferences Select Document Classes In the User defined classes list box add smartBASIC Click the plus sign to expand Document Classes and select smartBASIC In the new Files in class smartBASI C list box add the following two lines sb sblib Click to expand smartBASIC and select Syntax Select Enable syntax highlighting to enable it In the Syntax definition file dropdown menu enter or select the smartBASIC textpad syn file Click OK You should now have TextPad configured so that any Tile with Tile extension sb or sblib will be displayed with color syntax highlighting To change the colors of the syntax highlighting do the following 1 From the Configure Preferences dialog box select the Document Classes plus sign next to smartBASIC and select Colors 2 Change the color of any of the items as necessary For example smartBASIC FUNCTIONS are Keywords 2 smartBASIC SUBs are Keywords 3 and smartBASIC Event and Message IDs as used in the ONEVENT statement are Keywords 4 Figure 11 displays a sample of what a smarfBASIC code fragment looks like in TextPad Americas 1 800 492 2320 Option 2 19 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireles
410. t was called attr byRef attr AS STRING String variable containing new value to write to the characteristic and then to send as a notification to the client If there is no connection this function fails with an appropriate result code Interactive Command NO Example BleCharValueIndicate sb See in BL600CodeSnippets zip DIM nMy hate te abo Combrmcdl PUNCTION OnStarctup DIEM Te InSwe aS eiseics a ad RoE adda e Ro abere Hi DiMpncaCeec mice cece Sle ter ile eager cm lela Oratae 7 E CCD metadata for sole 77 Commie Sve view beandle aSveUuid rc BleSvcCommit 1 Bleband eUuid 6 0x1 8EE pSve initialise char write read enabled accept signed writes notifiable rc BleCharNew 0x22 BleHandleUuidl6 1 BleAttrMetaData 1 0 20 0 rc mdCccd 0 A commit char initaalised above with initial value Thi to service hMyChar roe BleCharCommit hove attr nMyChar re RleScanRpt Init SCRE Add 1 service handle to scan report PO PTCA NER OEA TUU Cll e Roe aswe l 1 L 1 1 commit reports to GATT table adRpt is empty rc BleAdvRptsCommit adRpt scRpts C BleAdvertStart 0 addrs 50 0 0 ENDEUNG 2c Ble event hancler Americas 1 800 492 2320 Option 2 261 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx conHndl nCtx IF nMsg
411. t byRef aiscardedCount AS INTEGER On exit this should contain O and it signifies the total number of notifications or indications that got discared because the ring buffer in the gatt client manager was Tull If non zero values are encountered it is recommended that the ring buffer size be increased by using BleGattcClose when the gatt client was opened using BleGattcOpen Interactive Command NO Example BleGattcNotifyRead sb See in BL600CodeSnippets zip ye Selever a USime BleGanicclolNeniivixesc Sule iiowelkecl iin CosniMlcje see j Goma Nosd ec Usb Dongle Pe OOOO yy Charactersitic at handle 15 has notify 16 cccd A Chaora ctersiti atu handle 12 has Indicate lo eced PIM tee ees Conna aandaa aa POt CHOON Om S techie lou DIM tee eiclixjoics eclclies selors Americas 1 800 492 2320 Option 2 307 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual me BDileAdvnpe Inte adkRpts 2 0 10 IE ro 0 THEN re BlleScankoe Init ScRpts ENDIF IF rc 0 THEN rc BleAdvRptsCommit adRpt scRpt ENDIF TE we 0 THEN re BleAdvertStart 0 addrs 50 0 0 2 ENDIF open the gatt client with default notify indicate ring buffer size IF rc 0 THEN re BleGattcOpen 0 0 ENDIF ENDEUNG re SUB Glosee onmecer ems rc BleDisconnect conHnd1l rc BleAdvertStop Pips UB FUNCTIO
412. t contains concatenated AD elements which will have been either constructed for an outgoing advert or will have been received in a scan depends on module variant nADTag byVAL nADTag AS INTEGER This parameter specifies the single byte tag value for the AD element that is to returned in the ADval parameter Only the first instance can be catered for If multiple instances are suspected then use BleAdvADbylndex to extract it ADval byREF ADval AS STRING When the nth index is found the data excluding single byte the tag value for that AT element is returned in this parameter Interactive Command NO Example BleAdvGetADbyIndex sb See in BL600CodeSnippets zip DIM Mey adie ads Tulla Sie Pilea ADVA Americas 1 800 492 2320 Option 2 217 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual AD with length 6 bytes tag OxDD Fics 06 DD G27 es 445 T AD with length 7 bytes tag OxDA adZs 07 EE Aa VER VCC iD VEE EEN CID S ell S 4 eicl2s PRLNT Vai ss Sirnex Zeo fullADe je wat nADTag OxDD rc BleGetADbyTag fullADS nADTag ADvalS IF re 0 THEN PRINT nAD element with tag Ox INTEGER H nADTag is StrHexizeS ADval ELSE PRINT e nbierormesreading Als INTEGER TTC JEND IL E nADTag OXEE rc BleGetADbyTag fullADS nADTag ADvalS IP lt ec O THEN PRINT nAD element with
413. t integer handle that associates the integer as an offset into the Bluetooth SIG 128 bit 16byte base UUID which is used for all adopted services characteristics and descriptors If the input value is not in the valid range then an invalid handle 0 is returned The returned handle shall be treated by the developer as an opaque entity and no further logic shall be based on the bit content apart trom all O s which represents an invalid UUID handle BLEHANDLEUUID 16 nUuid16 Returns INTEGER a nonzero handle shorthand for the UUID Zero is an invalid UUID handle Arguments nUuid16 byVal nUuid76 AS INTEGER nUuid16 is first bitwise ANDed with OxFFFF and the result will be treated as an offset into the Bluetooth SIG 128 bit base UUID Interactive Command NO Example BleHandleUuidl6 sb See in BL600CodeSnippets zip DM aiael DIM hUuidHRS uuid 0x180D this is UUID for Heart Rate Service hUuidHRS BleHandleUuidl16 uuid IF hUuidHRS THEN PRINT nFailed to create a handle Blo E PRIN YRandle for HRS Uuad ro Se Integer ky NUn dRo a AUU Tr dHR o 7a ENID ILE Americas 1 800 492 2320 Option 2 238 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output Handle for HRS Uuird as FEQLISOD 33482739 BLEHANDLEUUID16 is an extension function BleHandleUuid128 FUNCTION This function takes
414. ta l 0 20 0 metasuccess DNE eo Ee some valuc ly rc BleCharDescAdd 0x2905 attrs mdChrDsc Te eae Add the other Descriptor 0x29XX second one a dinar SEI sreMlile T re rotel C harbe C Add Ux7290G7abers machubse e Add the other Descriptor 0x29XX last one iets attrs some value3 re rotBleCharDescAdd 0x290 arries mahr DSC IFP cec 0 THEN PRINT nOther descriptors added successfully ELSE PRINT nFailed ENDI Expected Output Other descriptors added successfully BLECHARDESCADD is an extension function BleCharCommit FUNCTION This function commits a Characteristic which was prepared by calling BleCharNew and optionally BleCharDescUserDesc BleCharDescPrstnFrmt or BleCharDescAdd It is an instruction to the GATT table manager that all relevant attributes that make up the Characteristic should appear in the GATT table in a single atomic transaction If it successfully created a single composite Characteristic handle is returned which should not be confused with GATT table attribute handles If the Characteristic was not accepted then this function will return a non zero result code which conveys the reason and the handle argument that is returned will have a special invalid handle of O The characteristic handle that is returned references an internal opaque object that Is a linked list of all the attribute handles in the Characteristic which by definition implies that there will be a minimum of
415. table which was created using TABLEINIT and multiple TABLEADDs and returns the ID value associated with it It is especially useful for creating a parser for example to create an AT style protocol over a uart interface TABLELOOKUP string strtok Returns INTEGER Indicates success of command gt 0 signifies that the token was successfully found and the value is the ID 1 if the token is not found within the table 2 if the specified table is invalid 3 if the token is empty or gt 255 characters Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments string byRef string AS STRING The lookup table that is being searched strtok byRef strtok AS STRING The token whose position is being found Note string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Interactive Command NO Associated Commands TABLEINIT TABLEADD Americas 1 800 492 2320 Option 2 107 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Example TableLookup sb See in BL600CodeSnippets zip DIM ts PRINT Vebletnit 1o Va ia PRINT Tableted ts belle i a PRE GebteNd es wom 2 ant PRENT Tabl Adde te 3 in PRINT TableAdeai ts you 4 7 n mn PRINT Nabl
416. tag Ox INTEGER H nADTag is StrHexizeS ADval ELSE PRINT nheror redding AD Y INTEGER Eire JE NIDIL IE nADTAG OxFF Will fail because no AD exists in fullADS with the tag FF rc BleGetADbyTag fullADS nADTag ADvalS IF rc 0 THEN PRINT nAD element with tag Ox INTEGER H nADTag is StrHexizeS ADvalS ELSE PRIME nerve teading Ay a T TECER dice ENDIF Expected Output BLEGETADBYTAG is an extension function BleAdvRptsCommit FUNCTION This function is used to commit one or both advert reports If the string is empty then that report type Is not updated Both strings can be empty and in that case this call will have no effect The advertisements will not happen until they are started using BleAdvertStart function BLEADVRPTSCOMMIT advRopt scanRpt Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Americas 1 800 492 2320 Option 2 218 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Arguments advRpt byRef advRpt AS STRING The most recent advert report scanRot byRef scanRot AS STRING The most recent scan report Note If any one of the two strings is not valid then the call will be aborted without updating the other report even if this other report is valid Interactive Command NO Example BleAdvRptsCommit sb S
417. takenly set this to e g 100ms nFilterPolicy byVal nFi terPolicy AS INTEGER Specifies the filter policy for the whitelist as follows O Filter Policy Any 1 Filter Policy Filter Scan Request Allow Connection Request from Any 2 Filter Policy Filter Connection Request Allow Scan Request from Any 3 Filter Policy Filter Scan Request and Connection Request If the filter policy is not O then the whitelist is enabled and filled with all the addresses of all the devices in the trusted device database Interactive Command NO Example BleAdvertStart sb See in BL6O00CodeSnippets zip DIM addro addro T7 FUNCTION HndlrBlrAdvTimOut PRINT nAdvert stopped via timeout Americas 1 800 492 2320 Option 2 209 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual UME EA AE oop scibie savepa nay BKNDFUNC TO The advertising interval is set to 25 milliseconds The module will stop advertising after 60000 ms 1 minute IF BleAdvertStart 0 addrs 25 60000 0 0 THEN PRINT nAdverts Started PRINT nIf you search for bluetooth devices on your device you should see Card BECOME ELSE PRINT n nAdvertisement not successful ENDIF ChEVil TEVBE CET AD A ME OUTE AL E ire Mamie WALTEVENT Expected Output BLEADVERTSTART is an extension function BleAdvertStop FUNCTION This function causes the BL
418. tal input lines being pulled high externally Consult the hardware manual for more information on the input pin number By default it is SIO7 on the module but it can be changed by setting the config key 100 via AT CFG You can interact with the BL600 over the air via the Virtual Serial Port Service using the iOS BL600 Serial app available free on the Apple App Store You may download smartBASIC applications using a Windows application which will be available for free trom Laird The PC must be BLE enabled using a Laird supplied adapter Contact your local FAE for details As most of the AT commands are functional you may obtain information such as version numbers by sending the command AT 3 to the module over the air Note that the module enters interactive mode only if there is no autorun application or if the autorun application exits to interactive mode by design Hence in normal operation where a module is expected to have an autorun application the virtual serial port service will not be registered in the GATT table If the application requires the virtual serial port functionality then it shall have to be registered programmatically using the functions that follow in subsequent subsections These are easy to use high level functions such as OPEN READ WRITE CLOSE VSP Virtual Serial Port Events In addition to the routines for manipulating the Virtual Serial Port VSP service when data arrives via the receive characteristic
419. tarting up The GAP service contains five characteristics as listed at the following site htto developer bluetooth org gatt services Pages ServiceViewer asox u org bluetooth service generic_access xml BLEGAPSVCINIT deviceName nameWritable nAppearance nMinConninterval nMaxConninterval nSupervisionTout nSlaveLatency Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation Arguments deviceName byRef deviceName AS STRING The name of the device e g Laird_Thermometer to store in the Device Name characteristic of the GAP service Note When an advert report is created using BLEADVRPTINIT this field is read from the service and an attempt is made to append it in the Device Name AD If the name is too long that function fails to initialise the advert report and a default name is transmitted It is recommended that the device name submitted in this call be as short as possible nameWritable byVal nameWritable AS INTEGER If non zero the peer device is allowed to write the device name Some profiles allow this to be made optional nAppearance byVal nAppearance AS INTEGER Field lists the external appearance of the device and updates the Appearance characteristic of the GAP service Possible values org bluetooth characteristic gap appearance nMinConninterval byVal nMinConninterval AS INTEGER The preferred minimum connection interval updates the Peripheral Preferred Connection
420. te and CCCD SCCD Descriptors respectively BLECHARNEW nCharProps nUuidHandle mdVal mdCccd mdSccd Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation Arguments nCharProps byVal nCharProps AS INTEGER This variable contains a bit mask to specify the following high level properties for the Characteristic that will get added to the GATT table BIT Description Broadcast capable Sccd Descriptor has to be present Can be read by the client Can be written by the client without response Can be written Can be Notifiable Cccd Descriptor has to be present Can be Indicatable Cccd Descriptor has to be present Can accept signed writes Reliable writes NO UBWN gt nUuidHandle byVal nUuidHandle AS INTEGER This specifies the UUID that will be allocated to the Characteristic either 16 or 128 bits This variable is a handle pre created using one of the following functions BleHandleUuid16 BleHandleUuid128 BleHandleUuidSibling mdVal byVal ma Val AS INTEGER This is the mandatory metadata that is used to define the properties of the Value attribute that will be created in the Characteristic and will have been pre created using the help of the function BleAttrMetadata Americas 1 800 492 2320 Option 2 24 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual mdCccd byV
421. tech com bluetooth smart BASIC User Manual Expected Output SELECT is a core function BREAK BREAK is relevant in a WHILE ENDWHILE DO UNTIL DO DOWHILE FOR NEXT or SELECT ENDSELECT compound construct It forces the program counter to exit the currently processing block of statements For example in a WHILE ENDWHILE loop the statement BREAK stops the loop and forces the command immediately after the ENDWHILE to be processed Similarly in a DO UNTIL the statement immediately after the UNTIL is processed BREAK Interactive Command NO Example Break sb See in BL600CodeSnippets zip DIMA n 0 WHILE n lt 10 n n 1 IF n 5 THEN BREAK ENDIF PRIN ee 2m ENDWHI LE PRINT A MES NedN nA Expected Output Hello 1Hello 2Hello 3Hello 4 Finished BREAK is a core function CONTINUE CONTINUE is used within a WHILE ENDWHILE DO UNTIL DO DOWHILE or FOR NEXT compound construct where it forces the program counter to jump to the beginning of the loop CONTINUE Interactive Command YES Example Continue sb See in BL600CodeSnippets zip DIM n n 0 WALLE lt 10 n Americas 1 800 492 2320 Option 2 65 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual IF n 5 THEN CONTINUE ENDIF PRENI Hello a ENDWHI LE PRINT nkainashed win Expected Output Hello 1Hello 2Hello 3Hello 4Hel
422. ted 1 If nChr is greater than 255 2 If the string length cannot be extended to accommodate nBlocklen 3 if the resultant string will be longer than allowed 4 If nCAris greater than 255 or less than O 5 if the nBlockLen value is negative Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments string byRef string AS STRING The target string to be modified nChr byVal nChr AS INTEGER The character that will overwrite the existing characters nChr must be within the range 0 255 Americas 1 800 492 2320 Option 2 89 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual nindex byVal nindex AS INTEGER The starting point for the filling block referenced to a zero index nBlocklen byVal nBlocklen AS INTEGER The number of characters to be overwritten Note string cannot be a string constant e g the cat but must be a string variable and so if you must use a const string then first save it to a temp string variable and then pass it to the function Interactive Command NO Example StrSetBlock sb See in BL600CodeSnippets zip DIM sS sS HelloWorld PPI NISS AE ate PRINT StrSetBlock s 64 4 2 2 i eee PRINT StrSetBlock s 300 4 200 PS SE E eee Expected Output HelloWorld O Hell orld 4 Hell orld STRSETBLOCK is a core function STRFILL FUNCTION STRFILL
423. tement provides a run time exit point for a function before reaching the ENDFUNC statement EXITFUNC arithemetic_expression or string expression EXITFUNC can be used to provide a return value through the use of a simple or complex expression It is usually invoked in a conditional statement to facilitate an early exit from the function FUNCTION doThis byRef s as string AS STRING S S World IF a 0 THEN EXITFUNC S earth ENDIF ENDFUNC S world Americas 1 800 492 2320 Option 2 189 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual 6 BLE EXTENSIONS BUILT IN ROUTINES Bluetooth Low Energy BLE extensions are specific to the BL600 smartBASIC BLE module and provide a high level managed interface to the underlying Bluetooth stack MAC Address To address privacy concerns there are 4 types of MAC addresses in a BLE device which can change as often as required For example an iPhone will regularly change It s BLE MAC address and it always exposes only It s resolvable random address To manage this the usual 6 octet MAC address is qualified on air by a single bit which qualifies the MAC address as public or random If public then the format is as defined by the IEEE organisation If random then it can be up to 3 types and this qualification is done using the upper 2 bits of the most significant byte
424. tenetetecotrestacertenestede 95 ARACA E enr AEE 93 IREN eaae AE EEE EE AAE 86 IRPO S oie aE E E AEAEE 86 STRSETBLOCK ecnin 89 SIR OE TCP en sac eearurers 87 AR I WIP e 91 STRSPLITLEFT sisisasiccincsssscrevanhevmatessooniiacsctimcdsacou 99 EE ON en E pena toutes E 100 STRVALDEC acera 98 STRA OR asisas torera SEREEN ESENES EEOAE 101 102 103 SUID PAA E NE E N E E EEE 187 Americas 1 800 492 2320 Option 2 360 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Us E E E E 77 SY INFO oe A E 79 SY EIAs ALE OE eE 353 if gt 2 3 Baer eer eens wren te er 106 TABLEINI oo E 105 109 TABLELOOKUP sssucecercseitssosesccnnssvdeumnostseustaesentdes 107 TIMERCANCEL eee eee cece eeeeeeee eee eeees 116 TIMERRUNNING 00 eeeeee eee eneeees 115 TVET Sal scans cece piran a oea ei 113 NA Eger crtterctcrest neater atomsenenaceracheeectonsaiad 143 VARTCLO SE oireen npn Ner eN ir 130 VARTOLOSE PA seinne aS 131 AS R ossee E eenemteneaseae 140 JARTOEI C I nean eeesceeete weirs eede ete 141 UARTINE O ee eee er 133 UARTOPEN 6c scsccpstnsstecemeciaipetercdisieataceoesseaneon 127 UARTREAD isccapscnanicas toate Srcentensnesaeansnenents 136 137 UARTREADMATCH 0 eeeeeeeeeeeetteeeeeeees 138 VARTSE TR TS een eueetaulens ssa sceeeee 142 AIS WW REDE cicero anette stvaciemsinsnpedvasistueuvaisshentiisepattuer 134 WHILE ENDWHILE tisestivtsrcerwtinsitredamuitcneinsas
425. teractive Command NO Example BleAdvRptInit sb See in BL6O00CodeSnippets zip DIM advRpts advRpts DIM discovMode discovMode 0 DIM advAppearance advAppearance 1 DIM maxDevName maxDevName 10 IF BleAdvRptInit advRpt discovMode advAppearance maxDevName 0 THEN PRINT nAdvert report initialised ENDIF Expected Output Advert report initialised BLEADVRPTINIT is an extension function BleScanRptinit FUNCTION This function is used to create and initialise a scan report which will be sent in a SCAN_RSP message It will not be used until BLEADVRPTSCOMMIT is called This report is for use with SCAN_RESPONSE packets BLESCANRPTINIT scanRpt Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments scankot byRef scanRot ASSTRING This will contain a scan report Interactive Command NO Example BleScanRptInit sb See in BL600CodeSnippets zip DIM ScnRPE scopes IF BleScanRptInit scnRpt 0 THEN PRINT nScan report initialised EAUDIRG Americas 1 800 492 2320 Option 2 212 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output Scan report initialised BLESCANRPTINIT is an extension function BleAdvRptAddUuid16 FUNCTION This function is used to add a 16 bit UUID service list AD Advertising record to t
426. th mandatory n if the variable is an array For integer variables the display format can be selected by pretixing the variable with one of the integer type prefixes D Decimal H Hexadecimal O Octal B Binary This is an Interactive mode command and MUST be terminated by a carriage return for it to be processed Interactive Command YES Examples argc 08 11 00 h arge 08 H 0000000B 00 Americas 1 800 492 2320 Option 2 42 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual B argce 08 B 000000000000000000000001011 argv 0 08 hello 00 IS a core command Set Variable COMMAND When an application encounters a STOP BPnnn or END statement it falls into the Interactive mode of operation and does not discard the global variables so that they can be referenced in Interactive Mode The command is used to change the content of a known variable When the application is RESUMEd the variable contains the new value It is useful when debugging applications var lt n gt value Returns If the variable exists and the value is of a compatible type then the variable value is overwritten and the response to this command is nOO r If the variable exists and it is NOT of compatible type then the response to this command is nO1 tEO2 7 r If the variable does n
427. the appropriate commands all but one will be described when the command that triggers them is described The event EVGATTCTOUT is applicable for all Gatt Client related functions which result in transactions over the air The Bluetooth specification states that if an operation is initiated and is not completed within 30 seconds then the connection shall be dropped as no further Gatt Client transaction can be initiated Americas 1 800 492 2320 Option 2 26 7 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual EVGATTCTOUT event message This event message WILL be thrown if a Gatt Client transaction takes longer than 30 seconds It contains 1 INTEGER paramter Connection Handle Example EVGATTCTOUT sb See in BL600CodeSnippets zip ci DIM re CONME HUME LIN ONS DIM ro Tadke addr Scions rco BleAdyvRptInit adRpts 2 0 10 LE e 0 THEN 3 re BleScankRoc Init ScRets ENDIF IF rc 0 THEN rc BleAdvRptsCommit adRpts scRpt ENDIF te re 0 TEEN 929 re B leAGvertStare 0 adders 50 0 0 ENDL lopen the gatt client with default notify indicate ring butter size IF rc 0 THEN re BleGattcOpen 0 0 ENDIF EDEN Siac FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx conHndl nCtx IF nMsgID 1 THEN PRINT n n Disconnected EXITFUNC Q ELSEIF nMsgID 0 THEN PRINT n Connected ENDIF ENDFUNC 1
428. the leftmost string token from it and passes it back in the second paremeter The token is removed from the sentence and is not post processed in any way The function will return the length of the string in the token This means if O is returned then there are no more tokens in the sentence It makes it easy to create custom protocol for commands send by a host over the uart for your application For example if the sentence is My name is BL600 from Laird then the first call of this function will return My and the sentence will be adjusted to name is BL600 from Laird Note that BL600 will result in BL600 and then The parser logic is exactly the same as when in the command mode If you are not sure which alphabet character is a token in its own right then the quickest way to get an answer is to actually try it NOTE any text after either or will be taken as a comment just like the behaviour in the command mode EXTRACTSTRTOKEN sentence token Function Returns INTEGER The length of the extracted token Will be O of there are no more tokens to extract Exceptions Local Stack Frame Undertlow Local Stack Frame Overflow Arguments sentence bykef sentence AS STRING String that contains the sentence containing the tokens to be extracted token byRef token AS STRING The leftmost token from the sentence and will have been removed from the sentence Note string cannot be a string co
429. the module which has to be configured as an output in a smart BASIC application so that it drives the PC s DSR line The DCD line input on a PC is connected to SIO29 and should be configured as an output in an application and finally the RI line again an input on a PC Is connected to SIO30 Please request a schematic of the BL600 development kit to ensure that these SIO lines on the modules are correct wal UwTerminal v6 21 Terminal BASIC Config About CTS DSR DCD Ai RTSV DIR BREAK LocalEcho V LineMode Clear ClosePort Figure 7 Control options Next to the indicators are a number of control options Figure 7 which can be used to set the signals that appear on inputs to the module RTS and DTR The two additional control lines for the RS 232 interface Note If CTS RTS handshaking is enabled the RTS checkbox has no effect on the actual physical RTS output pin as it is automatically controlled via the underlying Windows driver To gain manual control of the RTS output disable Handshaking in the Configuration window BREAK Used to assert a break condition over the Rx line at the module It must be deasserted after use A Tx pin is normally at logic high gt 3v for RS232 voltage levels when idle a BREAK condition is where the Tx output pin is held low for more than the time it takes to transmit 10 bits If the BREAK checkbox is ticked then the Tx output is at non idle state and no communicatio
430. the values do not make sense For example when a divide operation is requested and the divisor passed to the function Is the value zero In these types of cases it Is impossible to generate a return of meaningful value but the event needs to be trapped so that the effects of doing that operation can be lessened The mitigation process is via the inclusion of an ONERROR handler as explained in detail later in this manual If the application does not provide an ONERROR handler and if an exception is encountered at run time then the application aborts to Interactive mode Note This is disastrous for unattended use cases A good catchall ONERROR is to invoke a handler in which the module is reset then at least the module resets from a known condition Americas 1 800 492 2320 Option 2 50 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Language Definitions Throughout the rest of this manual the following convention is used to describe smart BASIC commands and statements Command FUNCTION SUBROUTINE STATEMENT Description of the command COMMAND lt byRef byval gt arg1 lt AS type gt Returns TYPE Description Value that a function returns always byVal Exceptions ERRVAL Description of the error Arguments a list of the arguments for the command arg byRet TYPE A description with type of the
431. tialise a scan report PRINT a Blescankptinat e Advertise the VSP service in the scan report so that it can be seen by the client PRINT Ant BleAdyRptAddUuidl g SscRoes mind adRpt PRINT n BleAdvRptsCommit adRpt scRpt addrS because we are not doing a DIRECT advert PRINT a Bleek veresStart 0 addrc 2 0 30000070 Now advertising so can be connectable ONEVENT EVVSPRX CALL HandlerBleVSpRx ONEVENT EVVSPTXEMPTY CALL HandlerVSpTxEmpty PRINT nUse the iOS BL600 Serial app to test this wait for events and messages WALTEVENT Americas 1 800 492 2320 Option 2 341 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Laird Technologies smart BASIC User Manual BleVSpOpen FUNCTION This function opens the default VSP service using the parameters specified The service s UUID is 569a1L101 b8 490c 92cb lilbaSeadloeye By default Modemin and ModemOut characteristics are registered in the GATT table with the Rx and Tx FIFO characteristics To suppress Modem characteristics in the GATT table set bit 1 in the nFlags parameter value 2 If the virtual serial port is already open this function fails BLEVSPOPEN txbuflen rxbuflen nFlags svcUuid Returns INTEGER indicating the success of command O Opened successfully 0x604D Already open 0x604E Invalid Buffer Size Ox604C Cannot register Service in Gatt Table while BLE
432. tion Americas 1 800 492 2320 Option 2 220 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleSetCurConnParms FUNCTION This function triggers an existing connection identified by a handle to have new connection parameters For example interval slave latency and link supervision timeout When the request is complete a EVBLEMSG message with msgld 14 and context containing the handle will be thrown to the smartBASIC runtime engine if it was successful If the request to change the connection parameters fails an EVBLEMSG message with msgid 15 is thrown to the smartBASIC runtime engine BLESETCURCONNPARMS nConnHandle nMinintUs nMaxintUs nSuprToutUs nSlaveLatency Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments nConnHandale byVal nConnHandle AS INTEGER Specifies the handle of the connection that must have the connection parameters changed nMinintUs byVal nMinintUs AS INTEGER The minimum acceptable connection interval in microseconds nMaxintUs byVal nMaxintUs AS INTEGER The maximum acceptable connection interval in microseconds nSuprToutUs byVal nSuprToutUs AS INTEGER The link supervision timeout for the connection in microseconds It should be greater than the slave latency times the actual granted connection interval nSlaveLatency byVal nSlave
433. tion 2 169 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual FCLOSE fileHandle Returns N A as it is a subroutine Arguments fileHandle BYREF fileHandle AS INTEGER The handle of the file to be closed On exit it will be set to 0 Interactive Command NO See the full and detailed example in the FOPEN section FCLOSE is a core language function FREAD FUNCTION This function is used to read X bytes of data from a file previously opened with FOPEN and will return the actual number of bytes read FREAD fileHandle data maxReadLen Returns INTEGER The actual number of bytes read from the file Will be O if read from end ot Tile is attempted Arguments fileHandle BYVAL fileHandle AS INTEGER The handle of the file to be read from data BYREF data AS STRING The data read from file is returned in this string maxReadLen BYVAL maxReadLen AS INTEGER The max number of bytes to read from the file Interactive Command NO See the full and detailed example in the FOPEN section FREAD is a core language function FREADUNTIL FUNCTION This function is used to read X bytes or until and including a match byte is encountered whichever comes earlier trom a file previously opened with FOPEN and will return the actual number of bytes read includes the match byte if encountered Americas 1 800 492 2320 Option
434. tions an automatic gatt acknowledgement is sent when the data is saved in the ring buffer This acknowledgment happens even if the data was discarded because the ring buffer was full If however it is required that the data NOT be acknowledged when it is discarded on a full buffer then set the flags parameter in the BleGattcOpen function where the Gatt Client manager is opened In the case when an ack is NOT sent on data discard the Gatt Server will be throttled and so no further data will be notified or indicated by it until BleGattNotifyRead is called to extract data from the ring buffer to create space and it will trigger a delayed acknowledgement When the Gatt Client manager is opened using BleGattcOpen it is possible to specify the size of the ring buffer If a value of O is supplied then a default size is created SYSINFO 2019 in a smartBASIC application or the interactive mode command AT 2019 will return the default size Likewise SYSINFO 2020 or the command AT 2020 will return the maximum size Data that arrives via notifications or indications get stored in the ring buffer and at the same time a EVATTRNOTIFY event is thrown to the smartBASIC runtime engine This is an event in the same way an incoming UART receive character generates an event that is no data payload is attached to the event EVATTRIOTIFY event message This event WILL be thrown when an notification or an indication arrives from a gatt server The event cont
435. to a temp string variable and then pass it to the function Related Commands UARTOPEN UARTINFO UARTCLOSE UARTWRITE UARTREADMATCH UARTGETDSR UARTGETCTS UARTGETDCD UARTGETRI UARTSETDTR UARTSETRTS UARTSETDCD UARTSETRI VUARTBREAK UARTFLUSH Example DM Mae ce oe cs pias Shro Vout name ig BUNG RTO ShindimeUenircins Rimor o tarr 07 00 0 Allow enough time for data to reach rx buffer ENDFUNC 1 Americas 1 800 492 2320 Option 2 137 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PUMEGT LON Bivelee inc strLength UartReadn str 11 PRINT aa iS Gass ENDFUNC 0 ONEVENT EVTMRO CALL HndlrTmr0O ONEVENT EVUARTRX CALE ANd r Uar tR PRINT nWhat is your name n WALTEVENT Expected Output What is your name David Your name i UARTREADN is a core subroutine UartReadMatch FUNCTION This function is used to read the content of the underlying receive ring buffer and append it to the string variable supplied up to and including the first instance of the specified matching character OR the end of the ring buffer This function is very useful when interfacing with a peer which sends messages terminated by a constant character such as a carriage return 0x0D In that case in the handler if the return value is greater than O it implies a terminated message arrived and so can be process
436. to open I2C interface with error code INTEGER H rc ELSE PRINT nI2C open success BND F Read value from address 0x34 nSlaveAddr 0x6of nRegAddr 23 rc 2cReadReg8 nSlaveAddr nRegAddr nRegVal Americas 1 800 492 2320 Option 2 148 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual LE pels O THEN PRINT nFailed to Read from slave register INTEGER H rc ELSE PRINT nValue read from register is nRegVal ENDIF I2cClose handle close the port Expected Output ae eee I2C open success Value read from register is 99 IZCREADREG8 is a core function I2cWriteREG16 SUBROUTINE Note For firmware releases older than 1 2 54 4 there is an issue where some 12C slaves are not able to drive the ACK down to a low enough voltage level for the module to recognise it as an ACK This is a result of a bug in the BL600 s I2C driver which results in the SDA line not being released by the module This has been corrected in release 1 2 54 4 and the firmware is available as a uart download on request You should upgrade the firmware if you have an I2C slave not responding to the correct slave address This function is used to write a 16 bit value to 2 registers inside a slave and the first register is identified by an 8 bit register address supplied Note a handle parameter is NOT required as this f
437. to write event and message handler functions An application with user routines is highly modular allowing reusable functionality SUB A subroutine is a block of statements which constitute a user routine which does not return a value but takes arguments SUB routinename arglist EXITSUB ENDSUB A SUB routine MUST be defined before the first instance of it being called It is good practice to define SUB routines and functions at the beginning of an application immediately after global variable declarations A typical example of a subroutine block would be SUB somename argl AS INTEGER arg2 AS STRING DIM S AS INTEGER S argl IF argl 0 THEN EXITSUB ENDIF ENDSUB Defining the routine name The function name can be any valid name that is not already in use as a routine or global variable Defining the arglist The arguments of the subroutine may be any valid variable types i e INTEGER or STRING Each argument can be individually specified to be passed either as byVal or byRef By default simple variables INTEGER are passed by value byVal and complex variables STRING are passed by reference byRef However this default behaviour can be varied by using the SET directive during compilation of an application SET 1 0 Default Simple arguments are BYVAL SET 1 1 Default Simple arguments are BYREF SET 2 0 Default Complex arguments are BYVAL SET 2 1 Default Complex arguments are BYREF When a value Is pas
438. tooth org gatt Pages GattNamespaceDescriptors aspx Americas 1 800 492 2320 Option 2 250 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual nNSdesc byVal nN Sdesc AS INTEGER Valid range 0 to 65535 This value is a description of the organisation specified by nNameSpace Interactive Command NO Example BleCharDescPrstnFrmt sb See in BL600CodeSnippets zip DIM ro Mevasuecess Usir Deso usr Desc TA description DIM charcrUuic 3 CharUuid Blenandlevuidils 1 DIM charMet charMet BleAttrMetaData 1 1 20 0 metaSuccess DIM mdUsrDsc mdUsrDsc BleAttrMetaData 1 1 20 0 metaSuccess PE ines cece mime sec lea ete ae a Oretce 7 SCCD Me radara r or velar initialise char write read enabled accept signed writes indicatable rc BleCharNew 0x4B charUuid charMet 0 mdSccd rc BleCharDescUserDesc usrDescS mdUsrDsc IF rc 0 THEN PRINT nChar created and User Description usrDescS added ELSE PRINT nFailed ENDIF I ee I other optional descriptors CERE 16 bit signed integer 0x0E exponent 2 unit Ox271A amount concentration mole per cubic metre namespace 0x01 Bluetooth SIG SiGe Ctle none 10 0000 a imkmewn MF BleCharbDescPrstnErme Ox0E 2 0x27 lA 0x01 00000 0 THEN PRINT nPresentation Format Descriptor added BLSE PRINT nPresentation Format Descripto
439. ts var byValvar1 AS INTEGER The first of two variables to be compared ale byValvar2 AS INTEGER The second of two variables to be compared Interactive Command No Example MAX sb See in BL600CodeSnippets zip DIMESSI PSA sl 2 s2 4 PRINT 1 62 PRINT n The Maximum of these two integers is MAX s1 8s2 Expected Output sat 4 The Maximum of these two integers is 4 MAX is a core language function MIN FUNCTION Returns the minimum of two integer values MIN var var2 Returns INTEGER The returned variable is the arithmetically smaller of var7 and var2 Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments var byValvar1 AS INTEGER The first of two variables to be compared ale byValvar2 AS INTEGER The second of two variables to be compared Interactive Command No Americas 1 800 492 2320 Option 2 82 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Example MIN sb See in BL600CodeSnippets zip DIM 1 52 sl 2 s2 4 PRINT 1 62 PRINT nThe Minimum of these two integers is MIN s1 8s2 Expected Output Sd 4 The Maximum of these two integers is 2 MIN is a core language function String Routines When data is displayed to a user or a collection of octets need to be managed as a set it is useful to represent them as strin
440. ttcWrite returns a success The message contains 3 INTEGER parameters Connection Handle Handle of the Attribute Gatt status of the write operation Gatt status of the write operation is one of the following values where O implies the write was successfully expedited Ox0000 Success 0x0001 Unknown or not applicable status 0x0100 ATT Error Invalid Error Code 0x0101 ATT Error Invalid Attribute Handle 0x0102 ATT Error Read not permitted 0x0103 ATT Error Write not permitted 0x0104 ATT Error Used in ATT as Invalid PDU 0x0105 ATT Error Authenticated link required 0x0106 ATT Error Used in ATT as Request Not Supported 0x0107 ATT Error Offset specified was past the end of the attribute Americas 1 800 492 2320 Option 2 299 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Ox0108 ATT Error Used in ATT as Insufficient Authorisation 0x0109 ATT Error Used in ATT as Prepare Queue Full OxO10A ATT Error Used in ATT as Attribute not found OxO10B ATT Error Attribute cannot be read or written using read write blob requests OxO10C ATT Error Encryption key size used is insufficient OxO10D ATT Error Invalid value size OxO10E ATT Error Very unlikely error OxO10OF ATT Error Encrypted link required 0x0110 ATT Error Attribute type is not a supported grouping attribute 0x0111 ATT Error Encrypted link
441. ttiar yada 63 Laird Technologies
442. ty this characteristic is omitted byVal regDataList AS STRING The device s regulatory certification data list as defined in the specification It can be set as an empty string to omit submission byVal onpld AS STRING The device s plug and play ID as defined in the specification Can be set empty to omit submission Otherwise it shall be exactly 7 octets long where Byte 0 Vendor Id Source Byte 1 2 Vendor Id Byte 1 is LSB Byte 3 4 Product Id Byte 3 is LSB Byte 5 6 Product Version Byte 5 is LSB NO BleSvcRegDevinfo sb See in BL600CodeSnippets zip DIM Cr mann ine gt smell op e Numa aaRS se WwRewer e cilGlomige qi Diealns soy P manfNmeS Laird Technologies mdlNums srlNums empty to omit submission hwRevs SswRevs sysid empty O omit submission eo Dives com suo empty to omit submission PoE empty to omit submission Americas 1 800 492 2320 Option 2 23 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual rc BleSvcRegDevinfo manfNme mdlNumS srlNumS hwRevs swRevS syslds regDtaLst pnplds IP lre THEN PRINT nsucecess ELSE PRINT Var ovled 0x INTEGER H re ENDIF Expected Output Success BLESVCREGDEVINFO Is an extension function BleHandleUuid16 FUNCTION This function takes an integer in the range O to 65535 and converts it into a 32 bi
443. ual DiM hMyChawrre alo Comlndl HUNCIUONMOnStacEie DIL tee bis vey ib eieicies aClaor a a atro ai DIM charMet charMet BleAttrMetaData 1 0 20 0 rc DIM macccd mdSeca BleAterMevacata l i 2 0 1c A Commit oye ween handle peycuuled rc BleSvcCommit 1 BleHandleUuidl16 Ox18EE hSvc initialise char read enabled accept signed writes broadcast capable rc BleCharNew 0x03 BleHandleUuidl6 1 charMet 0 mdSccd eon e Claieie aliquige ve leech oa ywilela aiqulie wells es Ike idk sri Svaiey eS ray Clnerie rc BleCharCommit hSvc attrs hMyChar rc BleAdvRptiInit adRpts 0x02 0 20 commit reports to GATT table adRptS is empty rc BleAdvRptsCommit adRpt scRpts rc BleAdvertStart 0 addr 20 300000 0 Pe Go Lob ineh yen ely 161 j Chenme lly bind to low tranci ion one CETO Panse ENCEN RIC SUB CloseConnections rc BleDisconnect conHnd1L rc BleAdvertStop rc GpioUnbindEvent 1 ENDSUB FUNCTION HnodltBleMso BYVAL nMsolid BIVALO TT Conni ne wx IF nMsgiID 1 THEN PRINT n n Disconnected from client EX TEE UNC 0 ELOEIF nMsgiD 0 THEN PRINT n Connected to client BENDI E ENDEUNC I Americas 1 800 492 2320 Option 2 199 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual EFUNCTION HMndlirBtCNOPr AS TITNTECGER CloseConnections BNDEUNC i FUNCTION HndirCharseed BY
444. ue will be used by the underlying driver byVal rxbutlen AS INTEGER Set the receive ring buffer size to this value If set to O then a default value will be used by the underlying driver byVal stOptions AS STRING This string can be a constant MUST be exactly 5 characters long where each character is used to specify further comms parameters as follows Character Offset 0 DTE DCE role request T for DTE and C for DCE 1 Parity N for none O for odd and E for even 2 Databits 5 6 7 8 9 3 Stopbits 1 2 4 Flow Control N for none H for CTS RTS hardware X for xon xof Note Note There will be further restrictions on the options based on the hardware as for example a PC implementation cannot be configured as a DCE role Likewise many microcontroller uart peripherals are not capable of 5 bits per character but a PC is In DTE equipment DCD and RI are inputs while in DCE they are outputs Interactive Command No Americas 1 800 492 2320 Option 2 128 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Related Commands UARTINFO UARTCLOSE UARTWRITE UARTREAD UARTREADMATCH UARTGETDSR UARTGETCTS UARTGETDCD UARTGETRI UARTSETDTR UARTSETRTS UARTSETDCD UARTSETRI VARTBREAK UARTFLUSH Example UartOpen sb See in BL
445. uid handles to be searched for it also accepts instance parameters which are indexed from 0 which means the 4 instance of a characteristic with the same uuid in the 3 instance of a service with the same uuid will be located with index values 3 and 2 respectively Given that the results are returned in an event message a handler must be registered for the EVFINDCHAR event Depending on the size of the remote GATT server table and the connection interval the search of the characteristic may take many 100s of milliseconds and while this is in progress it is sate to do other non Gatt related operations like for example servicing sensors and displays or any of the onboard peripherals Note Itis not currently possible to scan for characteristics in included services This will be a future enhancement EVFINDCHAR event message This event message WILL be thrown if BleGattcFindChar returns a success The message contains 4 INTEGER parameters Connection Handle Characteristic Properties Handle for the Value Attribute of the Characteristic Included Service Uuid Handle If the specified instance of the service characteristic is not present in the remote Gatt Server Table then all parameters will contain O apart from the Connection Handle Characteristic Properties contains the properties of the characteristic and is a bit mask as follows Bit O Set if BROADCAST is enabled Bit 1 Set if READ is enabled Bit 2 Set if WRITE_
446. uirements a maximum of 20 bytes value attribute The following properties are enabled NOTIFY The CCCD descriptor also requires no authentication encryption Americas 1 800 492 2320 Option 2 338 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual The Modemin characteristic is defined with no authentication or encryption requirements a single byte attribute The following properties are enabled WRITE WRITE NO RESPONSE The ModemOut characteristic value attribute is with no authentication or encryption requirements a single byte attribute The following properties are enabled NOTIFY The CCCD descriptor also requires no authentication encryption For Modemin only bit zero is used which is set by 1 when the client can accept data and O when it cannot inverse logic of CTS in UART functionality Bits 1 to 7 are for future use and should be set to 0 For ModemOut only bit zero is used which is set by 1 when the client can send data and O when it cannot inverse logic of RTS in UART functionality Bits 1 to 7 are for future use and should be set to O Note Both flags in Modemin and ModemOut are suggestions to the peer just as in a UART scenario If the peer decides to ignore the suggestion and data is kept flowing the only coping mechanism is to drop new data as soon as internal ring buffers are full
447. ul operation Note if the buffer was full and the oldest value was overwritten then a non zero value of 0x5103 will still be returned Arguments circHandle byRef circHandle AS INTEGER This identities the circular buffer to write into nData byVal nData AS INTEGER This is the integer value to write into the circular buffer It is always written into the buffer Oldest is discarded to make space for this Interactive Command NO Example CircBufOverwrite sb See in BL600CodeSnippets zip DIM re lt irehHandle a re CircBufCreate 4 circHandle IF rc 0 THEN PRINT nThe circular buffer was not created n ELSE PRINT nThe circular buffer was created successfully n ENDL FOR i 1 TO 5 re CircBufOverwrite circHandle 1 LE re 0x5103 THEN PRINT nOldest value was discarded to write i ELSEIF re 0 THEN PRINT nFailed to write into the circular buffer BLSE PE ITUT An Americas 1 800 492 2320 Option 2 122 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual ENDIE NEXT Expected Output CIRCBUFOVERWRITE is an extension function CircBufRead FUNCTION This function is used to read an integer from the tail end of the circular buffer A nonzero resultcode will be returned if the buffer is empty or if the handle is invalid CIRCBUFREAD circHandle nData Returns INTEGER An integer
448. unction is used to interact with the main interface In the future a new version of this function will be made available if more than one 2C interface is made available most likely made available by bit bashing gpio I2CWRITEREG16 nSlaveAddr nRegAddr nRegValue Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments nSlaveAdar byVal nSlaveAdadr AS INTEGER This is the address of the slave in range O to 127 nRegAdar byVal nRegAdar AS INTEGER This is the 8 bit start register address in the addressed slave in range 0 to 255 nkegValue byVal nRegValue AS INTEGER This is the 16 bit value to be written to the register in the addressed slave Please note only the lowest 16 bits of this variable are written Interactive Command No Related Commands IZ2COPEN I2CCLOSE I2CWRITEREAD I2CWRITEREG8 I2CWRITEREG16 IZCWRITEREG32 IZCREADREGS8 I2CREADREG16 I2CREADREGS2 Americas 1 800 492 2320 Option 2 149 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Example I2cWriteRegl6 sb See in BL600CodeSnippets zip Please ensure that nSlaveAddr is the slave address of your I2C peripheral DIM rc handle nSlaveAddr nRegAddr nRegVal e Open 2C Peripheral rc I2cOpen 100000 0 handle IF ccls 0 THEN PRINT nFailed to open I2C interface with error code INTEGER H rc BLSE PRINT niZze
449. untime error and no ONERROR handler Figure 2 Module modes amp transitions Types of Applications There are two types of applications used within a smartBASIC module In terms of composition they are the same but run at different times Autorun This is a normal application named autorun case insensitive When a smartBASIC module powers up it looks for the autorun application If it finds it and if the nAUtoRUN pin of the module is at Ov then it executes it Autorun applications may be used to initialise the module to a customer s desired state make a wireless connection or provide a complete application program At the completion of the autorun application which is when the last statement returns or a STOP or END statement is encountered a smartBASIC module reverts to Interactive mode In unattended use cases the autorun application is expected to never terminate It is typical for the last Statement in an application to be the WAITEVENT statement Developers should be aware that an autorun application does not need to complete and exit to Interactive mode The application can be a complete program that runs within the smartBASIC module removing the requirement for an external processor Applications can access the GPIOs and ADCs and use ports UART I2C and SPI for example to interface with peripherals such as displays and sensors Note By default when the autorun application starts up and if the STDOUT is the
450. up to 3 fields The first field is 1 octet in length and contains the number of octets that follow it that belong to that record The second field is again a single octet and is a tag value which identifies the type of payload that starts at the next octet Hence the payload data is length 1 A special NULL AD record consists of only one field that is the length field when it contains just the 00 value The specification also allows custom AD records to be created using the Manufacturer Specitic Data AD record The reader is encouraged to refer to the Supplement to the Bluetooth Core Specification Version 1 Part A which has the latest list of all AD records You will need to register as at least an Adopter which is free to gain access to this information It is available at httos www bluetooth org docman handlers downloaddoc ashx doc_id 245130 BleAdvertStart FUNCTION This function causes a BLE advertisement event as per the Bluetooth Specification An advertisement event consists of an advertising packet in each of the three advertising channels The type of advertisement packet Is determined by the nAdvType argument and the data in the packet Is initialised created and submitted by the BLEADVRPTINIT BEADVRPTADDxxx and BLEADVRPTCOMMIT functions respectively If the Advert packet type nAdvType is specified as 1 ADV_DIRECT_IND then the peerAddr string must not be empty and should be a valid address When advert
451. using this function will result in over 1mA of continuous current consumption from the power supply If power is of importance use GpioAssignEvent instead which uses other resources to expedite an event GPIOBINDEVENT n ventNum nSigNum nPolarity Returns INTEGER a result code The most typical value is OxO000 indicating a successful operation Arguments nEventNum byVal nEventNum NTEGER The GPIO event number in the range of O N which will result in the event EVGPIOCHANn being thrown to the smart BASIC runtime engine nSigNum byVal nSigNum INTEGER The signal number as stated in the pinout table of the module nPolarity byVal Polarity INTEGER States the transition as follows O Low to high transition 1 High to low transition 2 Either a low to high or high to low transition Interactive Command NO Example GpioBindEvent sb See in BL600CodeSnippets zip FUNCTION BtnOPress PRINT nHello ENDFUNC 0 PRINT GpioBindEvent 0 16 1 j Bane event Oro high Voy teensi trom om solo otic on ONEVENT EVGPIOCHANO CALL BtnOPress When event 0 happens call Btn0OPress PRINT nPress button 0 WAL TEYVENIT Expected Output O Press button 0 Hello GPIOBINDEVENT is a Module function Americas 1 800 492 2320 Option 2 183 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual GpioUnbind
452. uto launch the application each time it powers up you can implement a complete design within the module At one end the radio connects and communicates while at the other end external interactions are available through the physical interfaces such as GPIOs ADCs 12C SPI and UART f you want to add a range of different wireless options to an existing product you can load applications into a range of modules with different wireless functionality This presents a consistent API interface defined to your host system and allows you to select the wireless standard at the final stage of production f you already have a product with a wired communications link such as a modem you can write a smartBASIC application for one of our wireless modules that copies the interface for your wired module This provides a fast way for you to upgrade your product range with a minimum number of changes to any existing end user firmware In many cases the example applications on our website and in the applications manual can be modified to speed up the development process What does a BLE Module Contain Our smartBASI IC based BLE modules are designed to provide a complete wireless processing solution Each one contains A highly integrated radio with an integrated antenna external antenna options are also available BLE Physical and Link Layer Higher level stack Multiple GPIO and ADC Wired communication interfaces like UART I2C and SP
453. uuid svcHandle rc BleCharNew 0x07 BleHandleUuidl16 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle Americas 1 800 492 2320 Option 2 323 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual rc BleCharValueRead chrHandle attrS cead 2 signed bytes from index 2 rc BleDecodeS16 attr vl1 2 PRINT Andata in Hex 0x INTEGER H vl PRINTI ndata in Decimal g eel al read 2 signed bytes from index 6 rc BleDecodeS16 attr vl1 6 PRINT Andata in Hex Ox INTEGER H wl PRINT ndata in Decimal Yo eee an Expected Output BLEDECODES16 is an extension function BleDecodeU16 This function reads two bytes from a string at a specified offset into a 32bit integer variable without sign extension If the offset points beyond the end of the string then this function fails BLEDECODEU16 attr nData nlndex FUNCTION Returns INTEGER the number of bytes extracted from the attribute string Can be less than the size expected if the nindex parameter is positioned towards the end of the string Arguments attr byRef attr AS STRING This references the attribute string from which the function reads nData byRef nData AS INTEGER This references an integer to be updated with the 2 byte data from attr without sign extension nindex byVal nindex AS INTEGER This is the zero based index i
454. value in the expression gt Greater Than results in a O or 1 value in the expression gt Greater Than Or Equal results in a O or 1 value in the expression Americas 1 800 492 2320 Option 2 58 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Equal To results in a O or 1 value in the expression I Not Equal To results in a O or 1 value in the expression amp Bitwise AND Bitwise XOR exclusive OR Bitwise OR amp amp Logical AND results in a O or 1 value in the expression AN Logical XOR results in a O or 1 value in the expression Logical OR results in a O or 1 value in the expression Conditionals Conditional functions are used to alter the sequence of program flow by providing a range of operations based on checking conditions Note smartBASIC does not support program flow functionality based on unconditional statements such as JUMP or GOTO In most cases where a GOTO or JUMP might be employed ONERROR conditions are likely to be more appropriate Conditional blocks can be nested This applies to combinations of DO UNTIL DOWHILE FOR IF WHILE and SELECT The depth of nesting depends on the build of smart BASIC but in general nesting up to 16 levels is allowed and can be modified using the AT CFG command DO UNTIL This DO UNTIL construct allows a block of one
455. variable argn byVal TYPE A description with type of the variable Interactive Command Whether the command can be run in Interactive Mode using the token Examples Examples using the command Note Always consult the release notes for a particular firmware release when using this manual Due to continual firmware development there may be limitations or known bugs in some commands that cause them to differ from the descriptions given in the following chapters Variables One of the important rules is that variables used within an application MUST be declared before they are referenced within the application In most cases the best place is at the start of the application Declaring a variable can be thought of as reserving a portion of memory for it smart BASIC does not support forward declarations If an application references a variable that has not been declared the parser reports an ERROR and aborts the compilation Variables are characterised by two attributes Variable Scope a Variable Class DIM The Declare statement is used to declare a number of variables of assorted types to be defined in a single statement Americas 1 800 492 2320 Option 2 51 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual If it is used within a FUNCTION or SUB block of code then those variables will only have local sco
456. ved across power cycles For example passwords Using the Module s Flash File System All smartBASIC modules hold data and application files in a simple flash file system which was developed by Laird and has some similarity to a DOS file system Unlike DOS it consists of a single directory in which all of the Tiles are stored Note When files are deleted from the flash file system the flash memory used by that file is not released Therefore repeated downloads and deletions eventually Till the file system requiring it to be completely emptied using the AT amp F1 command The command AT 6 returns statistics related to the flash file system when in interactive mode From within a smartBASIC application the function SYSINFO x where x is 601 to 606 inclusive returns similar information Note Non volatile records are stored in a special flash segment that is capable of coping with cases where there is no free unwritten flash but there are many deleted records Americas 1 800 492 2320 Option 2 11 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual 2 GETTING STARTED This chapter is a quick start guide for using smartBASIC to program an application It shows the key elements of the BASIC language as implemented in the module and guides you through using UWTerminal a Laird Terminal Emulation utility available for
457. ven paradigm Typically do something only when something happens This smartBASIC implementation has been designed trom the outset to feed events into the user application to facilitate that architecture and while waiting for events the module is designed to remain in the lowest power state smartBASIC uses a single pass compiler which can be extremely efficient in systems with limited memory They are called single pass as the source application is only passed through the parser line by line once That means that it has no knowledge of any line which it has not yet encountered and it forgets any previous line as soon as the first character of the next line arrives The implication is that variables and subroutines need to be placed in position before they are first referenced by any function which dictates the structure of a typical application In practice this results in the following structure for most applications Opening Comments Any initial text comments to help document the application Includes The cross compiler which is automatically invoked by UWTerminal allows the use of DEFINE and INCLUDE directives to bring in additional source files and data elements Variable Declarations Declare any global variables Local variables can be declared within subroutines and functions Americas 1 800 492 2320 Option 2 28 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech
458. vents EVNOTIFYBUF When in a connection and attribute data is sent to the GATT Client using a notify procedure for example using the function BleCharValueNotify or when a Write_with_no_response is sent by the Gatt Client to a remote server they are stored in temporary buffers in the underlying stack There is finite number of these temporary buffers and if they are exhausted the notify function or the write_with_no_resp command will fail with a result code of 0x6803 BLE_NO_TX_BUFFERS Once the attribute data is transmitted over the air given there are no acknowledges for Notify messages the buffer is freed to be reused This event is thrown when at least one buffer has been freed and so the smartBASIC application can handle this event to retrigger the data pump for sending data using notifies or writes_with_no_resp commands Note that when sending data using Indications this event is not thrown because those messages have to be confirmed by the client which will result in a EVCHARHVC message to the smartBASIC application Likewise writes which are acknowledged also do not consume these buffers Example EvNotifyBuf sb See in BL600CodeSnippets zip DIOM A har te paces COnlmall med y imal ike di Americas 1 800 492 2320 Option 2 202 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual FUNCTION Omstar tuo DIUM Tee
459. w block uninitialized Then the byte is overwritten If the nindex is such that the new string length exceeds the maximum attribute length this function fails The maximum length of an attribute as implemented can be obtained using the function SYSINFO n where n is 2013 The Bluetooth specification allows a length between 1 and 512 BleEncodeSTRING attr nIndex1 str nlndex2 nLen Returns INTEGER a result code The typical value is OxO000 indicating a successful operation Arguments attr byRef atir AS STRING This argument is the string that will be written to an attribute nindex 1 byVal nindex7 AS INTEGER This is the zero based index into the string attr where the new fragment of data is written If the string attr is not long enough to accommodate the index plus the length of the fragment it is extended If the new length exceeds the maximum allowable length of an attribute see SYSINFO 2013 this function fails str byRef str AS STRING This contains the source data which is qualified by the nlndex2 and nLen arguments that follow nindex2 byVal nindex2 AS INTEGER This is the zero based index into the string str from which data is copied No data is copied if this is negative or greater than the string nlen byVal nLen AS INTEGER This species the number of bytes from offset nindex2 to be copied into the destination string It is clipped to the number of bytes left to copy after the index Interactive Command NO Ex
460. w lairdtech com bluetooth smart BASIC User Manual j7 Mnitiealise and instantiate service Characteristic Start adverts Sub OnStarctup DIEM er a a a e e a E ateo DIM charMet charMet BleAttrMetaData 1 1 20 0 rc AC omna e ove Wile aande No veu rc BleSvcCommit 1 Blebandlevuidls 0x18EE hSvc initialise char read write enabled accept signed writes rc BleCharNew 0x4A BleHandleUuidl16 1 charMet 0 0 Add another descriptor eee CeSCKe we lline rc BleCharDescAdd 0x2999 attrS BleAttrMetadata 1 1 20 0 rc commit char initialised above with initial value hi to service hMyChar attr2S char value rco BleCharCommit Sve attr29 nMyChar re PleAdyvRotINit adRors 0x02 0 20 rc BleScanRptInit scRpt get UUID handle for other descriptor hotherDscr BleHandleUuidl6 0x2905 Add hSvc hMyChar and the other descriptor to the advert report ie BlehdvEpeNddUund iG adheres None WOenexDececm hi ly il Oo Pile Nayihor NecUmueiG Sekiors MO Meta D ce tan la ale lee alley commit reports to GATT table adRpt is empty rc BleAdvRptsCommit adRpt scRpts rc BleAdvertStart 0 addrS 20 300000 0 e Goro RamMa bare mn eA 16 1 7 Channel bind to low EranctiLon on PO pin 6 ENDSUB SUB CloseConnections rc BleDisconnect conHnd1 rc BleAdvertStop rc GpioUnbindEvent 1 ENDSUB FUNCTION Hides levisg BYVAL nMsgIld BYVAL mix conHndl nCtx IF nMsgID
461. whether the port is already open or how many bytes are waiting in the receive buffer to be read UARTINFO infold Function Returns INTEGER The value associated with the type of uart information requested Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments infold byVal infold AS INTEGER This specifies the type of uart information requested as follows if the uart is open O 1 the port is open O the port is closed And the following specify the type of uart information when the port is open 1 Receive ring buffer capacity 2 Transmit ring buffer capacity 3 Number of bytes waiting to be read from receive ring buffer 4 Free space available in transmit ring buffer 5 Number of bytes still waiting to be sent in transmit buffer 6 Total number of bytes waiting in rx and tx buffer If the uart is closed then regardless of the value of nfo d a O will be returned Note UARTINFO O will always return the open close state of the uart Interactive Command No Related Commands UARTOPEN UARTCLOSE UARTWRITE UARTREAD UARTREADMATCH UARTGETDSR UARTGETCTS UARTGETDCD UARTGETRI UARTSETDTR UARTSETRTS VARTSETDCD UARTSETRI VARTBREAK UARTFLUSH Example UartInfo sb See in BL600CodeSnippets zip DIM LC STALT UartClose IF UartInfo 0 0 THEN PRINT nThe Uart port was closed n ELSE PRINT nThe Uart port was not closed n JEND IE JE PRINT nReceive ring buffer capacity
462. which position the offset is to be calculated It shall be 1 to specify from the current position 2 from the end of the while and then for all other values from the beginning of the Tile When the start position is end of file then a positive offset value is used to calculate backwards from the end of file Hence supplying a negative value has no meaning Interactive Command NO Americas 1 800 492 2320 Option 2 172 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual See the full and detailed example in the FOPEN section FSEEK is a core language function Non Volatile Memory Management Routines These commands provide access to the non volatile memory of the module and provide the ability to use non volatile storage for individual records NvRecordGet FUNCTION NVRECORDGET reads the value of a user record as a string from non volatile memory NVRECORDGET recnum strvar Returns INTEGER the number of bytes that were read into strvar A negative value is returned if an error was encountered 1 Recnum is not in valid range or is unrecognised 2 Failed to determine the size of the record Ee The raw record is less than 2 bytes long possible flash corruption 4 Insufficient RAM 5 Failed to read the data record Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments re
463. which the 128 bit uuid AD record is to be added nUuidHandle byVal nUuldHandle AS INTEGER This is handle to a 128 bit uuid which was obtained using say the function BleHandleUuid128 or some other function which returns one like BleVSpOpen Interactive Command NO Example BleAdvAddUuid128 sb See in BL600CodeSnippets zip DIM ES r eC RPE achilles cle Gus a aad scRpts W PRINT Blescanhobinib sehen Open the VSP PRINT BleVspOpen 126 126 07 hnd Advertise the VSPservice in a scan report PRINT BleAdvRptAddUuidl128 scRpt hnd1l adRpt W PRINT BleAdvRousCommib adRors SORE addr because we are not doing a DIRECT advert PRINT BleAGvereStart 0 addrs 20 30000 0 Expected Output 00000 BLEADVRPTADDUUID128 is an extension function Americas 1 800 492 2320 Option 2 214 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleAdvRptAppendAD FUNCTION This function adds an arbitrary AD Advertising record field to the advert report An AD element consists of a LEN TAG DATA construct where TAG can be any value from O to 255 and DATA is a sequence of octets BLEADVRPTAPPENDAD advRpt nTag stData Returns INTEGER a result code The most typical value is 0x0000 indicating a successful operation Arguments Aadvkot byRef AdvAot AS STRING The advert report onto which the AD recor
464. writes new data into the VALUE attribute of a Characteristic so that it can be sent as a notification to the GATT client The characteristic is identified by a composite handle that was returned by the function BleCharCommit A notification does not result in an acknowledgement trom the client BLECHARVALUENOTIFY charHandle attr Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation Americas 1 800 492 2320 Option 2 258 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Arguments charHandle byVal charHandle AS INTEGER This is the handle to the characteristic whose value must be updated which was returned when BleCharCommit was called attr byRef attr AS STRING String variable containing new value to write to the characteristic and then send as a notification to the client If there is no connection this function fails with an appropriate result code Interactive Command NO Example BleCharValueNotify sb See in BL600CodeSnippets zip DIM NMC har ra awo Combine ll DUNGIIONPOnskakeup DiMisc SiC eclectic pCO ms cd a euler ati i DiM maCccod m cced bleAttrMetaditall il 20 J CCCD meta da ea oreha Commute Sve with handles hsovevuid rce BleSvcCommit 1 BleHandleUuidl6 Ox18EE hSvc initialise char write read enabled accept signed writes
465. x IF nMsgID 1 THEN PRINT n n Disconnected EXITFUNG 0 ELSEIF nMsgID 0 THEN PRINT n Connected so scan remote Gatt Table for ALL services uHndS BleHandleUuidl6 OxDEAD uuo FIZZ 3 3445560 coor EPCCh DEERE ROOT uus StrDehexizes uus unce BleHandlevuidl28 uus pis 2 BOE S S67 Ts SOM NC CIDE Ea OO wus StrDenexizes uus uHndD BleHandleUuidl28 uuSs sIdx 2 cldx l didz 1 handle will be 37 ce PleGatectimebDesc contndl Ume sildx ulmde cladx UMED didx IF rc 0 THEN BleDiscCharFirst will exit with 0 when operation is complete WALITEVENT SBME a sI dx 1 cIdx 3 didx 4 does not exist re BleGarcerindDesc conne unnes src unne crek dam Wr d lesz IF rc 0 THEN BleDiscCharFirst will exit with 0 when operation is complete WALTEVENT ENDIF CloseConnections ENIDE ENDFUNC 1 tunction Handlecraindbese chHmdil hndi as Integer Prine 4 ole SIND Biase Prints chmdil ching Dimi ele crincl fae IF hndl 0 THEN PRINTE AnDId NOT ind the descriptor E PRINT nFound the descriptor at handle hndl PRINT nove Ikebe ecules lnictiawmileh lt Wrenches i siclevcve a dT Americas 1 800 492 2320 Option 2 293 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual END E endfunc 0 asessasassassaasassssssesssas esas sas sa sess sas asaasssasssassessss
466. xtracted from the attribute string Can be less than the size expected if the nindex parameter is positioned towards the end of the string Americas 1 800 492 2320 Option 2 332 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Arguments attr byRef attr AS STRING This references the attribute string from which the function reads nindex byVal nindex AS INTEGER This is the zero based index into string attr from which data is read dst byRef dst AS STRING This argument is a reference to a string that will be updated with up to nMaxBytes of data from the index specified A shorter string will be returned if there are not enough bytes beyond the index nMaxBytes byVal nMaxBytes AS INTEGER This specifies the maximum number of bytes to read from attr Interactive Command NO Example BleDecodeString sb See in BL600CodeSnippets zip DIM chrHandle vie syechandike ro So decot DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc 7 ABCDEEGHIJ DIN e 89 eyeiere S aa ARIS AG a ae AC AN DIM uuid 3 uuid 0x1853 rc BleSvcCommit 1 BleHandleUuidl6 uuid svcHandle rc BleCharNew 0x07 BleHandleUuidl16 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle rc BleCharValueRead chrHandle attr read max 4 bytes from index 3 in the string rc BleDecodeSTRING attrs 3 decStr 4 PRINT And C decori
467. y complex examples which demonstrate complete applications For those with programming experience smartBASIC is easy to use because it is derived from BASIC language BASIC which stands for Beginners All Purpose Symbolic Instruction Code was developed in the early 1960s as a tool for teaching computer programming to undergraduates at Dartmouth College in the United States From the early 70s to the mid 80s BASIC in various forms was one of the most popular programming languages and the only user programming language in the first IBM PC to be sold in the early 80s Prior to that the first Apple computers were also deployed with BASIC Both BASIC and smartBASIC are interpreted languages but in the interest of run time speed on an embedded platform which has limited resources s martBASIC s program text is parsed and saved as bytecodes which are subsequently interpreted by the run time engine to execute the application On the BL600 module platform the parsing from code test to bytecode is done on a Windows PC using a Tree cross compiler Other platforms with more firmware code space also offer on board compiling capabilities The early BASIC implementations were based on source code statements which because they were line numbered resulted in non structured applications that liberally used GOTO statements At the outset sartBASIC was developed by Laird to offer structured programming constructs It is not line number based and it o
468. y have just 2 bytes which are treated as 16 bit integers This is reflected in smartBASIC applications so that INTEGER variables are used to manipulate those values instead of STRINGS BleEncode8 FUNCTION This function overwrites a single byte in a string at a specified offset If the string is not long enough then it will be extended with the new extended block uninitialized and then the byte specified is overwritten If the nindex is such that the new string length exceeds the maximum attribute length this function fails The maximum attribute length can be obtained using the function SYSINFO n where n is 2013 The Bluetooth specification allows a length between 1 and 512 BLEENCODES attr nData nlndex Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation Arguments attr byRef atir AS STRING This argument is the string that will be written to an attribute nData byVal nData AS INTEGER The least significant byte of this integer is saved The rest is ignored nindex byVal nindex AS INTEGER This is the zero based index into the string attr where the new fragment of data is written to If the string attr is not long enough to accommodate the index plus the length of the fragment it is extended If the extended length exceeds the maximum allowable length of an attribute see SYSINFO 2013 this function fails Americas 1 800 492 2320 Option 2 310 Laird Technologies Europe 44 162
469. y limited to use in the prototyping and debugging phases Once in Interactive Mode the command RESUME is used to restart the application from the next statement after the STOP statement Interactive Command NO Example Stop sb See in BL600CodeSnippets zip DIM i ss a 100 Note SPRINT replaces the content of s with exprlist each time it is used SPRINT sS a So DOW COMmea lms 100 PRINT wales vn SPRINT s INTEGER H a 7 So Mow Conta ms 164 SLOP PRINTE a SPRINT tso INTEGER O a eo Mow Contains 144 PRINT see ia SPRINT sS INTEGER B a M So now Contains LO no0 PRINT esse a Americas 1 800 492 2320 Option 2 73 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output 100 O1 0702 resume 00000064 00000000144 NNANANANANANANANNNANANANNANANAN0N0O0000001100100 STOP is a core function BP COMMAND The BP Breakpoint statement is used to place a BREAKPOINT in the body of an application The integer constant that is associated with each breakpoint is a developer supplied identifier which gets echoed to the standard output when that breakpoint is encountered This allows the application developer to locate which breakpoint resulted in the output Execution of the application is then paused and operation passed back to Interactive mode BP nnnn After execution is returned to
470. yRef atir AS STRING This argument is the string that will be written to an attribute Americas 1 800 492 2320 Option 2 311 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual nData byVal nData AS INTEGER The two least significant bytes of this integer is saved The rest Is ignored nindex byVal nindex AS INTEGER This is the zero based index into the string attr where the new fragment of data is written If the string attr is not long enough to accommodate the index plus the length of the fragment it is extended If the extended length exceeds the maximum allowable length of an attribute see SYSINFO 2013 this function fails Interactive Command NO Example BleEncodel6 sb See in BL600CodeSnippets zip DIM ec pe al e Geer o hema PRINT Y narctr S atte lwrite CD to index 2 re Bp lebhncode 6 akbro 0x444377 jjweite AB to andex 0 2222 will be Ignored rc BleEncodel6 attrS 0x22224241 0 write EF to index 3 rce Blebncodelb attro 0x1645 4 PRINT VAnarcctiS now YrattrS Expected Output attrs Laird attr now ABCDEF BLEENCODE16 is an extension function BleEncode24 FUNCTION This function overwrites three bytes in a string at a specified offset If the string is not long enough then it will be extended with the new extended block uninitialized and then the bytes sp
471. ytes from index 6 rc BleDecodeS 24 attr vl1 6 PRINT Andata in Hex 0x INTEGER H vl PRINT ndata in Decimal eae ia Expected Output BLEDECODES24 is an extension function BleDecodeU24 FUNCTION This function reads three bytes from a string at a specified offset into a 32bit integer variable without sign extension If the offset points beyond the end of the string then this function fails BLEDECODEU24 attr nData nindex Returns INTEGER the number of bytes extracted from the attribute string Can be less than the size expected if the nindex parameter is positioned towards the end of the string Arguments attr byRef attr AS STRING This references the attribute string from which the function reads nData byRef nData AS INTEGER This references an integer to be updated with the 3 byte data from attr without sign extension Americas 1 800 492 2320 Option 2 326 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual nindex byVal nindex AS INTEGER This is the zero based index into the string attr from which data Is read If the string attr is not long enough to accommodate the index plus the number of bytes to read this function fails Interactive Command NO Example BleDecodeU24 sb See in BL600CodeSnippets zip DIM chrdancile vis ychandle mec DIM mdVal mdVal BleAttrMetadata 1 1 50 0
472. zero based index into the string attr where the new fragment of data Is written If the string attr is not long enough to accommodate the index plus the length of the fragment it is extended If the new length exceeds the maximum allowable length of an attribute see SYSINFO 2013 this function fails Interactive Command NO Example BleEncodeSFloatEx sb See in BL600CodeSnippets zip DIM ro mantissa erp DIM catt e ratr S 7 weipe 2 147 148 647 ac SFLOAT ro index 0 re BIleEncodeSFIlodatEX attr 21474638647 0 rc BleDecodeSFloat attr mantissa exp 0 PRINT nThe number stored is mantissa x 10 exp Expected Output i aye cokes come a Rag ap Gna cheese The number stored is 214 x 10 7 BLEENCODESFLOAT is an extension function BleEncodeSFLOAT FUNCTION This function overwrites two bytes in a string at a specified offset as short 16 bit float value If the string is not long enough it is extended with the new block uninitialized Then the byte specified is overwritten If the nindex is such that the new string length exceeds the maximum attribute length this function fails The maximum attribute length can be obtained using the function SYSINFO n where n is 2013 The Bluetooth specification allows a length between 1 and 512 BLEENCODESFLOAT attr nMatissa nExponent nindex Returns INTEGER a result code The typical value is 0x0000 indicating a successful operation Arguments attr byRef at

Download Pdf Manuals

image

Related Search

Related Contents

Androidの設定  Manual do utilizador de HyperMedia Center Conteúdo  BOSST60 SIP Phone User Manual  catalogo_residenziale  CARRY-BIKE® VOLKSWAGEN T4 D  Gardena 08877-20 cordless hedge trimmer  300 万画素 C マウントカメラ AR-D300C 取扱説明書  Panasonic TH-42PHD8EK plasma panel  Vector VEC248 User's Manual  取扱説明書  

Copyright © All rights reserved.
Failed to retrieve file