Home
smartBASIC Core Functionality
Contents
1. 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 var1 var2 Returns INTEGER The returned variable is the arithmetically smaller of varl and var2 Local Stack Frame Underflow excepncn Local Stack Frame Overflow Arguments r byVal varl AS INTEGER a The first of two variables to be compared 2 byVal var2 AS INTEGER a The second of two variables to be compared Interactive Command me Example MIN sb See in Firmware Zip file DIMESSI sl 2 s2 4 PRINT 1 62 PRINT nThe Minimum of these two integers is MIN s1 8s2 Expected Output Embedded Wireless Solutions Support Center 84 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual lt 2 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 strings 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 LEFTS FUNCTION Retrie
2. STRSETBLOCK is a core function STRFILL FUNCTION STRFILL is Used to erase a string and then fill it with a number of identical characters STRFILL string nChr nCount INTEGER Represents command execution status O If successful If nChr is greater than 255 or less than O kelom 2 If the string length cannot be extended due to lack of memory 3 If the resultant string is longer than allowed or nCount is lt 0 STRING string contains the modified string Exceptions Local Stack Frame Undertlow Embedded Wireless Solutions Support Center 92 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Local Stack Frame Overflow Memory Heap Exhausted Arguments byRef string AS STRING string The target string to be filled byVal nChr AS INTEGER nChr 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 nChr to be added Interactive Command Di 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 fu
3. 5 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 found in your module s extention manual 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 Embedded Wireless Solutions Support Center 48 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 newsitrS LEFTS oldstringS 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 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 ona line Like a function it may affect the va
4. 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 Insert a Tab before the next variable Print the next variable without a space Example Print sb See in Firmware Zip file PRINT Hello an DIM a a 100 ERTEN PRINT nTn Hes YOT TNTECER be 100 ne PRL Ta Ota a ANTEC ER ei OO nn Embedded Wireless Solutions Support Center 72 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual PERIE STA Pinan OM INU Er a ale GM aay Expected Output In Hex 0x00000064 In Octal 00000000144 In Binary 00000000000000000000000001100100 PRINT is a core function 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 exprlist Arguments Stringvar A pre declared string variable Exprlist
5. Returns If the filename is valid AT FOW responds with nOO r Arguments filename string_constart 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 Interactive Y Command This is an Interactive Mode command and MUST be terminated by a carriage return for it to be processed Examples AT FOW myapp AI FOW is a core command AT FWR COMMAND AI 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 files 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 resoond 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 fo the file Interactive Yes Embedded Wireless Solutions Support Center 4 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Command This is an Interactive Mode command and MUST be terminated by a carriage return for it to be processed Ex
6. out ton l to event 2 Leo aprobinda ne a 11 1 oond Golo amp rencteron ow On volo Go OU eto 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 FUNCELON onevent evgpiochan2 call Btnilrel detects when button 1 is released and calls the function onevent evgpiochan3 call Btnlpress detects when button 1 is pressed and calls the Lon elon PRINT gt nWarcing for an event n WAITEVENT wair ror an event tO OCCULE PRINT nGot here because evgpiochan2 happened Expected Output Waiting for an event Button has been pressed EuUCton released Resume waiting for an event Button has been pressed Button released No more waiting for events Got here because evgpiochan3 happened 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 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 Interactive Yes Command Formatting with PRINT Expression Lists Embedded Wireless Solutions Support Center 7 Laird Technologies http ews support la
7. smart BASIC Core Functionality User Manual Note To preserve memory smart BASIC only allocates memory to string variables when they are first used and not when they are declared If foo many variables and strings are declared in 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 ONERROR 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 Firmware Zip file DIM nCmds AS INTEGER DIM seCmds 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 SieemeoalOl viele Ih arn SeOme cil ac oile2 ae ae Sieemesite ake 0 lh wre se mae ee 02 1 are SeOme saree
8. Local Stack Frame Underflow Local Stack Frame Overflow Arguments varld byVal varld 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 Each platform type has a unique identifier 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 Soace 602 Flash File System Data Segment Free Space 603 Flash File System Data Segment Deleted Space 611 Flash File System FAT Segment Total Soace 612 Flash File System FAT Segment Free Space 613 Flash File System FAT Segment Deleted Space 631 NvRecord Memory Store Segment Total Soace 632 NvRecord Memory Store Segment Free Space 633 NvRecord Memory Store Segment Deleted Space 64 Contig Keys Store Segment Total Soace 642 Config Keys Store Segment Free Space 643 Config Keys 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 Embedded Wireless Solutions Support Center i Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kon
9. 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 Siring variables are formatted in the following form lt type minchar gt strexpr 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 soaces 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 Example SPrint sb See in Firmware Zip file DIM a sS a 100 Note SPRINT replaces the content of SS with exprlist each time it is used SPRINT sS a 735 ROW COne aims 00 Pea gies emt SPRING kso INTEGER H a Ss HOw Contains o4 ERINES An SPRINT tso INTEGER a Se Now Contain AA PRENTE o ae SPRINT 39 INTEGER B a oS new Contains 1O00 PRINE 597 a Expected Output 100 00000064 00000000144 OODD0000000000000000000001100100 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
10. TM Laird smartBASI IC Core Funtionality User Guide Version 2 1 r0O global local 7 Americas 1 800 492 2320 Europe 44 1628 858 940 Hong Kong 852 2268 6567 x026 Embedded Wireless Solutions Support Center http ews support lairdtech com www lairdtech com bluetooth smart BASIC Core Functionality User Manual 2014 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 Merc
11. byRef intValue AS STRING The leftmost set of tokens constituting a legal integer value Is intValue j extracted from the sentence and will be removed from the sentence Interactive NO Command Embedded Wireless Solutions Support Center 106 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality 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 Example ExtractIntToken sb See in Firmware Zip file DIM sentence S DIM intyalue bytes DIM tokenS tknlen sentenceS 0x100 is a hex value PRINT nSentence is sentences bytes Extract IneToken Sentences imt Value PRINT AnincValue bytes bytes 2 intVvalue DO tknlen ExtractStrToken sentenceS tokenS PRINT aloken len tkmilen n 3 okan UNTIL tknlen 0 Expected Output Sentence is 0x100 is a hex value intValue bytes 5 256 Token 2 Token 1 Token 3 Token i Token 5 Token O EXTRACTINTTOKEN is a core function 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
12. eco S late SEemecapo ooo 4 an Seomes 6 A han ae nCmds 6 Print the 7 elements above in order DIM a AS INTEGER for 1 0 to necmds step 1 print si mdoli next Expected Output Embedded Wireless Solutions Support Center 54 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual ATSO 1 ATS512 4 ATS501 ATS502 1 ATS503 1 ATS504 1 AT amp W General Comments on Variables Variable Names begin with A to Z or _ and can have any combination of A to Z 0 to 9 and _ Note Variable names are not case sensitive for example fest and TEST 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 stringo AS STRING DIM orri the at the end of the name implies a string so AS STRING not necessary DIM templ AS INTEGER DIM alarmstate jf DO ae ee or he Mame imolies an ineegerc so AS INTEGER not necessary DIM array 10 AS STRING Constants Numeric Constants Numeric Constants can be defined in decimal hexadecimal octal or binary using the following nomenclature Decima
13. 8 GpioWrite 13 1 PRINT nDate at Location Ox01L384 ts Stehexizes cds SpiClose h Exoected Output Writing to location Ox1s0 O20180DEADBEEFBAADCODE Data at location Ox0180 is QJOOQOQQODEADBEERFBAADCODE Data at location 0x0180 ts DEADBEEF Data at location 0x0184 is BAADCODEFFFFFFFF SPIOPEN is a core subroutine 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 Eveeniion Local Stack Frame Underflow p Local Stack Frame Overflow Arguments handle byVal handle AS INTEGER Embedded Wireless Solutions Support Center Lo Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual This is the handle value that was returned when SPIOPEN was called which identifies the SPI interface to close Interactive Command NO nedeg SPICLOSE SPIREADWRITE SPIWRITE SPIREAD Commands 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 interf
14. Araumenic byVal nSlaveAdadr AS INTEGER gu This is the address of the slave in range 0 to 127 nSlaveAddr byVal nRegAddr AS INTEGER eae This is the 8 bit start register address in the addressed slave in range 0 to 255 byRef nRegValue AS INTEGER nRegAdar The 16 bit value from two registers in the addressed slave will be returned in this variable Interactive Command a Related IZCOPEN I2ZCCLOSE I2CWRITEREAD IZCWRITEREGS8 IZCWRITEREG 16 Commands I2CWRITEREG32 IZCREADREG8 IZCREADREGI6 IZCREADREG32 Example I2cReadRegl6 sb See in Firmware Zip file Please ensure that nSlaveAddr is the slave address of your I2C peripheral DIM rc handle nSlaveAddr nRegAddr nRegVal 7 7 Open 12C Peripheral rc I2cOpen 100000 0 handle IE ee tO THEN PRINT nratl ed to open 12C interlace with error code INTEGER re ELSE PRINT mi2e open success RN Dar Read value from address 0x34 nSlaveAddr 0x6of nRegAddr 0x34 rc I2cReadRegl6 nSlaveAddr nRegAddr nRegVal LIE ate ae 0 THEN PRINT nFailed to Read from slave register INTEGER H rc ELSE Embedded Wireless Solutions Support Center 151 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual PRINT nValue read from register is nRegVal ENDIF I2cClose handle close the port Expe
15. Local Stack Frame Overflow Uart has not been opened using UARTOPEN Arguments byVal bitMask AS INTEGER bitMask a l Sa This bit mask is used to choose which ring buffer to flush Embedded Wireless Solutions Support Center 141 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Bit Description O Set to flush the Rx buffer Set to flush the Tx buffer Set to flush both buffers Interactive Command NO Related UARTOPEN UARTINFO UARTCLOSE UARTWRITE UARTREAD UARTREADMATCH gs UARTGETCTS UARTGETDCD UARTGETRI UARTGETDSR UARTSETRTS UARTSETDCD ommands UARTBREAK UARTFLUSH Example UartFlushRx sb See in Firmware Zip file EUMNGWELON Shingle aiciriks lt Fimer o tart 02 0 Allow time for data to reach rx buffer ENDFUNC 1 BUNCT TON Shine i mice PRINT Uareintot3 gt byles In Che rx buller nY Var ne luck Oil lieere tex lovicie Sic PRINT User rinro s pytes Iin the rs bufi r after Flushing ENDFUNC 0 ONEVENT EVUARTRX CALL HndlxUarekx ONE VENT EVTMRO CALL HndlrTmroO PRINT msend me some textinn WALTEVENT Expected Output Send me some data Laird 6 bytes in the rx buffer O bytes in the rx buffer after flushing Example UartFlushTx sb See in Firmware Zip file DIM 3 Rello World DNCE UartWrite ss
16. 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 develooment board which has been briefly disconnected from the PC OpenPort Re opens the serial port after it has been manually closed Useful Shortcuts There are a number of shortcuts that can soeed up the use of UWTerminal Each time UWTerminal starts it asks you fo 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 l Locate and right click the UwTerminal 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 4 Edit the Target line to add the following commands Figure 8 accept com n baud bbb linemode where n is the COM port
17. ONEVENT EVUARTRX CALC HNAdAIrUartCR 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 OxOD In that case in the handler if the return value is greater than O it implies a terminated message arrived and so can be processed further UARTREADMATCH strMsg chr INTEGER Indicates the presence of the match character in strMsg as follows Returns 0 Data may have been appended to the string but no matching character Embedded Wireless Solutions Support Center 139 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 strmMsg 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
18. Token Token Token gt OUr e CT TN oe a ExtractStrloken 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 parameter The tokens are removed from the sentence The function will return the number of characters extracted from the left side of 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 will result in hex then and then value 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 is taken as a comment just like the behavior in the command mode EXTRACTINTTOKEN sentence S intValue FUNCTION etum INTEGER The length of the extracted token Will be O of there are no more tokens to extract Bvecoiions Local Stack Frame Undertlow Local Stack Frame Overflow Arguments byRef sentenceS AS STRING sentenceS String that contains the sentence containing the tokens to be extracted
19. follow these steps 1 Open Notepad 2 Enter the following text print nHello World n 3 Save the file with single line festl sb Note the following smart BASIC 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 first file so will be downloaded as this and so will this is my second file so 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 Zautorun 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 smart BASIC 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 code easier They are included in your application using the include statement which is is described later in this manual Embedded Wireless Solutions Support Center 19 Laird Technologies http ews
20. fopen fname r IF handle O0 THEN j daetermine the Size of the file flen filelen handle prints ihe file is T rilen O bytes long get the current position in the file should be 0 rc tLlell handle pes Prine A nC urrente PpostElon as pos read the first 11 bytes from the file frlen fread handle dataS 11 prints Dara throm miles iow acdakac get the current position in the file should be 11 re ftell handle fpos Print MAn Current poolon iis yo poS reposition the file pointer to 6 so that we can read 5 bytes again rc fseek handle 6 0 gee the current position in the file re ftell handle fpos read 5 bytes Embedded Wireless Solutions Support Center 168 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual frlen fread handle dataS S 5 print Mobat from tile 1s gt datas reposition EO Ene Stank on Tas re fseek handle 19 0 I read until a wl is encountered w ascii 0x77 frlen freaduntil handle dataS 0x77 32 print nbata from file as gt datas j timelly close the file which on exit will set the handle to 0 fclose handle ELSE print nrarled to open file fname ENDIF Exoected Output The file is 59 bytes long Current position is 0 Data from file is Hello World Current position i
21. is taken as a comment just like the behavior in the command mode EXTRACTSTRTOKEN sentenceS tokenS FUNCTION INTEGER Returns The length of the extracted token Will be O of there are no more tokens to extract Exceptions Local Stack Frame Underflow p Local Stack Frame Overflow Arguments byRef sentenceS AS STRING sentenceS a String that contains the sentence containing the tokens to be extracted byRef tokenS AS STRING tokenS The leftmost token from the sentence and will have been removed from the sentence Interactive Command me 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 Example ExtractStrToken sb See in Firmware Zip file DIM sentences tokenS tknlen sentenceS My name is BL600 from Pard PRINT nSentence is sentences DO tknlen ExtractStrToken sentenceS tokenS PRAE a teken sGheniu ielkmllene ne deel UNTIL tknlen Expected Output Embedded Wireless Solutions Support Center 105 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Sentence is My name is BL600 from Token len My Token i name Token rig Token gt BL6OO oy Tr roOMm hair Token
22. memory by printing the return value from the function directly without the use of a variable Example ResultCodes sb See in Firmware Zip file DIM cB nlteme roS rc CircBufItems cB nI Items PRINT INTEGER Ho re PRENTE A att Mew line j Printing return value directly PRINT INTEGER H Carehurhremns cB mlrems To remove the leading zeros SPRINT Foo INTEGER BH CircBurtitems cB niltems Strout eheore s Aaa ERENT oo Now highlight the last 4 characters of the result code in Uwlerminal and select Lookup Selected ErrorCode Terminal BASIC Contig About CTS DSAM OCD RI ATS DTR BREAKI LocalEcho LineModel Clear ClosePort Compile XCompile Load ACompile Load Run Lookup Selected ErrorCode Compile Load i Piman lma Exoected Output smartBASIC Error Code 073D gt RUN INV CIRCBUF HANDLE Embedded Wireless Solutions Support Center 77 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 valu
23. nUart Port was closed END Exoected Output baira Data in at least one buffer Uart Port not closed UARTCLOSEEX is a core function UARTInfo FUNCTION This function is used to query information about the default uart such as buffer lengths whether the port is already open or how many bytes are waiting in the receive buffer to be read UARTINFO infold Returns INTEGER The value associated with the type of uart information requested Exceptions Local Stack Frame Underflow is Local Stack Frame Overtlow Arguments byVal infold AS INTEGER This soecifies the type of UART information requested as follows if the UART is open 0 1 The port is open 0 The port is closed infold The following specify the type of uart information when the port is open 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 Embedded Wireless Solutions Support Center 134 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual If the UART is closed O is always returned regardless of the value of infold Note UARTINFO O always returns the open close state of the UART
24. 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 Embedded Wireless Solutions Support Center 24 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 World 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 HelloWorld sb to the module using XCompile Load in UwTerminal and then run the application in the usual way AT RUN helloworld The following output displays If you now change the print statement in the application to onetime Re he Wore lich 2 pag ia The n forces a new line each time the following output displays Or OO Sh GT cs Oo DOr e If you run AT DIR you will see that both of these programs are now loaded in memory They remain there until you remove them with AT DEL testl HelloWorld Embedded Wireless Solutions Support Center 2
25. type bus consisting of two lines which normally sit at 5 or 3 3v Some modules 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 Please refer to the specific user manual for clarification 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 hittp www 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 This function is used to open the main I2C peripheral using the parameters specified See the module reference manual for details of which pins expose the SCL and SDA functions I2COPEN nClockHz nCfgFlags nHande INTEGER Indicates success of command O Opened successfully 0x5200 Driver not found ee Ox5207 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 specified pins
26. 0 5 0 V7 KOR 4854197 50 510 PRINT StexoOr numeers 0 5 10 lif MOR 48 497 50 55 10 PRINT StexoOR numbers 05 1000 OR A ACS 0 ll ey 2 NOLO Expected Output aa 62 988 STRXOR is a core function EXTRACTSTRIOKEN This function takes a sentence in the first parameter and extracts the leftmost string token from it and passes it back in the second parameter The token Is removed from the sentence and is not Embedded Wireless Solutions Support Center 104 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 If easy to create custom protocol for commands send by a host over the vart for your application For example if fhe 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 alohabet 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
27. AAE EE EN E E E 50 BC OS PE E A N EA EA E E A EE E E E E E E EE 50 Language I II IN scarcer cat tare ete wi feasts E E E E A E TE EA EAE 51 CONA aa A EA T A A E E E E AE E 51 E E E tastwaenneekaaanbsmmaranensebeasne cunteaqeraeeaenemicaonmaumnnsniecanmneeanaunt 51 CONS AE o A E E A A E 55 Compiler Related Commands and Directives cccccsssscccccesssececcseseccceceeeeceeseesecessauaeecesseansecessaeaecessueuseeessagasess 56 ARAME ERP S OS rir E E T ene ee E E E E E 58 COn a E E AE E E A E 60 Sarea ea E a E A E E EET EAA A E AE A A E E E E A EA 67 Event Handling serari ieii r DN GE E A TN E N E EEA 68 Miscellaneous CommandsS ceeccceesccceecsceuccccusceeececeucseeueseeesseuucsueucseeueeseuecseeuceeeuesesseseuecseeuceeeueeeeueseeeuseeeueeeensess 71 6 Core Language Built in ROUTINGS cccccececeeseeecececececeeseaecececataeseseaeercusateesestanareusataesesearers 77 RE SUE COGS EE TEE S EE TO AA TEE A PE T A E E T E A A A T TE T 77 information ROUTINES soiien fa steele Sn Pe re st at EEEE E AAE E ae eee ee 78 Event amp Messaging ROUTINES ccccecccssscccsscccseeecsecenseeeseeeeseeeeseeeeseeeeseeeeeseeeeseeeesseeessaseesasceseueessuseseuesesasessuseseagess 81 Arithmetic Routines cccccecccsescceecceecceuceenceeeeceeuceeneseeuseeuceeeseeeseenseeueseuseeuseeeeseeuseeuseeeeseeuseeueeeeseeeteseeeeseenseaness 83 SUNE ROUMO Saeson e a E AE E E E E 85 TAE ROUE aa A E E E O 107 Miscellaneous ci 1114 2 Cee ena een
28. AS INTEGER This is the 8 bit start register address in the addressed slave in range 0 to 255 byRef nRegValue AS INTEGER nRegValue The 32 bit value from four registers in the addressed slave will be returned in this variable Interactive Command Ne Related Commands 2C OPEN I2ZC CLOSE I2CWRITEREADS IZCWRITEREGS IZCWRITEREG 16 Embedded Wireless Solutions Support Center 153 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual IZCWRITEREG32 IZCREADREG8 I2ZCREADREGI6 IZCREADREG32 Example I2cReadREG32 sb See in Firmware Zip file Please ensure that nSlaveAddr is the slave address of your I2C peripheral DIM handle DIM nSlaveAddr nRegAddr nRegVal DIM ro e I2cOpen 100000 OF hamdike IP cels 0 THEN PRINT A nFailed to open 120 interlace with error code INTEGER hh re ELSE PRINT nI2C open success RANDLE Read value from address 0x56 nSlaveAddr Ox6f mnRegAddr 0x56 re I 2cReadReg32 nSlaveAddr nRegAddr nRegVal IF cels 0 THEN PRINT nFailed to read from slave register ELSE PRINT nValue read from register is nRegVal ENDL I2cClose handle close the port Expected Output I2C open success Value read from register is 1108410076 IPCREADREG 16 Is a core function I2cWriteRead SUBROUTINE This func
29. Evesntions Local Stack Frame Underflow p Local Stack Frame Overflow Arguments nClockHz byVal nClockHz AS INTEGER This is the clock frequency to use See module specific documentation for valid Embedded Wireless Solutions Support Center 145 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual frequencies 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 nCfaFl O If set then a 500 microsecond low pulse will NOT be sent on open This low ad pulse is used to create a start and stop condition on the bus so that 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 3 Unused and MUST be set to 0 byRef nHandle AS INTEGER nHandle 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 IZCCLOSE IZCWRITEREAD IZCWRITEREG8 IZCWRITEREG 16 IZCWRITEREG372 Commands 2CREADREG8 I2CREADREG16 IZCREADREG32 Example I2cOpen sb See in Firmware Zip file DIM handle DIM re ro T copen 100000 0 h
30. Functionality User Manual Function FSEEK is provided to move that file pointer to an offset 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 filenameS modeS INTEGER A non zero integer representing an opaque handle to the file that was opened If RCIUInS the file failed to open for example because the mode specified writing to the file which is not allowed on certain platforms then the returned value will be 0 Arguments filenames BYREF filenameS AS STRING This string specifies the name of the file to open BYVAL modeS AS STRING modes Must always be set tor This string specifies the mode in which the file should be opened and for this module as only reading is allowed must always be specified as r Interactive Command ba Example FilelIo sb See in Firmware Zip file a First download a file into the module by submitting the following commands manually wait for a 00 response after each command Ve jy at fow myfile dat 77 attfwr Hello a arrive T Milena leebae V a attiwe This 1s something e Ab tEwe in a file whieh we can read 7 attfcl fae You can check you have the file in the file system by submitting the command AT DIR and you should see myfile dat listed ae DIM handle inames Phen elen dates tpos rc fnamesS myfile dat handle
31. 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 Embedded Wireless Solutions Support Center 8 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Arguments msgid byVal msgid AS INTEGER Will be presented to the EVMSGAPP handler in the msgid field msgCtx byVal msgCtx AS INTEGER Will be presented to the EVMSGAPP handler in the msgCtx field Interactive No Command Example SendMsgApp sb See in Firmware Zip file DIME FUNCTION HandlerMsgApp BYVAL nMsgIid AS INTEGER BYVAL nMsgCtx AS INTEGER AS INTEGER PRINT nild nMsgild Cex nMsqc rx ENDFUNG 1 ONEVENT EVMSGAPP CALL HandlerMsgApp re SendMsgApp 100 200 WAITEVENT Expected Output Td 100 Ctx 200 SENDMSGAPPFP is a core function Embedded Wireless Solutions Support Center 82 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Arithmetic Routines ABS FUNCTION Returns the absolute value of its INTEGER argument A
32. Interactive NO Command UARTOPEN UARTCLOSE UARTWRITE UARTREAD UARTREADMATCH Related UARTGETDSR UARTGETCTS UARTGETDCD UARTGETRI UARTSETDTR Commands UARTSETRTS UARTSETDCD UARTSETRI UARTBREAK UARTFLUSH Example UartInfo sb See in Firmware Zip file DIMENC TS edhe UartClose IF UartiInfo 0 0 THEN PRINT the Uart port was closed 1m BLSE PRINT nThe Uart port was not closed n DAN Bee PRINT nReceive ring buffer capacity Uarte aE il PRINT AnTransemit r109 Duffer capacity Ae ane EO 2 PRINT Vane bytes waiting In transmit Duller T Vari lamin ou S start GetTickCount DO UNTIL UartInfo 5 PRINT pvalook Geelicksince octarit milliseconds for transmit Durrer to De emptied Expected Output The Uart port was closed Receive ring buffer capacity 256 Transmit ring burrer capaci cy 256 No bytes waiting in transmit buffer 134 Took 142 milliseconds for transmit buffer to be emptied UARTINFO is a core subroutine UartWrite FUNCTION This function is used to transmit a string of characters UARTWRITE strMsg INTEGER O to N Actual number of bytes successfully written to the local transmit ring buffer Returns Embedded Wireless Solutions Support Center Bote Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual
33. 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 Navigating UWTerminal Terminal BASIC Config About CTS OSR OCO Ri AT Figure 5 UWWTerminal 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 smart BASIC window Can be used to run BASIC applications locally without a device connected to the serial port Embedded Wireless Solutions Support Center 15 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 smarfBASIC application Config Configuration window Used to set up various parameters within UWTerminal About Information window that displays when you start UWWTerminal It contains command line arguments and information that can facilitate the creation of a shortcut to the application and launch the emulator directly into the terminal screen The four LED type indicators
34. Local Stack Frame Underflow E i Local Stack Frame Overflow Ae ERRA Uart has not been opened using UARTOPEN or auto opened with PRINT statement Arguments 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 strMsg 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 NO Command UARTOPEN UARTINFO UARTCLOSE UARTREAD UARTREADMATCH Related F UARTGETDSR UARTGETCTS UARTGETDCD UARTGETRI UARTSETDTR Commands UARTSETRTS UARTSETDCD UARTSETRI UARTBREAK UARTFLUSH 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 fo a temp string variable and then pass it to the function Example UartWrite sb See in Firmware Zip file DIM ro otr 1 done cd atin contains a lot Of SoOace SO Lhat We Can Sabisty the condition In the TF statement strs Hello World PUI CAIRO InlerclibieUienac EL PRINT nTx buffer is now empty ENDFUNC O exit from WAITEVENT iae Uaie ei tiheewle mao onite str If there isn t enough space
35. PROM ons Decr y oe Ok Pee PRINT nFailed to decrypt BNDIF PRINT S ninpData T otre ize o Col Pring nowrData 7 etre 2e OurDatas Embedded Wireless Solutions Support Center 166 http ews support lairdtech com www lairdtech com bluetooth Laird Technologies Americas 1 800 492 2320 Europe 44 1628 858 9 40 Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Expected Output CBC context created successfully ENCrYpt OK inData 303132333435363738393A3B3C3D3E3F outData 55EAFC8281CC28054C4AA2 687 63AFA3B BnCrype OF inData 303132333435363738393A3B3C3D3E3F outData 2A8640BD480E092B432139CF28BA2C80 ENCrYypt OR inData 303132333435363738393A3B3C3D3E3F outData A418B500A3E0AC30F18DE6AE2E923314 CBC Gontext created successfully Decrypt OR inData 55EAFC8281CC28054C4AA268763AFA3B outData 303132333435363738393A3B3C3D3E3F Decrypt OK inData 2A8640BD480E092B432139CF28BA2C80 outData 303132333435363738393A3B3C3D3E3F DSCryoc OR inData A418B500A3E0AC30F18DE6AE2E923314 outData 303132333435363738393A3B3C3D3ESF AESDECRYPT is a core language function File 1 0 Functions A portion of module s flash memory is dedicated to a file system which is used to store smartBASIC applications and user data files Due to the internal requirement set by the smarfBASIC runtime engine because applications are interpreted in situ compiled app
36. Returns The total number of bytes read from the file specified by the handle Is 0 if an invalid handle is supplied Arguments fileHandle BYVAL fileHandle AS INTEGER a The handle of a file for which the total size is to be returned Interactive Command we See the full and detailed example in the FOPEN section FILELEN is a core language function FTELL FUNCTION This function is used determine the current file 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 INTEGER Returns The total number of bytes read from the file specified by the handle Will be 0 if an invalid handle is supplied Arguments BYVAL fileHandle AS INTEGER The handle of a file for which the total size is to be returned BYREF curPosition AS INTEGER curPosition This will be Updated with the current file position for the file soecified by the fileHandle fileHandle Interactive NO Command Embedded Wireless Solutions Support Center 17 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 file specified by the handle supplied T
37. Solutions Support Center 121 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual byVal nitems AS INTEGER This soecifies the maximum number of INTEGER values that can be stored in the nltems buffer If there isn t enough free memory in the heap then this function will fail and return an appropriate result code byRef circHandle AS INTEGER circHandle _ f the circular buffer is successfully created then this variable will return a handle that should be used to interact with it Interactive No Command Example CircBufCreate sb See in Firmware Zip file DIM cLrecHancle cLecHancle 2 re re CircBufCreate 16 circHandle PRINT YAn yro IF rcec 0 THEN PRINT nthe Circular butter circhandle was Not created ENDIF re CircBufCreate 32000 circHandle2 SAP ei Ue LENS al Gane TE IF rcec 0 THEN PRINT n gt The circular buffer circHandle2 was not created FINE LIS Expected Output O 20736 gt The circular buffer circHandle2 was not created CIRCBUFCREATE is an extension function CircBufDestroy SUBROUTINE This function is used to destroy a circular buffer previously created using CircBufCreate CIRCBUFDESTROY circHandle Arguments byRef circHandle AS INTEGER circHandle A handle referencing the circular buffer that needs to
38. Uae rh lire in TO Will flush before all chars have been transmitted PRINT Vartin oO bywes In the tx Duffer after flushing Expected Output HO bytes in the tx buffer after flushing UARTFLUSH is a core subroutine Embedded Wireless Solutions Support Center 142 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 INTEGER Indicates the status of the CTS line Returns 0 CTS line is NOT asserted 1 CTS line is asserted Local Stack Frame Underflow Exceptions Local Stack Frame Overflow Uart has not been opened using UARTOPEN Arguments None Interactive Command ne Related UARTOPEN UARTINFO UARTCLOSE UARTWRITE UARTREAD UARTREADMATCH an y UARTGETDSR UARTGETDCD UARTGETRI UARTSETDTR UARTSETRTS UARTSETDCD UARTSETRI JARTBREAK UARTFLUSH Example UartGetCTS sb See in Firmware Zip file IF UartGetCTS 0 THEN PRINTE Werle line is nor asserted ELSEIF UartGetCTS 1 THEN PRIM Cus line Ls asserted ENDIE Expected Output CTS line 1s not asserted UARTGETCTS is a core subroutine UartSetRTS SUBROUTI
39. YS KK KK KK KK Kk Function anc Subroucine definitions p p E EEE EEE E KKK KR KK KK KK S DE E KK I KK E S S S DS DS I E S IK KK S DE KK E S S IK KK KK E KK KK KK TS E E E T SSSS SSS SSS SS SS SSS SSS SSS SSS SSS SSS SSS SSS SS SSS SS SSS SSS SSS SS SSS SSS SSS SSS SSS SSS SSS SS SSS SSS SS SS SSS SSS SS SSS SSS SS SSS SSS SS SSS SSS SS SSS SSS SS SSS SS SSS SSS SSS SSS SSS SSS SSS function Ol Be omit lease tbis unction is called when the ouE rom O is released gpiowrite 18 0 elas TED 0 yours print Button 0 has been released n these lines are printed to the UART when the button is released Pene ALEP 10 Noud AON efor Onc Vick aa endfunc I SSSSS SSS SS SS SS SS SS SS SS SSS SSS SS SS SSS SSS SS SSS SSS SSS SSS SSS SSS SSS SSS SSS SS SSS SSS SSS SS SSS SSS SSS SSS SS SS SS SSS SSS SS SSS SSS SS SSS SSS SS SSS SS SSS SSS SS SSS SSS SS SSS SSS SSS SSS function button0Opress Athis function is called whem Che DUtCtCON O is pressed gpiowrite 18 1 pads TED O eral print Button 0 has been pressed n these lines are printed to the UART when the button is pressed Embedded Wireless Solutions Support Center 30 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Prine hE Oval eont while bine buibon is pressed in endfung 1 tunc ion Dutronlreleasel
40. 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 Embedded Wireless Solutions Support Center 77 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality 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 0 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 INTEGER a result code The most typical value is OxO000 indicating a successful Returns operation Note See module specific user manual for details 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
41. 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 fo make them work We believe that if wireless connectivity is going to be widely accepted there must be an easier way to manage it smart BASIC 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 smart BASIC 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 smart BASIC 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 smart BASIC 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
42. any additional external processing capability Why Write Applications smart BASIC for BLE has been designed to make wireless develooment quick and simple vastly cutting down time to market There are three good reasons for writing applications in smart BASIC Since the module can auto 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 ohysical interfaces such as GPIOs ADCs I2C 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 If you already have a product with a wired communications link such as a modem you can write a smart BASIC 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 the specific user manual for the module can be modified to soeed up the development process Embedded Wireless Solutions Support Center 8 Laird Technologies http ews suppo
43. data in the receive buffer rather than transfer it to the string Local Stack Frame Underflow Exceptions Local Stack Frame Overflow Uart has not been opened using UARTOPEN Arguments byRef strMsg AS STRING strMsg The content of the receive buffer will get appended to this string up to and including the match character byVal chr AS INTEGER Chr The character to match in the receive buffer for example the carriage return character OxOD Interactive Command aa Related UARTOPEN UARTINFO UARTCLOSE UARTWRITE UARTREAD UARTGETDSR Command UARTGETCTS UARTGETDCD UARTGETRI UARTSETDTR UARTSETRTS UARTSETDCD UARTSETRI UARTBREAK UARTFLUSH 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 Example UartReadMatch sb See in Firmware Zip file DIM re ocr ee Onar cemc ret 1 FUmecETon return value char 13 ASCII decimal value for carriage return strS Your name is StrZo Wi MMerenoceharacter 9 9 ot found Ex tr ice BUNGE TO Seine emeir ise IMimerstart 0 1070 Allow time for data to reach rx buffer ENDEUNG 1 BUNGTION Hindle rmicie rc UartReadMatch strsS char PRINT n Stres IF rc 0 THEN Pe StroeecCmr Sire2o charm 1 9 inser chiar Ene Mane Character PRINT str2 StrZo Vn aMerch character Mok found Exit
44. debugging SO is a core function RESUME 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 Embedded Wireless Solutions Support Center 45 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 n0O1 tEO029 r Interactive Yes Command This is an Interactive Mode command and MUST be terminated by a carriage return for it to be processed 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 If had processed a STOP or BP statement If there is nothing to abort then i
45. ea a ee P P ae a Se aa a Bearers aa When UwTerminal downloads the app it will store it as a filenname spas att wie CoNo Ees Of all eharacrenoup ko Ene Tr oae ee and Exc kucdma We a je aera F E E E E E E E E E E teelataleoh leche lesion qe aieai saci M i Simple development board button and LED test Tests the functionality of button 0 button 1 LED O and LED 1 on the development board DVK BL600 V01 ae 24 01 2013 Inicial yas Soin id p RR KKK KKK KKK KK KK KK I KK I KK I KK I KK KK I eK KK KK IK IKK KK KK kK Kk KK KK TS KR KKK KKK KKK KK KK KKK I KK KK E DE E DEE TS E I KK KK IK KK IK KK E DEE DS E DE E KK KK KK KK KK DS yy Definicions p BKK KKK KKK KK KK KK KK I KK KK IK I KK IK E DE E IK IK IK KK I KK KK KK KK KK KK KK TAS p KR KKK KKK KKK RK KKK KK KK E DE E I KK I KK KK I KK I KK KK E DE E I KK I KK KK KK KK KK KK OK i Nei loes te o E p KR KKK KKK KKK KK RK KK I KK KK KK I KK KK IK IK IK KK I I KK KK KK kK OK KK KK TS M ase ude VS der loulis pele p KR KKK KKK KKK KR KK KK KK IK I KK I KK KK IK I KK I KK KK IK I KK IK KK KK I KK KK KK KK Kk i Global Variable Declaracions p EER EEE S DE KKK KK KK KK KK US DS DE DE DE KK USUS US DE DE DS UE DS DE VS VE KK I KK DE US DS DS DE VS DE I KK IKK S DE TS DE S VS OK E KK KK DS DS VE DS kK Kk dim re declare re as integer variable p KR KKK KKK KKK S KKK KK KK KK KK I KK KK E S DE I KK I KK E US DS TS DS S DE I KK IKK KK DE S DS
46. ee ee eS SUB WaitWrite DO GpioWrite 13 0 wro 05 00 n rdS 2 xe SpiReadWri te wrs rds GpioWrite 13 1 UNTILL StrGerehrirds 1 ENDSUB SUB EnableWrite Gorowrite 13 0 Wro 06 wdSs 3 rec SpiWrite wrs GpioWrite 13 1 ER SUB le ee ee Configure the Chip Select line using SIO13 as an output a a a re Gorosecrrume 3 2 1 ensure CS is not enabled GpPilonrite l 1 Write DEADBEEFBAADCODE 8 bytes to memory at location 0x0180 ee re ee ee ee re ee E N E ere ere eee ee ee ee ee EnableWrite weo 0201130 DE AD BE VEE BA Wap VCO DE PRON YA nurit tO Locar ton Ux 160 So Siehexi7 eo Wiss GpioWrite 13 0 rc SpiwWrite wr Embedded Wireless Solutions Support Center 158 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Govowrirte 13 1 WaitWrite ee ie ate I OP E are oy eT TT Ga tral alu en ere ea gar era een reer aa JV Read trom wriccen locacion E ENE T EE A TE E E AE E E E TA I E A E A A e STA A wieo A 01e 6000 00 00 00 00 00 00 Ce rds W GpioWrite 13 0 rc SpiReadWrite wrs rds Goi1oWrite 13 1 PRINT mbdata at Wocation 0x00 me Strhexizes rds wie 03 O e GpioWrite 13 0 rce SpiWrite wr igo ls nae rc SpiRead rd 4 ERINE abatec at location Ox01C0 is SEbPnecazes eds Edos rc SpiRead rd
47. function STRDEHEXIZES 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 STRDEHEXIZES string FUNCTION Returns STRING A dehexed version of string Local Stack Frame Underflow ExcePnon Local Stack Frame Overflow Arguments byRef string AS STRING sing The string to be converted In situ cemocrg No If a parsing error occurs a nonfatal error is generated which must be handled or the application aborts Embedded Wireless Solutions Support Center 96 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality 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 Example StrDehexizeS sb See in Firmware Zip file DIM sS s 40414243 PRINT nhex dara ss PRIN WA a Danesa zee Str Dera izes Gos AWN letop at Tics Don he Jigit Th s 4041he1104243 PRINT n s Dehexized StrDehexizes sS Expected Output Hex data 40414243 Dehexized GABC AQD4Alhello4243 Dehexized GA STRDEHEXIZE is a core function STRVALDEC FUNCTION STRVALDEC converts a string of decimal numbers into the corr
48. in the burker until siro can be writen WHILE done IF ec lt StrLen strS THEN PRIND TO byres written PRINT anScill have T Str Len sti ro l byes Co wrie n PRINT YANO hI CIng shies D Tre r heL Le aaen done 0 ELSE PRINTY no Ering eer w e ean eeel done 1 ENDIF Embedded Wireless Solutions Support Center 136 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual ENDWHILE ONEVENT EVUARTTXEMPTY CALL HndlrUartTxEty WAL TEVENT Expected Output 256 bytes written Still have 18 bytes to write pol cing tetr Dy a0 String strS written successfully Tx buffer is now empty UARTWRITE is a core subroutine UartRead FUNCTION This function is used to read the content of the receive buffer and append it fo the string variable supplied UARTREAD strMsg INTEGER Oto N The total length of the string variable not just what got Returns 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 Local Stack Frame Undertlow Exceptions Local Stack Frame Overflow Uart has not been opened using UARTOPENxxx Arguments HM byRef strMsg AS STRING i The content of the receive buffer will get appended to this string Interactive NO Command UARTOPEN UARTINFO UARTCLOSE UARTWRIT
49. 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 9 ACKNOWLEDGEMENTS The following are required acknowledgements to address our use of open source code in smartBASIC 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 3
50. is OxO000 indicating a successful Nevins operation Exceptions Local Stack Frame Underflow p Local Stack Frame Overflow Arguments f byRef stWriteS AS STRING SAES This string contains the data that must be written Interactive Command NG pele SPICLOSE SPIREADWRITE SPIWRITE SPIREAD Commands Example See SpiExample sb 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 INTEGER a result code The typical value is 0xX0000 indicating a successful Reruns operation cenhor Local Stack Frame Underflow p Local Stack Frame Overflow Arguments stRead byRef stReadS AS STRING This string will contain the data that is read from the slave keadilan byVal nReadLen AS INTEGER This soecifies the number of bytes to be read from the slave Embedded Wireless Solutions Support Center 161 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Interactive Command NG EEG SPICLOSE SPIREADWRITE SPIWRITE SPIREAD Commands Example See SpiExample sb SPIREAD is a core function Cryptographic Fun
51. is a core language function RIGHTS FUNCTION Retrieves the rightmost n characters from a string RIGHTS string len Returns STRING The rightmost segment of length len from string Local Stack Frame Underflow Exceptions Local Stack Frame Overflow Memory Heap Exhausted Arguments cing byRef sting ASSTRING aS The target string which cannot be a const sting c lenath byVal length AS INTEGER engi The rightmost number of characters that are returned lt Interactive Command 9 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 Example RIGHTS sb See in Firmware Zip file DIM sS sS Parse DIM newS newS RIGHTS 39 3 PRIND new Nie Expected Output RIGHT is a core function Embedded Wireless Solutions Support Center 87 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual STRLEN FUNCTION STRLEN returns the number of characters within a string STRLEN string Returns INTEGER The number of characters within the string E i Local Stack Fra
52. is normally limited to use in the prototyping and debugging phases Embedded Wireless Solutions Support Center 74 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Once in Interactive Mode the command RESUME is used to restart the application from the next statement after the STOP statement Interactive No Command Example Stop sb See in Firmware Zip file DIM ap acs a 100 Note SPRINT replaces the content of s with exprlist each time it is used SPRINT sS a So Ow C ontan IOU PEA Se nes oa SPRINT s INTEGER H a loe TOW Contains 64 SMOR PRENTE sey TAY SPRINT sS INTEGER O a So Now Contains 144 ERITI Ane SPRINT sS INTEGER B a j So now Comeaims 1 100 100 PRINT ss vn Expected Output LOD O1 O02 resume 00000064 00000000144 NNDNNNDNDNDNDNDNDNNDNNNNNNN00000011001 00 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 Inter
53. module block diagram Bluetooth Low Energy Stack Embedded Wireless Solutions Support Center 4 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual smartBASIC Essentials smart BASIC is based upon the BASIC language If 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 smart BASIC implementations provides the standard functionality of any program such as Variables integer and string String processing functions Arithmetic functions Arrays single dimension only Binary operators 1 0 functions Conditionals Memory management Looping Event handling Functions and subroutines 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 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 smarfBASIC smart BASIC is one of the simplest embedded environments o
54. of the module This means if an autorun application exists in the module s file system it is automatically launched on power up il UwTerminal v1 70 Terminal Script Config About CTS DSR DCO AIM RIS DTR Copy the smart BASIC 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 at dir testl HelloWorld caAu tOru n 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 For example SautorunS 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 extl ext2 The resulting files after being stripped may overwrite other files Embedded Wireless Solutions Support Center 26 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Clear the UWTerminal screen by clicking the Clear button on the toolbar and then enter the com
55. pos If it is negative then the extracted string starts from offset length of string abs pos MIDS string pos length Returns TRING The length characters starting at offset pos of string Local Stack Frame Underflow Exceptions Local Stack Frame Overflow Memory Heap Exhausted Arguments string byRef string AS STRING The target string which cannot be a const string pos 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 Interactive Command a 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 Firmware Zip file DIM s sS Arsenic DIM newS newS MIDS sS 2 4 PRINT news yno Embedded Wireless Solutions Support Center 86 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Expected Output MID
56. 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 On return from the routine the statement that originally caused routine the error is reprocessed ONERROR NEXT routine On return from 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 a SUB routine which takes no parameters If must not be a function If must exist within the application PRIOR to this ONERROR command being compiled Interactive Command NO Embedded Wireless Solutions Support Center 67 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Example OnError sb See in Firmware Zip file DEM ves 7c SUB HandlerOnErr Do this when an error occurs DEMEI le GetLastError PRINT Error code Ox le denotes a Divide by zero error n PRINT Let s make b equal 25 inste
57. 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 UARTBREAK state Local Stack Frame Underflow Exceptions Local Stack Frame Overflow Uart has not been opened using UARTOPEN Arguments byVal newState AS INTEGER newState O to deassert and non zero to assert Interactive Command ne Related UARTOPEN UARTINFO UARTCLOSE UARTWRITE UARTREAD UARTREADMATCH eae aids UARTGETCTS UARTGETDCD UARTGETRI UARTGETDSR UARTSETRTIS UARTSETDCD UARTFLUSH UARTBREAK is a core subroutine Embedded Wireless Solutions Support Center 144 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual I2C Two Wire Interface or TWI Note The routines in this section only work if I2C is supported on the platform This section describes all the events and routines used to interact with the I2C peripheral if it is available on the platform An 12C interface is also known as a Two Wire Interface TWI and has a master slave topology An 2C interface allows multiple masters and slaves to communicate over a shared wired OR
58. support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User 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 hitp notepad plus sourceforge 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 l 2 oF 4 D 6 Copy the file smartBASIC notepad xml to the Notepad install folder Launch Notepad From the menu select Language gt Define your Language 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 Reopen Notepad and select Language gt smartBASIC from the menu If you use TextPad do the following l E E 9 10 11 IZ Copy the smartBASIC Textpad syn file from the firmware upgrade zip file to the Textpad install folder specifically the system subfolder As a one time procedure
59. 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 Embedded Wireless Solutions Support Center 107 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual TLV Tag Length Value TABLEINIT string INTEGER Indicates success of command Returns O Successful initialisation lt gt 0 Failure Local Stack Frame Underflow EXC CpIONS Local Stack Frame Overflow Arguments byRef string AS STRING String variable to be used for the Table Since it is byRef the string 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 mw Note string cannot be a string constant e g the cat but must be a string variable and so if
60. that is connected to the dev kit and bbb is the baudrate Embedded Wireless Solutions Support Center I7 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Target type Application Target location Target Target wget Uw Terminal exe accept com 5 baud 3600 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 l COM5 9600 N 8 1 Hcr 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 req 2 Type at 3 Press Enter You should get a 00 response Figure 10 uu UwTerminal v6 22 Terminal BASIC Contig About CTS OSA OCOM Al RTS DTR BRI Figure 10 Interactive command access UWTerminal supports a range of interactive commands fo interact directly with the module The foll
61. that you can run it To do this follow these steps 1 To manage file downloads right click on any part of the black UWTerminal screen to display the drop down menu Figure 2 CTS DSR OCD RI RTS DTRIV BREAK LocalEcho V LineMode Clear ClosePort Compile Load XCompile Load Run XCompile Load XCompile Download Font Run Automation Batch File Player Figure 12 Right click UWTerminal screen 2 Click XCompilet tLoad and navigate to the directory where you ve stored your fest sb file Note Do not select Compilet Load 3 Click Open In UWTerminal you should see the following display Embedded Wireless Solutions Support Center Z Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual TIO TO 0 Bl600Med a7 7 12 10 fe 9E56 5F81 lt lt Cross Compiling testl sb gt gt AT DEL testl AT FOW testl ATTPWRH FE900002250000000000FFFFFFFF3509E815FFC10 AT FWRH FB 0090054455354312E555743000110CK211000 AT FWRH FB0009000D000448656C6C6F20576F726C640A00 AT FWRH CC2114004A52000000110FD10F510 AT FCL DONE 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 invoked res
62. the first register Is identified by an 8 bit register address supplied Embedded Wireless Solutions Support Center 149 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality 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 I2C interface is made available most likely made available by bit bashing gpio IZCWRITEREG16 nSlaveAddr nRegAddr nRegValue Local Stack Frame Underflow eepnon Local Stack Frame Overflow Arguments byVal nSlaveAdadr AS INTEGER NSOVEAGAI This is the address of the slave in range 0 to 127 nRegAddr byVal nRegAddr AS INTEGER This is the 8 bit start register address in the addressed slave in range 0 to 255 byVal nRegValue AS INTEGER nRegValue 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 ne Related IZCOPEN I2CCLOSE I2CWRITEREADS IZCWRITEREGS IZCWRITEREG 16 Commands 2CWRITEREG32 IZCREADREG8 IZCREADREGI6 IZCREADREG32 Example I2cWriteRegl6 sb See in Firmware Zip file xPlease ensure that nSlaveAddr is the slave address of your I2C peripheral DIM rc handle nSlaveAddr nRegA
63. the function Example StrShiftLeft sb See in Firmware Zip file DIM sS a ess I73456 60 UNE NU e ony Strohtrehere ss 4 drop leftmost 4 characters PRINT s Expected Output 123456789 26 09 STRSHIFTLEFT is a core function STRCMP FUNCTION Compares two string variables STRCMP string1 string2 INTEGER A value indicating the comparison result O if string exactly matches string2 the comparison is case sensitive neue 1 if the ASCII value of string is greater than string2 if the ASCII value of string is less than string2 f Local Stack Frame Underflow Exceptions Local Stack Frame Overflow Arguments byRef string AS STRING string The first string to be compared byRef string2 AS STRING string2 The second string to be compared Embedded Wireless Solutions Support Center 94 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Interactive Command Be Note stringland string2 cannot be a string constant e g the cat but must be a string variable If you must use a const string then first save If to a temp string variable and then pass it to the function Example StrCmp sb See in Firmware Zip file BAOU e SA sl1S hello SZs world PRINT cr O mpole in PR TNE E a a ta PETNE e o ae An
64. times to change the tokeniser behaviour throughout a compilation SET commandliD commandValue Arguments cmdIiD cmdValue Any valid integer value Command ID and valid range is 0 10000 Currently smarfBASIC supports the following cmdlDs na AO N 10 11 Embedded Wireless Solutions Support Center http ews support lairdtech com O Smallest ve 32bit value 256 256 65535 65535 65535 65535 32767 3276 7 Largest ve 32bit value www lairdtech com bluetooth O 32 1024 1024 32 32 256 256 Default Simple Arguments type for routines 0 ByVal 1 ByRef Default Complex Arguments type for routines 0 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 Conditional compilation mask The Cmdld can also be referred to using the string S cmpif For example SET cmpif nnn The nnn value is a mask See Note 2 below for more details of how to use the cmpif conditional statement Fj Laird Technologies Americas 1 800 492 2320 Europe 44 1628
65. var arithexprl TO arithexpr2 STEP arithexpr3 statement block NEXT FOR var arithexpr DOWNTO arithexpr2 statement block NEXT FOR var arithexpr DOWNTO arithexpr2 STEP arithexpr3 statement block NEXT Embedded Wireless Solutions Support Center 6 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Statement block A valid set of program statements Typically several lines of application which can include nested conditional statement blocks Var A valid INTEGER variable which can be referenced in the statement block Arithexprl A valid arithmetic or logical expression arithexprl is enumerated as the starting point for the FOR NEXT loop Arithexpr2 A valid arithmetic or logical expression arithexpr2 is enumerated as the finishing point for the FOR NEXT loop Arithexpr3 A valid arithmetic or logical expression arithexpr3 is enumerated as the step in variable values in processing the FOR NEXT loop If STEP and arithexpr3 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 var starting with the value calculated or defined by arithexpr1 When the NEXT command is reached and processed the STEP value resu
66. will light while the button is pressed Button 0 has been released LED 0 should now go out utton 1 has been pressed ED 1 will light while the button is pressed utton 1 has been released ED 1 should now go out B L B L 4 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 soace 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 The response to every Interactive mode command has the following form lt linefeed character gt response text lt carriage return gt This format simplifies the parsing within the host processor The resoonse 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 O0 lt cr gt for a successful outcome or lt If gt 01 lt 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 constraine
67. x026 smart BASIC Core Functionality User Manual AT FCL Returns If the filename exists AT FCL responds with nOO r Arguments None Interactive Y Command This is an Interactive Mode command and MUST be terminated by a carriage return for it to be processed Examples AT FCL AI FCL is a core command 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 n0O r If the variable is a string type then the response Is n08 amp t Hello World r nOO r If the variable does not exist then the response to this command Is n01 tE023 r Where n linefeed t horizontal tab and r carriage return Note Ifthe optional type prefix is present the output value when It is an integer constant is disolayed in that base For example h var returns n08 tH nnnnnn r nOO r Arguments Embedded Wireless Solutions Support Center 43 Laird Technologies http ews support lairdtech com Americas 1 800
68. x026 smart BASIC Core Functionality User Manual 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 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 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 Firmware Zip file 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 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 arithexpr l TO arithexpr2 statement block NEXT FOR
69. 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 Firmware Zip file DIM tS 2tS Hel lo PRINT a ee eee te PRIT Vos To nole linc eo PRIN ates String now blank after being initialised as a table 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 nindex has been duplicated as it is entirely valid that more than one token generate the same ID value TABLEADD string strtok nID Embedded Wireless Solutions Support Center 108 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual INTEGER Indicates success of command QO Signifies that the token was successfully added 1 Indicates an error if nID gt 255 or lt 0 Returns 2 Indicates no memory is available to store token 3 Indicates that the token Is too large 4 Indicates the token Is empty earn eee Local Stack Frame Underflow p Local Stack Frame Overflow Arguments byRef string AS STRING string A string variable that has been initialised as a table using TABLEINIT byVal strtok AS STRING sirtok The string t
70. 00 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Ne DAWork BLE DEV_MAIN UwScript UwTerminal Targe UwScript Cross Compiler tc Laird Technologies 26H8 PLATFORM B1l666Med VERS IOM_ATIS 4 6 17 48 WERSIOM_SCRIPT 2 8 LANGUAGE HASH 9ES6 SFE61 JEEE Compiling file lt D Work BLE DEU_MAIN UserManualstesti sh gt W print SnHello World n LERROR Line 1 Code 1500 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 test1 Note smart BASIC commands variables and filenames are not case sensitive smart BASIC treats Testl fest and TEST as the same file The screen should display the following results when both forms of the command are entered attrun test Hello World OO Testl Hello World 00 You can check the file system on the module by typing AT DIR and pressing Enter you should see 06 testi 00 You have just written and run your first smart BASIC program To make It a little more complex try printing Hello World ten times For this we can use the conditional functions within smart BASIC 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 worth
71. 000 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 nCfgFlags Bit Description If set Then the least significant bit is clocked in out first 1 31 Unused and must be set to 0 byRef nHandle AS INTEGER nHandle 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 nelle SPICLOSE SPIREADWRITE SPIWRITE SPIREAD Commands SPIOPEN is a core function The following is an example which demonstrates usage of all the SPI related functions available in smartBASIC Example SpiExample sb See in Firmware Zip file Embedded Wireless Solutions Support Center 157 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual The SPI slave used here is the Microchip 25A512 See http wwl microchip com downloads en DeviceDoc 22237C pdf PEM aise DIMA handle DIM rl readlen DIM roer are O DIM wren PUNCEUG Se eewomorarms GpioWrite 13 0 wrS 05 00 rdsS _ rc SpiReadWrite wrs rds GpioWrite 13 1 ENDERUN StrGerChr rds 1 ieee ae a ee eS a E E j Walt Lor WR bit in Status flag to reset ee
72. 1 BREAKPOINT SO the 21 BREAKPOINT SO world Zi BREAKPOINT BP is a core function Embedded Wireless Solutions Support Center 76 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 6 CORE LANGUAGE BUILT IN ROUTINES Core Language built in routines are present in every implementation of smart BASIC These routines provide the basic programming functionality They are augmented with target specific routines for different platforms which are described in the extention manual for the target platform Result Codes Some of these built in routines are subroutines and some are functions Functions always return a value and for 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 helos 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 if 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
73. 2 bit types if available The combination of mix columns and byte substitution used here is based on that developed by Karl Malbrain His contribution is acknowledged Embedded Wireless Solutions Support Center loo Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual INDEX Te SE E E E E E aa 56 Read Variable essesssssessrrreeessssessssrrreessreee 43 Sel CIOS a srestresaneacocseccscenese eceiameees ances 44 ABORT aR a ees coereeustaus Rescaneeee 46 ADO oae 83 PTY a E AEA EAA 54 A e ee E 33 BZ EEE N EEEE N AE N EEE 48 A E EE AE E 47 PM AON E E 43 1 has al E E ee ee ee ee ee 40 PAP EN enan 47 PERRIN ooctcoariectesetcmelcoasion ects eers 37 38 40 41 42 7 as ee eee 39 EE E T E E E aose 48 BA O E E 6 e aAA E E E A A E A 75 BREA I ne snsoeenosenosesteasonssbonnocenteascseses 66 BYREF occpe cece dec eter ccevceevdeneeinvenonaenvceteeineacudnstecees 162 BIVALA A E E 162 CIRCBUFCREATE 121 162 163 165 167 169 170 171 172 CIRCBUFITEMS sasescescsssccresissecvesnsexiacsiaveceataveee 126 CIRCBUFOVERWRITE ereen 124 CIRCBUFREAD carebecertteen di conesinictaacien 125 CIRC BUPW RIVE vsscscestssescaciconssasidssesesinansneatcaosunte 123 SO INT UIE E E E E EAT 66 Declaring Variables esssccsereeesseseesssrrrrrrrereee 55 DE e des ststedaaccssediaedesesecedete
74. 2268 6567 x026 smart BASIC Core Functionality User Manual ELSE PRIN S NO a OTN oaa ENDINE Exoected Output Laird Rocks N ias 1 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 arithexpr statement block ENDWHILE 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 All WHILE Commands must be terminated with an ENDWHILE statement Interactive Command NO Example While sb See in Firmware Zip file DIME n 0 now print Hello ten times WELLE ASLO ERA E CO iar I 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 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 Em
75. 268 6567 x026 smart BASIC Core Functionality User Manual 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 octal hexadecimal or binary values Interactice Command we 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 locals simple variables This refers to the total amount of space the runtime engine will allocate for simple variables like INTEGER declared as local variables in user functions FUNCTION and subroutines SUB Note that if an array of 10 is declared then it takes up 10 locations This means that if there is a nest of function calls then in total they should not end up declaring space exceeding this amount 4 Maximum size of locals complex variables This refers to the total amount of space the runtime engine will allocate for complex variables like STRING declared as local variables in user functions FUNCTION and subroutines SUB Note that if an array of 10 is d
76. 492 2320 Europe 44 1 628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Var lt n gt Any valid variable with mandatory n if the variable is an array For integer variables the display format can be selected by prefixing the variable with one of the integer type prefixes D Decimal H Hexadecimal O Octal B Binary Interactive Yes Command This is an Interactive mode command and MUST be terminated by a carriage return for it to be processed Examples argc 08 11 00 h arge 08 H 0000000B 00 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 n0O1 tEO27 r If the variable does not exist then the
77. 5 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Note All responses to interactive commands are of the format NNN tOptionalText1 tOptionalText2 r where NN is 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 smart BASIC module is its ability fo 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 your module s pinout and if it is asserted at Ov it looks for and executes the autorun application In our development kits 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 module The DTR checkbox Is always selected by default in asserted state which translates to a Ov at the nAutoRUN input
78. 58 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual re I2cWriteRead nSlaveAddr stWriteS stRead nReadLen LE ee 0 Tan PRINT nFailed to WriteRead integer h rc BLSE PRTA e e a u s e e a a a a ENDIE 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 Note The routines in this section will only work if SPI is supported on the hardware you are developing for This section describes all the events and routines used to interact with the SPI peripheral if it is available on the platform 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 htto 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 significant bit first or last Note A dedicated SPI Chip Sel
79. 68 6567 x026 smart BASIC Core Functionality User Manual PRINT nFailed to encrypt ENDL E PRINS MmainDetawe cl rnexcmZe aa PRIN new ebabas YF Siena cme gt ec 10 j enerypt same data again re AesEncrypt inData S c 1 IF rc 0 THEN Ee abi PEI OK ETSE PRINT Ankalle o encrypt ENDIE PRIN Annata e etr he ize nbat PETT e aea a e a eo lh ecrypt same data again re AesEncrypt inData c 2 IF rc 0 THEN PRINT nemeryor OK BLSE PRINT nFailed to encrypt BANDE PRIE mambDete etre ze imbawac PRihhes Mele Dea 7 iowa 2eo e Rereate context for CBC mode 128 bit Keyo 0001 02 03 1024 105 06 07 08 09 0208 Ce 0b 0b Or fie VeCeOro Fh VOU WEP OS Pe 05 2b V0 Fe v0Oo PP 08 Fe ObD br Or rc AesSetKeylv 0x200 16 key initVectorS IF rc 0 THEN PRINT nCBC context created successfully BLSE PRINT nFailed to create EBC context ENDTE now decrypt the data rce AesDecrypt c 0 outData S IF rc 0 THEN PRINT nie Decr pU OR ELSE PRINT nFailed to decrypt BNDIE PRINT hinData gt strnexizes cs 0 PRIN moweData 9 Ssurmexize gt s oun Data now decrypt the data rc AesDecrypt c 1 outData S IF rc 0 THEN PRINT Ansi Wecryvot On BLSE PRINT nFailed to decrypt BN DLE PRINT tinWatea Sstrmexizes csl PRINT A nont Dora aa 465 out Dawa now decrypt the data rce AesDecrypt c 2 outDataS IF rc 0 THEN
80. 858 9 40 Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Note 1 Unlike other commands SET may not be combined with any other commands on a Note 2 line The syntax of the conditional compile statement is cmpif constant_integer_expression statement When nnn in the set command is 0 then any statements starting with cmpif will NOT get converted into any object code If nnn is non zero then for all cmpif constant_integer_expression statements if nnn amp Constant_integer_expression results in a non zero value then the statement s following the separator gets compiled into object code For example set cmpif Ox4 dim a a 0 cmpif 0x cmpif 0x5 cmpif 0x5 cmpif 0x2 print This will not get printed because 4 amp 1 is equal to 0 print This will get printed because 5 amp 1 no equal to 0 a 42 a will be set to 42 zZ 100 a will not be set to 100 Further note If constant_integer_expression amp mmm evaluates to 0 then the rest of the entire line will not get compiled even if the line contains multiple statements separated by the character Example set 1 1 set20 change default complex args to byVal change default simple args to byRef Arithmetic Expressions Arithmetic expressions are a sequence of integer constants variables and operators At runtime the arithmetic expression which is normally the right hand si
81. 92 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 smart BASIC cross compiler provided for free If this feature is available then the platform switches into Load mode when the compile AI 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 application 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 smart BASIC applications are read trom program memory and executed in situ from 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 Sautorun 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 asserte
82. 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual DTE DCE role request O T DITE C DCE Parity N None O Odd E Even 2 Databits 5 6 7 8 or 9 3 Stopbits 1 or 2 Flow Control 4 N None H CTS RTS hardware X Xon Xof may not be available see extension manual Related UARTINFO UARTCLOSE UARTWRITE UARTREAD UARTREADMATCH j q UARTGETDSR UARTGETCTS UARTGETDCD UARTGETRI UARTSETDTR ommanaS UARTSETRTS UARTSETDCD UARTSETRI UARTBREAK UARTFLUSH Interactive Command Ma 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 Note In DIE equipment DCD and RI are inputs while in DCE they are outputs Example UartOpen sb See in Firmware Zip file DIMERS SUING TON Sia celaU elicits hoe PRINT aData has arrived r ENDEUNG 15 7 remaim blocked in WALTER VENE FUNCTION BtnOPressed UartClose ENDFUNC 0 re GPIOBiIndEvent 0 lc 1 Eor our pom 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 sOCen CONPOLe cov ence DCD tend Rivaresinpure re UartOpen 9600 0 0 CN81H Oe
83. ART is closed it will be lost This is because the execution of VARTCLOSE takes a very short amount of time while the transfer of data from 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 Undertlow Local Stack Frame Overflow Arguments None Interactive NO Command Related UARTOPEN UARTINFO UARTWRITE UARTREAD UARTREADMATCH UARTGETCTS Commands UARTGETDCD UARTGETRI UARTSETDTR UARTSETRTS UARTSETDCD UARTSETRI UARTBREAK UARTFLUSH Embedded Wireless Solutions Support Center 132 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Example UartClose sb See in Firmware Zip file UartClose Le Uareinro 0 0 THEN PRINT nThe Uart port was closed BLSE PRINT nThe Uart port was not closed ENDIF LE Uarrtinro 0 0 THEN PRINT hand Now It 1o Open ENDIF Expected Output a The Uart port was closed and now it is open UARTCLOSE is a core subroutine UARTCloseEx FUNCTION This function is used to close a uart port which had been opened with UARTOPEN depending on t
84. An expression list which defines the data to be printed consisting of comma or semicolon separated arithmetic or string expressions Interactive yes Command 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 separator 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 Embedded Wireless Solutions Support Center is Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual
85. BROUTINE 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 12C interface is made available most likely made available by bit bashing gpio I2CWRITEREG8 nSlaveAddr nRegAddr nRegValue Local Stack Frame Underflow PAE RRAONS Local Stack Frame Overflow Arguments byVal nSlaveAddr AS INTEGER maavencee This is the address of the slave in range 0 fo 127 nRegAddr byVal nRegAddr AS INTEGER This is the 8 bit register address in the addressed slave in range O to 255 byVal nRegValue AS INTEGER nRegValue This is the 8 bit value to written to the register in the addressed slave Note Only the lowest eight bits of this variable are written Interactive NO Embedded Wireless Solutions Support Center 4 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Command Related IZCOPEN I2CCLOSE I2CWRITEREAD IZCWRITEREGS I2ZCWRITEREG 16 Commands 2CWRITEREG32 IZCREADREG8 IZCREADREGI16 IZCREADREG32 Example I2cWriteReg8 sb See in Firmware Zip file Please ensure that nSlaveAddr is the slave address
86. BS var Returns INTEGER Absolute value of var Exceptions Local Stack Frame Undertlow 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 overflow as 33 bits are required to convey the value Arguments var byVal var AS INTEGER The variable whose absolute value is required Interactive No Command Example ABS sb See in Firmware Zip file DIM sil as INTEGER SZ as INTEGER S12 aa 14 PREM oleae Gs ane 2 elgg ez Expected Output ABS is a core language function MAX FUNCTION Returns the maximum of two integer values MAX var var2 Returns INTEGER The returned variable is the arithmetically larger of varl and var2 Local Stack Frame Underflow Exceptions Local Stack Frame Overtlow Embedded Wireless Solutions Support Center 83 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Arguments r byVal varl AS INTEGER s The first of two variables to be compared var2 byVal var2 AS INTEGER The second of two variables to be compared Interactive Command Me Example MAX sb See in Firmware Zip file DIM sit sZ Ssil 2 s s27 4 PRINT 61 852 PRINT n The Maximum of these two integers is MAX s1 s2 Expected Output
87. E This routine is used to force a reset of the module RESET nType Local Stack Frame Underflow EXCEPNON Local Stack Frame Overflow Arguments nType byVal nType AS INTEGER Interactive Command ae This is for future Use Set To 0 Example RESET sb See in Firmware Zip file RESET 0 torce a res t ol the moule Expected Output Like when you reset the module using the interactive command ATZ the CTS indicator will momenterally change from green to red then back to green CTS DSR Dco Rie RIS DTR RESET is a core subroutine Random Number Generation Routines 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 1001 or at runtime SYSINFO 1001 will return 1 if the system generates random numbers using hardware noise or 0 if a pseudo random number generator Embedded Wireless Solutions Support Center 111 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 determin
88. E UARTREADMATCH UARTGETDSR Related P UARTGETCTS UARTGETDCD UARTGETRI UARTSETDTR UARTSETRTS UARTSETDCD Commands UARTSETRI UARTBREAK UARTFLUSH Note s rMsg 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 Example UartRead sb See in Firmware Zip file DIM rO wehenqem cia strS Your nane is Embedded Wireless Solutions Support Center Ia Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual PUNE 1 Ol Sind laWetcmniko lt d MimerStart 010070 Allow enough time for data to reach rx buffer ENDE ULE yt OIC ION Iehacleewimuet 4 strLength UartRead str PRIM Vn sbrs ENDFUNC 0 ONEVENT EVTMRO CALL HndlrTmr0O ONEVENT EVUARTRX CALL HndlrUarerRsx PRINT nWhat is your name n WALTEVENT Expected Output What is your name David Your name 1s 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 INTEGER Oto N The total length of the string variable not just what got Returns appended Th
89. EFT 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 STRING The leftmost length characters are returned and then those characters Returns are dropped from the argument list Local Stack Frame Underflow Exceptions 7 Local Stack Frame Overflow Memory Heap Exhausted Arguments byRef string AS STRING string The target string which cannot be a const string byVal length AS INTEGER length The number of leftmost characters that are returned before being dropped from the target string Interactive Command we 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 Example StrSplitLeftS sb See in Firmware Zip file DIM Origo origo ke T2 AoT PRIND otr o platero Orro ora An PRINT oga Expected Output Lao 45678 STRSPLITLEFT 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 O1 O02 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 Embedded W
90. ENDFUNC 0 ONEVENT EVUARTTXEMPTY CALL HndlrUartTxEty PRINT nsend thio via wert WALTEVENT Expected Output Send this via uart Tx buffer is empty UartOpen Note If communicating with a Mac OS X device the baud rate cannot be set above 230400 due to Mac having no support for these baud rates Embedded Wireless Solutions Support Center 129 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual FUNCTION This function is used to open the main default vart peripheral using the parameters specified If the uart is already open then this function will fail To prevent this call UartClose or UartCloseEx before calling this function 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 module 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 UARTOPEN baudrate txbuflen rxbuflen stOptions INTEGER Indicates success of commana O Opened successfull
91. Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual ENDFUNC 0 PRIINI Vth value on che Councert LS Vp GerTiLekCounec ONEVENT EVTMRO CALL HandlerTimer0 Timerscarcrc 0 1000 0 PRINT nWarting for Timer 10 WALTEVENT PRIINI YAnrhe value on che Counter LS now Go rele olin in Expected Output The value on the counter is 159297 Waiting for Timer 0 Timer 0 has expired The value on the counter is now 160299 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 stariTick is less than O which is a value that GETTICKCOUNT will never return then a 0 will be returned GETTICKSINCE startTick INTEGER A value in the range O to OX7FFFFFFF 2 147 483 647 in units of milliseconds starfTickr byVal startTick AS INTEGER This is a variable that was updated using the return value from GETTICKCOUNT and it is used to calculate the time elapsed since that update Returns Arguments None Interactive No Command Associated GETTIICKCOUNT Commands Example GetTickSince sb See in Firmware Zip file DIM stariTick clapseMs x x Startlick GerTiceckCounr DO BRTN Use x x 2 BRINE Ya Embedded Wireless Solutions Support Center 120 Laird Technologi
92. Expected Output 1 O STRCMP is a core function STRHEXIZES FUNCTION This function is used to convert a string variable into a string which contains all the bytes in the input string Converted to 2 hex characters It will therefore result in a string which is exactly double the length of the original string STRHEXIZES string STRING A printable version of string which contains only hexadecimal characters Returns and exactly double the length of the input string Local Stack Frame Undertlow Exceptions Local Stack Frame Overflow Memory Heap Exhausted Arguments byRef string AS STRING String The string to be converted into hex characters Interactive NO Command Embedded Wireless Solutions Support Center 75 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality 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 STRHEX2BIN Example StrHexizeS sb See in Firmware Zip file DIME Sirs s Lairo PRINT y Sn bo SitrHexizes SS PRINT Strlen ss vn EVO NPE ane cea ue gill PRINT Strbhen es a Expected Output Laird 5 4C61697264 10 STRHEXIZE is a core
93. FGKEYGET keyld value INTEGER a result code The most typical value is OxO000 indicating a successful Reruns operation Exceptions Local Stack Frame Underflow p Local Stack Frame Overflow Arguments byVal keyld AS INTEGER keyld 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 byRef value AS INTEGER value The integer variable that will be updated with the value of the configuration key if it exists Interactive See AT CFG Command Example NvCfgKeyGet sb See in Firmware Zip file Embedded Wireless Solutions Support Center I9 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual DIM vos vy 0 initial the value just in case the key does not exist PRINT NvCfigkeyGet 100 v PRA ae Expected Output 0 Souk 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
94. ND 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 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 Embedded Wireless Solutions Support Center 182 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Events related to the UART interface as described here 8 MODULE CONFIGURATION There are many features of the module that cannot be modified 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
95. NE 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 Embedded Wireless Solutions Support Center Ee Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Local Stack Frame Underflow Exceptions Local Stack Frame Overflow Uart has not been opened using UARTOPEN Arguments byVal newState AS INTEGER newState O to deassert and non zero to assert Interactive Command we Related UARTOPEN UARTINFO UARTCLOSE UARTWRITE UARTREAD UARTREADMATCH acing g UARTGETCTS UARTGETDCD UARTGETRI UARTGETDSR UARTSETDTR UARTSETDCD UARTSETRI VARTBREAK UARTFLUSH Note This subroutine is not implemented in some modules Refer fo module specific user manual if this is available 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
96. NG 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 passed 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 ENDSUB This statement ends a block of statements belonging to a subroutine If 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 rou
97. NVCFGKEYSET keyld value INTEGER Returns An integer result code The most typical value is OxO000 which indicates a successful operation Local Stack Frame Underflow ACRIOR Local Stack Frame Overflow Arguments byVal keyld AS INTEGER keyld 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 byVal value AS INTEGER oe If the configuration key keyld exists then it is uodated with the new value Interactive Command a WARNING You should minimise the number of writes as each time a record is changed empty flash is used up The flash 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 Example NvCfgKeyGet sb See in Firmware Zip file DIM re W 3 wW 0x8107 PRTI A Treo e AMO sn PRTA N a ea ee T OET Embedded Wireless Solutions Support Center 176 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual PRINT Vay eles for 100 is 2E Expec
98. Note STRPOS does a case sensitive search Note stringland 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 Example StrPos sb See in Firmware Zip file DIM slo 327 slS Are you there s2S there PRINT geo he ie Womden oo NOCCWCom Ae OOSTELOM sob POs Sls 1926 0 Exoected 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 nlndex 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 nindex INTEGER Represents command execution status O If the block is successfully updated Returns 1 lf nChr is greater than 255 or less than O 2 If the string length cannot be extended to accommodate nindex 3 If the resultant string is longer than allowed Local Stack Frame Underflow Exceptions Local Stack Frame Overflow Memory Heap Exhausted Embedded Wireless Solutions Support Center 89 Laird Technologies http ews support lairdtech com Ameri
99. ON 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 var consists of one mandatory element varname and one optional element AS type separated by whitespaces and described as follows Varname A valid variable name AS type Where type is INTEGER 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 INTEGER 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 Example DimExl sb See in Firmware Zip file DIM templ AS INTEGER DIM temp2 Will be an INTEGER by default DIM temp3 AS STRING DIM temp4 Will be a STRING by default DIM temps AS INTEGER Allowed but not recommended practice as there is a at end of name DIM temp6 AS STRING Allowed but not r
100. 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 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 Set Ready Output Inout 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 Note 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
101. VERE AVEIMRI CAG hence DT aeme a 1 TIMERSTART 0 900 1 start a 500 millisecond recurring timer PRINT 2 nlaweung for Timer O TIMER TART le ooo J7seare a L000 millisecond timer PRINTO nWairing Cor Timer bt WALTEVENT Expected Output Waiting for Timer 0 Waiting for Timer 1 Timer 0 has expired Timer Timer Timer has 1500 milliseconds to go has expired has 1000 milliseconds to go has expired has 500 milliseconds to go has expired has 0 milliseconds to go has expired Timer Timer Timer Timer Timer PrROrFOrFOER TIMERRUNNING Is a core function TimerCancel SUBROUTINE This subroutine stops one of the built in timers so that it will not generate a timeout event TIMERCANCEL number Arguments 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 If the value is not valid then a runtime error will be thrown with code INVALID_TIMER Interactive Command we Associated ONEVENT TIMERCANCEL TIMERRUNNING Commands Example TimerCancel sb See in Firmware Zip file ae eee Embedded Wireless Solutions Support Center 118 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual i 0 x 1 x is HandlerTimerO s return value Will switch to 0 when timerO has e
102. ace In the future a new version of this function will oe made available if more than one SPI interface is made available SPIREADWRITE stWrite stRead INTEGER a result code The typical value is OxO000 indicating a successful Returns operation E fon Local Stack Frame Underflow ed ale Local Stack Frame Overflow Arguments byRef stWriteS AS STRING ete This string contains the data that must be written byRef stReadS AS STRING stReadS 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 ae eSa SPICLOSE SPIREADWRITE SPIWRITE SPIREAD Commands Example See SpiExample sb SPIWRITEREAD is a core function Embedded Wireless Solutions Support Center 160 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual SpiWrite FUNCTION This function is used to write data to a SPI slave and any incoming data will be ignored 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 stWriteS Ret INTEGER a result code The typical value
103. ace 118 TIMERRUNNING 1 eecccceeeeceee anes 117 UMER TART are cece ceesee E 115 UART Events suactvovecusacontvaniwotasosmsestensiectaxerevarcess 128 UARTBREAK eenesssessssersssersssersssserss 144 UARTCLOSE vic cesdccvccsatcriewasivtsscsedssasnscievencuedueed 132 Embedded Wireless Solutions Support Center http ews support lairdtech com www lairdtech com bluetooth 189 UARTCLOSEEX 0 00 eeeecccessecceeeseseeeenes 133 UF JL US rn 14 UARTGETCTS cc ccc eccccceecescccccccsssccceseessecees 143 UARTINFO Renee en ener ee 134 OU ROR IN a eset aera petececneceeceeeis 130 UARTREAD 0000 cece eee ccc eeeeeeccceeeeeeeeees 137 138 UARTREADMATCH cccc cc eeeeecccceeeeeeeees 139 UARTSETRTS sscessscsssesacecivesscesncosesacdiestcovedessseshictes 143 OF 41d 4 Se rerien 135 Useful SOM CUTS cess cccovewacncedtuarecertercosostuorsdanteousas 17 Using UWTErMINll ccccccccccccccesseeeeeeeeeees 18 VONODIES oo eeeccceseeccceeseccccssecccesscccessceeeesceeees 51 WHILE ENDWHILE o oo eeeeeccceeeeeceeeeees 64 Laird Technologies Americas 1 800 492 2320 Europe 44 1 628 858 940 Hong Kong 852 2268 6567 x026
104. active NO Embedded Wireless Solutions Support Center 162 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Command Example AesSetKeylIv sb See in Firmware Zip file BTM keys ihe ech on DIMERS Create context for EBC mode 128 bit key o A 00 01 02 02 04 05 06107 08 09 0A 0B 0C ODA OEN Or initVector EBC does not require initialisation vector rc AesSetKeylv 0x100 16 key initVector S IF rc 0 THEN PRINT nEBC context created successfully Eo E PRINT nFailed to create EBC context LIS Ceedte context for EBC mode with XOR 1738 bit keys 00 01 02 03 0405 06 07 08 09 0A 0B 0C 0D On Or ime vecvtomo a Ol FEO bh OS ah Oy Oo Pn wh a Ob he ORA rc AesSetKeylv 0x101 16 key initVectorS IF rc 0 THEN PRINT nEBC XOR context created successfully Eo E PRINT nFailed to create EBC XOR context BND Create context for CBC mode 128 bit keyo 001010202 04 05 06107108 09 OA 0B 0C 0b 0b 0m ime Vectors ERP GI EF O3 PP 0O5 FR O7 EF 09 PR OBVER OD EF OR rc AesSetKeylv 0x200 16 key initVector S IF rc 0 THEN PRINT nCBC context created successfully Pili E PRINT nFailed to create CBC context ENID IL E Expected Output EBC context created successfully EBC XOR context created successfully CBC context cr
105. active mode BP nnnn After execution is returned to 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 Embedded Wireless Solutions Support Center 75 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Arguments nnnn A constant integer identifier for each breakpoint in the range 0 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 Interactive No Command Note Itis helpful to make the integer identifiers relevant to the program structure to help the debugging process A useful tip is fo set them to the program line Example BP sb See in Firmware Zip file PRINT Vaello BP 1234 PRINT vorlag PRONA PRINT Rocks BP 5678 PRINT he PRINT Swor ko Expected Output Depending on what order you use the commands SO and RESUME hello 21 BREAKPOINT 1234 resume worldLairdRocks Z
106. ad of O n n b 25 ENDSUB a 100 b 0 ONERROR REDO HandlerOnErr j Callse the Handleronbre routine After that the error causing statement below is reprocessed c a b Plant mow egual 2 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 On return from the routine the statement that originally routine caused the error is reprocessed ONFATALERROR NEXT routine 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 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
107. amples AT FWR nhelloworld r AT FWR 00 01 02 AT FWR is a core Command AT FWRH COMMAND AT FWRH 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 files to the 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 resoond 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 Interactive Y Command i This is an Interactive Mode command and MUST be terminated by a carriage return for it to be processed 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 AI FCL closes a file that has previously been opened for writing using AT FOW The group of commands AI FOW AT FWR AT FWRH and AT FCL are typically used for downloading files to the module s flash filing system Embedded Wireless Solutions Support Center 42 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567
108. amples 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 Variable Class DIM The Declare statement is Used to declare a number of variables of assorted types to be defined in a single statement Embedded Wireless Solutions Support Center lt Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual If it is Used within a FUNCTION or SUB block of code then those variables will only have local scope Otherwise they will have validity throughout the application If a variable is declared within a FUNCTI
109. 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 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 smart BASIC function or if 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 Embedded Wireless Solutions Support Center 29 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual The following is an example of an application btn button led test sb which monitors button presses and reflects them to leds on the BL600 development kit p KK KKK KKK KKK KKK KKK KK KK KK I KK KK KK I KK IK KK IK I KK IK KK KK I KK KK KK KK Kk Laird Technologies c 2013 a Fed SA See eae eae
110. andle IFP wc 0 THEN PRINT nFailed to open I2C interface with error code INTEGER h ELSE PRINT nI2C open success nHandle is handle Ba rs Expected Output I2COPEN is a core function I2cClose SUBROUTINE This subroutine is used to close a 12C port which had been opened with I2ZCOPEN This routine is safe to call if it is already closed HE I2C open success Handle is 0 I2ZCCLOSE handle Eveantions Local Stack Frame Underflow p Local Stack Frame Overflow Arguments handle byVal handle AS INTEGER Embedded Wireless Solutions Support Center 146 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual This is the handle value that was returned when IZCOPEN was called which identifies the I2C interface to close Interactive Command NO Related I2COPEN I2CWRITEREAD I2CWRITEREG8 I2CWRITEREG16 I2CWRITEREG32 Commands 2CREADREG8 I2CREADREG16 IZCREADREG32 Example I2cClose sb See in Firmware Zip file DIM handle DIM reo e 12cOpen 100000 0 hand ire ip re O THEN PRINT nFailed to open I2C interface with error code INTEGER h rc BLSE PRINT nI2C open success nHandle is handle ENDI I2cClose handle close the port I2cClose handle no harm done doing it again IZCCLOSE is a core subroutine I2cWriteREG8 SU
111. ar i unsigned short data while nSrchLen 0 data Gieigned int 0xritr amp pSrcstrt 8 Embedded Wireless Solutions Support Center 39 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual i data gt gt 1 if nCrcl6 amp 0x0001 data amp 0x0001 nCrecl6e nCrel6 gt gt 1 POLY else nCrels gt gt 1 nCre o nCrel6 data nCrcl6 nCrcl6 nCrel6 lt lt 8 data gt gt 8 amp Oxff return nCrcls AT DIR COMMAND Lists all application or data files in the module s flash file system AT DIR lt string gt Returns nO6 tFILENAME 1 r nO6 TFILENAME2 r nO6 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 Note The match string Is not case sensitive Interactive Y Command This is an Interactive Mode command and Must be terminated by a carriage return for it to be processed Examples AT DIR AT DIR new AT DIR is a core Command Embedded Wireless Solutions Support Center 36 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 w
112. asscesdsesauau tase caoiueheaes das euesiuaeiueetisesaeucce To TP E 74 SUR CIMIP scosisavesssesaranasuvorussacsovinmemwesiexsspcaamsatneaansoses 94 STR DEES CAPE croen orinn 101 SIRDEREXIZE cause deas gwen desu sues iuahansndesnaneeduabevandveoace 96 Gnd Stok APES en eee 100 SIRFICL oer 92 STRGETCHR Gael ne 90 SIRREX BIN A ene 98 99 Re a 95 MO CON N EEEE 56 SIRLEN i ee 88 SIRPOS erreira A A E 88 STRSETBLOC K icsicsscnsicenicavinicescrsassntedidcasimenianieantes 9 STRSETCHR ccceesssseseececcccccceeeeessseeeeeenees 89 SS OT Fg omacevousrondvousynueveusvouivounbunounouvounoun 93 STRSPLITLEFT ccs csaasacessncajencecseseesecesstesesesuses 102 OH traces deta sade E 102 Structuring an AG DIICOTION ic sescacessiacaccsagezacncans 29 SIRVALDEC ssecesesssasisestcnvssseornssaceaeassadsanseasetaavess 97 SUN A OUR pa 103 104 106 UB r E aut ecce ese cetenarsecasecesdceiauecs 179 Laird Technologies Americas 1 800 492 2320 Europe 44 1628 858 9 40 Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual LE AIEA EAE EEA OAA 48 S INEO coat cpeceese catcceskanscee tt cetcenebatacaenecacacese aaneees 79 a P Seer or oe A 80 TABLE ADD rerne 108 14 1B amp eee peer ee ee Posner rn ee 107 TABLELOOKUP eee ccc eesecceeeseceeeeees 110 1 aE EEEE E E E E 20 limier EVENTS oo cece ceeeecccesseccceescccceessceeeessceeeenes 114 TIMER GC AING Ebb iscsi esa scdoceccschaccasedoxessschacccazet
113. ation which is when the last statement returns or a STOP or END statement is encountered a smart BASIC 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 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 smart BASIC 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 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 paramoters 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 The storage space is module dependent Check the individual module data sheet Non Volatile Memory All smart BASIC modules contain user accessible flash memory The quantity of memory varies between modules check the appliable datasheet The flash memory is available for three purposes File s
114. be deleted On exit an invalid handle value will be returned Interactive NO Command Embedded Wireless Solutions Support Center 122 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Example CircBufDestroy sb See in Firmware Zip file DIM CircHancile circhandile2 re rc CircBufCreate 16 circHandle PRINTE Mnn re Merel ORAEN PRINT nilhe circular buifer circHhandle was not Created ENDIF CincBurtDestroy cr rehande PRINT nThe handle value is now circHandle so it has been destroyed Expected Output 0 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 INTEGER Returns An integer result code The most typical value is 0x0000 which indicates a successful operation Arguments byRef circHandle AS INTEGER circHandle this identifies the circular buffer to write into byVal nData AS INTEGER nData This is the integer value to write into the circular buffer Interactive No Command Example CircBufWrite sb See in Firmware Zip file D
115. bedded Wireless Solutions Support Center 18 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 statement 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 7 EVENTS A
116. bedded Wireless Solutions Support Center 64 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 the 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 arithexpr unconditional statement block CASE integerconstA statement block A CASE integerconstB statement block B CASE integerconstc integerconstd integerconste integerconsff 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
117. 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 from 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 DIR 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 Terminal BASIC Config About ETSO DSC DCDC RIO RTS DTR BREAK LocalEcho LineModel 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 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 Plea
118. cas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Arguments ti byRef string AS STRING siring The target string byVal nCHr AS INTEGER nChr The character that will overwrite the existing characters nChr must be within the range 0 and 255 byVal nindex AS INTEGER nindex The position in the string of the character that will be overwritten referenced to a zero index Interactive Command as 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 Example StrSetChar sb See in Firmware Zip file DIM s sS Hello PRINT StrSetChr 2 04 0 o4 is the ASCII decimal code for the char U PRIT er oei his ol 3 J 7 so will pe extended PRINT Vn os Expected Output 000 Gello ee STRSETCHR Is a core function STRGETCHR FUNCTION STRGETCHR is Used to return the single character at position nindex within an existing string STRGETCHR string nindex INTEGER The ASCII value of the character at position nindex within string where Returns 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 Local Stack Frame Underflow pxCepians Local Stack Frame Overflow Arguments tr
119. cate 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 tor se ese 10 Oe eoar d a An if i 3 then POR oa endif next When you launch the application using AT RUN the following displays w OO a GO Gar 4 Gor Ih fF If you launch the application using AT DBG the following displays Hello World 1 Hello World 2 Hello World 3 cal BREAKPOINT 3333 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 Embedded Wireless Solutions Support Center 28 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 from the current application position as shown below Hello World 1 Hello World 2 Hello World 3 21 BREAKPOINT 3333 I 8 resume Hello World 8 H
120. 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 This event is generated when one or more new characters have arrived EVUARTRX and have been stored in the local ring buffer This event is generated when the last character is transferred from the EVUARTTXEMPTY local transmit ring buffer to the hardware shift register Embedded Wireless Solutions Support Center 128 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Example EVUARTRX sb See in Firmware Zip file DIMENGE HUNGIKHIIONTANGIMmUane RAO PRING nData has arrived nr ENDFUNC 1 cemain blocked in WALIEVENT FUNCTION BtnOPressed ENDEUNG Q re GPIOBindEvent 0 16 1 PRINTE ere es Buton O to e k e tims Fapolrcebion nm ONEVENT EVUARTRX CALE HndireUarcerRsx ONEVENT EVGPIOCHANO CALL BtnOPressed WAITEVENT wait for rx tx and modem status events cole E TE amigos ss Expected Output Press Button 0 TG exit this application Data has arrived Data has arrived Data has arrived EXIN Note If you type unknown commands an E007 error displays in UwTerminal Example EVUARTTXEMPTY sb See in Firmware Zip file FUINCE BOI shave kaea PRINT nix butter is empty
121. con 0 ro gpiobindevent 2 Li 0 event suol burton 1 rc gpilobindevent 3 17 1 SiO burcon 1 oinds a gpio transition low to an event j Sines 42 Golo E e elon mtg roran binds a gpio transition low to an event onevent evgpiochanO call buttonOrelease detects when button 0 is released and Calls the runerion onevent evgpiochanl call buttonOpress Calls the function onevent evgpiochan2 call buttonlrelease Galles the runerzon onevent evgpiochan3 call buttonlpress calls che Funct ron detects when button 0 is pressed and detects when button 1 is released and detects when button 1 is pressed and Prine Ready to beqn button and ERED test n when the program is run Print Please press bur on 0 or burton ism in these lines are printed to the UART Embedded Wireless Solutions Support Center 3 Laird Technologies http ews support lairdtech com www lairdtech com bluetooth Americas 1 800 492 2320 Europe 44 1628 858 940 Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Wait for a synchronous event An application can have multiple lt WaitEvent gt statements waitevent whnen 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 Ready to begin button and LED test Please press button 0 or button 1 Button 0 has been pressed LED O
122. crypt sb See in Firmware Zip file TOILE VeCZOes DIM inbDatas outDatas Create context for EBC mode 128 bit keyo 00 01 02 06 04 0506 07 Ue 09 0208 0G 0b OF Or initVector EBC does not require initialisation vector rc AesSetKeyIv 0x100 16 key initVector IF rc 0 THEN PRINT nEBC context created successfully EESE PRINT Y nfariled tco create EBC conteze ENDIE Hg Bsleco OSS Seo sls aA oes Deol inDataS StrDehexizesS inDataS rce AesEncrypt inDatas outData IF rc 0 THEN PRIND neneryor OK isla PRINT nFailed to encrypt BNE PRINT ean Data gt strhexize gt inDatas PERINNE Mele Data m ye serhiexi7eolOlmDeatas Expected Output Embedded Wireless Solutions Support Center 164 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 EBC context created successfully EnCrEVyoc OK in nData 30313232534353603 36s93Asb3C3DSh3F outData USPzC 2BDL AZ obruezD CPBUsSoC Dee AESENCRYPT 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 AesSetKeylyv 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 AesSeiKeylV In terms of soeed of exe
123. cted Output ee I2C open success Value read from register is 16912 IPCREADREG16 Is a core function I2cWriteREG32 SUBROUTINE 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 12C interface is made available most likely made available by bit bashing gpio I2CWRITEREG32 nSlaveAddr nRegAddr nRegValue Local Stack Frame Underflow EKC EPNONS Local Stack Frame Overflow Arguments byVal nSlaveAddr AS INTEGER puavender This is the address of the slave in range 0 to 127 Peace byVal nRegAddr AS INTEGER g This is the 8 bit start register address in the addressed slave in range 0 to 255 nReaValue byVal nRegValue AS INTEGER g This is the 32 bit value to be written to the register in the addressed slave Interactive Command Ne Related IZCOPEN IZCCLOSE I2CWRITEREAD I2ZCWRITEREG8 IZCWRITEREG 16 Commands 2CWRITEREG32 IZCREADREG8 amp IZCREADREGI6 IZCREADREG32 Example I2cWriteReg32 sb See in Firmware Zip file Please ensure that nSlaveAddr is the slave address of your I2C peripheral DIM handle DIM nSlaveAddr nRegAddr nRegVal DIM re rce I12cOpen 100000 0 handle if ro O THEN Embedded Wireless Soluti
124. ctions 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 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 keyS initVector INTEGER Returns Is OxOO00 if the context Is created successfully Otherwise an appropriate resulfcode is returned which conveys the reason it failed Arguments BYVAL mode AS INTEGER This shall be as follows mode 0x100 for EBC mode 0x101 for EBC mode but data is XORed with same initVector everytime 0x200 for CBC mode BYVAL blockSize AS INTEGER Must always be set to 16 which is the size in bytes BYREF keyS AS STRING keyS This string specifies the key to use for encryption and decryption and MUST be exactly 16 bytes long BYREF initVectorS AS STRING If mode is 0x101 or 0x200 then this string MUST be supplied and it should 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 are 0 is going to be of no value blockSize initVectorS Inter
125. cution for example on the BL600 which does not have AES 128 decryption hardware assist the function has been timed to take roughly 570 microseconds AESDECRYPT inDataS outDataS INTEGER Returns Results in OxOO00 if the data is decrypted successfully Otherwise an appropriate resulfcode Is returned which conveys the reason it failed ALWAYS check this Arguments inData BYREF inDataS AS STRING This string MUST be eacitly 16 bytes long and should contain the data to decrypt BYREF outDataS AS STRING outDataS 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 NO Command Example AesDecrypt sb See in Firmware Zip file DIM e 2 said Cees DIM inData Oul Datar Col DINEE Create Context for CBC mode 128 DIE K a a aa e O O O 07 e a a E Oa Oa Oa a a Nee or he Oi Vai OS hr 05 EROA PE 09 ba 0b EEA ODRES OEN rc AesSetKeylv 0x200 16 key initVectorS IF rc 0 THEN PRINT nCBC context created successfully ELSE PRINT nFailed to create EBC context ENDIF encrypt some data inbData T OMS Sse Se a So SSNS OOOD E E inDataS StrDehexizeS inDataS re AesEncrypt inDatas c 0 IF rc 0 THEN PRINTY DENCE yP E OK ESE Embedded Wireless Solutions Support Center 165 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 22
126. d 1 If nChr is greater than 255 Returns 2 If the string length cannot be extended to accommodate nBlocklen 3 if the resultant string will be longer than allowed 4 If nChr is greater than 255 or less than O 5 if the nBlockLen value is negative Local Stack Frame Underflow Exceptions p Local Stack Frame Overflow Arguments string byRef string AS STRING Embedded Wireless Solutions Support Center 91 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual The target string to be modified byVal nChr AS INTEGER nChr The character that will overwrite the existing characters nChr must be within the range 0 255 byVal nIndex AS INTEGER nindex The starting point for the filling block referenced to a zero index nBlocklen byVal nBlocklen AS INTEGER The number of characters to be overwritten Interactive Command me 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 Example StrSetBlock sb See in Firmware Zip file DIM sS sS HelloWorld PRINDI o vn PRINT StrSetBlock s 64 4 2 WS m n ont ee ee PRINT StrSetBlock s 300 4 200 PS S i coer Expected Output HelloWorld 0 Hell orld 4 Hell orld
127. d then regardless of the existence of the autorun file it enters Interactive mode 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 bower down which provides a complete embedded application The modes of the module and transitions are illustrated in Figure 2 command AT RUN file STOP or END statement or runtime error and no ONERROR handler Figure 2 Module modes and transitions Embedded Wireless Solutions Support Center 11 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Types of Applications There are two types of applications used within a smart BASIC module In terms of composition they are the same but they run at different times Autorun This is a normal application named Sautorun S case insensitive When a smart BASIC module powers up it looks for the Sautorun S 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 applic
128. d Output Hello l1Hello 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 aes Example Continue sb See in Firmware Zip file DIME n 0 WALLE lt 10 n LE A 5 THIEN Embedded Wireless Solutions Support Center 66 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual CONTINUE ENDIF PRINT hello sn ENDWHILE PRINT nk ima shed n Expected Output Hello 1Hello 2Hello 3Hello 4Hello 6Hello VHello 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
129. d platforms like the BL600 modules The verbose explanation is a Embedded Wireless Solutions Support Center 32 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 lia m UwTerminal v6 22 P Terminal BASIC Config About CTS OSA Oco Ale GENERIC FAIL COMS9 9600 N 8 1 icr 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 ver
130. d to the flash file system when in Interactive mode From within a smart BASIC 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 3 GETTING STARTED This section is a quick start guide for using smart BASIC to program an application It shows the key elements of the BASIC language as implemented in the module and guides you through the use of UWTerminal a free Laird Terminal Emulation utility available and Laird s Development Kit to test and debug your application The examples in this section are based upon Laird s BL600 a BLE module However the principles apply to any smart BASIC enabled module Requirements To replicate this example you need the following items ABL600 series development kit UWrTerminal 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 Across compiler application with a name typically formatted as XComp_dddddddd_aaaa_bbbb exe where dddddddd is the first non space eight characters from the response to the AT I 0 command and aaaad bbbb is the hexadecimal output to the command ATI 13 Note aaaa bbbb is a hash signature of the module so that the correct cross compiler is used t
131. ddr nRegVal Open I2C Peripheral rc I2cOpen 100000 0 handle IF cels 0 THEN PRINT nFailed to open I2C interface with error code INTEGER H rc ELSE PRINT nI2C open success ENDIE Write nRegVal to register nRegAddr nSlaveAddr 0xef nRegAddr 0x34 nRegVal 0x4210 re I2cWriteReg16 nSlaveAddr nRegAddr nRegVal LP rol 0 THEN PRINT nFailed to Write to slave register INTEGER H rc ELSE PRINT n nRegVal written successfully to register nRegAddr END I2cClose handle close the port Expected Output I2C open success 16912 written successfully to register 52 Embedded Wireless Solutions Support Center 150 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual IPCWRITEREG16 is a core function I2cReadREG16 SUBROUTINE 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 12C interface is made available most likely made available by bit bashing gpio I2CREADREG16 nSlaveAddr nRegAddr nRegValue Local Stack Frame Underflow cepeng Local Stack Frame Overflow
132. de 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 Example Arithmetic sb See in Firmware Zip file DIM sumi birti bitz a pit 2 3 DIM volume height area height 5 area 20 sumi pitl T PIEZ volume height area Embedded Wireless Solutions Support Center 58 http ews support lairdtech com www lairdtech com bluetooth Laird Technologies Americas 1 800 492 2320 Europe 44 1 628 858 940 Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Prato noum 9 sum Prine nVolume volumes n Expected Output Suml 5 Volume 100 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 I logical NOT bit complement negative negate the variable or number multiplies it by 1 p
133. does an arithmetic exclusive or XOR of all the Unsigned bytes in that substring and then finally Embedded Wireless Solutions Support Center 103 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual XOkRs the signed initial value supplied For example if the string is O1 O02 03 04 05 and offset is 1 and length is 2 and initial value is 1000 then the output will be 1000 2 3 1001 STRXOR string nindex nBytes initVal FUNCTION INTEGER The result of the xor operation over the bytes in the substring If nindex or Returns nBytes are negative then the initVal will be returned Exceptions Local Stack Frame Undertlow i Local Stack Frame Overflow Arguments ti byRef string AS STRING eed String that contains the unsigned bytes which need to be XOR d Ind byVal nindex AS INTEGER a Index of first byte into the string ByVal nBytes AS INTEGER nBytes Number of bytes to process nitVal ByVal initVal AS INTEGER ge Initial value of the XOR Interactive Command we 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 Example StrXOR sb See in Firmware Zip file DIM numbers number 01234 PRINT StrxOR numbers
134. dom number generator function RAND Interactive N Command Associated RAND Commands Embedded Wireless Solutions Support Center Hg Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual RandSeed 1234 Note This subroutine has no effect on modules that have a hardware random number generator 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 Briefly the usage Is select a timer register a handler for if 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 e
135. dss 5 DOJ DOWHILE eredni i 6 B URTE e 60 RO ING rir 182 EAD UD aea A E AEA E 180 EXC SOS SE 50 ING ae E 182 I U eer E E EER 180 FORJ INE AT sessie 6 FONCTION 181 GEMMCK COUNT sisscestasoscaciecosvestdengsesinsaienshdanssens 119 GETTICK SINCE vic cicscscsscnsccnnsacnssaasanseasndacnaanacanes 120 GPIO EVONNS ccccscccnsssssscccssccassssssccessccaseens 178 GPIOUNBINDEVENT sstsscsscstvscascsatecasesavveasesatass 179 FT OY RE aae ersacctes 178 2G EVON S scrieri EE 145 OCLOSE oromere a rE AN iR 146 IF THEN ELSEIF ELSE ENDIF 63 LEPTE a 85 Embedded Wireless Solutions Support Center http ews support lairdtech com www lairdtech com bluetooth 184 SEA ELES ET E AEA T 83 MIDS ee E 86 a TEE A ESET 84 Notepad FE sats ccdesstored vr ctnenteestaeetetendecencetes 20 Numeric Constants cccceeceesescesscceseeesesessseens 55 ONERROR srie EE 67 OMEVEN T a E AA 69 INE AIA ROR oeccedecsvececteersntcecceeotcteoescaesaeeases 68 PRINT a aacesccesanbacestosasecssanteanaseesanseaatace 7 RAND ce 112 111 B Sa eee ne ene ene rere 112 RANDSEED Rae nnn re nee 113 RESET eA E 111 Fe JF caasoesbanacaseaesvaadiceasansianocendoanieess 78 ee E E E E meee 46 RIGHTS oeer E E 87 SELECT CASE CASE ELSE ENDSELECT 64 SENDMSGAPP eere 8 OO EENES OE AEAN AEAEE AN 45 OE VCS oae AAAS 156 SPIC LOS E eer EE 159 EOP EIN oirnne ER 156 SPIRA D ooeec re E EE 161 SPIREADWRITE eere 160 PVN RE eare 161 OI IRIN xtcowsta
136. e 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 orohaned values left on it Defining the arglist The arguments of the function may be any valid variable type 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 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 Em
137. e then highliting it in UwTerminal and selecting Lookup Selected ErrorCode GETLASTERROR Returns INTEGER Last error that was generated Exceptions Local Stack Frame Undertlow Local Stack Frame Overflow Arguments None Interactive No Command Example GetLastError sb See in Firmware Zip file DIM ert err GETLASTERROR PRINT Y nerrcorcr 9050 2 INTEGER H eter Expected Output If no errors from last application run error 0x00000000 GETLASTERROR Is a core function 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 Example ResetLastError sb See in Firmware Zip file DIM err err GETLASTERROR Embedded Wireless Solutions Support Center 78 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual REoOn LAs TERROR PRIME nerror 0x INTEGER H 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
138. e Enter key on the keyboard The smart BASIC implementation 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 If 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 smart BASIC has been designed to work on embedded systems where there is offen 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 In the following example program we are using the variable i to count how many times we print Hello World smart BASIC allows a couple of different variable types numbers 32 bit signed integers and strings Our program stored in a file called HelloWorld sb looks like the following Example HelloWorld sb 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 NEKT Some notes regarding 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
139. e or a received data packet but can be a software generated event too ONEVENT symbolic_name CALL When a particular event is detected program execution routine 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 Embedded Wireless Solutions Support Center 69 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality 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 If must not be a SUB routine If must exist within the application PRIOR to this ONEVENT command Symbolic_Name A symbolic event name which is predefined for a s
140. e read from the slave and on exit will contain the actual number that were actually read If the entry value is 0 then the read phase will be skipped NO IZCOPEN I2CCLOSE I2CWRITEREAD IZCWRITEREGS IZCWRITEREG 16 IZCWRITEREG32 IZCREADREG8 IZCREADREG 16 IZCREADREG32 I2cWriteRead sb See in Firmware Zip file Please ensure that nSlaveAddr is the slave address of your I2C peripheral BUD sete DIM handle DIM nSlaveAddr DIM stWriteS stRead nReadLen rc I2cOpen 100000 0 handle IE cels 0 THEN PRINT inkariled to open O anterface with error code T integer hl re ELSE PRINT nie open success ENDILE Write 2 bytes and read 0 nSlaveAddr 0x6f stWriteS 34 35 stReadS _ nReadLen 0 re I2cWriteRead nSlaveAddr stWriteS stRead nReadLen IF rec 0 THEN PRINT nFailed to WriteRead integer h rc ELSE PRINT Ann te a rr Aea eaa gt ea E 9 a e a eea ENIDILE Write 3 bytes and read 4 nSlaveAddr 0x6f stWriteS 34 35 43 stReadS _ nReadhlen 4 re I2cWriteRead nSlaveAddr stWriteS stRead nReadLen IF rec 0 THEN PRINT nFailed to WriteRead integer h rc ELSE ee a e a a a ea 9S a e aa ea a e E e aa sikeads ENDILE Write 0 bytes and read 8 nSlaveAddr 0x6f stWriteS stRead nReadLen 8 Embedded Wireless Solutions Support Center Bete Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 8
141. e 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 LocalStack Frame Underflow Exceptions Local Stack Frame Overflow Arguments None Interactive Command pe Associated RANDSEED Commands 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 Example RAND sb See in Firmware Zip file PRINT nRandom number 1s T RAND 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 ATI 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 Underflow _emespmene ss Local Stack Frame Overflow sss lt ssSsSSSSCi it Embedded Wireless Solutions Support Center 112 Laird Technologies h
142. eated successfully 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 AesSeiKeylV Embedded Wireless Solutions Support Center 163 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual For example on the BL600 which has AES 128 encryption hardware assist the function has been timed to take roughly 125 microseconds otherwise it can take about 500 microseconds on a 16Mhz ARM Cortex MO processor AESENCRYPT inDataS outDataS Returns Arguments inDataS outDataS Interactive Command Example DIM keyS DME I aie INTEGER Is 0x0000 if the data is encrypted successfully Otherwise an appropriate resulfcode is returned which conveys the reason it failed ALWAYS check this BYREF inDataS AS STRING This string is up to 16 bytes long and should contain the data to encrypt BYREF outDataS 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 NO AesEn
143. eclared then it takes up 10 locations This means that if there is a nest of function calls then in total they should not end up declaring space exceeding this amount 42 Maximum depth of nested user defined functions and subroutines 43 The size of stack for storing user functions simple variables This is the total depth of the stack which Is used to expedite reverse polish notation for arithmetic expressions This needs to be extended only if some very complex nested brackets exist in an arithemetic expression 44 The size of stack for storing user functions complex variables This is the stack used for performing complex epxressions like for example A A hello world 45 The size of the message argument queue length AI CFG is a core Command Embedded Wireless Solutions Support Center 40 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 AI 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 tor downloading files to the module s flash filing system For example web pages x 509 certificates or BLE data AT FOW filename
144. ecommended practice as no at end of name DIM Vedas ace ad 3 INTEGER variables and 1 STRING variable print We will now print each varaible on screen n Prene cenel Cene ceo sS iseime4s Eene semos al az ass ad Since the variables have not been instantiated they hold default values The comma inserts a TAB Expected Output Embedded Wireless Solutions Support Center 52 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality We will now print each varaible on screen 0 O 0 O 0 O 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 modify 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 then within a function or a subroutine that global variab
145. ect 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 Embedded Wireless Solutions Support Center 196 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual SPIOPEN nMode nClockHz nCfgFlags nHande INTEGER Indicates success of command O Opened successfully 0x5200 Driver not found Returns Ox5207 Driver already open Ox5225 Invalid clock frequency requested Ox521D Driver resource unavailable Ox522B Invalid Local Stack Frame Underflow Exceptions Local Stack Frame Overflow Arguments 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 nMode 0 0 0 l O 2 O 3 l l byVal nClockHz AS INTEGER nClockHz This is the clock frequency to use and can be one of 125000 250
146. ee 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 from a file previously opened with FOPEN and will return the actual number of bytes read includes the match byte if encountered FREADUNTIL fileHandle dataS matchByte maxReadLen INTEGER Returns The actual number of bytes read from the file Will be O if read from end of file is attempted Arguments fileHandle BYVAL fileHandle AS INTEGER The handle of the file fo be read from datas BYREF dataS AS STRING The data read from file is returned in this string BYVAL matchByte AS INTEGER matchByte Read until this matching byte is encountered or the max number of bytes are read Whichever condition is asserted first BYVAL maxReadLen AS INTEGER maxReadLen The max number of bytes to read from the file Interactive NO Command Embedded Wireless Solutions Support Center 170 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual See the full and detailed example in the FOPEN section FREADUNITIL is a core language function FILELEN FUNCTION This function is used determine the total size of the file in bytes FILELEN fileHandle INTEGER
147. eeess 177 RISE TO UIC 5 e e E E E E E E E ER 179 Evene ad MESAGE Serre E E EE EE EE eee 182 8 Module COMTGUGALION secsstessdcatnorencatassieawansvacnatesiacaanasacquies aegutansacastea aemwensiacamesiemstonrerases 183 O FCIINO WCAG SSIS vases aeaneaneraoat vouare E A EEE 183 E a ee ee ee eee ee ee ee ne 184 Embedded Wireless Solutions Support Center 5 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 1 SMARTBASIC DOCUMENTATION This Core Functionality user guide provides detailed information on the core aspects of Laird Technologies smart BASIC language which is embedded inside Laird modules This guide designed to make handling BLE enabled end products a straightforward process includes the following An explanation of the language s core functionality Instructions on how to start using the tools A detailed description of all language components and examples of their use A module specific user guide is also available to provide detailed information on applicable smartBASIC extensions relating to Bluetooth BLE and so on Both the Core Functionality and the module specific smarfBASIC extensions user guides are included in the firmware zip file 2 INTRODUCTION TO SMARTBASIC For those with programming experience smart BASIC is easy to use because it is derived from t
148. eis e hom Wo called whem Ene burton 1 is released gpiowrite 19 0 print Button 1 has been released n the button is released jon Mane Wilt Ik DOU inves tele elic arial endfunc 1 urne aED l or these lines are printed to the UART when PMc t lomo eroniercesc 7 Pits seuner Lone a when rie somtirom 1 is pressed qGplowrite 19 1 print Button 1 has been pressed n the button is pressed Prine SED lh Will light witle bine bDutron ts preco jm endfunc T j 7 Verne LEED Mon these lines are printed to the UART when p KR KKK KKK KKK KR KK KK KK IK I KK I KK KK IK I KK IK KK IK I KK IKK KK KK I KK KK KK KK Kk ij Bander definicions p KR KKK KKK KKK KK KK KK KK KR KK I US US KK DE DS DE I KK I KK KK IK I KK IK KK IK OK KK KK DS DS DE KK Kk p KR KKK KKK KKK KK KK KK KK KK KK IKK KK IK I KK IKK KK IK KK IK KK KK I KK KK KK KK Kk SOUL Le DE wo main In C p KKK KK KK KKK KK KK KK KK KK KK I KK KK IK KK I KK KK I KK KK IK KK KK KK KK KK kk KK TA Ce sGoreseenunme a a 7 Sere siol Putton O as a digital am with a weak pull up resistor re GOLoser tume l 7 seus Slol Buttons l as a digital in with a weak pull up resistor re Go1Osekfune ls 2 0 7 sers Siel3 LEDO as a digital out re GpLloseriune 19 2 0 j sets s109 TLTED as a Olgital our re gpiobindevent 0 16 0 pindo a ODO ran te von Nian roman event Sslol6 burton 0 re goeLlobindevent l le 1 SO UG bur
149. ello World 9 Hello World 10 Structuring an Application Applications must follow smart BASIC 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 driven paradigm Typically do something only when something happens This smart BASIC implementation has been designed from 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 smart BASIC 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 helo document the application Includes The cross compiler which is automatically invoked by UWTerminal allows the use of DEFINE
150. en as DCH NO poriuy 16 GCavabits otopi tS Cre ris flow Con ol IF cels 0 THEN PRINT nFailed to open UART interface with error code INTEGER H rc ELSE PRINT nUART open success ENDIF Embedded Wireless Solutions Support Center 131 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual PRINT mPrese DuleeonU to exil this appl ication im WAITEVENT wait for rx events PRINT MANEXLEINO N Expected Output UART open successful Press buttonu to exit this application laird Data has arrived Data has arrived Data has arrived Data has arrived Data has arrived Data has arrived EXITING sa 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 see hardware specific user manual for actual default value 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 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 U
151. ent 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 Embedded Wireless Solutions Support Center 50 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality 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 byRef TYPE A description with type of the 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 Ex
152. es http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual UNTIL x 32768 elapseMs GetTickSince startTick PRINT n nThe Do Until loop took elapseMS msec to process Exoected Output The Do Until loop took 21 msec to process 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 oush pop manner This section describes functions that allow these to be created so that they can be expedited as fast as possible without the soeed 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 capacity set by the caller Most often it will be Used as a first in first out queue CIRCBUFCREATE nltems circHandle INTEGER Returns hn tlt An integer result code The most typical value is OxO000 which indicates a successful operation Arguments Embedded Wireless
153. esponding 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 Local Stack Frame Underflow EXCEPNON Local Stack Frame Overflow Arguments byRef string AS STRING string The target string m NO If STIRVALDEC 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 Embedded Wireless Solutions Support Center 97 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality 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 Example StrValDec sb See in Firmware Zip file DIM s s 1234 PRINT wa er al Deolen s 1234 PRINT ne SenValbec ss 8 ee ey PRN va Sere ubeen so s 2345hello PRINT n tr Valbec es sS hello PRN Vere er alec ss Expected Output STRVALDEC is a core function STRHEX2BIN This function is used to convert up to 2 hexadecimal characters at an offset in the input string i
154. ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 adaress Interactive No Command Example SysInfo sb See in Firmware Zip file PRN iors Imroon 4 MO SNS NEOS 4 PACs s Vom module PRINE ns ysintos 14 Pe oy SUNOS 4 aes ono ine sc amcdom addisees PRK vas vie Iiaico 0 SS NEOs 0 Expected Output SysInfos 4 O1L FA 84 D7H D9 03 Syeintoe 14 O1L FA 84 D7H D9 03 SysInio 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
155. 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 Embedded Wireless Solutions Support Center 68 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 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 handler returns a zero value then the next statement after WAITEVENT is processed Otherwise WAITEVENT continues to wait for another event WAITEVENT Interactive Command ie BUNGE ION Punco PRINT ak Oo ENDFUNC 1 FUNCTION Punci PRN DEVIT ENDFUNC 0 ONEVENT EVO CALL Fungo ONEVENT EVI CALL Funcl WALTEVENT Weal ror an event bOmeOCcelic 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 chang
156. g 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 Interactive NO Command Example SysInfo sb See in Firmware Zip file PRINT ios inte 2003 USS EINE O ZIONS Vo Numbat von femmes PRINT Ss ysinke O00 Hee NSIS LOO BASIC compiler HASH value PRINT noys Ini o Oe 010 9S VGINrO Oxc0l0 77 Code memony page size from TOR Exoected Output For BL600 Syertnio 1000 1315469536 SySlnio 2005 8 Syeinio Uxs010 1024 SYSINFO is a core language function SYSINFOS FUNCTION Returns an informational string value depending on the value of varld argument SYSINFOS varld Returns STRING Value of information corresponding to integer ID requested Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments varld byVal varld 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 Embedded Wireless Solutions Support Center 80 Laird Technologies http
157. he 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 smart BASIC are interpreted languages but in the interest of run time soeed on an embedded platform which has limited resources smart BASIC s program text is parsed and saved as bytecodes which are subsequently interpreted by the run time engine to execute the application On some module platforms which have limited code flash space the parsing from source code to bytecode is done on a Windows PC using a free cross compiler supplied by Laird Other platforms with more firmware code space also offer on board compiling capabilities in addition to the external cross compilation utility 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 smart BASIC was developed by Laird to offer structured programming constructs It is not line number based and it offers the Usual modern constructs like sub
158. he flag mask in the input parameter Please see UartClose for more details UARTCLOSEEX nFlags INTEGER keilum An integer result code The most typical value is 0x0000 which indicates a successful operation If Ox5231 is returned it implies one of the buffers was not empty so not closed Exceptions Local Stack Frame Underflow i Local Stack Frame Overflow Arguments 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 nFlags has the same effect as UartClose routine Bits 1 to 31 are for future Use and must be set to O Interactive NO Command UARTOPEN UARTINFO UARTWRITE UARTREAD UARTREADMATCH UARTGETCTS sais p UARTGETDCD UARTGETRI UARTSETDTR UARTSETRTS UARTSETDCD UARTSETRI ae UARTBREAK UARTFLUSH Embedded Wireless Solutions Support Center Io Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Example UartCloseEx sb See in Firmware Zip file DME DINER UartClose rel Uar Open 9600 0 0 CNSlH open as DTE at 300 baudrate odd parity Sdaeaotes li stropo cra reo 1 on Control PRIN haice IF UareClosekx 1 0 THEN PRINE Y nDarca in are least one burrter Uart Porr nor closed Eos rol Vartooen 9600 0 0 CNelH open as DIE at 300 baudrate odd parity PRINT
159. he offset is relative to the beginning of the file or the Current position or the end of the file which is soecified by the whence parameter FSEEK fileHandle offset whence INTEGER Returns Is O if successful Arguments fileHandle BYVAL fileHandle AS INTEGER The handle of a file for which the file pointer is to be moved BYVAL offset AS INTEGER offset This is the offset relative to the position defined by the whence parameter BYVAL whence AS INTEGER This parameter specifies from 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 whence all other values from the beginning of the file 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 ne 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 fo 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 sirvarS Embedded Wireless Solutions Support Center I2 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Eur
160. ifies that the token was successfully found and the value is the ID Returns 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 Local Stack Frame Underflow E ti PORRES Local Stack Frame Overflow Arguments byRef string AS STRING string The lookup table that is being searched irtok byRef strtok AS STRING me The token whose position is being found Interactive Command we 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 fo a temp string variable and then pass it to the function Associated Commands TABLEINIT TABLEADD Example TableLookup sb See in Firmware Zip file DIM te PRINT Webletlni ethos Vm va PRINT TableAdd PRINT TableAdd PRINT TableAdd PRINT TableAdd core nelle wie vine Se WOmLa me in ioc TEOT 3 TUA TA Eo LEONA 4 F MATANE PRINT Tapletookup ro bo An PRINT Hablelbookua tes Hello mn PRIME TableLookup o 7 you me Expected Output Embedded Wireless Solutions Support Center 110 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 TABLELOOKUPFP is a core function Miscellaneous Routines This section describes all miscellaneous functions and subroutines RESET SUBROUTIN
161. il re DIM circHandle DIM i re CircBufCreate 1l16 circHandle LF re 0 then PRINT nilhe circular buffer was not created n BLSE PRINT nThe circular buffer was created successfully n HNDI E J write 3 values into che circular bourter Embedded Wireless Solutions Support Center I2 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual POR i le ROS re CircBufWrite circHandle i IF rc 0 then PRINT nWal led to write into the Circular butter n ATOE PRINE i was successtuly written to the circular Duller I BND I E NIET 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 INTEGER An integer result code The most typical value is 0x0000 which indicates a Returns successful operation Note If the buffer was full and the oldest value
162. in the section Arithmetic Expressions IntegerconstX One or more comma seperated integer constants corresponding to one of the possible values of arithexpr which identifies the block that will get processed Interactive Command NO Example SelectCase sb See in Firmware Zip file DIMERORE a 3 b 4 Use to write multiple commands on one line SELECT a o CASE 10 c 10 CASE 12 J7fenis block will get processed c CASE 14 156 789 1022 c CASH Bilis c 0 ENDS hike E PRINTI G Expected Output Embedded Wireless Solutions Support Center 65 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 Firmware Zip file DIM Mm n 0 WHILE n lt 10 n n 1 IF n 5 THEN BREAK ENDIF PRINT Hello sd ENDWHILE PRINT in re ohed in Expecte
163. in byRef string AS STRING siring The string from which the character is to be extracted ainda byVal nindex AS INTEGER The position of the character within the string zero based see Embedded Wireless Solutions Support Center 90 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual example Interactive NO Command 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 Example StrGetChar sb See in Firmware Zip file DIM sS sS Hel lo PRN sess ne PRENT SerGerehnr ss 0 ASC value for I nm PRINT StrGetChr ss l gt ASCII value fore vn PRINT otrGet hr so O0 error an PRINTF StrcetChr so 0 gt error n Expected Output ASCII value for H ASCII value for e a Oe a SCrrCor STRGETCHR is a core function STRSETBLOCK FUNCTION STRSETBLOCK allows a specified 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 INTEGER Represents command execution status O Ifthe block is successfully update
164. ing 99 reser sirZs ret 0 BLSE PRINT n n nNow type something without the letter a n strS You sent reset strs Embedded Wireless Solutions Support Center 140 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual elie 7r o 7 ASCII decimal value for a ret l ENDIF ENDEUNG creat ONEVENT EVTMRO CALL Hindi linn 6 ONEVENT EVUARTRX CALL HndlrUartRx PRINT nWhat is your name n WALTEVENT Expected Output What is your name Your name is David Now type something without the letter a You sent hello Match character a not found FRI TING 2 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 message 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 fo transmit data to from the buffers UARTFLUSH bitMask Local Stack Frame Underflow Exceptions
165. irdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 separator 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 type minchar gt strexpr lt separator gt Type
166. ireless Solutions Support Center 102 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual STRSUM string nindex nBytes initVal FUNCTION INTEGER The result of the arithmetic sum operation over the bytes in the substring If Returns nindex or nBytes are negative then the initVal will be returned Local Stack Frame Underflow EXCEPTIONS Local Stack Frame Overflow Arguments byRef string AS STRING string String that contains the unsigned bytes which need to be arithmetically dded byVal nindex AS INTEGER nindex Index of first byte into the string ByVal nBytes AS INTEGER nBytes Number of bytes to process ByVal initVal AS INTEGER initVal Initial value of the sum Interactive Command me 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 Example 2 Strosum so See in Firmware Zip file DIM s SSS 0a A5 PRIT tro ome Ono mn 48 97 65 37 60 0 PRINT troum SS O 5 Oy 5 vay 48 97 65 37 604 10 PRINT troum oo 4 lOO an 60 100 Exoected Output en oh 160 STRSUM is a core function STRXOR This function identifies the substring starting from a specified offset and specified length and then
167. is means the caller does not need to call strlen function to determine how many bytes in the string that need to be processed Local Stack Frame Underflow Exceptions Local Stack Frame Overflow Uart has not been opened using UARTOPENxxx Arguments Pave byRef strMsg AS STRING g The content of the receive buffer will get appended to this string byval nMaxLen AS INTEGER nMaxLen The output string strMsg will never be longer than this value If a value less than 1 is soecitied it will be clipped to 1 and if gt that OxFFFF it will be clipped to OxFFFF Interactive Command we Related UARTOPEN UARTINFO UARTCLOSE UARTWRITE UARTREADMATCH UARTGETDSR Embedded Wireless Solutions Support Center 138 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual UARTSETRI UARTBREAK UARTFLUSH 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 Example DEM we o trlength otr Siro Your name is BUNGE Ol Sr nciliat aiswiw lt limerstart 0 10070 Allow enough time for data to reach rx buffer ENDEUNC UIE IOs Naliovel EO strLength UartReadn str 11 PRs Va Sees ENDFUNC 0 ONEVENT EVTMRO CALL Hindle Imro
168. ite i ELSEIF ce 0 THIEN PRINT Y nFfailed TO write 1nTO the circular buffer BENDIS re CircBuriltems cirecHandle nitems IF rc 0 THEN PRINT Vna emabbems 7 icems in the circular butter BNDL E NEXT Expected Output The circular buffer was created successfully items J the circular buffer items J the circular buffer items J the circular buffer 4 items in the circular buffer Oldest value was discarded to write 5 4 items in the circular buffer CIRCBUFITEMS is an extension function Embedded Wireless Solutions Support Center 127 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Serial Communications Routines In keeping with the event 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
169. l D 1234 or 1234 default Hex H 1234 or 0x1234 Octal O 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 Embedded Wireless Solutions Support Center 595 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual A hexadecimal constant consists of a string consisting of characters 0 to 9 and A To F a tof 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 A binary constant consists of a string consisting of characters 0 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 cons
170. laying out the rules of the application source syntax smartBASIC Statement Format The format of any line of smart BASIC is defined in the following manner COMMENT COMMAND STATEMENT DIRECTIVE lt COMMENT gt TERMINATOR Embedded Wireless Solutions Support Center Zo Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 th
171. le cannot be accessed Variable Class smart BASIC supports two generic classes of variables Simple Numeric variables There is currently one type INTEGER 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 platforms 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 BL600 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 Firmware Zip file DIM 1s ac SlRING DIM ae as STRING aS Laird oe Alo Rocke it Here we are concatenating the two strings jong ian abs Expected Output LairdrRocks Embedded Wireless Solutions Support Center 53 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026
172. lication files must be stored in one continguous memory block This means the file system Is currently restricted so that if is NOT possible for an application to open a file and then write fo If To store application data so that they are non volatile use the functions described in the section Non Volatile Memory Management Routines All user data files must be preloaded using the following commands which are described in the section Interactive Mode Commands AT FOW AT FWR or AT FWRH AT FCL The utility UwTerminal helps with downloading such files but is not required With the use of READ FTELL and FSEEK downloading configuration files such as digital certificates can be a useful and convenient way of making an app behave in a 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 file 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 fo the size of the read Embedded Wireless Solutions Support Center 167 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core
173. lting from arithexpr3 is added to var if TO is specified or subtracted from var if DOWNTO is specified The function continues to loop until the variable var contains a value less than or equal to arithexpr2 in the case where TO Is specified or greater than or equal to arithexpr2 in the alternative case where DOWNTO is specified Note In smart BASIC the Statement Block is ALWAYS executed at least once Interactive Command NO Example ForNext sb See in Firmware Zip file DIM a FORTA IEE 2 PRINT Helio NEXT PIE A al FOR a 2 DOWNTO 1 PRINT Hello NEXT foe tar te ine FOR a l TO 4 STEP 2 PRINT HeLllo NEXT Expected Output HelloHello HelloHello HelloHello FOR NEXT Is a core function Embedded Wireless Solutions Support Center 62 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 expressio
174. lue of variables used as parameters if it accepts them as references rather than values For example STRSHIFTLEFT stringS 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 If an argument is passed as byRef then the function or subroutine byRef 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 specified number of places STRSHIFTLEFT stringS num It is used 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 Argumen
175. mand 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 no effect The following output displays World World World World World World World World World World FO Crs CO Cl E GW Nf In UWTerminal next clear the screen using the Clear button and then unselect the checkbox labelled DTR so that the nAuUTORUN 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 smart BASIC 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 smart BASIC 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
176. mand and must be terminated by a carriage return for it fo be processed Adding the sign to an AT DEL command can be used to force the deletion of an open tile For example use AT DEL filename to delete an application which you have just exited after running it Examples AT DEL data AT DEL myapp AI DEL is a core Command Embedded Wireless Solutions Support Center 3 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 Returns If the filename does not exists the AT RUN will resoond 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 Interactive Command ues This is an Interactive
177. mask Integer corresponding to a bit mask or the character Interactive Command es The mask is an additive integer mask with the following meaning Erases normal file system and system config keys see AI CFG for examples of config keys 16 Erases the User config keys only Embedded Wireless Solutions Support Center 47 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 0x100 Erases the Config Keys Dictionary and set to defaults only if enabled in the build Ox40000_ Erases the user keys dictionary see NvRecordGet Set only if enabled in the build 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 fo be processed 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 n0O r Arguments None Interactive Command This is an Interactive Mode command and MUST be terminated by a carriage return for it fo be processed Examples AT Z AT Z is a core command
178. me Underflow ACERTAS Local Stack Frame Overflow Arguments byRef string AS STRING string The target string which cannot be a const string Interactive Command oe Example StrLenS sb See in Firmware Zip file DIM ss So Helloworla PRINT Nin So te St riem Gome byes Lona Expected Output 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 INTEGER Zero indexed position of string2 within string 1 Returns gt 0 If string2 is found within string and specifies the location where found If string2 is not found within string E fi Local Stack Frame Underflow AREPA Local Stack Frame Overflow Arguments trina byRef string AS STRING siring The target string in which string2 is to be searched for byRef string AS STRING string2 The string that is being searched for within string This may be a single character string Embedded Wireless Solutions Support Center 88 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual tart byVAL startpos AS INTEGER sai sie Where to start the position search Interactive Command ne
179. mode command and must be terminated by a carriage return for it fo 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 AI 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 Examples AT RUN NewApp or NewApp AT RUN is a core command AT DBG COMMAND AI DBG runs a precompiled application that is stored in the flash file system In contrast to AT RUN debugging is enabled AT DBG filename Embedded Wireless Solutions Support Center 38 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Returns If the filename does not exists the AT DBG will resoond with an error response When the application aborts or if the application reaches its end a deferred 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 Interactive Yes Command This is an Interactive mode command and must be terminated by a carriage return for it fo be pr
180. n startup M n 1 255 specifies a comport number BAUD n 1200 921600 Could be limited to 115200 depending on PC hardware Figure 3 UWWTerminal opening screen 3 Click Accept fo open the configuration screen Embedded Wireless Solutions Support Center 14 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Terminal BASIC Config About OK Cancel Quit COM Poll for port V Use AT FWRH Command Comport Baudrate 9600 X 48 Max 4T FWRH Command Length C Tep Socket Parity None v Stop Bits 1 v Line Terminator CR Data Bits 8 X CL Handshaking CTS RTS V Trace Log BASIC comms traffic in Terminal Window OCRA LE COLRER Log Filename l Append Figure 4 UWWTerminal Configuration screen 4 Enter the COM port that you have used to connect the develooment board The other default parameters should be Baudrate 9600 Parity None Stop Bits 1 Data Bits 8 Handshaking CTS RTS Note Comport not Tcp Socket should be selected on the left Other modules may use different settings please check the corresponding extension manuals for this information 5 Select Poll for port fo 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
181. n 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 blown customised terminal emulator for Windows available upon request at no cost See Chapter 2 UWlerminal for information on writing smart BASIC applications using UWTerminal UWTerminal also embeds smart BASIC to automate its own functionality the extension smart BASIC functions facilitate the automation of terminal emulation functionality smartBASIC Operating Modes Any platform running smart BASIC 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 fo the behavior of a modem using AT commands Interactive mode can be used by a host processor to directly configure 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 Embedded Wireless Solutions Support Center 10 Laird Technologies http ews support lairdtech com Americas 1 800 4
182. ncounter 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 0 value then the application will exit the module from Run Mode into Interactive Mode which will be disastrous for unattended operation 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 I 2003 or at runtime by SYSINFO 2003 Example EVTMRn sb See in Firmware Zip file FUNCTION HandlerTimer0 PRINT nTimer 0 has expired ENDFUNC 1 cemain blocked in WAILTEVENT FUNCTION HandlerTimerl PRINT nTimer 1 has expired ENDFUNC 0 eie From WAL Ven ONEVENT EVTMRO CALL HandlerTimerO ONEVENT EVTMR1 CALL HandlerTimerl Timer eare 0 500 l State a 500 millisecond recurring Eimer Embedded Wireless Solutions Support Ce
183. nction Example StrFPill sb See in Firmware Zip file DIM hello PERTANT as oi PRINT Sere ill ss Aa a iat PRIN oo Gall ELINT trr soo 7 Expected Output hello CHCKCECECECTC 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 for 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 Local Stack Frame Underflow Ex tion ene Local Stack Frame Overflow Embedded Wireless Solutions Support Center 93 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Arguments byRef string AS STRING string The string to be shifted left byVal numChrs AS INTEGER nume The number of characters that the string is shifted to the left j If numChrs is greater than the length of the string then the returned string will be empty Interactive Command we 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
184. ne enra Na AE E T E RE E a ere 111 Random Number Generation Routines cccccecccsecccecccseccceccencecnecceceenceeneceeceeuceeueseestenseeueeeeseeuseenseeeeeeeeseeness 111 Embedded Wireless Solutions Support Center 4 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual PUERTO RTECS eari omord steabunnsiliseneseiaiaesabedale E E E 114 Circ lar Buffer Management FUNCTIONS fcincoccssesrecncocasntrensessansnncsiestineganeutiniaundunonetardansauoatoarsanstoeadanmtuneaeeiionedesteenetae 121 Serial COMMUNICATIONS ROUTINES ecirccvascssic scatuacerseicearanndebgesadaCanacsaneegoaninidamadantiegoanidedeuadasebanentarieansuaaanaedsaedeansuatungentbas 128 POE eB eal Interiace or TW Ioaea nsns ert ner rrnn tC Be fort petite es Snir nor Re tren E rer eee 145 SPIN EN CS reteset dane sects nasncsneceattsns Garces serene waite bate tester Dace tine Sete E slg pond bated pas dareanea T 156 TT aie VV FONC ONS ate pcs ps ccesrare tare E edness ener EEE nn ca eee aries E pan cease er EAE 162 Pero F INCE ONS eE E EE EEEE 167 Non Volatile Memory Management ROutines ccccssccccsssccccesecccsensccsaeeeccseaecessescesseecessucesseuscesseneeesaaesessaaees 172 Input Output Interface ROUTINES cccccccccccccccccccccecceeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
185. ng Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual byVal nSlaveAdadr AS INTEGER PI OVEAGNI This is the address of the slave in range 0 to 127 nRegAddr byVal nRegAddr AS INTEGER This is the 8 bit register address in the addressed slave in range 0 to 255 byRef nRegValue AS INTEGER nRegValue The 8 bit value from the register in the addressed slave will be returned in this variable Interactive Command ee Related IZCOPEN I2CCLOSE I2CWRITEREADS IZCWRITEREGS8 IZCWRITEREG 16 Commands 2CWRITEREG32 IZCREADREG8 IZCREADREGI6 IZCREADREG32 Example I2cReadReg8 sb See in Firmware Zip file Please ensure that nSlaveAddr is the slave address of your I2C peripheral DIM rc handle nSlaveAddr nRegAddr nRegVal Open I2C Peripheral rc I12cOpen 100000 0 handle IE cels 0 THEN PRINT nFailed to open I2C interface with error code INTEGER H rc ELSE PRINT i Ze ooenmsuCceese ENDINE Read value from address 0x34 nSlaveAddr 0x6of nRegAddr 23 re I 2cReadReg8 nSlaveAddr nRegAddr nRegVal LE pels Q THEN PRINT nFailed to Read from slave register INTEGER H rc BLSE PRINT nValue read from register is nRegVal ENDIF I2cClose handle close the port Expected Output O S I2C open success Value read from register is 99 IZCREADREG8 Is a core function I2cWriteREG16 SUBROUTINE This function is used to write a 16 bit value to 2 registers inside a slave and
186. ns 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 arithexpr_1 THEN statement block A ENDIF IF arithexpr_1 THEN statement block A ELSE statement block B ENDIF IF arithexpr_1 THEN statement block A ELSEIF arithexpr_2 THEN statement block B ELSE statement block C ENDIF Statement block A B C A valid set of zero or more program statements 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 Firmware Zip file DIMEN n 1 ie el O N PRINT Laird Rocks n ENDIF IF n 0 THEN PRIN Sao eas lt 0 ELSEIF n 1 THEN BRENA a Embedded Wireless Solutions Support Center 63 Laird Technologies http ews support lairdtech com www lairdtech com bluetooth Americas 1 800 492 2320 Europe 44 1628 858 940 Hong Kong 852
187. nter 114 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual PRINT nWartting for Timer 0 Waninesesteenes iL LOO 0 V Secu cr LOCO ml Llrsecene hime t PRINT nWartimg for Timer 1 WAITEVENT PRINT nGot here because TIMER 1 expired and handler returned 0 Expected Output Waiting for Timer 0 Waiting for Timer 1 Timer 0 has expired Timer 0 has expired Timer 1 has expired Got here because TIMER 1 expired and handler returned 0 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 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 number SYSINFO 2003 If the value is not valid then a runtime error will be thrown with code INVALID_TIMER byVal interval AS INTEGER A valid time in milliseconds between 1 and 1 000 000 000 11 6 days Note although the time is specified in milliseconds the resolution of the hardware timer may have more g
188. nto an integer value in the range O to 255 STRHEX2BIN string offset FUNCTION INTEGER A value in the range 0 to 255 which corresponds to the up to 2 hex Returns characters at the specified offset in the input string Local Stack Frame Underflow pacernen Local Stack Frame Overflow Arguments byRef string AS STRING string The string to be converted into hex characters byVal offset AS INTEGER offset This is the offset from where up to 2 hex characters will be converted into a binary number Interactive Command big Embedded Wireless Solutions Support Center 98 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality 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 STRHEXIZE Example StrHex2Bin sb See in Firmware Zip file DIM s So 010270804057 PRIN erer Bahia SS 4 6 ia 3 4C61697264 PRINT Strhex2Bin 39 2 ae Expected Output 4 97 STRHEX2BIN is a core function STRING from INTEGER Three functions above STRVALDEC STRHEX2BIN and EXTRACTINTTOKEN enable conversion of a string into an INTEGER value To achieve the reverse that is an INTEGER into a string the q
189. number designated for that special I O pin corresponds to the nSigNum argument GPIOREAD nSigNum INTEGER the value from the signal If the signal number is invalid then it will return value 0 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 Returns Note See module specific user manual for details 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 0 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 GpioContigPWM If the GPIO pin has been configured as a FREQUENCY output then the nNewValue specifies the desired frequency in Hertz in the range O to 4000000 Setting a value of O makes the output a constant low value Setting a value greater than 4000000 will clio the output to a 4MHz signal GPIOWRITE nSigNum nNewValue Note See module specific user manual for details 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 Embedded Wireless Solutions Support Center 170 Laird Technologies http ews suppo
190. o 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 Embedded Wireless Solutions Support Center ee Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 terminal emulation application with additional GUI extensions to allow easy interactions with a smart BASIC 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 UWWTerminal 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 smart BASIC embedded so you can locally write and run smart BASIC applications This allows you
191. o read from the circular buffer BLSE PRINT NData n ENDIF NEXT Expected Output The circular buffer was created successfully WELLING Oldest value was discarded to write 5 Reading 2 2 i CIRCBUFREAD is an extension function CircBufltems FUNCTION This function is used to determine the number of integer items held in the circular buffer Embedded Wireless Solutions Support Center 126 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual CIRCBUFITEMS circHandle niltems INTEGER a result code Returns The typical value is Ox0000 indicating a successful operation If 0x5102 is returned it implies the buffer was empty so nothing was read Arguments byRef circHandle AS INTEGER circHandle this identifies the circular buffer which needs to be queried byRef nitems AS INTEGER nData This returns the total items waiting to be read in the circular buffer Interactive No Command Example CircBufItems sb See in Firmware Zip file DIM rc circHandle i nItems rc CircBufCreate 4 circHandle IF rc 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 CircBurOverwrite cCircHandle 1 LE ee 0x5103 THEN PRINT nOldest value was discarded to wr
192. ocessed 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 Examples AT DBG NewApp AI 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 AI CFG Is used to set a 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 2 syntax is used to query the current value When the value is read the syntax of the response Is 2 Oxhhhhhhhh dddd Embedded Wireless Solutions Support Center 37 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2
193. of Memory Arguments recnum byVal recnum AS INTEGER Embedded Wireless Solutions Support Center 173 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual The record number that is to be read in the range 1 ton where n is the maximum number of records allowed by the specific module strvar byRef strvarS AS STRING The string variable that will contain the data read from the record strdef byVal strdefS AS STRING The string variable that will supply the default data if the record does not exist Interactive Command we Example NvRecordGetEx sb See in Firmware Zip file DIM r PRINT NvRecordGetEx 100 r default bytes read PRINTE ete ares Expected Output 7 bytes read default NVRECORDGETEX is a module function NvRecordSet FUNCTION NVRECORDSET writes a value to a user record in non volatile memory For each record saved an extra 28 bytes is used as an overhead so it is recommended to minimise the writing of small records NVRECORDSET recnum sirvarS INTEGER Returns the number of bytes written If an invalid record number is soecified then 1 is returned There are a limited oe number of user records which can be written to depending on the specific module E tions Local Stack Frame Underflow ASEE Local Stack Frame Overflow Argument
194. of your I2C peripheral DIM rc handle nSlaveAddr nRegAddr nRegVal Open I2C Peripheral rc I2cOpen 100000 0 handle IFP rel 0 THEN PRINT nFailed to open I2C interface with error code INTEGER H rc ELSE PRINT ni2C open success ENDINE Write nRegVal to register nRegAddr nSlaveAddr 0x6f nRegAddr 23 nRegVal 0x63 rc I2cWriteReg8 nSlaveAddr nRegAddr nRegVal IF rc 0 THEN PRINT nFailed to Write to slave register INTEGER H rc SE PRINT n niRegVal written successtully to register nRegqAddr hei I2cClose handle close the port Expected Output I2C open success 99 written successfully to register 23 IZCWRITEREG8 Is a core function I2cReadREG8 SUBROUTINE 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 I2C interface is made available most likely made available by bit bashing gpio IZCREADREGS8 nSlaveAddr nRegAddr nRegValue Local Stack Frame Underflow Exceptions p Local Stack Frame Overflow Arguments Embedded Wireless Solutions Support Center 148 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Ho
195. oken to be added to the table byVal nID AS INTEGER nID The identifier number that is associated with the token and should be in the range 0 to 255 Interactive Command me 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 TABLEINIT TABLELOOKUP Example TableAdd sb See in Firmware Zip file DIM eo PRONE To blera roe a PRINT Tabletdd ts Hello E PRINT TableAdd ts everyone 2 n Ee TNT Tan L Adde gt co ASO ou ia BRN TaLe Adde On a in PRINT ts Tokens are stored in TLV format Tag LengthValue Expected Output 01 05Hello 02 08everyone TABLEADD Is a core function TABLELOOKUP Embedded Wireless Solutions Support Center 109 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual FUNCTION TABLELOOKUP searches for the specified token within an existing lookup 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 INTEGER Indicates success of command gt 0 sign
196. ons Support Center 1aZ Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual PRONE neadiled fo open IZe interface wath error code T TNTECER kh ire ELSE PRINT nI2C open success ENE nSlaveAddr Oxof nRegAddr 0x56 nRegVal 0x4210FEDC re I2cWriteReg32 nSlaveAddr nRegAddr nRegVal IF rel 0 THEN PRINT nFailed to Write to slave register INTEGER H rc BLOS PRINT 2n nkegval written successfully to register nRegAddr ENDL I2cClose handle close the port Expected Output I2C open success 1108410076 written successfully to register 86 IZCWRITEREG372 is a core function I2cReadREG32 FUNCTION 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 12C interface is made available most likely made available by bit bashing gpio I2CREADREG32 nSlaveAddr nRegAddr nRegValue Local Stack Frame Underflow AEPS Local Stack Frame Overflow Arguments byVal nSlaveAddr AS INTEGER M AVEAGAL This is the address of the slave in range 0 to 127 nRegAddr byVal nRegAddr
197. ope 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual INTEGER the number of bytes that were read into strvarS A negative value is returned If an error was encountered sf Recnum is not in valid range or is unrecognised Returns 20 Failed to determine the size of the record The raw record is less than 2 bytes long possible flash 3 corruption 4 Insufficient RAM 5 Failed to read the data record E i Local Stack Frame Underflow sa PUTS Local Stack Frame Overflow Arguments byVal recnum AS INTEGER recnum 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 strvars byRef strvarS AS STRING The string variable that will contain the data read from the record Interactive Command we Example NvRecordGet sb See in Firmware Zip file DIM r PRINT NvRecordGet 100 r bytes read PREN Te Vnt iS Expected Output When no data present in record O bytes read NVRECORDGET is a module function NvRecordGetEx FUNCTION NVRECORDGEIX reads the value of a user record as a string from non volatile memory and if it does not exist or an error occurred then the specified default string Is returned NVRECORDGETEX recnum strvarsS sirdef Returns INTEGER the number of bytes that are read into strvars Local Stack Frame Underflow Exceptions Local Stack Frame Overflow Out
198. ositive 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 0 or 1 value in the expression lt Less Than Or Equal results in a O or 1 value in the expression gt Greater Than results in a 0 or 1 value in the expression gt Greater Than Or Equal results in a O or 1 value in the expression 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 A Bitwise XOR exclusive OR Bitwise OR Embedded Wireless Solutions Support Center 97 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 smart BASIC does not support program flow functionality based on unconditional statements such as JUMP or GOTO In m
199. ost 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 ATI CFG command DO UNTIL This DO UNTIL construct allows a block of one 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 Firmware Zip file DIM a AS INTEGER don t really need to supply AS INTEGER a 1 DO a atl PRINT a UNTIL a 10 loop will end when A gets to the value 10 Expected Output 2345678910 DO UNTIL is a core function Embedded Wireless Solutions Support Center 60 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567
200. owing ones are typical AT Returns 00 if the module is working correctly ATI3 Shows the revision of module firmware Check to see that it is the latest version ATI13 Shows the hash value of the smart BASIC build ATl4 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 Embedded Wireless Solutions Support Center 18 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 Your First smarftBASIC Application Create Hello World App Let s start where every other programming manual starts with a simple program to display Hello World on the screen We use Notepad to write the smart BASIC application To write this smart BASIC application
201. pecific 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 aie Note This example was written for the BL600 module so the signal numbers used in the GploBindEvent statements may be different depending on your module Example OnEvent sb See in BL600CodeSnippets Dit ine FUNCTION BtnOpress PRINT nButton 0 has been pressed ENDFUNC 1 Will continue waiting for an event BPUNGEION Bente l PRINT nButton 0 released Resume waiting for an event n ENDFUNC 1 FUNCTION Btnlpress PRINT nButton 1 has been pressed ENDEUNC 1 FUNCTION Btnlrel PRINT nButton 1 released No more waiting for events n ENDFUNC 0 rc gpiobindevent 0 16 0 JJ OIMNAS GoOLe Eranolelom hign om s1e6 6 ourcon 0 to event 0 Embedded Wireless Solutions Support Center 70 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual ko Goloebimdevemt 1 le 1 oind Gp lhovrkats teen lew on ciol Dutton d to event 1 rc gpiobindevent 2 17 0 DUNS POO LO Crane e hon Mtcm Ons LO lo
202. pioBindEvent or GpioAssignEvent respectively GPIOUNBINDEVENT nEventNum GPIOUNASSIGNEVENT nEventNum Ret INTEGER a result code The most typical value is OxO000 indicating a successful eee operation Note See module specific user manual for details 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 offen used to perform frequently repeated tasks in an application and to write event and message handler functions An application with user routines is highly modular allowing reusable functionality SUB Embedded Wireless Solutions Support Center 179 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual A subroutine is a block of statements which constitute a user routine which does not return a value but takes argumenis 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 STRI
203. r if the handle is invalid CIRCBUFREAD circHandle nData INTEGER Returns An integer result code The most typical value is 0x0000 which indicates a successful operation If Ox5102 is returned it implies the buffer was empty so nothing was read Arguments byRef circHandle AS INTEGER circHandle this identifies the circular buffer to read from byRef nData AS INTEGER nData This is the integer value to read from the circular buffer Interactive No Command Example CircBufRead sb See in Firmware Zip file DIM re CirchHandle 1 nData Embedded Wireless Solutions Support Center 125 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual re CircBufCreate 4 circHandle LE pe 0 TREN PRINT nThe circular buffer was not created EOE PRINT nThe circular buffer was created successfully n PIS E Us Wiese Liane Gnas 4 BNDL E FOR i 1 T 5 rc CircBufOverwrite circHandle i IE ze 05103 THEN PRINT Anoldest value was discarded to write i vn ELSEIF re 1 0 THEN PRINT Anfailed TO write inlO the circular buffer E TOE PRINT CANTI ENDL NEXT read 4 values from the circular butter PRINT nReading n OR Ie ice re CircBufRead circHandle nData IF re 0x5102 THEN PRINT The buffer was empty ELSELF e ee 0 THEN PRINT Failed t
204. ranularity than that Submit the command AT 2002 or at runtime SYSINFO 2002 to determine the actual granularity in microseconds ery Oris 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 1 000 000 000 then a runtime error will be thrown with code INVALID_INTERVAL An error will be thrown for lesser values dependent on the platform and the hardware constraints For Embedded Wireless Solutions Support Center 115 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual example the BL600 module has a maximum time of 8192000 2 hrs 16 min If the recurring argument is set to non zero then the minimum value of the interval is 1Oms byVal recurring AS INTEGER peeves Set to 0 for a once only timer or non 0 for a recurring timer Interactive Command ss Associated ONEVENT TIMERCANCEL Commands When the timer expires it will set the corresponding EVIMRn 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
205. ree Deleted 33 BASIC core version number 36 Config Keys Store stats Total Free Deleted 601 Flash File System Data Segment Total Soace 602 Flash File System Data Segment Free Space 603 Flash File System Data Segment Deleted Space 604 Flash File System FAT Segment Total Soace 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 function definition See Note 2 below OxC12C Will return a 16 bit running CRC for data downloaded for files using AT FWR pr AT FWRH All other numbers currently return the manufacturer s name For ATi4 the TT in the response Is the type of address as follows OO Public IEEE format address 01 Random static address default as shipped 02 Random Private Resolvable used with bonded devices 03 Random Private Non Resolvable used for reconnections Please refer to the Bluetooth specification for a further description of the types Embedded Wireless Solutions Support Center 34 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Interactive Command Yes This is an Interac
206. rer ere ce ere tere 8 What Does a BLE Module Contain smisiissrcaropnnsiisrcen ieri ane a E a a Eaa S AUA Spaa a 9 TTPA TCE Ch iS aaa EE E EO E O 10 Developing with smart BASIC cccccccsssecccessecccenececeeseccceuseccseuecccsauececeuseeeseaseccsaeeessusecessueceesauececsagecessaesessaeeess 10 smart BASIC Operating Modes cccccccsssecccsecccenececeesecesaseccssnscessaeseeseueeeeseuscesseeeesaueeeesauecessauscessueeessuseessanseees 10 Type Or FB ON CANONS eee EE E 12 Nom Yole MENON anaE A E ausavsananensesasvoeueaceanees 12 Using the Modules Flash File SysteMercnceeeriincnnnieiriiinr ene EE EENE ETA 13 sC r E E AEE A E AS 13 Be Sl CN TURNS eea uate sa ceaneoscecioimacacasuatoesuciuyeesus cea saeaunleusionuatecsinee erat quenaganeieceds tens eauiaseres 13 VV UI TS ecrire T EE E aed wnearanecemaseeronmnrneesantaenenreerauacneusaceoune 13 BAT aap a A EE E E E E arate nearness AEE E eden ice ete acetone E E A E A 14 Your First smart BASIC Application ccccccsscccccnsecccessccceesececsuseccsauecccsasecessuseecseneeecsuecessaeeesseueeecsaecessuseessaaeeess 19 4 Interactive Mode COMMANAS cccccceeececececeeueuaeaeataeaeaeaeaeaeaeeeaeueueeeaeeeeeananenenenereneneneneneeeeeens 32 PTE ssctssstrs scars S ss nd singe tnt ic tng cnc road E as Snecma eed ep emda ood eee 33 Bis SMart BAIC CO MMant E A 48 N D a A T A A A E A AE A AA A E EA 48 PCO a A A A E A A T A 49 SUDO UTO a A E E E 49 EEEIEE N e AA P TEE A E E A T E NE E A A
207. response to this command Is Embedded Wireless Solutions Support Center 44 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual n01 tE023 r If the variable exists but the new value is missing then the response to this command Is n01 tE26 r Where n linefeed t horizontal tab and r carriage return Arguments Var lt n gt The variable whose value is to be changed value A string_constant or integer_constant of appropriate form for the variable Interactive Y Command This is an Interactive Mode command and MUST be terminated by a carriage return for it to be processed Examples after an app exits which had DIM d a global variable called argc is a core command 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
208. routines functions while if and for loops smart BASIC 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 smart BASIC application source code consists of the following Variable declarations and initialisations Subroutine definitions Event handler routines Startup code Embedded Wireless Solutions Support Center 6 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 Embedded Wireless Solutions Support Center 7 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Why Do We Need smartBASIC Programming languages are mostly designed for arithmetic operations data processing string manipulation
209. rt lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual What Does a BLE Module Contain Our smart BASIC based BLE modules are designed to provide a complete wireless processing solution Each module contains the following Ahighly 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 SPI A smart BASIC 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 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 smart BASIC module from a hardware perspective on the left and a firmware software perspective on the right 44 connection pads ASIC Apoplicati User smarBASIC Application Non Vol File System for smartBASIC Apps Example App 256K Flash ARM Cortex MO smartBASIC smartBASIC 16K RAM run time engine provides safe access to BLE stack drivers and non vol stores I O UART I2C SPI Drivers BLE Radio Internal on Figure 1 BLE smartBASIC
210. rt lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual number of digital inputs that can auto generate is hardware dependent For example in the BL600 module N can be 0 1 2 or 3 Use GpioBindEvent to generate these events EVDETECTCHANn 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 example in the BL600 module N can only be 0 Use GpioAssignEvent to generate these events GpioBindEvent GpioAssignEvent FUNCTION These 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 GPIOBINDEVENT nEventNum nSigNum nPolarity GPIOASSIGNEVENT nEventNum nSigNum nPolarity INTEGER a result code The most typical value is OxO000 indicating a successful Returns operation Note See module specific user manual for details Generally BindEvent consumes more power than the AssignEvent function and the choice as to which is used is based on the specific use case with regards to how much power can be used GpioUnbindEvent GpioAssignEvent FUNCTION This routine unbinds the runtime engine event from a level transition bound using G
211. s byVal recnum AS INTEGER recnum The record number that is to be read in the range 1 to n where n depends on the specific module strvars byRef strvarS AS STRING The string variable that will contain the data to be written to the record Interactive Command Embedded Wireless Solutions Support Center 174 Laird Technologies http ews support lairdtech com www lairdtech com bluetooth Americas 1 800 492 2320 Europe 44 1628 858 940 Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 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 Example NvRecordSet sb See in Firmware Zip file DEM Woo tes GC ts we HelloWorld PRINT NvRecordSet 500 wS bytes written n PRINT NvRecordGetEx 500 r default bytes read n EME Ain ees Exoected Output 10 bytes written 10 bytes read HelloWorld NVRECORDSET is a module function NvCfgKeyGet FUNCTION NVCFGKEYGET reads the value of a built in configuration key See AT CFG for a list of configuration keys NVC
212. s 11 Data from file is World Data from file is is something ina file w FOPEN Is a core language function FCLOSE FUNCTION This function is used to close a file previously opened with FOPEN It fakes a handle parameter as a reference and will on exit set that handle to O which signifies an invalid file handle FCLOSE fileHandle Returns N A if 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 ne 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 dataS maxReadLen Embedded Wireless Solutions Support Center 169 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual INTEGER Returns The actual number of bytes read from the file Is 0 if read from end of file is attempted Arguments fileHandle BYVAL fileHandle AS INTEGER The handle of the file fo be read from datas BYREF dataS AS STRING The data read trom file is returned in this string mokeadien BYVAL maxReadLen AS INTEGER The max number of bytes to read from the file Interactive Command ve S
213. s using the NN format STRESCAPES string 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 Returns linefeed n horizontal tab t E AN Chr lt HH chr gt Ox7F HH Local Stack Frame Underflow Exceptions Local Stack Frame Overflow Memory Heap Exhausted Arguments ti byRef string AS STRING siring The string to be converted Interactive Command a If a parsing error is encountered a nonfatal error will be generated which needs to be handled otherwise the script 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 Associated Commands STRDEESCAPE Example StrEscapeS sb See in Firmware Zip file DIM sc to So Helle W0wor la tS StrEscapes s PRIMM Stelken sol ia Veer Rh sot elhem rs ia Expected Output Bs 13 Embedded Wireless Solutions Support Center 100 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual STRDEESCAPE SUBROUTINE STRDEESCAPE is used to convert an e
214. scaped 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 None string now contains de escaped characters converted as follows r carriage return Returns n linefeed t horizontal tab Ay HH ascii byte HH Local Stack Frame Underflow Exceptions Local Stack Frame Overflow String De Escape Error E g chrs after the are not recognized Arguments byRef string AS STRING string The string to be converted in situ Interactive Command nO 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 Example StrDeescape sb See in Firmware Zip file DI eo ace se nelle e o ey PRINT Sop TAn oer Len 39 Via StrDeescape s Pei E a vine E E E a ile Expected Output Hello 40world ies Hello world L1 Embedded Wireless Solutions Support Center 101 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual STRSPLITLEFTS FUNCTION STRSPLITL
215. se request a schematic of the BL600 development kit fo ensure that these SIO lines on the modules are correct Terminal BASIC Config About CTS DSR DCD Fi RTS DIR BREAKI LocalEcho LineModel Clear ClosePort Figure 7 Control options Embedded Wireless Solutions Support Center 16 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 ohysical 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 If 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 communication is possible with the UART device connected to the serial port
216. ser Manual Lt Mt Mahahahehahahahehehehehehehehehehehehehehehehehehehehehahahahehahahahahahahehahehehshehehehehehehehehehehahshahshahahaieheiahahahahahahehehahahahehehehehehel Handler definitions a J PP He He he he de he he ie he he e he ie e he Ae e Ae ie he he e he Ae e Ae e he Ae e ie Ae e ie ie e Ae e ie Ae e Ae Ae e ie e e Ae e Ae e e Ae e e Ae e ie e e e e e e e e e e e e e e e ke Uart Inactivity timer handler Of SS SSS SS SSS function handlerUartTimer as integer dim re Close the uart and set up TX RX RTS lines as gpio and for a hi lo transition fon the RX line to be detected if UartCloseEx i 0 then re GpioSetFunc 21 2 1 TX set high on default re GpioSetFunc 23 2 0 RTS set low by default re GpioSetFunc 22 1 2 RX Pull high input amp irq on hi2lo transition rce GpiocAssignEvent UART GPIO ASSIGN CHANNEL 22 1 if re 0 then print nGpioAssignEvent Failed endif endif endfunc 1 6 6 6 63 6 6 6 6 6 6 7 Delay before uart is opened 0 ffm rr a function handlerOpenDelay as integer dim re free up the level transition detection rce GpiocUnAssignEvent UART _GPIO ASSIGN CHANNEL Open the uart rc UartOpen 9600 0 0 CN81H send an ack character print i endfunc 1 Figure 11 Example of a smartBASIC code fragment in TextPad Download Hello World App You must now load the compiled output of this file into the smart BASIC module s File System so
217. sion of UWterminal AT AT is an Interactive mode command It must be terminated 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 AT I or ATI COMMAND Provides compatibility with the AT command set of Laird s standard Bluetooth modules ATi num Returns nlO TMM tinformation r n0O r Where n linefeed character Ox0A t horizontal tab character 0x09 MM a number see below Embedded Wireless Solutions Support Center 33 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Information string consisting of information requested associated with MM r carriage return character OxOD Arguments num Integer Constant A number in the range of 0 to 65 535 Currently defined numbers are O Name of device 3 Version number of module firmware 4 MAC address in the form TT AAAAAAAAAAAA 5 Chipset name 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 F
218. smaller than the remaining time lf either number or interval is invalid an Error is thrown Example EVTMRn sb See in Firmware Zip file SUB HandlerOnErr PRINT Timer serors 3 Gerclasturcror BNDSUB FUNCTION HandlerTimerl PRINT nTimer 1 has expired ENDEUNC 1 cremain blocked in WAITEVENT FUNCTION HandlerTimer2 PRINT nTimer 2 has expired ENDFUNC 0 exit from WAITEVENT ONERROR NEXT HandlerOnErr ONE VENTE EVIMR I CALI Handler Tames 1 OE VEE AVIMR CA anc lew aime 1 2 Timer care O 00 IL I start a 500 millisecond recurring timer PRINT V nstarteci Timer 0 wich invalid inerval amec cadre e Ol j stare a 500 millisecond recurring cimer PRINT aan tiene for Timer 1 imn e eae 2 LOCO 10 etart a 1000 millisecond Cimer PRINT nWavrerng for Tiner 2 WALTEVENT PRINT nGot here because TIMER 2 expired and Handler returned 0 Expected Output Embedded Wireless Solutions Support Center 116 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality Timer Error 1770 Started Timer 0 with invalid inerval Waiting for Timer 1 Waiting for Timer 2 Timer 1 has expired Timer 1 has expired Timer 2 has expired Got here because TIMER 2 expired and Handler returned 0 TIMERSTART is a core subroutine TimerRunning FUNCTION This function de
219. 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 smarfBASIC list box add the following two lines so 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 file with file extension sb or sblib will be disolayed with color syntax highlighting To change the colors of the syntax highlighting do the following l 2 From the Configure Preferences dialog box select the Document Classes plus sign next to smartBASIC and select Colors 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 1 displays a sample of what a smartBASIC code fragment looks like in TextPad Embedded Wireless Solutions Support Center 20 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality U
220. t will return a success 0O response Interactive Yes Command This is an Interactive Mode command and MUST be terminated by a carriage return for it fo be processed 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 Embedded Wireless Solutions Support Center 46 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual AT REN COMMAND Renames an existing file AT REN oldname newname Returns OK if the file 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 Interactive Yes Command oldname and newname must contain a valid filename which cannot contain the following seven characters S 2 lt gt This is an Interactive Mode command and MUST be terminated by a carriage return for if fo be processed 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 Integer
221. tant string by escaping using a starting character and two hexadecimal digits Some characters are treated specially and only require a single character after the character The table below lists the supported characters and the corresponding string Linefeed n i 22 or Carriage y A 4 return Horizontal 42 Tab 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 Embedded Wireless Solutions Support Center 56 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual cases it is useful to modify this default behaviour particularly within user defined functions and subroutines or when developing applications and temporary code needs to be added to monitor variables using print statements 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
222. ted 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 smart BASIC 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 GPIOSETFUNC nSigNum nFunction nSubFunc INTEGER a result code The most typical value is OxO000 indicating a successful Returns operation Note See module specific user manual for details 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 Note This is a sticky configuration calling it affects all PWM outputs already configured 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
223. termines 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 number 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 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 lf the value is not valid then a runtime error will be thrown with code INVALID TIMER Interactive Command ee Associated ONEVENT TIMERCANCEL Commands Example TimerRunning sb See in Firmware Zip file SUB HandlerOnErr PRINT Timer mreror GeclascbError ENDSUB FUNCTION HandlerTimer0O PRINT nTimer 0 has expired PRINT WY uliaeig l has T TimerRUnnInNg l mill seconds to cio ENDEUNG Ti remain blocked in WAITEVENT FUNCTION HandlerTimerl PRINT nTimer 1 has expired ENDFUNC 0 exit from WAITEVENT Embedded Wireless Solutions Support Center 117 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual ONERROR NEXT HandlerOnErr ONE VENE EVIMRO CALI Handler Timer ONE
224. tine Note that any variables declared within the subroutine lose their scope once ENDSUB is processed EXITSUB Embedded Wireless Solutions Support Center 180 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual This statement provides an early run time exit from 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 ENDFUNC 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 us
225. tion is used to write from O to 255 bytes and then immediately after that read 0 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 12C interface is made available most likely made available by bit bashing gpio I2CWRITEREAD nSlaveAddr stWrite stRead nReadLen Local Stack Frame Underflow Exceptions p Local Stack Frame Overflow Arguments Embedded Wireless Solutions Support Center 154 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual nSlaveAdadr stWriteS stReadS nReadLen Interactive Command Related Commands Example byVal nSlaveAdadr AS INTEGER This is the address of the slave in range 0 to 127 byRef stWriteS 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 stReadS AS STRING This string will be written to with data read from the slave if and only if nReadLen is not O byRef nReadLen AS INTEGER On entry this variable contains the number of bytes to b
226. tive mode command and must be terminated by a carriage return for it fo be processed Example AT a 3 10 SI PHO Peles 00 AT I 4 10 4 0I D3IA920731TB50 AT iis a core command Note 1 The information returned by this Interactive command can be useful from within a running application a built in function called SYSINFO cmdlid can be used to return exactly the same information and cmdid is the same value as used in the list above Note 2 OxC12C works only if enabled in the build 12 looks like an R so a mnemonic for CRC The CRC Is generated using the C function Calcl16bitCrcNonTableMethod defined below with the starting value of 0x0000 AT DIR This is an Interactive mode command and must be terminated by a carriage return for it to be processed fs xx Given an array of bytes a new 16 bit CRC is calculated using the slow method Slow method because it 16 used once to calc Lang Dash KX idea 16 12 5 ee this is the CCITT CRC 10 polynomial kX X X dy xx This works out to be 0x1021 but the way the algorithm works xx lets us use 0x8408 the reverse of the bit pattern The high xx bit is always assumed to be set thus we only use 16 bits to xx represent the 17 bit value kK y define POLY 0x8408 unsigned short Calc1l16bitcCrce unsigned short nCrcl6 init value or a previously calculated value const unsigned char pSrcsStr unsigned short nSrcLen an bytes unsigned ch
227. to write smart BASIC 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 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 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 This application is provided by Laird Technologies without warranty You are welcome to check our website for the latest version This message is displayed EITHER because accept is not specified in the command line OF at least one command line option has been specified with an invalid parameter You can launch this application and bypass this window by creating a shortcut link and passing ACCEPT as a command line option Other command line options are ACCEPT Bypass About screen o
228. torage Files which are not applications can also be stored in flash memory for example X 501 certificates 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 preserved across power cycles For example passwords Embedded Wireless Solutions Support Center 12 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Using the Module s Flash File System All smart BASIC 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 files 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 fill the file system requiring it fo be completely emptied using the AT amp F 1 command The command AT 6 returns statistics relate
229. ts may be either byVal or byRef In general and by default string arguments are passed byRef The reason for this is twofold Embedded Wireless Solutions Support Center 49 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual I Itsaves valuable memory soace because a copy of the string which may be long does not need to be copied to the stack Astring 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 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 ev
230. ttp ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Arguments byVal maxval AS INTEGER maxval The return value will not exceed the absolute value of this variable Interactive Command ae Associated RANDSEED Commands 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 Example RANDEX sb See in Firmware Zip file DIM x 5 010 PRINT Random mumoer between O and x gt ms RANDmX 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 the 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 numbers that are generated It has no effect on platforms with a hardware random number generator RANDSEED seed Local Stack Frame Underflow Exceptions p Local Stack Frame Overflow Arguments byVal seed AS INTEGER Seed The starting seed value for the ran
231. uestion arises as to what format the string should be in decimal hexadecimal octal or binary There is also the question of whether the string should be decorated For example converting the integer value 1234 into hex gives 4D2 but there may be a need to decorate it so that you have 0x4D2 Given there are a lot of options as to how the output should be which could result in a whole suite of integer to string functions the solution provided in smartBASIC is the SPRINT statement which functions like a PRINT statement but instead of it going to a standard output port like the uart it gets appended to a string variable For example To convert an integer value into hex and decorate it with the Ox prefix use the statements DIM myInt mystrs myInt 1234 convert to hex string 0x4D2 SPRINT Pmyo TU integer Mynt To convert an integer value into a binary string use the statements DIM myInt myStrs myInt 11 FSOnVverte to binary string 1011 SPRINT myStr integer b myInt Embedded Wireless Solutions Support Center 99 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual STRESCAPES 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 character
232. ulting 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 file 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 O iD O Blo00Med AL L ako 10 is 9E20 oF et v2 Cross Compiler xComp BlGUUMed F256 Srel exe nou found ir 2 Please save a copy to the same folder as UwTerminal exe 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 UWTerminal exe or the folder that contains the smart BASIC application testl 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 Embedded Wireless Solutions Support Center 22 Laird Technologies http ews support lairdtech com Americas 1 8
233. 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 values Each breakpoint statement has the following syntax BP nnnn 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 nnnn s 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 Embedded Wireless Solutions Support Center 27 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual 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 lo
234. ury Park Wooburn Green Bucks HP10 OHH UK Tel 44 0 1628 858 940 Fax 44 0 1628 528 382 Embedded Wireless Solutions Support Center 2 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual REVISION HISTORY 2 0 r 1 Feb 2013 Created by splitting from BL600 user manual 2 0 r2 14 Aug 2014 Fix typo errors 2 0 r3 16 Mar 2015 Added cmpif nnn statement 2 0 r4 22 May 2015 Added STRING from INTEGER section 2 1 rO 18 Aug 2015 AT OxC12C Embedded Wireless Solutions Support Center 3 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual CONTENTS ROVISION PUI SCO IY gcceecestsec acest octea nee ecietncacis cd caeeciee tances 4 cairns A 3 COMENS cacpeptetcnsmeaenasnnont ca samoaie ns cnens eas ameaseaacnons E seensensueaneconuaarseso ua 4 le sma BASIC OO CONME AGO sacs teense aananateneciountassacsacaneceaetoorscaseaereneutonyeceenevceasrae aceateasennunasian 6 2 WATROGUCTION TO SalI BAS G e 6 Why Do We Need smart BASIC ccccsscccccsseccccsscecceescecsesecccaeneeesaeseeeseecessaseeessaeeeeseueeessaueeeseaecesseuseessaeeessesessanseess 8 WOY Write APPICIUODS T airorriiorno rr onn EER E r EE omen eter re tener nee car
235. ves the leftmost n characters of a string LEFT string length Returns STRING The leftmost length characters of string as a STRING object Local Stack Frame Underflow Exceptions Local Stack Frame Overflow Memory Heap Exhausted Arguments mig byRef string A3 ARAG The target string which cannot be a const string length byVal length AS INTEGER The number of leftmost characters that are returned Interactive NO Command 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 Example LEFTS sb See in Firmware Zip file DIM newstring DIM s s Arsenic aene e a LEMS es 2 Prelie Mews rmimcgo a in Embedded Wireless Solutions Support Center 85 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual Expected Output LEFT is a core language function MIDS 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
236. was overwritten then a non zero value of 0x5103 will still be returned Arguments byRef circHandle AS INTEGER circHandle this identifies the circular buffer to write into byVal nData AS INTEGER nData 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 No Command Example CircBufOverwrite sb See in Firmware Zip file DIM te cimechand les a re CircBurCreate 4 circHandle IF re 0 THEN PRINT nThe circular buffer was not created n Embedded Wireless Solutions Support Center 124 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1628 858 940 www lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual ELSE PRINT nThe circular buffer was created successfully n TNE IE E BOR 41 1 165 re CircBufOverwrite circHandle 1 LE re 0x5103 THEN PRINT nOldest value was discarded to write oa ELSEIF re 1 0 THEN PRINT nbatled to write into the circular buffer E DOE PRINTANE T ENID IL E NEXT Expected Output The circular buffer was created successfully Oldest value was discarded to write 5 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 o
237. ww lairdtech com bluetooth Hong Kong 852 2268 6567 x026 smart BASIC Core Functionality User Manual AT DEL COMMAND This command deletes a file from the module s flash file system When the file is deleted the space it occupied does not get marked as free for use again 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 command AT I 6 to get information about the file system It resoond with the following 10 6 aaaa bbbb cccc Where aaaa Is the total size of the file system bbbb Is the free soace 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 file 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 resoond 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 Interactive Y Command This is an Interactive Mode com
238. xpired so that the application can STOP FUNCTION HandlerTimer0 PRINT nTimer 0 has expired starting again IF i 4 THEN PRINT nCancelling Timer 0 TimerCancel 0 PRINT nTimer O ran e times x 0 ENDILE eae ENDPUNC x ONEVENT EVTMRO CALL HandlerTimer0O mmer sizar 07 5 00m 1 PRINT nWadtung for Timer 0 Should rune 5 times WALTEVENT Expected Output Waiting for Timer 0 Should run 5 times Timer has expired starting again Timer has expired starting again Timer has expired starting again Timer has expired starting again Timer has expired starting again Cancelling Timer 0 Timer 0 ran 5 times 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 runtime SYSINFO 2004 This function returns that free running counter If wraps to O when the counter reaches Ox FFFFFFF GETTICKCOUNT INTEGER A value in the range O to OX7FFFFFFF 2 147 483 647 in units of Returns milliseconds Arguments None Interactive No Command Associated SE TICKSINCE Commands Example GetTickCount sb See in Firmware Zip file FUNCTION HandlerTimer0O PRINT n nTimer 0 has expired Embedded Wireless Solutions Support Center 119 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320
239. y 0x5208 Invalid baudrate 0x5209 Invalid parity Ox520A Invalid databits Ox520B Invalid stopbits Ox520C Cannot be DTE because DCD and RI cannot be inputs Returns Cannot be DCE because DCD and RI cannot be Ox520D outputs Ox520E Invalid flow control request Ox520F Invalid DTE DCE role request Invalid length of stOptions parameter must be five Ox5210 characters Ox521 1 Invalid Tx buffer length Ox5212 Invalid Rx buffer length Local Stack Frame Undertlow Exceptions Local Stack Frame Overflow Arguments byVal baudrate AS INTEGER The baudrate for the uart Note that the higher the baudrate the more baudrate 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 txbuflen AS INTEGER txbuflen Set the transmit ring buffer size to this value If set to O then a default value will be used by the underlying driver byVal rxbuflen AS INTEGER Rxbuflen 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 stOptions character is used to specify further comms parameters as follows Character Offset Embedded Wireless Solutions Support Center 130 Laird Technologies http ews support lairdtech com Americas 1 800 492 2320 Europe 44 1 628 858
Download Pdf Manuals
Related Search
Related Contents
Multibrackets 7350022733053 flat panel desk mount Tarox 1000085 notebook User`s manual Rollei Sportsline 100 oranje ADATA SP800 32GB Copyright © All rights reserved.
Failed to retrieve file