wifi-it basic programmers manual

175
(c) 2011 North Pole Engineering, Inc. WiFi-Basic Programmers Manual Version 2.3

Upload: j0880j

Post on 06-Nov-2015

233 views

Category:

Documents


1 download

DESCRIPTION

WiFi-IT Basic Programmers Manual

TRANSCRIPT

  • (c) 2011 North Pole Engineering, Inc.

    WiFi-BasicProgrammers Manual

    Version 2.3

  • WiFi-IT! Basic Language ReferenceI

    2011 ... North Pole Engineering, Inc.

    Table of ContentsForeword 0

    Part I Introduction 1................................................................................................................................... 11 Welcome ................................................................................................................................... 12 What's New ................................................................................................................................... 33 Notation Used in this Document ................................................................................................................................... 44 Modes of Operation

    Part II WiFi Basic Program Structure 5................................................................................................................................... 51 Project Configuration Panel ................................................................................................................................... 62 Source File

    Part III Quick Start Guide 7................................................................................................................................... 81 Connecting the Hardware ................................................................................................................................... 82 Starting the IDE ................................................................................................................................... 93 Project 1 - BLINK

    .......................................................................................................................................................... 11Writing the Program

    .......................................................................................................................................................... 11Configuration Settings

    .......................................................................................................................................................... 14Compiling the Program

    .......................................................................................................................................................... 16Loading the Program

    .......................................................................................................................................................... 18Debug the Program ................................................................................................................................... 204 Project 2 - RSSI

    .......................................................................................................................................................... 21RSSI Program

    .......................................................................................................................................................... 23Run the Program ................................................................................................................................... 245 Project 3 - Temp Sensor

    .......................................................................................................................................................... 24TempSensor program

    .......................................................................................................................................................... 27Configuration Settings

    .......................................................................................................................................................... 28Set up the Hardware

    .......................................................................................................................................................... 29Debug the Program

    Part IV Programming Reference 32................................................................................................................................... 331 General Information

    .......................................................................................................................................................... 33Numeric Base Specification

    .......................................................................................................................................................... 33Literal Constants

    .......................................................................................................................................................... 34Program Lines

    .......................................................................................................................................................... 34Keywords ................................................................................................................................... 342 Error Handling

    .......................................................................................................................................................... 34Active Error Handling

    .......................................................................................................................................................... 35Passive Error Handling

    .......................................................................................................................................................... 36Double Faults

    .......................................................................................................................................................... 36Error Handling Keywords ......................................................................................................................................................... 36ERROR......................................................................................................................................................... 37ESUB - ENDESUB......................................................................................................................................................... 38ON_ERROR

  • IIContents

    II

    2011 ... North Pole Engineering, Inc.

    ......................................................................................................................................................... 38RESUME

    ......................................................................................................................................................... 38RESUME_NEXT................................................................................................................................... 393 Date/Time Functions

    .......................................................................................................................................................... 39DAY

    .......................................................................................................................................................... 40HOUR

    .......................................................................................................................................................... 40MINUTE

    .......................................................................................................................................................... 40MONTH

    .......................................................................................................................................................... 40MONTHNAME

    .......................................................................................................................................................... 41NOW

    .......................................................................................................................................................... 42SECOND

    .......................................................................................................................................................... 42WEEKDAY

    .......................................................................................................................................................... 42WEEKDAYNAME

    .......................................................................................................................................................... 43YEAR ................................................................................................................................... 434 Flow Control

    .......................................................................................................................................................... 44DO - UNTIL | LOOP

    .......................................................................................................................................................... 45END

    .......................................................................................................................................................... 45EXITDO | EXITFOR | EXITWHILE

    .......................................................................................................................................................... 45FOR - TO - STEP - NEXT

    .......................................................................................................................................................... 46GOSUB

    .......................................................................................................................................................... 47RETURN

    .......................................................................................................................................................... 47IF - THEN - ELSE - ENDIF

    .......................................................................................................................................................... 48QUIT

    .......................................................................................................................................................... 49SUB - ENDSUB

    .......................................................................................................................................................... 49TASK - REPEAT_TASK

    .......................................................................................................................................................... 49WHILE - WEND ................................................................................................................................... 505 Interfaces

    .......................................................................................................................................................... 51ADC

    .......................................................................................................................................................... 52FLASH ......................................................................................................................................................... 52READ......................................................................................................................................................... 53WRITE.......................................................................................................................................................... 53GPIO ......................................................................................................................................................... 54GPIO Configuration......................................................................................................................................................... 55GETDIR......................................................................................................................................................... 56SETINPUT......................................................................................................................................................... 57SETOUTPUT.......................................................................................................................................................... 57I2C ......................................................................................................................................................... 57I2C Configuration......................................................................................................................................................... 58CONFIGURE......................................................................................................................................................... 59INPUT......................................................................................................................................................... 60OUTPUT.......................................................................................................................................................... 61PWM ......................................................................................................................................................... 61PWM Configuration......................................................................................................................................................... 63START......................................................................................................................................................... 63STOP......................................................................................................................................................... 64UPDATE.......................................................................................................................................................... 64SPI ......................................................................................................................................................... 66SPI Configuration......................................................................................................................................................... 68CONFIGURE......................................................................................................................................................... 69INPUT......................................................................................................................................................... 71OUTPUT.......................................................................................................................................................... 72UART ......................................................................................................................................................... 73UART Configuration......................................................................................................................................................... 74INPUT

  • WiFi-IT! Basic Language ReferenceIII

    2011 ... North Pole Engineering, Inc.

    ......................................................................................................................................................... 75OUTPUT

    ......................................................................................................................................................... 76UART_RX................................................................................................................................... 776 Intrinsic Constants

    .......................................................................................................................................................... 78ADHOC

    .......................................................................................................................................................... 78ALARM1

    .......................................................................................................................................................... 78ALARM2

    .......................................................................................................................................................... 78AUTO

    .......................................................................................................................................................... 78COLD_BOOT

    .......................................................................................................................................................... 78CURRENT

    .......................................................................................................................................................... 79Error Codes

    .......................................................................................................................................................... 81ERRORFLAG

    .......................................................................................................................................................... 81FALSE

    .......................................................................................................................................................... 81INFRASTRUCTURE

    .......................................................................................................................................................... 82NONE

    .......................................................................................................................................................... 82OFF

    .......................................................................................................................................................... 82ON

    .......................................................................................................................................................... 82PRIMARY

    .......................................................................................................................................................... 82PROVISION

    .......................................................................................................................................................... 83SECONDARY

    .......................................................................................................................................................... 83TRUE

    .......................................................................................................................................................... 83WEP_OPEN

    .......................................................................................................................................................... 83WEP_SHARED

    .......................................................................................................................................................... 84WPA_ENTERPRISE

    .......................................................................................................................................................... 84WPA_PERSONAL

    .......................................................................................................................................................... 84WPA2_ENTERPRISE

    .......................................................................................................................................................... 84WPA2_PERSONAL ................................................................................................................................... 847 Miscellaneous Functions

    .......................................................................................................................................................... 85Comment

    .......................................................................................................................................................... 85ABS

    .......................................................................................................................................................... 85BYTECOPY

    .......................................................................................................................................................... 86CBYTE

    .......................................................................................................................................................... 87CINT

    .......................................................................................................................................................... 88DELAY

    .......................................................................................................................................................... 88EVENT

    .......................................................................................................................................................... 89SERIAL_NUMBER

    .......................................................................................................................................................... 90TIMER

    .......................................................................................................................................................... 90UBOUND ................................................................................................................................... 918 Power Management

    .......................................................................................................................................................... 91Power Configuration

    .......................................................................................................................................................... 91Sleep Mode Operation

    .......................................................................................................................................................... 93RECEIVER

    .......................................................................................................................................................... 93SLEEP

    .......................................................................................................................................................... 94SLEEP_MODE

    .......................................................................................................................................................... 95UART_RX

    .......................................................................................................................................................... 95XMIT_POWER ................................................................................................................................... 959 Networking

    .......................................................................................................................................................... 96Networking Overview

    .......................................................................................................................................................... 98Wireless Configuration .......................................................................................................................................................... 100IP and Port ranges .......................................................................................................................................................... 101Notes on using TCP .......................................................................................................................................................... 102Socket Operations ......................................................................................................................................................... 103ACCEPT......................................................................................................................................................... 104CLOSE

  • IVContents

    IV

    2011 ... North Pole Engineering, Inc.

    ......................................................................................................................................................... 104GET_SENDER_CID

    ......................................................................................................................................................... 105GET_SENDER_IP

    ......................................................................................................................................................... 106GET_SENDER_PORT

    ......................................................................................................................................................... 106LISTEN

    ......................................................................................................................................................... 107OPEN

    ......................................................................................................................................................... 108POLL

    ......................................................................................................................................................... 109POLL_SEND

    ......................................................................................................................................................... 110RECEIVE

    ......................................................................................................................................................... 111SEND.......................................................................................................................................................... 112Network Configuration ......................................................................................................................................................... 113CHANNEL......................................................................................................................................................... 114DHCP......................................................................................................................................................... 115GATEWAY......................................................................................................................................................... 115IP$......................................................................................................................................................... 116IP_ADDRESS......................................................................................................................................................... 117LINK......................................................................................................................................................... 118LINKED?......................................................................................................................................................... 118MAC_ADDRESS......................................................................................................................................................... 119PASSPHRASE......................................................................................................................................................... 121RSSI......................................................................................................................................................... 122SCAN......................................................................................................................................................... 124SCAN_RESULT......................................................................................................................................................... 125SCAN_ELEMENT......................................................................................................................................................... 126SECURITY......................................................................................................................................................... 128SSID......................................................................................................................................................... 129SUBNET......................................................................................................................................................... 130UNLINK......................................................................................................................................................... 131VALIP......................................................................................................................................................... 131WEPKEY

    ................................................................................................................................... 13310 Operators .......................................................................................................................................................... 133Arithmetic Operators .......................................................................................................................................................... 134Comparison Operators .......................................................................................................................................................... 134Bitw ise Operators .......................................................................................................................................................... 135String Operators

    ................................................................................................................................... 13611 String Functions .......................................................................................................................................................... 136Heap Management .......................................................................................................................................................... 137CHR$ .......................................................................................................................................................... 137HEX$ .......................................................................................................................................................... 138HEX_VAL .......................................................................................................................................................... 139INSTR$ .......................................................................................................................................................... 139LEFT$ .......................................................................................................................................................... 140LEN$ .......................................................................................................................................................... 140MID$ .......................................................................................................................................................... 141RIGHT$ .......................................................................................................................................................... 141STR$ .......................................................................................................................................................... 142TOBYTEARRAY .......................................................................................................................................................... 142TOSTRING .......................................................................................................................................................... 143VAL

    ................................................................................................................................... 14312 Variables and Datatypes .......................................................................................................................................................... 144Variable Naming and Limitations .......................................................................................................................................................... 144Numeric Data Type Coercion .......................................................................................................................................................... 144CONST .......................................................................................................................................................... 145Variables

  • WiFi-IT! Basic Language ReferenceV

    2011 ... North Pole Engineering, Inc.

    ......................................................................................................................................................... 145DIM

    ......................................................................................................................................................... 146STATIC

    Part V Guides 147................................................................................................................................... 1471 Regaining Access to a Device ................................................................................................................................... 1502 Updating the Device Firmware ................................................................................................................................... 1533 Setting Up an Ad Hoc Network ................................................................................................................................... 1554 Data Monitor Protocol ................................................................................................................................... 1565 SPI Timing Diagrams

    Part VI Programming Examples 160................................................................................................................................... 1601 SPI SRAM ................................................................................................................................... 1632 UART0 Input / Output

    Part VII Definitions 164

    Index 167

  • Introduction 1

    2011 ... North Pole Engineering, Inc.

    1 Introduction

    1.1 Welcome

    IntroductionWiFi-Basic is a high-level programming environment for the NPE WiFi-IT! 802.11 WLAN module. Itis based on the Basic computer language and provides extensions to support network andwireless communication. WiFi-Basic simplifies writing programs that read sensors, controlhardware actuators, perform calculations and communicate over standard 802.11 Wi-Fi networks.

    ScopeThis document provides a general introduction to the concepts of wireless programming andusing the development environment but it mainly concentrates on defining the languageoperators and keywords as a reference to writing WiFi-Basic code. The operators and keywordsare organized by section and generally, include examples.

    1.2 What's NewHere are the updates for the latest release and previous releases.

    Installation 2.3.0IDE

    1. Export Manufacturing Package option added to File Menu. Combines WiFi Firmware,compiled WiFi-Basic code, and Project Configuration Settings into one package which canbe loaded using Manufacturing Loader application.

    Compiler1. New EDK+ compiler commands added: SECURITY, PASSPHRASE, WEPKEY2. New compiler commands added: SERIAL_NUMBER

    Firmware1. Battery monitor threshold lowered from 2.0V to 1.2V. Previously the firmware would lock

    out code execution if VBAT went below 2.0V. VBAT can now go down to 1.2V.

    Installation 2.2.01. See new documentation section: Data Monitor Protocol.

    IDE2. Graphing capability added for Data Monitor Perspective.3. Changed configuration panel for I2C.

    Compiler3. New EDK+ compiler commands added: Date/Time Functions, GETDIR, SETINPUT,

    SETOUTPUT, CONFIGURE I2C, CONFIGURE SPI, UART_RX, SCAN, SCAN_ELEMENT,SCAN_RESULT

    4. New compiler commands added: BYTECOPY, CBYTE, CINT, String Operator5. MAC_ADDRESS can now be assigned directly to byte arrays.6. Fixed problem with static integers not aligning on word boundaries when preceded by

  • WiFi-IT! Basic Language Reference2

    2011 ... North Pole Engineering, Inc.

    static bytes. See STATIC for recommendations on declaring static variables. Firmware

    2. Fixed problem with ext_reset. ext_reset now works correctly.

    Installation 2.0.01. See new documentation sections: Networking Overview, Wireless Configuration, IP and

    Port Ranges, Notes on using TCP, Power Configuration, Sleep Mode Operation, HeapManagement.

    2. The development environment now supports compilations for both the WL11 and WL10modules.

    IDE1. Added a Data Monitor perspective. This allows data packets to be received from a node and

    viewed by the user.2. Added support for both the WL10 and WL11 modules.3. Updated the licensing procedures.

    Compiler7. New EDK+ compiler commands added: CHANNEL, FLASH, GATEWAY, RECEIVER, SLEEP,

    SLEEP_MODE, SSID, SUBNET. 8. New compiler commands added: HEX$, HEX_VAL, PWM.9. Commands that have a modified operation from V1.06: CHANNEL, LINK.10.TCP protocol support has been added.

    Installation 1.0.61. See the new documentation section, Modes of Operation for an explanation of the

    different modes that the Run Time Engine (RTE), on the module, can assume.IDE

    1. Fixed a problem where sleep mode was not restored after a debug session wasterminated.

    2. Modified IDE to operate with new Rev. C EDK base board.3. Added new wireless setting to the Project Configuration Panel including, DHCP on/off,

    static IP address, static subnet mask, static Gateway IP Address.4. The ADC configuration tab has been removed. Enabling the ADC is now done

    automatically by the Run-Time Engine.Compiler

    1. New commands added: Event, VALIP, GET_SENDER_CID, MAC_ADDRESS, IP_ADDRESS, SHL,SHR, IP$, CHANNEL and XMIT_POWER.

    3. Error codes now have intrinsic constants defined for them. See Error Codes.4. The GPIO function now accepts variables, constants and functions in its specification

    parameter.5. The compiler will flag as an error a subroutine without a RETURN.

    Installation 1.0.3IDE

    1. Improved device communication.2. Serial port device configuration and debugging is enabled.3. Updated syntax highlighting to support new commands. Fixed some problems with

    certain words not being highlighted.

  • Introduction 3

    2011 ... North Pole Engineering, Inc.

    Compiler1. New commands added: LINK, UNLINK, LINKED?, SUB, ENDSUB, ESUB ENDESUB, RESUME,

    RESUME_NEXT, QUIT, ON_ERROR2. QUIT has been redefined to operate in TASK-REPEAT_TASK or within SUB-ENDSUB.

    Previously, it was restricted to ESUB-ENDESUB.3. Names have changed for ADC0, now DIE_TEMP, and ADC3, now BATTERY. ADC1 and ADC2

    still refer to the external ADC inputs.4. A number of intrinsic constants have been added to the compiler. They are: ADHOC,

    CURRENT, ERRORFLAG, FALSE, INFRASTRUCTURE, PRIMARY, PROVISION, SECONDARY andTRUE.

    5. Active Error handling has been added to the Run-Time Engine (RTE).6. Problems with using functions as parameters to other functions have been fixed.7. More rigorous syntax error checking has been added. Many of the error messages only

    indicate that a syntax error has been detected. These error messages will be furtherdefined in later releases.

    8. The ability to change the default numeric base to HEX has been removed.

    1.3 Notation Used in this Document1. Curly brackets "{ }" enclose optional statements or parameters.2. The pipe symbol "|" separates valid options for a single parameter. The pipe symbol occurs

    between valid option, of which only one may be selected.3. The less than "" symbols enclose a parameter specification.4. The following notation is used to indicate parameter types.

    Byte value. This is a variable or constant value between 0 and 255.

    Byte variable.

    Byte array variable.

    const Constant or number.

    Integer value. An i-value can be a variable of type integer or constant.

    Integer variable.

    Integer array variable.

    Numeric value. A value of type byte or integer. An n-value can be anumeric variable, an array item or a numeric constant.

    Numeric variable. A variable of type byte or integer.

    Numeric array variable (byte or integer).

    String variable.

    String value. An s-value can be a string variable or string constant.

    String or Integer value. This can be a variable or constant of type string orinteger.

    String or Integer variable.

    String or byte value. This can be a variable or constant of type string or

  • WiFi-IT! Basic Language Reference4

    2011 ... North Pole Engineering, Inc.

    byte.

    String or byte variable.

    String variable or byte array.

    String or Integer variable, or byte array.

    5. The colon character ":" is used in examples to indicate any number of interveningprogramming statements.

    6. Topic icons in HTML help, marked with a red asterisk in the contents panel are available inthe EDK+ version only.

    1.4 Modes of OperationThis section describes the different operating modes of the WiFi-IT! module. It pertains mostlyto the Runtime Engine (RTE) running on the module, but also references the IDE.

    Provisioning Mode'Provisioning' refers to editing conifguration settings and loading/debugging BASIC programs. The module has two provisioning modes: WiFi and UART, only one of which may be selected ata time. The default provisioning mode is WiFi.

    In WiFi provisioning mode, the module sends out identifying multicast messages which causeits MAC address to appear in the IDE's devices list. If a MAC address appears in the devices listalong with the 'Connected' keyword, then that module is in WiFi provisioning mode and iscurrently connected to the IDE. If a MAC address appears with the 'Disconnected' keyword, thenthat module was enumerated but has since lost connection. Note that the module may beassociated to only one network at a time. This means the IDE must be on the same networkwith which the module is associated in order to establish a connection. See Overview ofWireless Operation.

    In UART provisioning mode, the module still follows normal network association rules, but itdoes not send out identifying multicast messages and does not establish a connection with theIDE over WiFi. Instead, UART0 is reserved for the connection to the IDE. In UART provisioningmode, BASIC commands that use UART0 are still allowed, although they will return an error of EPROVMODE. Modules in UART provisioning mode will not appear in the IDE's devices list.Instead, the user must go to the Device menu and select the Load, Debug, and Edit optionsthere. The IDE will then provide a menu to select the COM port to which the module isconnected.

    To switch a module from WiFi to UART provisioning mode, right-click on the device in theDevices list and select "Switch Device to UART Config Mode". The IDE will send a command toswitch the module's configuration and then remove it from the Devices list.

    To switch a module from UART to WiFi provisioning mode, select "Switch Device to WiFi ConfigMode" from the Device menu. Then specify the COM port the device is connected to. After afew moments for network association, the module should appear in the Devices list.

  • Introduction 5

    2011 ... North Pole Engineering, Inc.

    Operating ModeThere are two main 'operating' modes: Idle and Run. In Idle mode, the BASIC program is notexectuted and the module does not enter the sleep state. It simply idles, waiting for commandsfrom the IDE. In Run mode, the BASIC program is executed, and if the Enable Sleep option hasbeen selected in the Project Configuration Panel, the module will enter the sleep statebetween iterations of the TASK REPEAT_TASK structure.

    The module is in the Idle mode by default. Once configuration settings and a BASIC programhave been loaded using "Load Project into Device", the module is switched to Run mode. Themodule will stay in Run mode unless a new project is loaded using "Debug project on Device". Otherwise, it is not possible to exit run mode.

    When debugging, either over UART or WiFi, the module is in Idle mode. When the Runcommand is issued from the IDE debugger, the module enters a special Idle/Debug state. Themodule obeys all rules for normal Run mode in this state, including low-power/sleep states. This allows more accurate debugging, but will cause the module to appear unresponsive whilein the low-power state. Idle/Debug is not the same as normal Run mode. If the module losespower, it will reawaken in the Idle state, without starting the BASIC RTE.

    Note that if a device firmware update is performed (see Updating the Device Firmware), themodule is reverted to the Idle mode and no WiFi Basic program is loaded.

    Override ModeGPIO(25) allows the user to force the module into an override mode. If GPIO(25) is held high aspower is applied, the provisioning mode is forced to UART and the operating mode is forced toIdle. This allows a module to be forced into a known state and prevents any BASIC programcurrently loaded from running. In this state, the Project Configuration Panel can be examinedfrom the IDE and/or a new project can be loaded.

    2 WiFi Basic Program Structure

    Each WiFi-Basic program is made up of two main parts; the Program Configuration Panel (PCP)settings and the executable code. The PCP provides a graphical user interface (GUI) forconfiguration of WiFi parameters and device interface settings. These settings are used toautomatically configure the hardware before the program starts. The executable code consistsof program statements between TASK and REPEAT_TASK plus any subroutines and errorhandlers.

    Project Configuration PanelSource File

    2.1 Project Configuration PanelThe Project Configuration Panel is accessed through the Integrated Development Environment(IDE), by selecting the project from the navigator, then right-clicking and choosing ProjectConfiguration Panel, from the drop down menu. The Project Configuration Panel opens in theeditor window and allows you to setup the module's wireless parameters, and select and

  • WiFi-IT! Basic Language Reference6

    2011 ... North Pole Engineering, Inc.

    configure device interfaces. Figure 1, shows an example of configuring the wireless settings fora project.

    Figure 1: Project Configuration Panel for Wireless Settings

    Once the configuration is saved, the initialization code, used to enable and configure the on-chip peripheral interfaces, is automatically generated.

    2.2 Source FileThe source file is where all the programming action takes place. A project contains one sourcefile and all code must be placed into this file.

    The structure of a WiFi-Basic program consists of a declaration section, where all variables andconstants are defined. This is followed by the TASK loop which contains the executable programstatements. The main task code is placed between the TASK and REPEAT_TASK directives.Following this are subroutines and error handlers. Subroutines are defined using the SUB andENDSUB keywords. Error handlers are defined using the ESUB and ENDESUB keywords.

    There are two operating modes: always-on and low-power. To enable low-power mode, select"Enable Sleep" in the Devices tab in the PCP. In either mode, the code between TASK andREPEAT_TASK is executed once. When execution hits the REPEAT_TASK directive, control

  • WiFi Basic Program Structure 7

    2011 ... North Pole Engineering, Inc.

    returns to the TASK directive at the top of the program. If sleep is enabled, the module willpower off between REPEAT_TASK and TASK. If sleep is not enabled, control returnsimmediately to the TASK statement. Whether sleep is enabled or not, the TASK directive clearsall non-static variables and re-initializes the Run-Time Engine (RTE). Numeric variables are setto the value 0 and strings are set to null. Click the link for more information on Sleep ModeOperation.

    Subroutines and error handling routines exist outside of the TASK directive and follow theREPEAT_TASK directive. All subroutine and error handling routines must be labeled; the labelcan be up to 32-characters in length and must begin with an alpha-character but may containnumeric characters and the underscore character.

    The general format of a WiFi-Basic program is shown below (comments are highlighted ingreen).

    'Variable and Constant declaration area.DIM Variable1 AS INTEGER

    CONST Constant1 = 1234567

    TASK 'This is where the WiFi-Basic statements that make up the main program reside. : :REPEAT_TASK

    'Subroutines and error handlers are specified after the main task.SUB Routine1 : : RETURNENDSUB

    ESUB Ehandler ' Optional error handling routine. : : RESUME_NEXT ' Can also use QUIT and RESUME to exit error handlers.ENDESUB

    END

    The last line in a program is always the END directive.

    3 Quick Start Guide

    The Quick Start Guide leads you through writing , loading, debugging and running a WiFi-Basicprogram.

    Three example applications are presented. All three require the WiFi-IT! EDK. The first programdemonstrates use of GPIOs and the low-power sleep state. The second program makes use of

  • WiFi-IT! Basic Language Reference8

    2011 ... North Pole Engineering, Inc.

    the Wi-Fi functions to send Received Signal Strength Indicator (RSSI) readings to the IDE. Thethird program uses the I2C interface to read the temperature sensor on the SCard and sendthese readings to the IDE. It also demonstrates debugging over the UART as opposed to theWiFi network.

    3.1 Connecting the HardwareThe EDK and EDK+ contain a preconfigured Wi-Fi access point, the DCard, the SCard, two WiFi-IT!modules, the connecting cables and power supplies. The instructions below take you throughsetting up the system and connecting it to your computer.

    1. Unpack the Access Point (AP), attach it to your PC and power it up (Note: You may want todisconnect your network cable and plug the AP directly into your PC LAN connection. Youmust plug your PC LAN connection into one of the PC ports - not the internet port - of theAP). The AP is setup to serve IP addresses through DCHP. Make sure your PC is setup torequest an IP address through DHCP.

    a. Disable any firewall software you may be running.

    2. Test that you can access the AP through a web browser. Bring up a web browser and enterthe AP address into the browser address textbox (see the document enclosed with the APfor the IP address of the AP). Use the username and password included in the APdocumentation to login.

    a. Close the browser.

    3. Connect the EDK power supply to the wall plug and plug it into the DCard. A red LEDshould light, indicating power has been correctly applied. Flip the DCard power switch,SW10, to the left. The green LED should light.

    a. Return the EDK power switch to the OFF position.

    4. Unpack and plug one of the two WiFi-IT! Modules into the DCard at J2. Do not turn theDCard power on at this time. Note: You do not need to attach the USB cable to the DCard,since each WiFi-IT! module has been preloaded with the WiFi-IT! RTE, so all connectionscan occur over the wireless connection.

    5. You're ready to go!

    Go to: Starting the IDE

    3.2 Starting the IDEStart the IDE by double-clicking on the WiFi-Basic Icon on the desktop or select it through theStart Menu.

    When the IDE is started, it creates the WiFi-IT folder on your desktop. Inside the WiFi-IT folderit creates the workspace directory, where all projects are stored in separate subdirectories. Thefirst time you open the IDE it looks as shown below.

  • Quick Start Guide 9

    2011 ... North Pole Engineering, Inc.

    The Navigator view is on the left and defaults to Devices and Projects. The Devices tree showsWiFi-IT! nodes that are connected to the IDE. These nodes may be programmed and configuredthrough the IDE. Below that is the Projects tree, it lists all of the projects in the Workspace. We'llcover the other views as we use them.

    Important Note: Currently, the IDE only scans network interfaces at startup. If a network(such as your Netgear access point) is connected after the IDE has been started, it will not beable to see any modules that join that network.

    Go to: Project 1 - Blink

    3.3 Project 1 - BLINKNow lets get started!

    Make sure the power is off on the DCard and connect a WiFi-IT! node to J2. Do not turn on thepower at this time.

    Create a Project: Right-click Projects in the Navigator tab and select New Project (or select NewProject from the File menu). Type Blink into the dialog box. The dialog should look like thatshown below.

  • WiFi-IT! Basic Language Reference10

    2011 ... North Pole Engineering, Inc.

    Click Ok. Expand the Projects tree and you should see that the Blink project has been created.

    Expand the Blink project. You will see two files - the Blink.tb file is the WiFi-IT Basic source codefile and the Blink.map file is the map file used for debugging.

    Open Blink.tb for Editing: To open Blink.tb double-click the filename. A new tab will be createdas shown below.

    Go to: Writing the Program

  • Quick Start Guide 11

    2011 ... North Pole Engineering, Inc.

    3.3.1 Writing the Program

    Enter the program as shown below into the editing window (you can copy and paste it, if you'dlike). NOTE: There is an error in the program but we want to enter it as shown.

    Since this program is going to sleep between executions, we need to remember the state of thevariable 'Temp' across power cycles so it must be declared as a STATIC variable. Variablesdeclared using the DIM keyword are re-initialized each time the task loop is repeated. Also,whenever the node enters the sleep state all of the GPIO pins power off. Therefore, the LED willgo out while the node is sleeping. To show the LED, we have added a DELAY statment to delayentering sleep for 200 milliseconds.

    '' This program blinks LEDs on GPIO 30 and 31' in an alternating pattern.'

    STATIC Temp AS INTEGER

    TASKIF (Temp AND 0x01) = 0 THEN

    GPIO(31) = 1GPIO(30) = 0Temp1 = 0x01

    ELSEGPIO(31) = 0GPIO(30) = 1Temp = 0x00

    ENDIF

    DELAY 200 ' Leave the LEDs on for sometime.GPIO(31) = 0GPIO(30) = 0

    REPEAT_TASK

    END

    After entering the code, select File | Save or press ctrl-S to save the changes.Now we need to configure the device settings. Go to: Configuration Settings.

    3.3.2 Configuration Settings

    Beyond writing the code, we need to initialize the hardware for each node we will program.This is done through the Program Configuration Panel (PCP).

    Open the Program Configuration Panel: To access the PCP, right-click the project title (Blink) andselect 'Edit Project Device Configuration'. The IDE workbench should look like the figure below.

  • WiFi-IT! Basic Language Reference12

    2011 ... North Pole Engineering, Inc.

    The top section of the PCP gives an overview of the current device settings. The first tabcontains settings that affect the entire device; such as wireless settings and power settings.

    Set the Wireless/Network Settings: The network settings determine which network(s) themodule will join and the settings to use on that network.

    WAP Settings: WAP 1, WAP 2 and Ad Hoc can be left blank. WAP 1 and WAP 2 specifyPRIMARY and SECONDARY network names. On power up, the module will first attempt tojoin these networks before falling back to NpeWiFiConfig. Since we will leave the AP setto NpeWiFiConfig, we do not need to specify WAP 1 or WAP 2. The module will notattempt to create or join an Adhoc network unless Adhoc is specified under RadioSettings.

    IP Settings: This specifies the IP Configuration for the project. The IP configuration

  • Quick Start Guide 13

    2011 ... North Pole Engineering, Inc.

    applies to all networks: WAP 1, WAP 2, NpeWiFiConfig, or Adhoc. In our case, the AP isacting as a DHCP server so we want to make sure Enable DHCP is checked. When EnableDHCP is checked, Static IP, Subnet Mask, and Gateway IP Address are ignored and areinstead assigned by the DHCP server.

    Radio Settings: Make sure Join Network on Startup is checked. Then under Network(s) toJoin, select Infrastructure. This means the node will attempt to join all infrastructurenetworks in order at power on. In our case, this will skip WAP 1 and WAP 2 since they areblank, and go directly to NpeWiFiConfig.

    Important Note: Incorrect network settings may leave the module in a state where itis not attempting or is not able to join a network. In this case, the module is stillfunctional and the firmware and any project downloaded are still running, but themodule is not accessible. It may be necessary to access the module over USB to restorethe network settings. See Regaining Access to a Device.

    Set the Project Power Settings: Scroll the Device Settings window until the Power panel isvisible. Check 'Enable Sleep', this activates the low-power mode in the node. Now set 'SleepTime' to 2000 ms. This will cause the node to wake up every two seconds to execute the WiFiBasic code.

    Important Note: The power settings will trigger execution of the WiFi Basic program everytwo seconds regardless of how much time is spent in execution. Also, execution will beginregardless of whether the module entered the sleep state. Certain background tasks, such asnegotiation of DHCP, may temporarily prevent the module from entering the sleep state. Thesleep state may be confirmed visually on the DCard by observing that the DC_CTRL LED is off.

  • WiFi-IT! Basic Language Reference14

    2011 ... North Pole Engineering, Inc.

    Select GPIO: Click the GPIO tab located at the bottom of the Project Configuration Panel.

    Locate GPIOs 30 and 31. Click the Output Enable checkboxes for GPIOs 30 and 31.

    Once the configuration settings have been entered we need to save them. Click the'x' on theeditor tab for Blink's project configuration.

    A dialog appears asking you if you want to save the changes, click Yes.

    NOTE: You may also press to save your changes.

    Go to: Compiling the Program

    3.3.3 Compiling the Program

    At this point we have entered the program, saved it and configured the device settings for anydevice that will be loaded with the program. Now we need to compile the program and fix anyerrors that may occur.

    Compile the Program: Right-click the project (Blink) and select Compile Project from the drop-down menu. The results of the compile are shown below.

  • Quick Start Guide 15

    2011 ... North Pole Engineering, Inc.

    Notice the console window indicates an error has been detected and has marked the offendingline number with a red x. To get additional information click the Notifications tab next to theconsole tab.

    The Notifications tab shows errors for all projects. You can click on Location, Resource orDescription to sort the errors. Double-clicking on any error in the Notifications tab will take youto the offending line in the program code.

    The error we encountered shows that the line contains an unrecognized word. Looking at line 12we see that the variable Temp was mistyped as Temp1. Delete the '1', save the change (ctrl-S)and recompile.

    Now there should be no errors. We are ready to load the program into a WiFi-IT! node.

  • WiFi-IT! Basic Language Reference16

    2011 ... North Pole Engineering, Inc.

    Go to: Loading the Program

    3.3.4 Loading the Program

    To load a program into a device we need to connect to it through the default provisioningnetwork, NpeWiFiConfig.Perform the following steps:

    1. Make sure the wireless access point (AP) that came with your EDK is powered andconnected to your computer via the provided ethernet cable.The cable should be connected to one of the downstream ports as shown, and not tothe Internet uplink port. We are not connecting our network to the Internet at thistime.

    2. Disable any firewalls on the computer running the IDE. If firewalls are not disabled,usually Windows will ask whether you wish to permit communication over a COM portor network port. Always select "Unblock" in these dialogs.

    3. If the IDE was running before the AP was connected, close, then restart the IDE.

    Important Note: Currently, the IDE only scans the PC network interfaces at startup. If a network is connected after the IDE has been started, it will not be able to see anymodules that join that network.

    4. Connect a module to the DCard as shown.

  • Quick Start Guide 17

    2011 ... North Pole Engineering, Inc.

    5. Make sure the power switch is off and connect the AC adapter.

    6. Make sure both the FLASH DL and L2 DBG switches are in the up position, as shown. This ensures the module will operate in its normal run mode.

  • WiFi-IT! Basic Language Reference18

    2011 ... North Pole Engineering, Inc.

    7. Power up the WiFi-IT! node by turning on power to the DCard. The red LED should goout and the green LED should light.

    8. Wait for Device to join NpeWiFiConfig: The node should power up and begin lookingfor the configuration Access Point. After no more than 30 seconds the device MACAddress should appear under the Device tree, in the project Navigator. If it doesn'tpower off the DCard and verify the network connection to the Wi-Fi access point.

    9. Right click on the device's MAC address and select 'Load Project Into Device'. Thenselect 'Blink' and click Ok.

    Important Note: When a program is loaded over the air, it is loaded using thenetwork that the node is currently connected to. In the case of the EDK/EDK+ thedefault network SSID is NpeWiFiConfig on Wi-Fi channel 6. Once the code is started(immediately after loading), the node will reconfigure the wireless connection settingsto those specified in the project configuration panel for that project. This could causethe node to lose connectivity to the current network.

    At this point the program should be loaded and running. Every two seconds the module powerson briefly and alternately lights either GPIO30 or GPIO31.

    Go to: Debug the Program

    3.3.5 Debug the Program

    Let's load the program in debug mode. This will allow you to familiarize yourself with the debugtools. At this point the DCard should be powered up and the nodes MAC address should belisted under the Devices tree in the Navigation view.

    Download the Code in Debug Mode: Once the MAC address appears under the Device heading,right-click it and select Debug Project on Device. This will bring up a dialog where you can select

  • Quick Start Guide 19

    2011 ... North Pole Engineering, Inc.

    the project to load, as shown below.

    Important Note: The IDE allows you to reload a project or start a debugging session on amodule that's already been loaded, as long as that module has maintained its connection withthe AP.

    Click on Blink, then click the OK button. The Progress Information dialog will appear. Wait forthe operation to complete.

    The IDE will then load the Debug perspective, shown below.

  • WiFi-IT! Basic Language Reference20

    2011 ... North Pole Engineering, Inc.

    From the debug perspective you can run, step, view variables and set breakpoints, all from thetop tool bar. As you hang your cursor over each of the buttons a tooltip appears to explain thebutton function and the hot key associated with that function. The Window menu allows you toopen tabs for Variables, Breakpoints and Register displays.

    Click the step button (or press F6) to single-step through the program. You should see thevariable change state according to the line of code executed. In addition, you will see the LEDsconnected to the GPIO pins change state.

    When you are finished debugging, click the Terminate button (red square in the toolbar) to exitand return to the standard IDE configuration.

    3.4 Project 2 - RSSIHopefully, you have gone through Project 1. The directions for this example assume that you arefamiliar with using the IDE.This program will display the node's received signal strength indicator (RSSI) in the IDE. It mustcreate a data packet recognizable by the IDE. Once the IDE receives these packets, the node'sRSSI will be visible in the IDE's Data Monitor Perspective.

    Go to: RSSI Program

  • Quick Start Guide 21

    2011 ... North Pole Engineering, Inc.

    3.4.1 RSSI Program

    This application shows you how to build UDP packets and open a connection to send them fromthe WiFi-IT! node to another station.

    Create a new project named RSSIDemo (File | New Project). Enter the code shown below.

    '' Program Name: RSSIDemo.tb' Date : Feb 2nd, 2011' Description : Report RSSI to IDE'

    ' VariablesDIM ipAddr AS STRINGDIM sendCID AS INTEGERDIM macAddr AS STRINGDIM varName AS STRINGDIM varValue AS INTEGER

    ' We need to use byte arrays for sending and' receiving data over the network.' The value in parentheses is the max index.' Array indexes start at 0. Thus this array' has 30 elements.DIM dataPkt(29) AS BYTE

    ' Constants' Packet types recognized by IDE.CONST VARIABLE = 0x01CONST GRAPHDATA = 0x02CONST MESSAGE = 0x03CONST RAW = 0x04

    ' Data types recognized by IDE.CONST StringType = 0x00CONST IntType = 0x01CONST ByteType = 0x02

    TASK ' The IDE listens for packets at the multicast ' address 224.0.0.100:20000 ' Multicast addresses are not point-to-point. They ' are one to many. To receive packets directed ' towards a multicast address, the receiving application ' must register for them. Any number of applications on ' any number of network stations could register to ' receive these packets. GPIO(31) = 1 ipAddr = "224.0.0.100" sendCID = OPEN UDP ipAddr, 20000 IF sendCID = ERRORFLAG THEN ' ERRORFLAG is a system constant. ' Failed to open socket

  • WiFi-IT! Basic Language Reference22

    2011 ... North Pole Engineering, Inc.

    GPIO(31) = 0 QUIT ENDIF ' Now format the data packet. Format is: ' Preamble ('W', 'B'): 2 bytes ' Device MAC: 6 bytes ' Packet Type: 1 byte ' Number of data values: 1 byte ' Data: n bytes ' Preamble dataPkt(0) = 0x57 ' W dataPkt(1) = 0x42 ' B ' MAC address ' The MAC address is only available as a ' string in the format "xx:xx:xx:xx:xx:xx". ' We need to use string commands to extract ' the byte values. ' String indexes start at 1, not 0. dataPkt(2) = MAC_ADDRESS ' Packet Type ' Variable packet types present data as pairs ' of data values. Each pair contains a string ' and an integer. The string contains the name ' of the variable and the integer contains its value. dataPkt(8) = VARIABLE ' Const defined above. ' Number of data values is 2 - ' 1 string/integer pair to represent RSSI dataPkt(9) = 2 ' First data item, String = "RSSI" ' String type contains length of string followed ' by that many bytes varName = "RSSI" dataPkt(10) = StringType dataPkt(11) = LEN$(varName) dataPkt(12) = TOBYTEARRAY(varName) ' Second data item is actual RSSI value ' Int type contains no of ints followed by data varValue = RSSI dataPkt(16) = IntType dataPkt(17) = 1 ' 1 integer value dataPkt(18) = CBYTE(varValue) ' Store in little-endian ' Done formatting packet. Now send it. SEND sendCID, dataPkt(0), 22 ' In case we forget to enable sleep, this will ' prevent us from spamming the network with traffic. DELAY 500

  • Quick Start Guide 23

    2011 ... North Pole Engineering, Inc.

    GPIO(31) = 0 REPEAT_TASK

    ' Define subroutines and error handlers here.

    END

    Go to: Run the Program

    3.4.2 Run the Program

    Once you have created the project and copied in the program text, perform the following stepsto finish configuring the project and start the program:

    Open the Project Configuration Panel (right-click the project and select Edit Project DeviceConfiguration, from the popup menu).Enter the SSID and Channel of a wireless access point on your network (useNpeWiFiConfig, channel 6, if you like). In the Power settings, check Enable Sleep and set aSleep Time of 5000 milliseconds.Switch to the GPIO tab on the PCP and click Output Enable for GPIO 31. Close the PCP and save the results.Compile the project and make sure no errors were detected.Now, select a Device from the Devices tree, right-click and select Load Project to Device.When the load has completed and GPIO 31 is flashing on the DCard.

    Now switch to the Data Monitor Perspective in the IDE and you should see your node's MACaddress with a corresponding RSSI value. Select "Switch to Data Monitor Perspective" from theWindow menu. The IDE should look as shown below with a new RSSI value updating every fiveseconds.

  • WiFi-IT! Basic Language Reference24

    2011 ... North Pole Engineering, Inc.

    3.5 Project 3 - Temp SensorThis project will walk you through loading and debugging a project in UART provisioning mode. In this mode, debugging operations are handled entirely over the UART. This is useful fordebugging programs that manipulate network settings, or create their own private adhocnetwork. It also helps debug network traffic since otherwise a lot of packets can be generatedbetween the IDE and the Run Time Engine (RTE) during a debug session.

    3.5.1 TempSensor program

    Like the RSSI demo, this program will also continuously report a value that will display in theIDE's Data Monitor perspective.Unlike the RSSI demo, this data will be displayed on a graph.This time we will be grabbing temperature readings from the SCard provided in your EDK.

    Create a new project named TempSensor (File | New Project). Enter the code shown below.

    '' Temperature Sensor Demo' Demonstrates use of the TMP112 sensor on the SCard.' http://focus.ti.com/docs/prod/folders/print/tmp112.html

  • Quick Start Guide 25

    2011 ... North Pole Engineering, Inc.

    '

    DIM I2Cmd(7) AS BYTEDIM I2CData(7) AS BYTEDIM iTemp AS INTEGERDIM iCharCnt AS INTEGERDIM dataPkt(63) AS BYTEDIM sendCID AS INTEGERDIM varName AS STRINGDIM varValue AS INTEGER

    CONST TSENSOR_ADRS = 0x48CONST TSENSOR_P_TEMP = 0 ' Pointer to Temperature registerCONST TSENSOR_P_CONFIG = 1 ' Pointer to Configuration register.

    ' Packet types recognized by IDE.CONST VARIABLE = 0x01CONST GRAPHDATA = 0x02CONST MESSAGE = 0x03CONST RAW = 0x04

    ' Data types recognized by IDE.CONST StringType = 0x00CONST IntType = 0x01CONST ByteType = 0x02

    TASK GOSUB SetupTemp GOSUB ReadTemp GOSUB ConvertTemp GOSUB SendTemp DELAY 2000REPEAT_TASK

    ' SetupTemp - Perform a one-shot temperature conversion at 4Hz.' Should take 26ms for temp sensor to complete conversion.SUB SetupTemp I2Cmd(0) = TSENSOR_P_CONFIG I2Cmd(1) = %11100000 I2Cmd(2) = %10100000 OUTPUT I2C TSENSOR_ADRS, I2Cmd(0), 3 DELAY 50 RETURNENDSUB ' ReadTemp - Read the temperature from the TI TMP112.' Data is read out in big-endian format, so we need to normalize it and' put it into little-endian format.SUB ReadTemp I2Cmd(0) = TSENSOR_P_TEMP OUTPUT I2C TSENSOR_ADRS, I2Cmd(0), 1 ' Set pointer to Temp regs.

  • WiFi-IT! Basic Language Reference26

    2011 ... North Pole Engineering, Inc.

    iCharCnt = INPUT I2C TSENSOR_ADRS, I2CData, 2 ' Read temperature data. iTemp = I2CData(0) SHL 4 ' Right-justify temp reading iTemp = iTemp + (I2CData(1) SHR 4) ' into iTemp RETURN ENDSUB

    ' ConvertTemp - Converts the temperature reading to an integer value.' Temp reading is 16 steps per degree Celsius.' Shift by 4 to get rid of fractional part, then sign' extend to get a full 4-byte value.SUB ConvertTemp iTemp = iTemp SHR 4 IF (iTemp AND 0x80) = 0x80 THEN iTemp = iTemp AND 0xFFFFFF00 ENDIF RETURNENDSUB

    ' SendTemp - Send temperature reading to the IDE.' Packet is formatted to appear in IDE's Data Monitor perspective.SUB SendTemp sendCID = OPEN UDP "224.0.0.100", 20000 IF sendCID = ERRORFLAG THEN ' ERRORFLAG is a system constant. ' Failed to open socket RETURN ENDIF

    ' Now format the data packet. Format is: ' Preamble ('W', 'B'): 2 bytes ' Device MAC: 6 bytes ' Packet Type: 1 byte ' Number of data values: 1 byte ' Data: n bytes ' Preamble dataPkt(0) = 0x57 ' W dataPkt(1) = 0x42 ' B ' MAC address dataPkt(2) = MAC_ADDRESS ' Packet Type dataPkt(8) = GRAPHDATA ' Const defined above. ' Number of data values is 3 - ' 1 string value with the Graph Title ' 1 string value with the Y-Axis Label ' 1 integer value with the Y Value dataPkt(9) = 3 ' First data item, Graph Title: "Temperature" ' String type contains length of string followed

  • Quick Start Guide 27

    2011 ... North Pole Engineering, Inc.

    ' by that many bytes varName = "Temperature" dataPkt(10) = StringType dataPkt(11) = LEN$(varName) dataPkt(12) = TOBYTEARRAY(varName) ' Second data item, Y-Axis Label = "Deg Celcius" ' String type contains length of string followed ' by that many bytes varName = "Deg Celcius" dataPkt(23) = StringType dataPkt(24) = LEN$(varName) dataPkt(25) = TOBYTEARRAY(varName) ' Third data item is actual temperature value ' Int type contains no of ints followed by data varValue = iTemp dataPkt(36) = IntType dataPkt(37) = 1 ' 1 integer value dataPkt(38) = CBYTE(varValue) ' Store in little-endian ' Done formatting packet. Now send it. SEND sendCID, dataPkt(0), 42 RETURNENDSUB

    END

    Go to: Configuration Settings

    3.5.2 Configuration Settings

    If your Netgear AP is still set to "NpeWiFiConfig", channel 6. The wireless settings can be leftblank. Make sure that 'Enable DHCP' is set and 'Network(s) to Join' is set to Infrastructure.

  • WiFi-IT! Basic Language Reference28

    2011 ... North Pole Engineering, Inc.

    For this project, we can also disable the sleep settings, since we have a DELAY statement beforeREPEAT_TASK instead.

    Now, for the I2C settings, navigate to the select the I2C configuration tab and enable the I2Cinterface. The default settings will work fine for the temp sensor.

    Go to: Set up the Hardware

    3.5.3 Set up the Hardware

    Before running the program, we need to make sure we have the hardware set up correctly. Follow the same procedure for Loading the Program you used for the Blink demo. Then performthe following additional steps:

    Make sure SW7 is set to the down position. This connects UART0 of the WiFi-IT! module withthe onboard Serial to USB interface.

    Connect the SCard to J1 of the DCard.

  • Quick Start Guide 29

    2011 ... North Pole Engineering, Inc.

    Finally, make sure the serial interface is connected to one of the available USB ports on your PC.

    Now we are ready to download and debug our program.Go to: Debug the Program

    3.5.4 Debug the Program

    Now we are ready to try debugging the program in wired mode. Right click on the device in theDevices list and select "Switch Device to UART Config Mode". The device should disappear fromthe Devices list since it is no longer communicating with the IDE over the wireless connection. Compile the program if you have not done so already, and then perform the following steps tostart a debug session over UART.

    Select "Device | UART | Debug Project". The IDE will ask which COM port to use.

  • WiFi-IT! Basic Language Reference30

    2011 ... North Pole Engineering, Inc.

    If you are unsure which COM port is assigned to the DCard, you can check the Windows DeviceManager. Make sure the USB cable is connected and the DCard powered on or the COM port willnot appear in the Device Manager. To get to the Device Manager, right-click on My Computerand select Properties (or alternatively select System in Windows Control Panel). Click theHardware tab, then click Device Manager. The DCard's USB to serial translator will show upunder "Ports (COM & LPT)" as "Silicon Labs CP210x USB to UART Bridge".

    Next, select the TempSensor project from the project selection dialog and wait for the progressbar to finish. You should now see the Debug perspective halted on the first line of theTempSensor program. From here you can set and clear breakpoints, single step individualsource lines, and run and halt the program the same as if you were in WiFi provisioning mode.

  • Quick Start Guide 31

    2011 ... North Pole Engineering, Inc.

    To see the data output from this program, remove all breakpoints, click 'Go', then select"Window | Switch to Data Monitor Perspective". You should see a temperature readingreported in degrees Celsius every two seconds. When you are doing viewing readings, return tothe debug perspective by selecting "Window | Switch to Debug Perspective".

  • WiFi-IT! Basic Language Reference32

    2011 ... North Pole Engineering, Inc.

    When you are finished debugging, click the red square to terminate the debug session.

    4 Programming Reference

    This section is a compilation of the keywords, statements and operators that make up WiFi-Basic. The commands are grouped by function for easy location. The table below defines thegrouping.

    Group Name DescriptionNumeric BaseSpecification

    Overview of base specification for literal constants.

    Error Handling This section describes generation of errors and the two modesin which they can be handled: active and passive.

    Flow Control The statements in this section control the flow of execution of aprogram.

    Date/Time Functions Functions to get/set the RTC and to convert the RTC time to year,month, day, hour, minute, and second.

    Interfaces Contains subsections on how to use each of the hardwareinterfaces: ADC, GPIO, I2C, PWM, SPI, and UART.

  • Programming Reference 33

    2011 ... North Pole Engineering, Inc.

    Intrinsic Constants Built-in, predefined keywords that translate to constant values.Miscellaneous Collection of general statements.Networking Overview of socket operations and network mangement.

    Operations for managing WiFi networks, opening and closingconnections, and sending and receiving data.

    Operators A listing of Arithmetic, Comparison, Bitwise and Stringoperators.

    String Functions Functions for the manipulation and creation of string types.Variables & Datatypes This section contains a description of the supported variable and

    data types. Statements for declaring variables and constants in aprogram can be found here.

    4.1 General InformationThe information contained in this section provides some general information on writing code inWiFi-Basic. It is important to read and understand these simple rules and compiler limitationsin order to write code that compiles successfully.

    4.1.1 Numeric Base Specification

    Constants can be specified in base-10 (decimal), base-16 (hexadecimal) and base-2 (binary).The prefixes, listed below are used to specify the numeric base for a constant. The prefix mustnot be separated from the number and the base specified will only apply to that specificnumber.

    Prefix Base% Binary0x Hexadecimal

    Examples:Expression Decimal Value DescriptionMyVar = %1010 MyVar = 10 Specify a binary number.

    VarX = 0x105

    MyVar = VarX AND 0xFF MyVar = 5 Specify a Hexadecimal number. Mask to returnthe lower 8-bits.

    MyVar = 0x20 + 10 MyVar = 42 The default numeric base is 16. Add 2016 to 1010(=3210 + 10 = 42).

    4.1.2 Literal Constants

    1. Hexadecimal numbers can be entered by preceding them with "0x". e.g. 0x10 = 16decimal

    2. Binary numbers can be entered by preceding them with "%". e.g. %10000 = 16 decimal

  • WiFi-IT! Basic Language Reference34

    2011 ... North Pole Engineering, Inc.

    3. Constant names are not case sensitive.4. String constants are currently not supported.

    4.1.3 Program Lines

    1. Each program line is treated as a complete statement, which must be terminated by acarriage-return and/or line-feed.

    2. The maximum number of characters in a line cannot exceed 128.3. Line numbers are not allowed in WiFi-Basic, labels are used when specifying the target for

    subroutine calls or when defining error handlers.

    4.1.4 Keywords

    1. All WiFi-IT! Basic keywords can be entered in upper, lower or mixed case. All keywordsare case insensitive.

    4.2 Error HandlingWiFi-Basic implements two types of runtime error handling; passive and active. By defaultruntime errors are handled passively, meaning if the programmer does not check for errors,WiFi-Basic will continue execution regardless of any error condition. This may cause erraticbehavior in a program, so it is advisable to perform some type of error handling.

    When the WiFi-IT! Basic program has enabled active error handling, the WiFi-Basic Run TimeEngine will jump to the declared error handler when an error is detected. The programmer canthen handle the error appropriately whether that means returning to the program to continueexecution, aborting the current run or some other action.

    4.2.1 Active Error Handling

    Active error handling is enabled when an error handling routine is defined. The program willjump to the active error handler when an error is detected. The ON_ERROR keyword is used todefine the error handler. Active error handling can be disabled by specifying zero as theoperand of the ON_ERROR keyword, as shown in the example below. The ON_ERROR keywordcan be used more than once in a program.

    When active error handling is operating and an error is detected, the RTE will interruptexecution at the point where the error is detected. The statement is not necessarily completed.If RESUME is used to return from the error handler, execution will begin at the start of thestatement. If RESUME_NEXT is used, the remaining statement code is skipped and executionbegins with the next instruction. The QUIT keyword can be used in an error handler if the erroris not one handled by the error handler. An error handler must exit using one of these keywords the RETURN keyword cannot be used in an error handler and will cause a compiler error.

    Error handlers are defined outside the TASK REPEAT_TASK loop, using the ESUB ENDESUB

  • Programming Reference 35

    2011 ... North Pole Engineering, Inc.

    keywords. Within the error handler, any number of program statements can be used to analyseand correct execution of the program. The ERROR keyword maintains the value of the errorcode that invoked the error handler for the duration of the ESUB, regardless of how many timesit is read. This is a change from the default behavior of ERROR when operating in passive errorhandling mode.

    A list of runtime error codes can be found at Error Codes.

    Active Error Handling Example:DIM cid(10) AS INTEGER

    TASK : ON_ERROR ErrHandler ' Define an error handler - Active Error handling isenabled. : cid(8) = OPEN UDP "192.168.0.1", 8255 : ON_ERROR 0 ' Active error handling is disabled. :REPEAT_TASK

    ESUB ErrHandler ' This is the active error handler for the program. When an error occurs, ' program execution transfers to this routine. IF ERROR = ECIDLIMIT THEN ' Too many open connections. CLOSE cid(0) ELSE QUIT ' We don't know what the error is, so return to REPEAT_TASK. ENDIF RESUME ' The error has been handled, return to the line that caused ' the error and try again.ENDESUBEND

    4.2.2 Passive Error Handling

    When a runtime error is encountered, the default behavior of WiFi-Basic is to place the errorcode into the system variable, ERROR and complete the statement. No other action is taken bythe RTE. If the programmer does not check the ERROR variable and handle the error condition,execution will continue as if the error had not occurred.

    The ERROR system variable can be checked at anytime and if it is non-zero, the appropriateaction can be taken. Once the ERROR variable is read it is reset to EOK, therefore if the value isreferenced multiple times it should be saved into a temporary variable.

    If the ERROR variable is not read, it maintains the value of the last error condition until a newerror condition occurs. The ERROR variable is only set to EOK at the beginning of the TASK loop,when the ERROR variable is read in passive mode, or when exiting an error handler in activemode.

  • WiFi-IT! Basic Language Reference36

    2011 ... North Pole Engineering, Inc.

    A list of runtime errors can be found at Error Codes.

    Passive Error Handling Example:DIM cid(10) AS INTEGER

    TASK DO cid(8) = OPEN UDP "192.168.0.1", 8255 IF cid(8) = -1 THEN ' An error has occurred! We didn't get a valid Connection ID. IF ERROR = ECIDLIMIT THEN ' Too many open connections. CLOSE cid(0) ENDIF ENDIF UNTIL cid(8) (-1) :REPEAT_TASKEND

    4.2.3 Double Faults

    An error occuring within an error handler is called a double fault. When running normally (notdebugging) double faults cause an automatic QUIT to occur. There is no indication to the runningprogram that a double fault error occurred.

    Double faults can be caught, but only in the debugger. If a double fault occurs while debugging,the program automatically halts at the REPEAT_TASK statement (no breakpoint is necessary).The IDE will show the original error code, the error code of the double fault, and the line thedouble fault occurred on.

    4.2.4 Error Handling Keywords

    Error handling keywords are used to define active error handlers and control the flow ofexecution between the main program and error handlers.

    ESUB - ENDESUBON_ERRORRESUMERESUME_NEXT

    See also the QUIT keyword, which is valid in error handlers.

    4.2.4.1 ERROR

    { =} ERRORIF ERROR {= } THEN The ERROR system variable holds the runtime error code of the last error that occurred. Theoperation of ERROR differs depending on the type of error handling that is in effect. See Error

  • Programming Reference 37

    2011 ... North Pole Engineering, Inc.

    Handling, for more information on the types of error handling supported by WiFi-Basic.

    Passive Error Handling:When passive error handling is active, the first read of ERROR sets it back to zero (EOK status).

    Active Error Handling:When active error handling is enabled, the operation of ERROR changes depending on the codethat is executing.

    Outside of the error handler: 1. ERROR will always read as EOK since it is reset by the RESUME and RESUME_NEXT

    statements.

    Within the error handler:1. Multiple reads of ERROR do not set it back to EOK. ERROR retains the same value throught

    out the execution of the error handler. 2. A second error while executing the error handler code will cause ERROR to be updated

    with the new error code.3. An error while executing the error handler code perfo