You are on page 1of 175

WiFi-Basic

Programmers Manual
Version 2.3

(c) 2011 North Pole Engineering, Inc.

WiFi-IT! Basic Language Reference

Table of Contents
Foreword

Part I Introduction

1 Welcome
................................................................................................................................... 1
2 What's ...................................................................................................................................
New
1
3 Notation
...................................................................................................................................
Used in this Document
3
4 Modes of
...................................................................................................................................
Operation
4

Part II WiFi Basic Program Structure

1 Project...................................................................................................................................
Configuration Panel
5
2 Source ...................................................................................................................................
File
6

Part III Quick Start Guide

1 Connecting
...................................................................................................................................
the Hardware
8
2 Starting...................................................................................................................................
the IDE
8
3 Project...................................................................................................................................
1 - BLINK
9
Writing the Program
.......................................................................................................................................................... 11
Configuration..........................................................................................................................................................
Settings
11
Com piling the..........................................................................................................................................................
Program
14
Loading the Program
.......................................................................................................................................................... 16
Debug the Program
.......................................................................................................................................................... 18

4 Project
...................................................................................................................................
2 - RSSI
20
RSSI Program.......................................................................................................................................................... 21
Run the Program
.......................................................................................................................................................... 23

5 Project
...................................................................................................................................
3 - Temp Sensor
24
Tem pSensor ..........................................................................................................................................................
program
24
Configuration..........................................................................................................................................................
Settings
27
Set up the Hardw
..........................................................................................................................................................
are
28
Debug the Program
.......................................................................................................................................................... 29

Part IV Programming Reference

32

1 General
...................................................................................................................................
Information
33
Num eric Base..........................................................................................................................................................
Specification
33
Literal Constants
.......................................................................................................................................................... 33
Program Lines
.......................................................................................................................................................... 34
Keyw ords
.......................................................................................................................................................... 34

2 Error Handling
................................................................................................................................... 34
Active Error Handling
.......................................................................................................................................................... 34
Passive Error ..........................................................................................................................................................
Handling
35
Double Faults .......................................................................................................................................................... 36
Error Handling..........................................................................................................................................................
Keyw ords
36
ERROR ......................................................................................................................................................... 36
ESUB - ENDESUB
......................................................................................................................................................... 37
ON_ERROR
......................................................................................................................................................... 38
2011 ... North Pole Engineering, Inc.

Contents

II

RESUME ......................................................................................................................................................... 38
RESUME_NEXT
......................................................................................................................................................... 38

3 Date/Time
...................................................................................................................................
Functions
39
DAY
.......................................................................................................................................................... 39
HOUR
.......................................................................................................................................................... 40
MINUTE
.......................................................................................................................................................... 40
MONTH
.......................................................................................................................................................... 40
MONTHNAME .......................................................................................................................................................... 40
NOW
.......................................................................................................................................................... 41
SECOND
.......................................................................................................................................................... 42
WEEKDAY
.......................................................................................................................................................... 42
WEEKDAYNAME
.......................................................................................................................................................... 42
YEAR
.......................................................................................................................................................... 43

4 Flow Control
................................................................................................................................... 43
DO - UNTIL | LOOP
.......................................................................................................................................................... 44
END
.......................................................................................................................................................... 45
EXITDO | EXITFOR
..........................................................................................................................................................
| EXITWHILE
45
FOR - TO - STEP
..........................................................................................................................................................
- NEXT
45
GOSUB
.......................................................................................................................................................... 46
RETURN
.......................................................................................................................................................... 47
IF - THEN - ELSE
..........................................................................................................................................................
- ENDIF
47
QUIT
.......................................................................................................................................................... 48
SUB - ENDSUB .......................................................................................................................................................... 49
TASK - REPEAT_TASK
.......................................................................................................................................................... 49
WHILE - WEND.......................................................................................................................................................... 49

5 Interfaces
................................................................................................................................... 50
ADC
.......................................................................................................................................................... 51
FLASH
.......................................................................................................................................................... 52
READ
......................................................................................................................................................... 52
WRITE
......................................................................................................................................................... 53
GPIO
.......................................................................................................................................................... 53
GPIO Configuration
......................................................................................................................................................... 54
GETDIR ......................................................................................................................................................... 55
SETINPUT ......................................................................................................................................................... 56
SETOUTPUT
......................................................................................................................................................... 57
I2C
.......................................................................................................................................................... 57
I2C Configuration
......................................................................................................................................................... 57
CONFIGURE
......................................................................................................................................................... 58
INPUT
......................................................................................................................................................... 59
OUTPUT ......................................................................................................................................................... 60
PWM
.......................................................................................................................................................... 61
PWM Configuration
......................................................................................................................................................... 61
START ......................................................................................................................................................... 63
STOP
......................................................................................................................................................... 63
UPDATE ......................................................................................................................................................... 64
SPI
.......................................................................................................................................................... 64
SPI Configuration
......................................................................................................................................................... 66
CONFIGURE
......................................................................................................................................................... 68
INPUT
......................................................................................................................................................... 69
OUTPUT ......................................................................................................................................................... 71
UART
.......................................................................................................................................................... 72
UART Configuration
......................................................................................................................................................... 73
INPUT
......................................................................................................................................................... 74
2011 ... North Pole Engineering, Inc.

II

III

WiFi-IT! Basic Language Reference


OUTPUT ......................................................................................................................................................... 75
UART_RX ......................................................................................................................................................... 76

6 Intrinsic
...................................................................................................................................
Constants
77
ADHOC
.......................................................................................................................................................... 78
ALARM1
.......................................................................................................................................................... 78
ALARM2
.......................................................................................................................................................... 78
AUTO
.......................................................................................................................................................... 78
COLD_BOOT .......................................................................................................................................................... 78
CURRENT
.......................................................................................................................................................... 78
Error Codes .......................................................................................................................................................... 79
ERRORFLAG .......................................................................................................................................................... 81
FALSE
.......................................................................................................................................................... 81
INFRASTRUCTURE
.......................................................................................................................................................... 81
NONE
.......................................................................................................................................................... 82
OFF
.......................................................................................................................................................... 82
ON
.......................................................................................................................................................... 82
PRIMARY
.......................................................................................................................................................... 82
PROVISION .......................................................................................................................................................... 82
SECONDARY .......................................................................................................................................................... 83
TRUE
.......................................................................................................................................................... 83
WEP_OPEN .......................................................................................................................................................... 83
WEP_SHARED .......................................................................................................................................................... 83
WPA_ENTERPRISE
.......................................................................................................................................................... 84
WPA_PERSONAL
.......................................................................................................................................................... 84
WPA2_ENTERPRISE
.......................................................................................................................................................... 84
WPA2_PERSONAL
.......................................................................................................................................................... 84

7 Miscellaneous
...................................................................................................................................
Functions
84
Com m ent
.......................................................................................................................................................... 85
ABS
.......................................................................................................................................................... 85
BYTECOPY
.......................................................................................................................................................... 85
CBYTE
.......................................................................................................................................................... 86
CINT
.......................................................................................................................................................... 87
DELAY
.......................................................................................................................................................... 88
EVENT
.......................................................................................................................................................... 88
SERIAL_NUMBER
.......................................................................................................................................................... 89
TIMER
.......................................................................................................................................................... 90
UBOUND
.......................................................................................................................................................... 90

8 Power...................................................................................................................................
Management
91
Pow er Configuration
.......................................................................................................................................................... 91
Sleep Mode Operation
.......................................................................................................................................................... 91
RECEIVER
.......................................................................................................................................................... 93
SLEEP
.......................................................................................................................................................... 93
SLEEP_MODE .......................................................................................................................................................... 94
UART_RX
.......................................................................................................................................................... 95
XMIT_POWER .......................................................................................................................................................... 95

9 Networking
................................................................................................................................... 95
Netw orking Overview
.......................................................................................................................................................... 96
Wireless Configuration
.......................................................................................................................................................... 98
IP and Port ranges
.......................................................................................................................................................... 100
Notes on using
..........................................................................................................................................................
TCP
101
Socket Operations
.......................................................................................................................................................... 102
ACCEPT ......................................................................................................................................................... 103
CLOSE ......................................................................................................................................................... 104
2011 ... North Pole Engineering, Inc.

Contents

IV

GET_SENDER_CID
......................................................................................................................................................... 104
GET_SENDER_IP
......................................................................................................................................................... 105
GET_SENDER_PORT
......................................................................................................................................................... 106
LISTEN ......................................................................................................................................................... 106
OPEN
......................................................................................................................................................... 107
POLL
......................................................................................................................................................... 108
POLL_SEND
......................................................................................................................................................... 109
RECEIVE ......................................................................................................................................................... 110
SEND
......................................................................................................................................................... 111
Netw ork Configuration
.......................................................................................................................................................... 112
CHANNEL......................................................................................................................................................... 113
DHCP
......................................................................................................................................................... 114
GATEWAY
......................................................................................................................................................... 115
IP$
......................................................................................................................................................... 115
IP_ADDRESS
......................................................................................................................................................... 116
LINK
......................................................................................................................................................... 117
LINKED? ......................................................................................................................................................... 118
MAC_ADDRESS
......................................................................................................................................................... 118
PASSPHRASE
......................................................................................................................................................... 119
RSSI
......................................................................................................................................................... 121
SCAN ......................................................................................................................................................... 122
SCAN_RESULT
......................................................................................................................................................... 124
SCAN_ELEMENT
......................................................................................................................................................... 125
SECURITY......................................................................................................................................................... 126
SSID
......................................................................................................................................................... 128
SUBNET ......................................................................................................................................................... 129
UNLINK ......................................................................................................................................................... 130
VALIP ......................................................................................................................................................... 131
WEPKEY ......................................................................................................................................................... 131

10 Operators
................................................................................................................................... 133
Arithm etic Operators
.......................................................................................................................................................... 133
Com parison..........................................................................................................................................................
Operators
134
Bitw ise Operators
.......................................................................................................................................................... 134
String Operators
.......................................................................................................................................................... 135

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

12 Variables
...................................................................................................................................
and Datatypes
143
Variable Nam..........................................................................................................................................................
ing and Lim itations
144
Num eric Data..........................................................................................................................................................
Type Coercion
144
CONST
.......................................................................................................................................................... 144
Variables
.......................................................................................................................................................... 145
2011 ... North Pole Engineering, Inc.

IV

WiFi-IT! Basic Language Reference


DIM
......................................................................................................................................................... 145
STATIC ......................................................................................................................................................... 146

Part V Guides

147

1 Regaining
...................................................................................................................................
Access to a Device
147
2 Updating
...................................................................................................................................
the Device Firmware
150
3 Setting
...................................................................................................................................
Up an Ad Hoc Network
153
4 Data ...................................................................................................................................
Monitor Protocol
155
5 SPI Timing
...................................................................................................................................
Diagrams
156

Part VI Programming Examples

160

1 SPI SRAM
................................................................................................................................... 160
2 UART0
...................................................................................................................................
Input / Output
163

Part VII Definitions


Index

164
167

2011 ... North Pole Engineering, Inc.

Introduction

Introduction

1.1

Welcome

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

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

1.2

What's New
Here are the updates for the latest release and previous releases.
Installation 2.3.0
IDE
1. Export Manufacturing Package option added to File Menu. Combines WiFi Firmware,
compiled WiFi-Basic code, and Project Configuration Settings into one package which can
be loaded using Manufacturing Loader application.
Compiler
1. New EDK+ compiler commands added: SECURITY, PASSPHRASE, WEPKEY
2. New compiler commands added: SERIAL_NUMBER
Firmware
1. 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.0
1. See new documentation section: Data Monitor Protocol.
IDE
2. Graphing capability added for Data Monitor Perspective.
3. Changed configuration panel for I2C.
Compiler
3. 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 <> Operator
5. MAC_ADDRESS can now be assigned directly to byte arrays.
6. Fixed problem with static integers not aligning on word boundaries when preceded by

2011 ... North Pole Engineering, Inc.

WiFi-IT! Basic Language Reference

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.0
1. See new documentation sections: Networking Overview, Wireless Configuration, IP and
Port Ranges, Notes on using TCP, Power Configuration, Sleep Mode Operation, Heap
Management.
2. The development environment now supports compilations for both the WL11 and WL10
modules.
IDE
1. 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.
Compiler
7. 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.6
1. 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 was
terminated.
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.3
IDE
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.

2011 ... North Pole Engineering, Inc.

Introduction

Compiler
1. New commands added: LINK, UNLINK, LINKED?, SUB, ENDSUB, ESUB ENDESUB, RESUME,
RESUME_NEXT, QUIT, ON_ERROR
2. 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 and
TRUE.
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 further
defined in later releases.
8. The ability to change the default numeric base to HEX has been removed.

1.3

Notation Used in this Document


1. 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 "<" and greater than ">" symbols enclose a parameter specification.
4. The following notation is used to indicate parameter types.
<b-value>

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

<b-variable>

Byte variable.

<b-array>

Byte array variable.

const

Constant or number.

<i-value>

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

<i-variable>

Integer variable.

<i-array>

Integer array variable.

<n-value>

Numeric value. A value of type byte or integer. An n-value can be a


numeric variable, an array item or a numeric constant.

<n-variable>

Numeric variable. A variable of type byte or integer.

<n-array>

Numeric array variable (byte or integer).

<s-variable>

String variable.

<s-value>

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

<si-value>

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


integer.

<si-variable>

String or Integer variable.

<sb-value>

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

2011 ... North Pole Engineering, Inc.

WiFi-IT! Basic Language Reference

byte.
<sb-variable> String or byte variable.
<sb-array>

String variable or byte array.

<sib-variable> String or Integer variable, or byte array.


5. The colon character ":" is used in examples to indicate any number of intervening
programming statements.
6. Topic icons in HTML help, marked with a red asterisk in the contents panel are available in
the EDK+ version only.

1.4

Modes of Operation
This section describes the different operating modes of the WiFi-IT! module. It pertains mostly
to 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 at
a time. The default provisioning mode is WiFi.
In WiFi provisioning mode, the module sends out identifying multicast messages which cause
its MAC address to appear in the IDE's devices list. If a MAC address appears in the devices list
along with the 'Connected' keyword, then that module is in WiFi provisioning mode and is
currently connected to the IDE. If a MAC address appears with the 'Disconnected' keyword, then
that module was enumerated but has since lost connection. Note that the module may be
associated to only one network at a time. This means the IDE must be on the same network
with which the module is associated in order to establish a connection. See Overview of
Wireless Operation.
In UART provisioning mode, the module still follows normal network association rules, but it
does not send out identifying multicast messages and does not establish a connection with the
IDE over WiFi. Instead, UART0 is reserved for the connection to the IDE. In UART provisioning
mode, 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 options
there. The IDE will then provide a menu to select the COM port to which the module is
connected.
To switch a module from WiFi to UART provisioning mode, right-click on the device in the
Devices list and select "Switch Device to UART Config Mode". The IDE will send a command to
switch 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 Config
Mode" from the Device menu. Then specify the COM port the device is connected to. After a
few moments for network association, the module should appear in the Devices list.

2011 ... North Pole Engineering, Inc.

Introduction

Operating Mode
There are two main 'operating' modes: Idle and Run. In Idle mode, the BASIC program is not
exectuted and the module does not enter the sleep state. It simply idles, waiting for commands
from the IDE. In Run mode, the BASIC program is executed, and if the Enable Sleep option has
been selected in the Project Configuration Panel, the module will enter the sleep state
between iterations of the TASK REPEAT_TASK structure.
The module is in the Idle mode by default. Once configuration settings and a BASIC program
have been loaded using "Load Project into Device", the module is switched to Run mode. The
module 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 Run
command is issued from the IDE debugger, the module enters a special Idle/Debug state. The
module 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 while
in the low-power state. Idle/Debug is not the same as normal Run mode. If the module loses
power, 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), the
module is reverted to the Idle mode and no WiFi Basic program is loaded.

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

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) for
configuration of WiFi parameters and device interface settings. These settings are used to
automatically configure the hardware before the program starts. The executable code consists
of program statements between TASK and REPEAT_TASK plus any subroutines and error
handlers.
Project Configuration Panel
Source File

2.1

Project Configuration Panel


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

2011 ... North Pole Engineering, Inc.

WiFi-IT! Basic Language Reference

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

Figure 1: Project Configuration Panel for Wireless Settings


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

2.2

Source File
The source file is where all the programming action takes place. A project contains one source
file and all code must be placed into this file.
The structure of a WiFi-Basic program consists of a declaration section, where all variables and
constants are defined. This is followed by the TASK loop which contains the executable program
statements. 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 and
ENDSUB 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 and
REPEAT_TASK is executed once. When execution hits the REPEAT_TASK directive, control

2011 ... North Pole Engineering, Inc.

WiFi Basic Program Structure

returns to the TASK directive at the top of the program. If sleep is enabled, the module will
power off between REPEAT_TASK and TASK. If sleep is not enabled, control returns
immediately to the TASK statement. Whether sleep is enabled or not, the TASK directive clears
all non-static variables and re-initializes the Run-Time Engine (RTE). Numeric variables are set
to the value 0 and strings are set to null. Click the link for more information on Sleep Mode
Operation.
Subroutines and error handling routines exist outside of the TASK directive and follow the
REPEAT_TASK directive. All subroutine and error handling routines must be labeled; the label
can be up to 32-characters in length and must begin with an alpha-character but may contain
numeric characters and the underscore character.
The general format of a WiFi-Basic program is shown below (comments are highlighted in
green).
'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
:
:
RETURN
ENDSUB
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.

Quick Start Guide


The Quick Start Guide leads you through writing , loading, debugging and running a WiFi-Basic
program.
Three example applications are presented. All three require the WiFi-IT! EDK. The first program
demonstrates use of GPIOs and the low-power sleep state. The second program makes use of

2011 ... North Pole Engineering, Inc.

WiFi-IT! Basic Language Reference

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

3.1

Connecting the Hardware


The 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 through
setting 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 to
disconnect your network cable and plug the AP directly into your PC LAN connection. You
must plug your PC LAN connection into one of the PC ports - not the internet port - of the
AP). The AP is setup to serve IP addresses through DCHP. Make sure your PC is setup to
request 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 enter
the AP address into the browser address textbox (see the document enclosed with the AP
for the IP address of the AP). Use the username and password included in the AP
documentation to login.
a. Close the browser.
3. Connect the EDK power supply to the wall plug and plug it into the DCard. A red LED
should 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 the
DCard 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 connections
can occur over the wireless connection.
5.

You're ready to go!

Go to: Starting the IDE

3.2

Starting the IDE


Start the IDE by double-clicking on the WiFi-Basic Icon on the desktop or select it through the
Start Menu.
When the IDE is started, it creates the WiFi-IT folder on your desktop. Inside the WiFi-IT folder
it creates the workspace directory, where all projects are stored in separate subdirectories. The
first time you open the IDE it looks as shown below.

2011 ... North Pole Engineering, Inc.

Quick Start Guide

The Navigator view is on the left and defaults to Devices and Projects. The Devices tree shows
WiFi-IT! nodes that are connected to the IDE. These nodes may be programmed and configured
through the IDE. Below that is the Projects tree, it lists all of the projects in the Workspace. We'll
cover 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 be
able to see any modules that join that network.
Go to: Project 1 - Blink

3.3

Project 1 - BLINK
Now lets get started!
Make sure the power is off on the DCard and connect a WiFi-IT! node to J2. Do not turn on the
power at this time.
Create a Project: Right-click Projects in the Navigator tab and select New Project (or select New

Project from the File menu). Type Blink into the dialog box. The dialog should look like that
shown below.
2011 ... North Pole Engineering, Inc.

10

WiFi-IT! Basic Language Reference

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 code
file 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 created
as shown below.

Go to: Writing the Program

2011 ... North Pole Engineering, Inc.

Quick Start Guide

3.3.1

11

Writing the Program


Enter the program as shown below into the editing window (you can copy and paste it, if you'd
like).
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 the
variable 'Temp' across power cycles so it must be declared as a STATIC variable. Variables
declared 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 will
go out while the node is sleeping. To show the LED, we have added a DELAY statment to delay
entering sleep for 200 milliseconds.
'
'
'
'

This program blinks LEDs on GPIO 30 and 31


in an alternating pattern.

STATIC

Temp

AS INTEGER

TASK
IF (Temp AND 0x01) = 0 THEN
GPIO(31) = 1
GPIO(30) = 0
Temp1 = 0x01
ELSE
GPIO(31) = 0
GPIO(30) = 1
Temp = 0x00
ENDIF
DELAY 200
GPIO(31) = 0
GPIO(30) = 0

' Leave the LEDs on for sometime.

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) and
select 'Edit Project Device Configuration'. The IDE workbench should look like the figure below.

2011 ... North Pole Engineering, Inc.

12

WiFi-IT! Basic Language Reference

The top section of the PCP gives an overview of the current device settings. The first tab
contains 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) the
module 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 specify
PRIMARY and SECONDARY network names. On power up, the module will first attempt to
join these networks before falling back to NpeWiFiConfig. Since we will leave the AP set
to NpeWiFiConfig, we do not need to specify WAP 1 or WAP 2. The module will not
attempt to create or join an Adhoc network unless Adhoc is specified under Radio
Settings.

IP Settings: This specifies the IP Configuration for the project. The IP configuration
2011 ... North Pole Engineering, Inc.

Quick Start Guide

13

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

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

Important Note: Incorrect network settings may leave the module in a state where it
is not attempting or is not able to join a network. In this case, the module is still
functional and the firmware and any project downloaded are still running, but the
module is not accessible. It may be necessary to access the module over USB to restore
the network settings. See Regaining Access to a Device.
Set the Project Power Settings: Scroll the Device Settings window until the Power panel is
visible. Check 'Enable Sleep', this activates the low-power mode in the node. Now set 'Sleep
Time' to 2000 ms. This will cause the node to wake up every two seconds to execute the WiFi
Basic code.

Important Note: The power settings will trigger execution of the WiFi Basic program every
two seconds regardless of how much time is spent in execution. Also, execution will begin
regardless of whether the module entered the sleep state. Certain background tasks, such as
negotiation of DHCP, may temporarily prevent the module from entering the sleep state. The
sleep state may be confirmed visually on the DCard by observing that the DC_CTRL LED is off.
2011 ... North Pole Engineering, Inc.

14

WiFi-IT! Basic Language Reference

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 the
editor 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 <ctrl-s> 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 any
device that will be loaded with the program. Now we need to compile the program and fix any
errors that may occur.
Compile the Program: Right-click the project (Blink) and select Compile Project from the dropdown menu. The results of the compile are shown below.

2011 ... North Pole Engineering, Inc.

Quick Start Guide

15

Notice the console window indicates an error has been detected and has marked the offending
line number with a red x. To get additional information click the Notifications tab next to the
console tab.
The Notifications tab shows errors for all projects. You can click on Location, Resource or
Description to sort the errors. Double-clicking on any error in the Notifications tab will take you
to the offending line in the program code.
The error we encountered shows that the line contains an unrecognized word. Looking at line 12
we 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.

2011 ... North Pole Engineering, Inc.

16

WiFi-IT! Basic Language Reference

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 provisioning
network, NpeWiFiConfig.
Perform the following steps:
1. Make sure the wireless access point (AP) that came with your EDK is powered and
connected to your computer via the provided ethernet cable.
The cable should be connected to one of the downstream ports as shown, and not to
the Internet uplink port. We are not connecting our network to the Internet at this
time.

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 port
or 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 any
modules that join that network.

4.

Connect a module to the DCard as shown.

2011 ... North Pole Engineering, Inc.

Quick Start Guide

17

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.

2011 ... North Pole Engineering, Inc.

18

WiFi-IT! Basic Language Reference

7.

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

8.

Wait for Device to join NpeWiFiConfig: The node should power up and begin looking
for the configuration Access Point. After no more than 30 seconds the device MAC
Address should appear under the Device tree, in the project Navigator. If it doesn't
power 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'. Then
select 'Blink' and click Ok.
Important Note: When a program is loaded over the air, it is loaded using the
network that the node is currently connected to. In the case of the EDK/EDK+ the
default network SSID is NpeWiFiConfig on Wi-Fi channel 6. Once the code is started
(immediately after loading), the node will reconfigure the wireless connection settings
to those specified in the project configuration panel for that project. This could cause
the node to lose connectivity to the current network.

At this point the program should be loaded and running. Every two seconds the module powers
on 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 debug
tools. At this point the DCard should be powered up and the nodes MAC address should be
listed 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
2011 ... North Pole Engineering, Inc.

Quick Start Guide

19

the project to load, as shown below.


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

Click on Blink, then click the OK button. The Progress Information dialog will appear. Wait for
the operation to complete.
The IDE will then load the Debug perspective, shown below.

2011 ... North Pole Engineering, Inc.

20

WiFi-IT! Basic Language Reference

From the debug perspective you can run, step, view variables and set breakpoints, all from the
top tool bar. As you hang your cursor over each of the buttons a tooltip appears to explain the
button function and the hot key associated with that function. The Window menu allows you to
open tabs for Variables, Breakpoints and Register displays.
Click the step button (or press F6) to single-step through the program. You should see the
variable change state according to the line of code executed. In addition, you will see the LEDs
connected to the GPIO pins change state.
When you are finished debugging, click the Terminate button (red square in the toolbar) to exit
and return to the standard IDE configuration.

3.4

Project 2 - RSSI
Hopefully, you have gone through Project 1. The directions for this example assume that you are
familiar with using the IDE.
This program will display the node's received signal strength indicator (RSSI) in the IDE. It must
create a data packet recognizable by the IDE. Once the IDE receives these packets, the node's
RSSI will be visible in the IDE's Data Monitor Perspective.
Go to: RSSI Program

2011 ... North Pole Engineering, Inc.

Quick Start Guide

3.4.1

21

RSSI Program
This application shows you how to build UDP packets and open a connection to send them from
the 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

' Variables
DIM
ipAddr
DIM
sendCID
DIM
macAddr
DIM
varName
DIM
varValue

AS
AS
AS
AS
AS

STRING
INTEGER
STRING
STRING
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 = 0x01
CONST
GRAPHDATA = 0x02
CONST
MESSAGE = 0x03
CONST
RAW = 0x04
' Data types recognized by IDE.
CONST
StringType = 0x00
CONST
IntType = 0x01
CONST
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

2011 ... North Pole Engineering, Inc.

22

WiFi-IT! Basic Language Reference

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
dataPkt(1) = 0x42

' W
' 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

2011 ... North Pole Engineering, Inc.

Quick Start Guide

23

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 steps
to finish configuring the project and start the program:
Open the Project Configuration Panel (right-click the project and select Edit Project Device
Configuration, from the popup menu).
Enter the SSID and Channel of a wireless access point on your network (use
NpeWiFiConfig, channel 6, if you like). In the Power settings, check Enable Sleep and set a
Sleep 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 MAC
address with a corresponding RSSI value. Select "Switch to Data Monitor Perspective" from the
Window menu. The IDE should look as shown below with a new RSSI value updating every five
seconds.

2011 ... North Pole Engineering, Inc.

24

3.5

WiFi-IT! Basic Language Reference

Project 3 - Temp Sensor


This 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 for
debugging programs that manipulate network settings, or create their own private adhoc
network. It also helps debug network traffic since otherwise a lot of packets can be generated
between 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 the
IDE'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

2011 ... North Pole Engineering, Inc.

Quick Start Guide

25

'
DIM
DIM
DIM
DIM
DIM
DIM
DIM
DIM

I2Cmd(7)
I2CData(7)
iTemp
iCharCnt
dataPkt(63)
sendCID
varName
varValue

AS
AS
AS
AS
AS
AS
AS
AS

CONST
CONST
CONST

TSENSOR_ADRS
TSENSOR_P_TEMP
TSENSOR_P_CONFIG

BYTE
BYTE
INTEGER
INTEGER
BYTE
INTEGER
STRING
INTEGER
= 0x48
= 0
= 1

' Pointer to Temperature register


' Pointer to Configuration register.

' Packet types recognized by IDE.


CONST
VARIABLE = 0x01
CONST
GRAPHDATA = 0x02
CONST
MESSAGE = 0x03
CONST
RAW = 0x04
' Data types recognized by IDE.
CONST
StringType = 0x00
CONST
IntType = 0x01
CONST
ByteType = 0x02
TASK
GOSUB
GOSUB
GOSUB
GOSUB

SetupTemp
ReadTemp
ConvertTemp
SendTemp

DELAY 2000
REPEAT_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
RETURN
ENDSUB
' 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.

2011 ... North Pole Engineering, Inc.

26

WiFi-IT! Basic Language Reference

iCharCnt = INPUT I2C TSENSOR_ADRS, I2CData, 2

' Read temperature data.

iTemp = I2CData(0) SHL 4


iTemp = iTemp + (I2CData(1) SHR 4)

' Right-justify temp reading


' 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
RETURN
ENDSUB
' 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
dataPkt(1) = 0x42

' W
' 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

2011 ... North Pole Engineering, Inc.

Quick Start Guide

27

' 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
RETURN
ENDSUB
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 left
blank. Make sure that 'Enable DHCP' is set and 'Network(s) to Join' is set to Infrastructure.

2011 ... North Pole Engineering, Inc.

28

WiFi-IT! Basic Language Reference

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

Now, for the I2C settings, navigate to the select the I2C configuration tab and enable the I2C
interface. 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 perform
the following additional steps:
Make sure SW7 is set to the down position. This connects UART0 of the WiFi-IT! module with
the onboard Serial to USB interface.

Connect the SCard to J1 of the DCard.

2011 ... North Pole Engineering, Inc.

Quick Start Guide

29

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 the
Devices list and select "Switch Device to UART Config Mode". The device should disappear from
the 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 to
start a debug session over UART.
Select "Device | UART | Debug Project". The IDE will ask which COM port to use.

2011 ... North Pole Engineering, Inc.

30

WiFi-IT! Basic Language Reference

If you are unsure which COM port is assigned to the DCard, you can check the Windows Device
Manager. Make sure the USB cable is connected and the DCard powered on or the COM port will
not appear in the Device Manager. To get to the Device Manager, right-click on My Computer
and select Properties (or alternatively select System in Windows Control Panel). Click the
Hardware tab, then click Device Manager. The DCard's USB to serial translator will show up
under "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 progress
bar to finish. You should now see the Debug perspective halted on the first line of the
TempSensor program. From here you can set and clear breakpoints, single step individual
source lines, and run and halt the program the same as if you were in WiFi provisioning mode.

2011 ... North Pole Engineering, Inc.

Quick Start Guide

31

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 reading
reported in degrees Celsius every two seconds. When you are doing viewing readings, return to
the debug perspective by selecting "Window | Switch to Debug Perspective".

2011 ... North Pole Engineering, Inc.

32

WiFi-IT! Basic Language Reference

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

Programming Reference
This section is a compilation of the keywords, statements and operators that make up WiFiBasic. The commands are grouped by function for easy location. The table below defines the
grouping.
Group Name
Numeric Base
Specification
Error Handling
Flow Control
Date/Time Functions
Interfaces

Description
Overview of base specification for literal constants.
This section describes generation of errors and the two modes
in which they can be handled: active and passive.
The statements in this section control the flow of execution of a
program.
Functions to get/set the RTC and to convert the RTC time to year,
month, day, hour, minute, and second.
Contains subsections on how to use each of the hardware
interfaces: ADC, GPIO, I2C, PWM, SPI, and UART.

2011 ... North Pole Engineering, Inc.

Programming Reference

Intrinsic Constants
Miscellaneous
Networking

Operators
String Functions
Variables & Datatypes

4.1

33

Built-in, predefined keywords that translate to constant values.


Collection of general statements.
Overview of socket operations and network mangement.
Operations for managing WiFi networks, opening and closing
connections, and sending and receiving data.
A listing of Arithmetic, Comparison, Bitwise and String
operators.
Functions for the manipulation and creation of string types.
This section contains a description of the supported variable and
data types. Statements for declaring variables and constants in a
program can be found here.

General Information
The information contained in this section provides some general information on writing code in
WiFi-Basic. It is important to read and understand these simple rules and compiler limitations
in 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 must
not be separated from the number and the base specified will only apply to that specific
number.
Prefix
%
0x

Base
Binary
Hexadecimal

Examples:
Expression
MyVar = %1010

4.1.2

Decimal Value
MyVar = 10

Description
Specify a binary number.

VarX = 0x105
MyVar = VarX AND 0xFF

MyVar = 5

Specify a Hexadecimal number. Mask to return


the lower 8-bits.

MyVar = 0x20 + 10

MyVar = 42

The default numeric base is 16. Add 2016 to 1010


(=3210 + 10 = 42).

Literal Constants
1. Hexadecimal numbers can be entered by preceding them with "0x". e.g. 0x10 = 16
decimal
2. Binary numbers can be entered by preceding them with "%". e.g. %10000 = 16 decimal

2011 ... North Pole Engineering, Inc.

34

WiFi-IT! Basic Language Reference

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 a
carriage-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 keywords
are case insensitive.

4.2

Error Handling
WiFi-Basic implements two types of runtime error handling; passive and active. By default
runtime 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 erratic
behavior 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 Time
Engine will jump to the declared error handler when an error is detected. The programmer can
then handle the error appropriately whether that means returning to the program to continue
execution, 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 will
jump to the active error handler when an error is detected. The ON_ERROR keyword is used to
define the error handler. Active error handling can be disabled by specifying zero as the
operand of the ON_ERROR keyword, as shown in the example below. The ON_ERROR keyword
can be used more than once in a program.
When active error handling is operating and an error is detected, the RTE will interrupt
execution 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 the
statement. If RESUME_NEXT is used, the remaining statement code is skipped and execution
begins with the next instruction. The QUIT keyword can be used in an error handler if the error
is 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
2011 ... North Pole Engineering, Inc.

Programming Reference

35

keywords. Within the error handler, any number of program statements can be used to analyse
and correct execution of the program. The ERROR keyword maintains the value of the error
code that invoked the error handler for the duration of the ESUB, regardless of how many times
it is read. This is a change from the default behavior of ERROR when operating in passive error
handling 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 is
enabled.
:
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.
ENDESUB
END

4.2.2

Passive Error Handling


When a runtime error is encountered, the default behavior of WiFi-Basic is to place the error
code into the system variable, ERROR and complete the statement. No other action is taken by
the 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 appropriate
action can be taken. Once the ERROR variable is read it is reset to EOK, therefore if the value is
referenced 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 new
error 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 active
mode.

2011 ... North Pole Engineering, Inc.

36

WiFi-IT! Basic Language Reference

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_TASK
END

4.2.3

Double Faults
An error occuring within an error handler is called a double fault. When running normally (not
debugging) double faults cause an automatic QUIT to occur. There is no indication to the running
program 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 the
double fault occurred on.

4.2.4

Error Handling Keywords


Error handling keywords are used to define active error handlers and control the flow of
execution between the main program and error handlers.
ESUB - ENDESUB
ON_ERROR
RESUME
RESUME_NEXT
See also the QUIT keyword, which is valid in error handlers.

4.2.4.1

ERROR

{<i-variable> =} ERROR
IF ERROR {= <n-value>} THEN
The ERROR system variable holds the runtime error code of the last error that occurred. The
operation of ERROR differs depending on the type of error handling that is in effect. See Error

2011 ... North Pole Engineering, Inc.

Programming Reference

37

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 code
that 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 performs a automatic QUIT operation.
4. The keywords, RESUME and RESUME_NEXT set ERROR back to EOK before returning to the
main program.
The ERROR system variable may be captured in an integer type variable or used in comparison
statements, as shown in the examples for Active Error and Passive Error handling.
4.2.4.2

ESUB - ENDESUB

ESUB <Routine Name>


:
ENDESUB
The ESUB keyword is always used outside of the TASK REPEAT_TASK program directives. ESUB
defines the start of an error handling subroutine or error handler.
Error handlers are not called directly within the program but instead are called by the system
when a runtime error is detected. Error handlers may return back to the program or may chose
to quit operation. Quitting operation effectively returns control to the REPEAT_TASK statement,
which puts the module into sleep mode if a sleep period has been set. The directives, RESUME
and RESUME_NEXT may be used within an error handler and only within an error handler.
All variables in WiFi-Basic are global. Any variable that has been defined is available to be
referenced or changed in an error handler.
Example:
TASK
:
ON_ERROR ErrHandler ' If an error occurs in code following this directive
:
' the RTE will transfer execution to ESUB ErrHandler.
:
REPEAT_TASK

2011 ... North Pole Engineering, Inc.

38

WiFi-IT! Basic Language Reference

ESUB ErrHandler
IF ERROR = ENOMEM THEN
:
' Do something to fix the error.
RESUME
' Now go retry the code that failed.
ELSE
IF ERROR = EINVAL THEN
:
' Retry the code that failed.
RESUME_NEXT ' Restart execution after the line that originally failed.
ENDIF
QUIT
' Fatal unhandled error condition.
ENDIF
ENDESUB
END

4.2.4.3

ON_ERROR

ON_ERROR label | 0
The ON_ERROR keyword is used to specify an active error handler or to disable active error
handling. Specifying 0 (zero) as the operand will disable active error handling and return to
passive error handling mode. The ON_ERROR keyword may be used multiple times within a
program. It is not allowed in error handlers and will cause a compiler error.
If an error occurs within an error handler, the RTE will execute a QUIT action immediately (see
Double Faults).
4.2.4.4

RESUME

RESUME
The RESUME keyword returns execution to the beginning of the statement that caused the
error. If the error condition has been corrected the code will execute successfully and the
program will continue normally.
Important Note:
If the error condition is not corrected in the error handler an infinite loop may be created.
The error handler keeps jumping back to retry the same statement, which keeps generating
the same error.
The RESUME keyword cannot be used within TASK REPEAT_TASK and will cause a compiler
error.
4.2.4.5

RESUME_NEXT

RESUME_NEXT
RESUME_NEXT causes execution to continue with the statement following the line that
caused the error. The line that caused the error is left uncompleted. This keyword is used if
the statement that caused the error does not need to be retried.
The RESUME_NEXT keyword cannot be use within TASK REPEAT_TASK and will cause a
2011 ... North Pole Engineering, Inc.

Programming Reference

39

compiler error.

4.3

Date/Time Functions
The date and time functions of WiFi-Basic provide a means for getting date and time
information from a DateTime value. A DateTime is the same format as a Unix time value: it is a
32-bit integer representing the number of seconds elapsed since midnight UTC of January 1,
1970, not counting leap seconds. Assigning a value to NOW updates the count in the Real Time
Clock (RTC). The RTC continues counting upward from that point. Reading NOW returns the
current RTC value. Any DateTime value can be provided to the other date/time functions. It
does not have to be the current number of seconds since January 1, 1970.
Important Note: After a cold boot sequence the RTC begins counting at 0. It is up to the
WiFi-Basic program to set the current Unix time using the NOW keyword prior to reading it. The
RTC will persist across sleep cycles and reset via ext_reset, but not across loss of VBAT.
NOW
YEAR
MONTH
MONTHNAME
DAY
WEEKDAY
WEEKDAYNAME
HOUR
MINUTE
SECOND

4.3.1

Get or set the current Unix time (in seconds) in the RTC.
Returns a number from 1970 to 2038 indicating the year portion of a
given DateTime.
Returns a number from 1 to 12 indicating the month portion of a given
DateTime.
Returns a string indicating the month portion of a given DateTime.
Returns a number from 1 to 31 indicating the day portion of a given
DateTime.
Returns a number from 1 to 7 indicating the weekday of a given
DateTime.
Returns a string indicating the weekday of a given DateTime.
Returns a number from 0 to 23 indicating the hour of a given DateTime.
Returns a number from 0 to 59 indicating the minute of a given
DateTime.
Returns a number from 0 to 59 indicating the second of a given
DateTime.

DAY
{i-variable =} DAY(<i-value>)

EDK+ only

The DAY function returns a number between 1 and 31 indicating the day of the month of a
given DateTime. A DateTime is a 32-bit integer representing the number of seconds elapsed
since midnight UTC of January 1, 1970.
See example in YEAR.

2011 ... North Pole Engineering, Inc.

40

4.3.2

WiFi-IT! Basic Language Reference

HOUR
{i-variable =} HOUR(<i-value>)

EDK+ only

The HOUR function returns a number between 0 and 23 indicating the hour portion of a given
DateTime. A DateTime is a 32-bit integer representing the number of seconds elapsed since
midnight UTC of January 1, 1970.
Example:
' Variables
DIM
currentTime

AS INTEGER

TASK
...
currentTime = NOW
OUTPUT UART0 "The current time is "
OUTPUT UART0 STR$(HOUR(currentTime)) & ":" & STR$(MINUTE
(currentTime)) & ":" & STR$(SECOND(currentTime)) & CHR$(10)
DELAY 1000
REPEAT_TASK
END

4.3.3

MINUTE
{i-variable =} MINUTE(<i-value>)

EDK+ only

The MINUTE function returns a number between 0 and 59 indicating the minute portion of a
given DateTime. A DateTime is a 32-bit integer representing the number of seconds elapsed
since midnight UTC of January 1, 1970.
See example in HOUR.

4.3.4

MONTH
{i-variable =} MONTH(<i-value>)

EDK+ only

The MONTH function returns a number between 1 and 12 indicating the month portion of a
given DateTime. A DateTime is a 32-bit integer representing the number of seconds elapsed
since midnight UTC of January 1, 1970.
See example in YEAR.

4.3.5

MONTHNAME
{s-variable =} MONTHNAME(<i-value>)

EDK+ only

The MONTHNAME function returns a string indicating the month portion of a given DateTime.
A DateTime is a 32-bit integer representing the number of seconds elapsed since midnight
UTC of January 1, 1970.
2011 ... North Pole Engineering, Inc.

Programming Reference

41

The string returned is one of the following:


Month
Month Name
1
"January"
2
"February"
3
"March"
4
"April"
5
"May"
6
"June"
7
"July"
8
"August"
9
"September"
10
"October"
11
"November"
12
"December"
See example in NOW.

4.3.6

NOW
<i-variable> = NOW
NOW = <i-value>

EDK+ only

The NOW directive sets or returns the current Unix time value (known as a DateTime in
WiFi-Basic) in the RTC. A DateTime is the number of seconds elapsed since midnight UTC of
January 1, 1970, not counting leap seconds. The RTC is updated immediately. The TIMER
directive is not affected and always returns the number of milliseconds since initial poweron. DateTimes are stored as normal 32-bit integers.
Important Note: After a cold boot sequence the RTC begins counting at 0. It is up to
the WiFi-Basic program to set the current Unix time using the NOW keyword prior to
reading it. The RTC will persist across sleep cycles and reset via ext_reset, but not across
loss of VBAT.
Example:
DIM
DIM
DIM
DIM
DIM

currentTime
weekdayStr
monthStr
dayStr
yearStr

AS
AS
AS
AS
AS

INTEGER
STRING
STRING
STRING
STRING

TASK
' Read current time from network,
' and store into currentTime
...
NOW = currentTime

2011 ... North Pole Engineering, Inc.

42

WiFi-IT! Basic Language Reference

OUTPUT UART0 "The current date is "


weekdayStr = WEEKDAYNAME(NOW)
monthStr = MONTHNAME(NOW)
dayStr = STR$(DAY(NOW))
yearStr = STR$(YEAR(NOW))
OUTPUT UART0 weekdayStr & " " & monthStr & ", " & dayStr & " " & yearStr & CHR$
(10)
...
REPEAT_TASK
END

4.3.7

SECOND
{i-variable =} SECOND(<i-value>)

EDK+ only

The SECOND function returns a number between 0 and 59 indicating the second portion of a
given DateTime. A DateTime is a 32-bit integer representing the number of seconds elapsed
since midnight UTC of January 1, 1970.
See example in HOUR.

4.3.8

WEEKDAY
{i-variable =} WEEKDAY(<i-value>)

EDK+ only

The WEEKDAY function returns a number between 1 and 7 indicating the day of the week of a
given DateTime. 1 represents Sunday, 2 represents Monday, 3 represents Tuesday, etc. A
DateTime is a 32-bit integer representing the number of seconds elapsed since midnight UTC
of January 1, 1970.

4.3.9

WEEKDAYNAME
{s-variable =} WEEKDAYNAME(<i-value>)

EDK+ only

The WEEKDAYNAME function returns a string indicating the day of the week of a given
DateTime. A DateTime is a 32-bit integer representing the number of seconds elapsed since
midnight UTC of January 1, 1970.
The string returned is one of the following:
Weekday
Weekday Name
1
"Sunday"
2
"Monday"
3
"Tuesday"
4
"Wednesday"
5
"Thursday"
2011 ... North Pole Engineering, Inc.

Programming Reference

6
7

43

"Friday"
"Saturday"

See example in NOW.

4.3.10 YEAR
{i-variable =} YEAR(<i-value>)

EDK+ only

The YEAR function returns a number between 1970 and 2038 indicating the year portion of a
given DateTime. A DateTime is a 32-bit integer representing the number of seconds elapsed
since midnight UTC of January 1, 1970.
Example:
' Variables
DIM
releaseDate

AS INTEGER

' Constants
TASK
releaseDate = 1009756800
OUTPUT UART0 "Pearls Before Swine first launched in the Washington Post on "
OUTPUT UART0 STR$(MONTH(releaseDate)) & "/" & STR$(DAY(releaseDate)) & "/" &
STR$(YEAR(releaseDate)) & CHR$(10)
DELAY 2000
REPEAT_TASK
END

4.4

Flow Control
These statements control the flow of execution in a WiFi-Basic program.
DO - UNTIL | LOOP
END
ESUB - ENDESUB
EXITDO | EXITFOR | EXITWHILE
FOR - TO - STEP - NEXT
ON_ERROR
GOSUB
RETURN
IF - THEN - ELSE - ENDIF
QUIT
SUB - ENDSUB
TASK - REPEAT_TASK
WHILE - WEND

2011 ... North Pole Engineering, Inc.

44

4.4.1

WiFi-IT! Basic Language Reference

DO - UNTIL | LOOP
DO
:
.. Statements to execute
:
UNTIL <logical-expression> | LOOP
DO begins a looping structure that is terminated either by UNTIL <logical-expression> or
LOOP.
If the loop is terminated by UNTIL, all instructions between DO and UNTIL are executed until
the logical expression evaluates to TRUE. When the loop terminates execution continues
with the statement following the UNTIL. If the logical-expression evaluates to FALSE the
loop continues with execution of the statement following the DO. The DO-UNTIL loop
structure will always execute at least once.
If a WiFi-Basic function is used as a term in the logical-expression, it must be on the left side
of the comparison operator. If the loop is terminated by LOOP, all instructions between DO
and LOOP are executed forever. In the case of a DO LOOP, the loop can be exited using
EXITDO.
Example 1:
DIM MyVar AS INTEGER
TASK
DO
MyVar = GPIO(6)
'Sets MyVar to 1 when GPIO(6) is a logical high.
UNTIL (MyVar AND 0x1) = 1
REPEAT_TASK
END

The statements between DO and UNTIL are executed until the value of MyVar is odd. This
construct requires the variable MyVar to be updated at sometime during execution of the loop
otherwise, the loop will execute indefinitely.
Example 2:
'This example is the same as shown in Example 1, except it is written using the DO
'LOOP 'structure.
DIM MyVar AS INTEGER
TASK
DO
MyVar = GPIO(6)

'Sets MyVar to 1 when GPIO(6) is a logical high.

IF (MyVar AND 0x1) = 1 THEN


EXITDO
ENDIF
LOOP
REPEAT_TASK
END

2011 ... North Pole Engineering, Inc.

Programming Reference

4.4.2

45

END
END
Terminate program compilation. The last statement in any program must be the END
statement. The END statement is placed after all error handlers and subroutines.

4.4.3

EXITDO | EXITFOR | EXITWHILE


EXITDO | EXITFOR | EXITWHILE

EXITFOR is
Unimplemented
Leaves a code block such as DO UNTIL, FOR NEXT, WHILE WEND. The execution skips
the rest of the block and goes to the statement following the loop terminating keyword.
Where there is multiple Do / For / While blocks nested, the associated EXIT keyword will
skip to the end of the innermost block of that type.

Example:
DIM i AS INTEGER
DIM TooMuch AS INTEGER
TASK
TooMuch = 5
FOR i = 1 TO 10
IF i > TooMuch THEN
EXITFOR
ENDIF
NEXT
REPEAT_TASK
END

4.4.4

FOR - TO - STEP - NEXT


FOR <n-variable> = <expression> TO <expression> {STEP <expression>}
:
NEXT
A looping structure that takes a starting value, a limit and optionally a STEP value and
executes the program lines between the directives. Expressions are evaluated when the
FOR statement is encountered, subsequent iterations use pre-stored values.
If the STEP value is negative, the variable counts down. The body of the loop is not
executed if the end condition is true initially. If STEP evaluates to zero, an infinate loop is
generated.
When NEXT is encountered the variable is incremented by the STEP amount and the
termination conditions are checked.
If the termination condition is TRUE execution falls through to the statement following
the NEXT statement.
If the termination condition is FALSE execution returns to the statement following the
FOR statement.

2011 ... North Pole Engineering, Inc.

46

WiFi-IT! Basic Language Reference

Example 1:
DIM i AS INTEGER
TASK
:
FOR i = 1 TO 10 STEP 2
.. Statements to execute
NEXT
:
REPEAT_TASK
END

The statements between FOR and NEXT will be executed 5 times. The first time through i = 1 at
NEXT i is incremented by 2 ( i = 3 ) and since it is less than 10 execution continues with the
statement follow the FOR. This continues for i = 5, i = 7, i = 9. The next time NEXT is encountered
variable "I" is incremented to 11. It is then compared to the termination value (10), the test fails
and execution continues with the statement following NEXT.
Example 2:
DIM i AS INTEGER
TASK
:
FOR i = 3 TO (-2) STEP (-1)
.. Statements to execute
NEXT
:
REPEAT_TASK
END

In this example variable "i" is initially set equal to 3 and the statements between FOR and NEXT
are executed with "i" taking on the values of 2, 1, 0, -1, -2 in successive iterations. The
statements between FOR and NEXT are executed six times before the loop terminates.

4.4.5

GOSUB
GOSUB label
Transfer execution to the program to the subroutine defined by label. On RETURN from the
subroutine, execution continues with the program statements following this statement.
Example:
' Loop monitoring input GPIO(10). When it goes high, turn off the LEDs
' on GPIO(30) and GPIO(31).
TASK
GPIO(30) = 1
GPIO(31) = 1
DO
IF GPIO(10) = 1 THEN GOSUB ClearLED ENDIF
IF GPIO(30) = 0 AND GPIO(31) = 0 THEN EXITDO ENDIF
LOOP

2011 ... North Pole Engineering, Inc.

Programming Reference

47

REPEAT_TASK
SUB ClearLED
GPIO(30) = 0
GPIO(31) = 0
RETURN
ENDSUB
END

4.4.6

'Turn off LED indicators.

RETURN
RETURN
Returns from a subroutine to the statement following the calling GOSUB.
Example:
TASK
:
GOSUB SendCR
:
GOSUB SendCR
:
REPEAT_TASK
SUB SendCR
:
RETURN
ENDSUB

'Go execute code at SendCR.


'Go execute code at SendCR.

'Return to statement following GOSUB.

END

4.4.7

IF - THEN - ELSE - ENDIF


IF <expression> THEN
True
{ ELSE }
False ...
ENDIF
Compare data using bitwise, logical or comparison operators. The result determines which
execution path is taken. A non-zero value evaluates to TRUE , while zero evaluates to FALSE.
If the expression evaluates to true then the statements after THEN are executed and the
statements after ELSE are skipped. If the expression evaluates to false then the statements
after THEN are skipped and the statements after ELSE are executed. If an ELSE block is not
included, then no statements between THEN and ENDIF are executed.
NOTE: The entire IF - THEN - ELSE - ENDIF construct may be placed on one line, but the entire
expression must fit into one line of no more than 128 characters.
Example 1:
DIM x AS INTEGER
DIM y AS BYTE

2011 ... North Pole Engineering, Inc.

48

WiFi-IT! Basic Language Reference

TASK
x = 257
y = 5
IF x > y THEN
...True statements executed...
ELSE
...False statements not executed...
ENDIF
:
REPEAT_TASK
END

NOTE: When evaluating numeric expressions, the variable(s) in <expression> determines the
size of the operands compared. In the example above y will be cast as a positive integer (a
value between 0 and 255), even though it is defined as a byte, before the comparison occurs.
Example 2:
TASK
IF GPIO(31) = 0 THEN
GPIO(31) = 1
ENDIF
:
REPEAT_TASK
END

4.4.8

QUIT
QUIT
The QUIT keyword immediately stops the program by returning control to the REPEAT_TASK
statement. This causes the node to go into deep sleep, if the sleep function has been
enabled. The next time the node awakens, or if the sleep function has not been enabled,
execution will start at the TASK keyword.
QUIT can be used at any time in a WiFi-Basic program. It can be executed in the TASK REPEAT_TASK loop, in error handlers, ESUB - ENDESUB or in regular subroutines, SUB ENDSUB.
Example:
DIM cidListen AS INTEGER
CONST PORT_8999 = 0x8999
TASK
:
cidListen = LISTEN UDP PORT_8999
IF ERROR <> 0 THEN
QUIT
' We could not open the port!
ENDIF
REPEAT_TASK
END

2011 ... North Pole Engineering, Inc.

Programming Reference

4.4.9

49

SUB - ENDSUB
SUB <Routine Name>
:
ENDSUB
The SUB keyword is always used outside of the TASK REPEAT_TASK program directives. SUB
defines the start of a subroutine. Subroutines must always use the RETURN keyword to return
back to the line of code following the GOSUB which called the subroutine.
All variables in WiFi-Basic are global and are available to be referenced or changed in a
subroutine.
Example:
SUB SendCRLF
OUTPUT UART0 CHR$(0x0D)
OUTPUT UART0 CHR$(0x0A)
RETURN
ENDSUB

' Output a carriage return character to UART0.


' Output a Line feed character to UART0.

4.4.10 TASK - REPEAT_TASK


These two directives enclose the main body of the WiFi-Basic program. Upon reaching the
REPEAT_TASK statement, if sleep is enabled, the module will sleep for the duration specified in
the Project Configuration Panel. If sleep is disabled, execution immediately loops back to the
TASK statement. Sleep enable and sleep period can be set in the PCP. All non-static variables
are reinitialized whether or not sleep mode is enabled.
TASK
Marks the beginning of the WiFi-Basic program.
REPEAT_TASK
Marks the end of the WiFi-Basic program. Loops back to the TASK statement if sleep is disabled
or goes into sleep mode if sleep is enabled.
For a more comprehensive overview, see also Source File and Sleep Mode Operation.
Example:
TASK
:
REPEAT_TASK

' Program statements.

4.4.11 WHILE - WEND


WHILE <expression>
..
.. Statements to execute while expression is TRUE...
..
WEND
2011 ... North Pole Engineering, Inc.

50

WiFi-IT! Basic Language Reference

A looping structure that takes a starting expression and repeats the loop until the
expression is false. If the expression is false at the loop entry, then the loop is not
executed. A WHILE loop must be terminated by a balancing WEND statement.
Example:
DIM TermValue AS INTEGER
DIM StartValue AS INTEGER
TASK
StartValue = 0
TermValue = 9
WHILE (StartValue < TermValue)
IF GPIO(29) = 1 THEN
StartValue = StartValue + 1
ENDIF
:
WEND
REPEAT_TASK
END

4.5

' GPIO(29) must be 1 for 9 passes.

Interfaces
Each interface refers to a processor peripheral and is represented by a unique name. Before
beginning a program, the interfaces that are to be used in the program must be declared and
configured. The Project Configuration Panel in the IDE is used to select and configure the
interfaces that will be used in a program.
ADC
GPIO
I2C
PWM
SPI
UART
Some GPIOs are shared with an interface. Enabling an interface overrides GPIO functionality.
The interface names that are used in WiFi-Basic are listed in the table, shown below.
Interface
Name
UART0
UART1
MSPI
SSPI
I2C
DIE_TEMP

Description

Serial interface.
Serial interface.
Master SPI port.
Slave SPI port.
Addressable serial interface.
Die Temperature.

GPIO(s) assigned to interface


- GPIO(s) unavailable if the Interface
is selected.
GPIO(0), GPIO(1), GPIO(24), GPIO(25)
GPIO(2), GPIO(3), GPIO(26), GPIO(27)
GPIO(4), GPIO(5), GPIO(6), GPIO(7), GPIO
(13), GPIO(14), GPIO(15)
Not supported
GPIO(8), GPIO(9)

2011 ... North Pole Engineering, Inc.

Programming Reference

ADC1
ADC2
BATTERY
PWM0
PWM1
PWM2
GPIO

4.5.1

Analog-to-Digital Converter
input 1.
Analog-to-Digital Converter
input 2.
Battery voltage input.
Pulse-Width-Modulated output
0.
Pulse-Width-Modulated output
1.
Pulse-Width-Modulated output
2.
GPIO pins are normally available
to the program unless otherwise
reserved. GPIO pins default to
input unless specified otherwise
in the Program Configuration
Panel (PCP).

51

GPIO(10)
GPIO(11) Not supported on WL11
Modules
GPIO(12) Not supported on WL11
Modules

ADC
<n-variable> = DIE_TEMP | ADC1 | ADC2 | BATTERY
The ADC is a 10-bit analog-to-digital converter. Two inputs are used internally to monitor
battery voltage and die temperature, and the other two inputs are connected to external
pins. The table below defines the mapping between ADC ports and the function of the
specific port.
DIE_TEMP
ADC1
ADC2
BATTERY

Die Temperature input. (internal)


Analog-to-Digital Converter input 1.
Analog-to-Digital Converter input 2.
Battery voltage input. (internal)

WiFi-Basic uses the 1.8V supply as the reference. If you want to calculate the actual voltage
for ADC1 or ADC2, you can use the equations shown below where VDD_ADC is the output of
the onboard 1.8V regulator.
V actual = Value ((V DD_ADC-0.036) / 1023)
Measurement of the Battery voltage (VDD_RTC) is done using an internal ADC channel. The
value returned by BATTERY has already been converted into millivolts and should be
between 2000 and 3700. Below 2000 the module will power off.
Measurement of the die temperature is returned in degrees celsius.
Runtime Errors:
Error Code Error Description
EIO
Error reading device.
2011 ... North Pole Engineering, Inc.

52

WiFi-IT! Basic Language Reference

Example:
DIM inputVal AS INTEGER
CONST THRESHOLD = 768

'This value corresponds to 1.35v

TASK
' This code will call trigger event when ADC1
' drops below 1.35v
inputVal = ADC1
IF inputVal < THRESHOLD THEN
GOSUB TriggerEvent
ENDIF
REPEAT_TASK
SUB TriggerEvent
:
RETURN
ENDSUB
END

4.5.2

FLASH
The WiFi-IT! module reserves 256 bytes of internal FLASH space for use by the WiFi-Basic
program. No configuration is necessary to use the the internal FLASH. It is always available
through the READ FLASH and WRITE FLASH operations.

4.5.2.1

READ

{<i-variable> =} FLASH READ <i-value>, <b-array>, <length>

EDK+ only

This function is called to read data from internal flash memory. Data is read into the byte
array specified by <b-array>. Reading starts at the offset specified by <i-value> and
continues for <length> bytes. FLASH READ returns the number of bytes actually read. The
offset must be between 0 and 255 and offset and length together cannot be greater than
256 bytes.
Important Note: The FLASH space reserved for WiFi-Basic is not cleared during a
project load. After a firmware update, this space will contain all Fs. After it is written by a
WiFi-Basic program, it will always contain what was last written, regardless of the number
of project loads.
Runtime Errors:
Error Code
EINVAL

Error Description
Invalid offset, or offset plus length is greater than 256.

Example:
DIM paramArray(9)
DIM bytesRead
DIM idx

AS BYTE
AS INTEGER
AS INTEGER
2011 ... North Pole Engineering, Inc.

Programming Reference

DIM setting

53

AS INTEGER

TASK
bytesRead = FLASH READ 0, paramArray(0), 10
FOR idx = 0 TO 9
setting = paramArray(idx)
:
NEXT
REPEAT_TASK
END

4.5.2.2

WRITE

{<i-variable> =} FLASH WRITE <i-value>, <b-array>, <length>

EDK+ only

This function is called to write data to internal flash memory. Data is read from the byte
array specified by <b-array>. Writing starts at the offset specified by <i-value> and continues
for <length> bytes. FLASH WRITE returns the number of bytes actually written. The offset
must be between 0 and 255 and offset and length together cannot be greater than 256 bytes.
Runtime Errors:
Error Code
EINVAL

Error Description
Invalid offset, or offset plus length is greater than 256.

Example:
DIM
DIM
DIM
DIM

paramArray(9)
value
bytesWritten
idx

AS
AS
AS
AS

BYTE
BYTE
INTEGER
INTEGER

TASK
FOR idx = 0 TO 9
:
' Assign some number to 'value'
paramArray(idx) = value
NEXT
bytesWritten = FLASH WRITE 0, paramArray(0), 10
REPEAT_TASK
END

4.5.3

GPIO
<n-variable> = GPIO (expression)
The GPIO keyword is used to read and/or write the value of a GPIO pin that has been
declared as in input or an output. The expression passed to the GPIO function must
evaluate to a number between 0 and 31. The expression may contain variables, constants or
other functions that provide a numeric output. A read operation returns a 1 when the GPIO
is at a Logic High and 0 when it is at a Logic Low.
NOTE: All GPIO pins default to input. They may be changed to output in the Project
Configuration Panel (PCP).

2011 ... North Pole Engineering, Inc.

54

WiFi-IT! Basic Language Reference

GPIO(x) = {0 | 1 | <n-value> | const | expression}


The GPIO command is used to set the output value of a GPIO pin that has been declared as
an output. A zero sets the pin to a Logic Low, while a one sets it to a Logic High. If a variable,
constant or expression evaluates to a non-zero value the GPIO is set to the logic high value.
Value
0
1

Variable
=0
<>0

Constant
Expression
=0
=0
<>0
<>0
GPIO Output Value

GPIO value
Logic Low
Logic High

Runtime Errors:
Error Code Error Description
EINVAL
Invalid parameter.
Examples:
DIM GPIO_4 AS INTEGER
DIM GPIO_5 AS INTEGER
DIM GPIO_6 AS INTEGER
TASK
GPIO_4 = GPIO(4)

'Set GPIO_4 to 1/0 depending on GPIO(4).

GPIO_5 = GPIO_4 XOR 1 AND 1 'GPIO_5 is set to the opposite value of GPIO_4.
GPIO(5) = GPIO_5
'GPIO(5) is set to opposite polarity of GPIO(4).
GPIO_6 = 25
GPIO(6) = GPIO_6
REPEAT_TASK
END

4.5.3.1

'Set GPIO(6) to 1 because the GPIO_6 is non-zero.

GPIO Configuration

GPIO configuration is done through the Project Configuration Panel (PCP). To setup the GPIO
configuration select the GPIO tab in the PCP. Note: All GPIOs default to input with internal pulldown.
Important Note: Most of the GPIO pins are also used for other interfaces. GPIOs are only
available as GPIOs if the alternative function of the pin is not enabled. For example, GPIO(10) is
only available if PWM0 is not enabled.

2011 ... North Pole Engineering, Inc.

Programming Reference

55

Output Enable - If clear, the pin is an input. If set, the pin is an output.
Pull Enable - Enables an internal pull-up or pull-down resistor when a GPIO is in input mode.
If clear, the pin is left floating.
High/Pull Up - This setting differs depending on whether the pin is output or input.
For input pins: This setting is only valid if Pull Enable is set. It determines the direction
of the internal pull up/down resistor. If set the resistor is a pull-up. If clear the resistor
is a pull-down.
For output pins: This setting determines the default state of the pin (before being
assigned by a GPIO statement). If set it is output high. If clear, it is output low.
There are five possible GPIO states, all of which are demonstrated in the above figure.
Input with no internal pull up/down (Demonstrated by GPIOs 0 through 7)
Input with internal pull-down low (Demonstrated by GPIOs 8 through 15)
Input with internal pull-up high (Demonstrated by GPIOs 16 through 23)
Output with default ouput low (Demonstrated by GPIOs 24 through 27)
Output with default output high (Demonstrated by GPIOs 28 through 31)
Important Note: The setting in the GPIO configuration panel do not take effect
immediately after coming out of sleep. The default state of the GPIO registers at wake/
power-on is to place every GPIO in an input state with internal pull-down. There is a small
amount of time before the software is able to apply the settings.
4.5.3.2

GETDIR

<n-variable> = GETDIR (expression)

EDK+ only

The GETDIR keyword is used to query the direction of a GPIO. The expression passed to the
GETDIR function must evaluate to a number between 0 and 31. The expression may contain
variables, constants or other functions that provide a numeric output. GETDIR returns 1 if
the GPIO is set to output and 0 if it is set to input.
2011 ... North Pole Engineering, Inc.

56

WiFi-IT! Basic Language Reference

Runtime Errors:
Error Code
EINVAL

Error Description
Invalid parameter.

Example:
' Switch direction of GPIO(31)
IF GETDIR(31) = 1 THEN
SETINPUT(31)
ELSE
SETOUTPUT(31)
ENDIF

4.5.3.3

SETINPUT

SETINPUT (expression)

EDK+ only

The SETINPUT keyword is used to change the direction of a GPIO to input. It does not affect
the pull-enable and pull up/down settings in the PCP. The expression passed to the
SETINPUT function must evaluate to a number between 0 and 31. The expression may
contain variables, constants or other functions that provide a numeric output.
Runtime Errors:
Error Code
EINVAL

Error Description
Invalid parameter.

Example:
'
'
'
'
'
'
'
'
'

Use a resistor to pull up or down GPIO(30).


GPIO(31) will follow. Use alarm1 to switch
roles. GPIO(29) indicates mode.
GPIO(29) off: GPIO(31) follows GPIO(30).
GPIO(29) on: GPIO(30) follows GPIO(31).
Set GPIOs 29, 30, and 31 to OUTPUT in the PCP
and disable any internal pull up/down.
WARNING: Be careful not to connect an output
directly to 3.3V or GND.

' Variables
DIM
gpioVal
STATIC gpio30following

AS INTEGER
AS INTEGER

' defaults to 0

TASK
IF gpio30following = TRUE THEN
GPIO(29) = 1
SETINPUT(31)
SETOUTPUT(30)
gpioVal = GPIO(31)
GPIO(30) = gpioVal
ELSE
GPIO(29) = 0
SETINPUT(30)
SETOUTPUT(31)

2011 ... North Pole Engineering, Inc.

Programming Reference

57

gpioVal = GPIO(30)
GPIO(31) = gpioVal
ENDIF
IF (EVENT AND ALARM1) = ALARM1 THEN
IF gpio30following = TRUE THEN
gpio30following = FALSE
ELSE
gpio30following = TRUE
ENDIF
ENDIF
DELAY 100
REPEAT_TASK
END

4.5.3.4

SETOUTPUT

SETOUTPUT (expression)

EDK+ only

The SETOUTPUT keyword is used to change the direction of a GPIO to output. It does not
affect the output value previously assigned to the GPIO. The output value may be assigned
while the GPIO is in input mode. The output value takes effect immediately on execution
of the SETOUTPUT function. The expression passed to the SETOUTPUT function must
evaluate to a number between 0 and 31. The expression may contain variables, constants or
other functions that provide a numeric output.
Runtime Errors:
Error Code
EINVAL

Error Description
Invalid parameter.

See example in SETINPUT.

4.5.4

I2C
The WiFi-IT! module contains one I2C interface. The I2C interface is selected and the
parameters are configured in the Project Configuration Panel (PCP). Once configured the
interface can be used to read and write data to addressed peripherals.
When selected, the I2C interface takes over the corresponding GPIOs. I2C signals map to GPIOs
as follows:
I2C_CLK
GPIO(9)

4.5.4.1

I2C_DATA
GPIO(8)

I2C Configuration

I2C hardware configuration is done through the Project Configuration Panel (PCP). To setup the
I2C hardware configuration select the I2C tab in the PCP. The I2C interface is compilant to the I2C
Bus Specification Version 2.1.
2011 ... North Pole Engineering, Inc.

58

WiFi-IT! Basic Language Reference

I2C Enable - Enables the I2C interface.


I2C Speed - The I2C interface supports 100 Kbps or 400 Kbps (actual 392 Kbps).
I2C Address Mode - Chooses 7-bit or 10-bit addressing mode.
I2C Retry - When acting as a master receiver, if the slave gives a NoAck before the programmed
number of transfers, the controller will keep on retrying until the transfer is completed. Set
retry to REPEATED_START to use a repeated start bit for these retries. Set retry to STOP_START
to use a stop bit followed by a start bit.
4.5.4.2

CONFIGURE

CONFIGURE I2C <bus-speed>, <address-mode>, <retry>

EDK+ only

Reconfigures the I2C bus at run-time.


<bus-speed> = Specifies the I2C bus speed. Must be set to BUS_100K or BUS_400K.
<address-mode> = Specifies the I2C address mode. Must be set to ADDRESS_7BIT or
ADDRESS_10BIT.
<retry> = When acting as a master receiver, if the slave gives a NoAck before the
programmed number of transfers, the controller will keep on retrying until the transfer is
completed. Set retry to REPEATED_START to use a repeated start bit for these retries. Set
retry to STOP_START to use a stop bit followed by a start bit.
Runtime Errors:
Error Code
EINVAL

Error Description
Invalid parameter.

Example:
TASK
...
' Hypothetical configuration...
' Light Sensor and Temp Sensor both
' connected to I2C bus, but light
2011 ... North Pole Engineering, Inc.

Programming Reference

59

' sensor can operate at high speed.


CONFIGURE I2C BUS_400K, ADDRESS_7BIT, REPEATED_START
GOSUB ReadLightSensor
CONFIGURE I2C BUS_100K, ADDRESS_7BIT, REPEATED_START
GOSUB ReadTempSensor
...
REPEAT_TASK
SUB ReadLightSensor
...
RETURN
ENDSUB
SUB ReadTempSensor
...
RETURN
ENDSUB
END

4.5.4.3

INPUT

<i-variable> = INPUT I2C <address>, <b-array>, <count>


Read the number of data bytes specified from the addressed I2C peripheral.
<i-variable> = Number of characters actually read from the addressed peripheral. If -1 is
returned an error has occurred and the ERROR system variable will be set
with the resulting error code.
<address> = The address of the peripheral to read. The address is right-shifted, therefore
the highest address is 127 (0x7F) for 7-bit addressing and 1023 (0x3FF) for 10-bit
addressing.
<b-array> = Specifies the byte array where the read data will be stored. An index is not
specified as the array is filled from index 0 for <count> characters.
<count> = The number of bytes to read from the peripheral.
Byte-arrays are limited by available memory. If the number of characters specified by
<count> exceeds the array size a runtime error will be generated and the read will
terminate. The actual number of data bytes is returned by the function as an integer value.
Runtime Errors:
Error Code
EINVAL
ECONFIG
ESLAVEADDRESS
2011 ... North Pole Engineering, Inc.

Error Description
Invalid parameter.
Perpheral is not enabled/configured.
Address parameter is invalid.

60

WiFi-IT! Basic Language Reference

ENORESP

The peripheral failed to respond.

Example:
'Read the light level from a sensor at address 81 hex on the I2C bus. Then scale the
value
'to get the illumination in LUX.
DIM iLightLevel AS INTEGER
DIM iLightData AS INTEGER
DIM byLightData(1) AS BYTE
'Returned data is 2-bytes long - MSB in byte 0.
CONST SENSOR_ADRS = 0x81
CONST LUX_MULTIPLIER = 50000
CONST LUX_SCALE_FACTOR = 32768
TASK
iLightData = INPUT I2C SENSOR_ADRS, byLightData, UBOUND(byLightData,1)+1
iLightLevel = byLightData(0) * 0x100 + byLightData(1)
'Convert to
Integer.
iLightLevel = (iLightLevel * LUX_MULTIPLIER) / LUX_SCALE_FACTOR
REPEAT_TASK
END

4.5.4.4

OUTPUT

{<i-variable> =} OUTPUT I2C <address>, <b-array>, <count>


Write data to the selected peripheral on the I2C bus.
<i-variable> = An optional variable that contains the number of characters actually output.
If -1 is returned an error has occurred and the ERROR system variable will be
set with the resulting error code.
<address> = The address of the peripheral that will be selected to receive the data. The
address is right-shifted, therefore the highest address is 127 (0x7F) for 7-bit
addressing and 1023 (0x3FF) for 10-bit addressing.
<b-array> = Specifies the starting byte in the data array to be sent to the selected
peripheral.
<count> = The number of bytes to write.
The actual number of data bytes written is returned by the function as an integer value.
Capturing this value is optional.
Runtime Errors:
Error Code
EINVAL
ECONFIG
ESLAVEADDRESS
ENORESP

Error Description
Invalid parameter.
Perpheral is not enabled/configured.
Address parameter is invalid.
The peripheral failed to respond.
2011 ... North Pole Engineering, Inc.

Programming Reference

61

Example:
DIM byCmdPacket(2)
DIM iBytesWritten

AS BYTE
AS INTEGER

CONST MEM_CMD_ADRS = 0x11


CONST READ_CMD = 0x82

' Memory I2C command register address.


' Memory read command.

TASK
byCmdPacket(0) = READ_CMD
:
OUTPUT I2C MEM_CMD_ADRS, byCmdPacket(0), 1
'Setup the address to read.
byCmdPacket(1) = 0x01
byCmdPacket(2) = 0x00

' Read address 0x100.

iBytesWritten = OUTPUT I2C MEM_CMD_ADRS, byCmdPacket(1), 2


bytes are written.
IF iBytesWritten <> 2 THEN
'An error has occurred!
:
ENDIF
REPEAT_TASK
END

4.5.5

' Only the address

PWM
The WiFi-IT! module contains three PWM channels. The PWMs are selected and the parameters
are configured in the Project Configuration Panel (PCP). Once configured, the PWM commands
can be used to start and stop the PWM channel, or change its duty cycle.
When selected, the PWM channel takes over the corresponding GPIO. PWM channels map to
GPIOs as follows:
PWM0
GPIO(10)

PWM1
GPIO(11)

PWM2
GPIO(12)

Important Note: PWM1 and PWM2, as are the associated GPIO pins, are
not available on the WL11 family of modules.
4.5.5.1

PWM Configuration

Each PWM has settings to control its frequency, ploarity, and duty cycle. All PWMs must run off
the same clock, but they may use different frame periods, effectively giving them different
frequencies.

2011 ... North Pole Engineering, Inc.

62

WiFi-IT! Basic Language Reference

Global PWM settings:


Clock Frequency - Base clock frequency to use for all PWM channels: 11MHz or 44MHz.
Clock Select - If Bus is selected, the base clock is the PWM clock. If Prescale is selected, the
base clock is divided by the Prescale value to determine the PWM clock.
Prescale - Prescaler value for PWM clock when Clock Select is set to Prescale.
Settings specific to each PWM channel:
Enable - Enables the specified PWM channel.
Frame Period - The number of PWM clock cycles that constitutes one frame for this
channel. The minimum value for this is 2. The frame period cannot be changed at runtime.
On Time - A value between 1 and (Frame Period - 1) that specifies how many clock cycles
within the frame the output should be on. The duty cycle is determined by dividing the On
Time by the Frame Period. The on time is changed at runtime using the UPDATE command.
Polarity - If set to Normal, PWM output is active high when on. If set to Inverted, PWM
output is active low when on.
Example:
Set up a PWM driver for an LED that will be operated at 200Hz with 1000 possible values for
the duty cycle. The LED is on with output 1 and off with output 0.
Since we need 1000 steps during the frame, we'll set the Frame Period to 1000.
There are 200 frames per second, or 200 * 1000 clocks per second for a clock speed of 200KHz.
We can achieve this with a Base Clock Frequency of 11MHz and a Prescale of 55. Note that we
must set Clock Select to Prescale.
Since the LED is on when output is high, we will set Polarity to Normal.
2011 ... North Pole Engineering, Inc.

Programming Reference

63

PWMs are started until a START command is reached in the WiFi-Basic program. UPDATE may
be used to change the On Time anytime in the program, so we'll just set the default value to 1.
Following are example timing diagrams for different on times. PWMs can be started,
stopped, and assigned new on times during execution.

On Time = 750 (Duty Cycle = 75%) 10ms shown

On Time = 125 (Duty Cycle = 12.5%) 10ms shown


4.5.5.2

START

START PWM<channel>
Start PWM operation on the specified channel. PWM0, PWM1 and PWM2 are available on
the WL10 family of modules. Only PWM0 is available on the WL11 family of modules. The
compiler will not detect whether an invalid PWM interface has been specified.
<channel> = The channel on which to start PWM operations: 0, 1, or 2.
Runtime Errors:
Error Code
EINVAL
ECONFIG

Error Description
Invalid parameter.
Perpheral is not enabled/configured.

Example:
See UPDATE
4.5.5.3

STOP

STOP PWM<channel>
Stop PWM operation on the specified channel. PWM0, PWM1 and PWM2 are available on
the WL10 family of modules. Only PWM0 is available on the WL11 family of modules. The
compiler will not detect whether an invalid PWM interface has been specified.
<channel> = The channel on which to stop PWM operations: 0, 1, or 2.
2011 ... North Pole Engineering, Inc.

64

WiFi-IT! Basic Language Reference

Runtime Errors:
Error Code
EINVAL
ECONFIG

Error Description
Invalid parameter.
Perpheral is not enabled/configured.

Example:
See UPDATE
4.5.5.4

UPDATE

UPDATE PWM<channel> <n-value>


Start PWM operation on the specified channel.
<channel> = The channel on which to start PWM operations: 0, 1, or 2.
<n-value> = The new on time for the specified channel. The on time must be >= 1 and < the
Frame Period specified in the PCP.
Runtime Errors:
Error Code
EINVAL
ECONFIG

Error Description
Invalid parameter.
Peripheral is not enabled/configured.

Example:
DIM onTime

AS INTEGER

TASK
START PWM0
' Pulse duty-cycle on channel 0
FOR onTime = 1 to 99
UPDATE PWM0 onTime
DELAY 10
NEXT
FOR onTime = 99 to 1 STEP (-1)
UPDATE PWM0 onTime
DELAY 10
NEXT
STOP PWM0
REPEAT_TASK
END

4.5.6

SPI
Master SPI (MSPI)
There are two SPI interfaces available on the WiFi-IT! module. The master mode SPI interface,

2011 ... North Pole Engineering, Inc.

Programming Reference

65

MSPI, has up to four chip selects associated with it. W henever the M SPI is selected chip select
(CS) 0 is ena bled a nd not a va ila ble to use a s a GPIO.
Slave SPI (SSPI)
The SSPI interface is not currently supported in WiFi-Basic.
General SPI Information
Currently, WiFi-Basic only supports full-duplex operation on the SPI interface. When operating
in full-duplex mode read data is returned as write data is being transmitted. To obtain the read
data execute the INPUT function following the OUTPUT function. To emulate a half-duplex
write operation, issue an OUTPUT and ignore the returned data. To emulate a half-duplex read
operation, issue a dummy OUTPUT for the desired read length, followed by an INPUT to
retrieve the bytes read.
Important Note:
The INPUT command does not initiate a SPI transfer. It only returns the read bytes buffered
during the last OUTPUT command. If there are multiple OUTPUT commands issued back-to-back
only the data received from the last OUTPUT command are available from INPUT. Note also that
a read length cannot be specified with the INPUT command. All bytes received during the last
OUTPUT are returned.
In the example shown below, we need to transmit 7-bits of control and address data to read 8bits of data from the device. This can be done in either of two ways. In full duplex mode, we
will send 16-bits of write data; that is a zero followed by a 1 (the R/W bit = read) followed by 6address bits (0x20), followed by 8 bits of "don't care" data. We can do this by dimensioning our
output byte array to 2-bytes and setting byte 0 to 0x60. Outputting two bytes will cause the
device to return the data on the second byte. To read this data, we would issue an INPUT
command, for 2 bytes, immediately after the OUTPUT command. The data will be returned in
the second byte of the input array.

SPI Full Duplex Write/Read Operation

The code for this example is shown in the INPUT command example.
Note on SPI Terminology:
Din is also known as MOSI (Master Out - Slave In) in some SPI terminology.
Dout is also known as MISO (Master In - Slave Out) in some SPI terminology.
CPOL sets the base value of the clock polarity. This corresponds to the Clock Polarity
2011 ... North Pole Engineering, Inc.

66

WiFi-IT! Basic Language Reference

setting in the PCP.


CPHA sets the phase of the clock. This setting corresponds to the Clock Phase setting in
the PCP.
When selected, the SPI interface takes over the corresponding GPIOs. At least four GPIOs are
taken over for DIN, DOUT, CLK, and CS0. In addition, CS1, CS2, and CS3 take over their GPIOs if
enabled. SPI signals map to GPIOs as follows:
MSPI_CLK MSPI_DIN MSPI_DO MSPI_CS0 MSPI_CS1 MSPI_CS2 MSPI_CS3
UT
GPIO(5)
GPIO(6)
GPIO(7)
GPIO(4)
GPIO(13)
GPIO(14)
GPIO(15)
4.5.6.1

SPI Configuration

WiFi-Basic supports the MSPI interface only. The SSPI interface is not supported in the current
version.
SPI hardware configuration is done through the Project Configuration Panel (PCP). To setup the
SPI hardware configuration select the SPI tab in the PCP.

SPI GPIO Override:


SPI Enable - Enables the SPI interface. Chip select 0 (CS0) is enabled automatically when the
module is enabled.
CS1 GPIO Enable - Enables MSPI chip select 1 (CS1). To specify CS1 in the interface parameter to
either INPUT or OUTPUT, it must first be enabled here.
CS2 GPIO Enable - Enables MSPI chip select 2 (CS2). To specify CS2 in the interface parameter to
2011 ... North Pole Engineering, Inc.

Programming Reference

67

either INPUT or OUTPUT, it must first be enabled here.


CS3 GPIO Enable - Enables MSPI chip select 3 (CS3). To specify CS3 in the interface parameter to
either INPUT or OUTPUT, it must first be enabled here.
NOTE for chip select CS0: The GainSpan SPI hardware frames each data word when operating
with a clock phase of 0. That is, the chip select is driven high between each data word. Many
devices expect the chip select to be held low for the duration of a transfer. If your device
requires chip select to be held low continuously and also requires a clock phase of 0, it is
recommended to use a chip select CS1, CS2, or CS3. Framing of each word is not an issue when
clock phase is set to 180.
SPI Data and Clock Settings:
Protocol - The protocol to use for transfer
1. Motorola: This selection provides standard 4-wire SPI operation, SCLK, MOSI, MISO and SS.
2. TI: This selection provides Synchronous Serial Protocol (SSP) compatibility.
3. National: This selection provides MicroWire compatibility.
Clock Polarity (CPOL) - Indicates the default state of the clock line. Can be set to Active High or
Active Low.
Clock Phase (CPHA) - Indicates which edge to sample the data, independent of rising/falling
transition. A Clock Phase = 0 means sample on the leading (first) clock edge, while Clock Phase =
180 means sample on the trailing (second) clock edge. Note that with Clock Phase = 0 the data
must be stable for a half cycle before the first clock cycle.
The timing diagram, shown below, depicts the relationship between the interface signals and
the settings for Clock Polarity and Clock Phase.

Data Word Size - Sets the number of bits in a data word. This should be set to the word size of
2011 ... North Pole Engineering, Inc.

68

WiFi-IT! Basic Language Reference

the attached device. The valid selections are; 8-bits, 16-bits, 24-bits and 32-bits. Only 8-bit word
sizes are supported in the current release.
Base Clock Frequency - Selects the base clock to use. This setting, along with Clock Divider,
determines the MSPI clock frequency.
Rx Filter Enable - This setting is not used.
Duplex Mode: This setting is not used. All operations are full duplex from the perspective of
the WiFi-IT! module. For half duplex operations, it may be necessary to issue two OUTPUT
statements followed by one INPUT statement. The first OUTPUT sends data to the device. The
second OUTPUT sends junk while the device returns data. The INPUT statement returns the data
buffered during the read/write operation of the second OUTPUT.
Clock Divider - Sets the divider that will be applied to the Base Clock Frequency to create MSPI
clock. The MSPI clock is the base clock frequency divided by clock divider. For example, for a
base clock frequency of 22MHz and a divider of 10, the MSPI clock will run at 2.2MHz. Note: only
even values are supported for clock divider.
4.5.6.2

CONFIGURE

CONFIGURE MSPI <protocol>, <mode>, <i-value>

EDK+ only

Reconfigures the SPI bus at run-time.


<protocol> = Specifies the SPI protocol. Must be MOTOROLA, TI, or NATIONAL. See SPI
Configuration for more details.
<mode> = Specifies clock polarity and phase. Must be one of the following:
Mode Setting
Clock Polarity
Clock Phase
HIGH_0
Active High
0 degress
HIGH_180
Active High
180 degrees
LOW_0
Active Low
0 degrees
LOW_180
Active Low
180 degrees
<i-value> = Sets the divider that will be applied to the Base Clock Frequency to create MSPI
clock. The MSPI clock is the base clock frequency divided by clock divider. For example, for
a base clock frequency of 22MHz and a divider of 10, the MSPI clock will run at 2.2MHz. The
base clock frequency is set in the PCP and cannot be changed at run-time. Note: only even
values are supported for clock divider.
Runtime Errors:
Error Code
EINVAL

Error Description
Invalid parameter.

Example:
TASK
...
2011 ... North Pole Engineering, Inc.

Programming Reference

'
'
'
'

69

Hypothetical configuration...
Light Sensor and Temp Sensor both
connected to SPI bus, but sensors
operate at different clock phase.

CONFIGURE MSPI MOTOROLA, HIGH_0, 22


GOSUB ReadLightSensor
CONFIGURE MSPI MOTOROLA, HIGH_180, 22
GOSUB ReadTempSensor
...
REPEAT_TASK
SUB ReadLightSensor
...
RETURN
ENDSUB
SUB ReadTempSensor
...
RETURN
ENDSUB
END

4.5.6.3

INPUT

<n-variable> = INPUT MSPI | SSPI {<intfc>}, <b-array>

SSPI
Unimplemented

The SPI INPUT command is used to retrieve the data returned during a transfer initiated by
an SPI OUTPUT operation. Since the SPI receives data at the same time it sends data, the
received data is held in an internal buffer (maximum size 1024 bytes) until the INPUT
command is executed. The INPUT command does NOT initiate any action on the SPI
interface. The INPUT command can only be used after an OUTPUT command or a runtime
error will be generated. The INPUT command does not need to immediately follow the
OUTPUT command.
n-variable = The number of bytes read is returned as a numeric value (either byte or
integer). When specifying a byte variable, you must maker sure that the
number of bytes received never exceeds 255, the maximum value a byte
variable can hold.
MSPI | SSPI = Specifies either of two interfaces, MSPI or SSPI. The SSPI interface is
currently not supported in WiFi-Basic.
<intfc> = Specifies the Chip Select (CS) signals to transition when the SPI interface is
activated. Multiple CS signals may be logically OR'ed together. When the MSPI
interface is selected, the <intfc> parameter must be specified whether or not the
MSPI is configured in master mode. When the SSPI interface is specified the
2011 ... North Pole Engineering, Inc.

70

WiFi-IT! Basic Language Reference

<intfc> parameter is not allowed and should not be specified.


NOTE: Depending on the hardware configuration, the chip select lines controlled
by the MSPI do not need to be used to select the target peripheral, instead a GPIO
may be used as the chip select. In this case, the <intfc> parameter must still be
specified and the associated GPIO will change state, but since it is not connected
to the hardware peripheral, it will have no effect.
<b-array> = The byte array where the read data will be stored. An array index is not
specified. Data will always be stored starting at index 0.
Chip Select
Value (<intfc>)
0x1
0x2
0x4
0x8
Runtime Errors:
Error Code
ECONFIG
ESLAVEADDRESS
ENODATA

GPIO

Description

GPIO(4)
GPIO(13)
GPIO(14)
GPIO(15)

MSPI_CS0
MSPI_CS1
MSPI_CS2
MSPI_CS3

Error Description
Peripheral is not enabled/configured.
Interface parameter is invalid.
An SPI INPUT operation was performed before an SPI OUTPUT operation.

Example:
' The MSPI is configured in Full-Duplex mode. Output the command to read a register
' and read the byte of data returned during the OUTPUT command.
DIM byCommand(3)
DIM byReadData(3)
DIM byOutput(4)

AS BYTE
AS BYTE
AS BYTE

DIM i
DIM iCount

AS INTEGER
AS INTEGER

CONST
CONST
CONST
CONST

=
=
=
=

READ_CMD
READ_ADRS
CS1
UNUSED

0x40
0x20
%0010
%1000

' Command is 1-byte followed by an empty byte.

' Enable chip select 1.


' Unused chip select.

TASK
' Use the MSPI statement to control
byCommand(0) = READ_CMD
byCommand(1) = READ_ADRS
byCommand(2) = 0
OUTPUT MSPI CS1, byCommand(0), 3
iCount = INPUT MSPI CS1, byReadData
:

the chip select directly...

' Dummy data.


' Output the command and 8 additional bits.
' Get the data returned.

2011 ... North Pole Engineering, Inc.

Programming Reference

71

' Manually control the chip select using a GPIO statement...


' Note that case the <intfc> parameter is still required.
GPIO(18) = 1
' Deselect the peripheral.
byCommand(0) = READ_CMD
FOR i = 5 TO 10
byCommand(1) = i
GPIO(18) = 0
' Select device.
OUTPUT MSPI UNUSED, byCommand(0), 2
GPIO(18) = 1
' Deselect device.
iCount = INPUT MSPI UNUSED, byReadData
byOutput(i-5) = byReadData(2)
' Copy read data to output array.
NEXT
REPEAT_TASK
END

4.5.6.4

OUTPUT

{<n-variable> =} OUTPUT MSPI | SSPI {<intfc>,} <b-array>, <n-value>

SSPI
Unimplemented

The OUTPUT command transmits data on the selected SPI interface using the preconfigured
settings from the Project Configuration Panel.
<n-variable> = The number of bytes output is returned as a numeric value (either byte or
integer) and can be optionally captured. When specifying a byte variable,
you must maker sure that the number of bytes output never exceeds 255,
the maximum value a byte variable can hold.
<intfc> = Specifies the chip select (CS) that will be activated by the hardware when a
transfer takes place.
NOTE: When the MSPI interface is used, the <intfc> parameter must be specified whether
or not it is actually used by the hardware. When the SSPI interface is specified the <intfc>
parameter is not allowed and should not be specified.
<b-array> = A byte array that contains the data to transmit. An index must be specified and
the data transfer begins with the data byte at that index offset.
<n-value> = A byte, integer or constant that specifies the number of bytes to transfer.
NOTE: Depending on the hardware configuration, the chip select lines controlled by the
MSPI may not be used to select the target peripheral. A GPIO may be used as the chip
select. In this case, the <intfc> parameter must still be specified and the associated GPIO
will change state, but since it is not connected to the hardware peripheral, it will have no
effect.
Chip Select
Value (<intfc>)
2011 ... North Pole Engineering, Inc.

GPIO
Activated

Description

72

WiFi-IT! Basic Language Reference

0x1
0x2
0x4
0x8
Runtime Errors:
Error Code
EINVAL
ECONFIG
ESLAVEADDRESS

GPIO(4)
GPIO(13)
GPIO(14)
GPIO(15)

Master SPI Chip Select 0


Master SPI Chip Select 1
Master SPI Chip Select 2
Master SPI Chip Select 3

Error Description
Invalid parameter.
Peripheral is not enabled/configured.
Interface parameter is invalid.

Example:
' Send a byte array containing the control bytes to display an ASCII
' string on an LCD display.
DIM
DIM
DIM
DIM

sSpiData
bSpiData(29)
bySpiCmd(2)
iByteCnt

AS
AS
AS
AS

STRING
BYTE
BYTE
INTEGER

CONST CS1 = 1

' LCD is on Chip Select 1.

TASK
sSpiData = " This is a Test."
bySpiCmd(0) = 0x81
bySpiCmd(1) = 0x00
bySpiCmd(2) = 0x00

'
'
'
'

String data to display


LCD write command.
LCD row number, (first row).
LCD column number (first column)

iByteCnt = OUTPUT MSPI CS1, bySpiCmd(0), 3

' Send command to

LCD
bSpiData(0) = TOBYTEARRAY sSpiData
iByteCnt = OUTPUT MSPI CS1, bSpiData(0), LEN$(sSpiData)
display.
REPEAT_TASK
END

4.5.7

' Send data to

UART
There are two asynchronous serial interfaces available on the WiFi-IT! Module; UART0 and
UART1. The interfaces are configured using the Project Configuration Panel dialog. When the
module comes out of sleep mode, the UART interfaces are configured to their preset values.
When selected, a UART interface takes over the corresponding GPIO pins. UART interfaces map
to GPIO pins as follows:
UART0_RX
GPIO(0)

UART0_TX
GPIO(1)

UART0_CTS
GPIO(24)

UARTO_RTS
GPIO(25)

UART1_TX
GPIO(2)

UART1_RX
GPIO(3)

UART1_CTS
GPIO(26)

UART1_RTS
GPIO(27)
2011 ... North Pole Engineering, Inc.

Programming Reference

73

Important Note:
Enabling either of the UART interfaces will increase power consumption. This is because the WiFi-IT!
module normally enters a low-power state when idle where the main clock is halted. This clock is
used to operate the UART interface, and since UART data may be received asynchronously, the WiFiBasic Run Time Engine will keep this clock running when one or both UARTs is enabled. Note that
the application CPU will still halt when idle.
4.5.7.1

UART Configuration

UART configuration is done through the PCP. To open the PCP, right-click the project and select
Edit Project Device Configuration. To select and configure the UART click the UART tab at the
bottom of the page.

Enable - Enables the selected UART interface.


Baud Rate - Selects the desired character transmission/reception speed. The valid rates are from
9600 to 921600 baud. It is advisable to keep the rate at 115200 or slower, unless special routing
precautions have been taken.
# Data Bits - Sets the character size to 5, 6, 7, or 8 bits.
Parity - Selects parity. The valid selections are; NONE, ODD, EVEN, MARK, or SPACE. If NONE is
selected the parity bit is not included in the character. MARK provides the parity bit but it is
always high. SPACE provides the partity bit but it is alway low.
# Stop Bits - Selects 1 or 2 stop bits.
Flow Control - Select RTS/CTS to enable hardware flow control. NOTE: hardware flow control
will not operate correctly on the WiFi-IT! DCard. It will operate correctly when the WiFi-IT!
module is attached to a peripheral card.

2011 ... North Pole Engineering, Inc.

74

4.5.7.2

WiFi-IT! Basic Language Reference

INPUT

{<i-variable> =} INPUT UART0 | UART1 <s-value> | <b-array>


This function is called to read characters from the specified UART. The UART buffers
incoming characters and the INPUT command returns all of the characters in the buffer or
the maximum number of characters that the buffer can hold, whichever is smaller. This is a
non-blocking call and returns immediately to the caller with the number of characters
received. The data can be returned as a string <s-value> or as a byte array <b-array>. If
returned as a byte array, data will be filled starting at array index zero.
For string variables, the data is placed at the first character location in the string. The
number of characters received is returned in <i-variable>. Received strings can NOT be
greater than the maximum string length (256 characters). Data will be truncated if the buffer
is holding more than 256 characters and multiple INPUT statements will be required to read
all of the data.
The number of characters or bytes received is returned by the INPUT command and can be
optionally captured into an integer variable.
Runtime Errors:
Error Code
EINVAL
ECONFIG
EPROVMODE
of Operation.
ENOMEM

Error Description
Invalid parameter.
Perpheral is not enabled/configured.
Operation perfomred on UART0, in UART provisioning mode. See Modes
Out of string space.

String Data Example:


DIM MyString AS STRING
DIM NumChars AS INTEGER
TASK
NumChars = INPUT UART0 MyString
REPEAT_TASK
END

The number of characters waiting in the UART buffer will be read into the variable MyString and
then execution will continue at the statement following the INPUT statement.
Binary Data Example:
DIM RcvData(3)
DIM NumChars

AS BYTE
AS INTEGER

TASK
DO
NumChars = INPUT UART1 RcvData
UNTIL NumChars <> 0
REPEAT_TASK
END

2011 ... North Pole Engineering, Inc.

Programming Reference

75

Input up to 4 bytes of data into RcvData(0) through RcvData(3). Because the INPUT statement is
contained in a DO UNTIL loop, it acts like a blocking statement. Meaning program flow cannot
continue until some characters are received. The actual number of characters read will be
returned in NumChars.
4.5.7.3

OUTPUT

{<i-variable> =} OUTPUT UART0 | UART1 <sb-array> {, <count>}


The OUTPUT command transmits data on the selected interface using the preconfigured
interface settings from the Project Configuration Panel. Data can be output from ASCII strings
or byte arrays. In the case of an ASCII string, the <count> field is not used and should be left
blank. For data contained in a byte array, the <count> field is required and specifies the
number of elements in the byte array to transmit, starting from element specified.
The number of characters or bytes transmitted is returned by the OUTPUT command and can
be optionally captured into an integer variable.
Runtime Errors:
Error Code
EINVAL
ECONFIG
EPROVMODE
of Operation.

Error Description
Invalid parameter.
Perpheral is not enabled/configured.
Operation perfomred on UART0, in UART provisioning mode. See Modes

String Example:
DIM LineMsg
DIM LineCnt
DIM CharsXmitted

AS STRING
AS INTEGER
AS INTEGER

TASK
LineMsg = "The number of lines is "
LineCnt = 6
LineMsg = LineMsg & STR$(LineCnt) & "."
CharsXmitted
lines is 6.
REPEAT_TASK
END

= OUTPUT UART1 LineMsg

'UART1 Outputs:

The number of

NOTE: No carriage return or line feed is output. To add a carriage return, line feed or other
control character use the CHR$ function. For example; append the character CHR$(13) to add a
carriage return or CHR$(10) to add a line feed.
Byte Array Example:
DIM MyData(3)
DIM i
DIM CharsXmitted
TASK

2011 ... North Pole Engineering, Inc.

AS BYTE
AS INTEGER
AS INTEGER

76

WiFi-IT! Basic Language Reference

MyData(0)
MyData(1)
MyData(2)
MyData(3)

=
=
=
=

0x54
0x45
0x53
0x54

CharsXmitted
REPEAT_TASK
END

4.5.7.4

'ASCII
'ASCII
'ASCII
'ASCII

character
character
character
character

'T'
'E'
'S'
'T'

= OUTPUT UART0 MyData(0), 4

'UART0 Outputs:

TEST

UART_RX

UART_RX = <ON | OFF>

EDK+ only

The intrinsic constants ON and OFF must be used with this statement. UART_RX cannot be
assigned to a variable. UART_RX can not be read unless it is used in a conditional statement or
comparison operation.
UART_RX enables or disables reception on both UARTs. Since the UART is an asynchronous
interface, and since the UARTs are powered by the main system clock, this clock cannot be
idled during periods of inactivity. Disabling UART reception allows this clock to be gated and
the module to enter lower power modes while not in standby. If one or both UARTs are
enabled in the PCP, then UART_RX is enabled by default. It is up to the WiFi-Basic program to
allow lower power modes by explicitly issuing "UART_RX OFF". If neither UART is enabled,
the firmware will idle the main clock as needed and there is no need to explicitly issue
"UART_RX OFF".
Example:
' Variables
DIM
inputStr
DIM
bytesRcvd
STATIC uartRxDisabled
STATIC msgTimer

AS
AS
AS
AS

STRING
INTEGER
INTEGER
INTEGER

TASK
' GPIO(31) indicates UART Rx on or off
IF uartRxDisabled THEN
GPIO(31) = 0
ELSE
GPIO(31) = 1
ENDIF
' Echo back any received characters
bytesRcvd = INPUT UART0 inputStr
IF bytesRcvd > 0 THEN
OUTPUT UART0 inputStr
ENDIF
' Alarm 1 toggles UART receive on/off
IF (EVENT AND ALARM1) = ALARM1 THEN
IF uartRxDisabled = TRUE THEN
uartRxDisabled = FALSE
UART_RX ON

2011 ... North Pole Engineering, Inc.

Programming Reference

77

ELSE
uartRxDisabled = TRUE
UART_RX OFF
ENDIF
ENDIF
' Output message every 5 seconds.
' UART Tx works, even if UART Rx is off
IF TIMER > (msgTimer + 5000) THEN
msgTimer = TIMER + 5000
OUTPUT UART0 "Hello!" & CHR$(10)
ENDIF
REPEAT_TASK
END

4.6

Intrinsic Constants
Constant symbols defined in the language. Intrinsic constants should be used whenever
possible as the actual numeric value of these constants could change between revisions of WiFiBasic.
Intrinsic constants can only be used on the right side of an equal sign; in either an assignment or
relational comparison statement. Intrinsic constants may be used between TASK REPEAT_TASK, SUB - ENDSUB or ESUB - ENDESUB keywords.
ADHOC
ALARM1
ALARM2
AUTO
COLD_BOOT
CURRENT
Error Codes
ERRORFLAG
FALSE
INFRASTRUCTURE
NONE
OFF
ON
PRIMARY
PROVISION
SECONDARY
TRUE
WEP_OPEN
WEP_SHARED
WPA_ENTERPRISE

2011 ... North Pole Engineering, Inc.

A list of error codes that can be returned by the Run Time Engine (RTE).

78

WiFi-IT! Basic Language Reference

WPA_PERSONAL
WPA2_ENTERPRISE
WPA2_PERSONAL

4.6.1

ADHOC
ADHOC
EDK+ only
System defined, intrinsic constant that is used as a parameter to the SSID, CHANNEL, and LINK
functions.
ADHOC corresponds to the network configuration for Adhoc in the Program Configuration
Panel (PCP).
ADHOC is also a network type returned by SCAN_ELEMENT(NETWORK).

4.6.2

ALARM1
ALARM1
System defined, intrinsic constant that can be ANDed with the EVENT system variable to
determine whether an external trigger on the Alarm 1 input has occurred.

4.6.3

ALARM2
ALARM2
System defined, intrinsic constant that can be ANDed with the EVENT system variable to
determine whether an external trigger on the Alarm 2 input has occurred.

4.6.4

AUTO
AUTO
EDK+ only
System defined, intrinsic constant that is used with SECURITY. AUTO specifies the module
may join an open network, or a network secured by WEP open key, WPA pre-shared key, or
WPA2 pre-shared key encryption.

4.6.5

COLD_BOOT
COLD_BOOT
System defined, intrinsic constant that can be ANDed with the EVENT system variable to
determine whether a cold boot has occurred.

4.6.6

CURRENT
CURRENT
EDK+ only
System defined, intrinsic constant that is used as a parameter to the SSID and CHANNEL
functions.
CURRENT specifies the SSID of the current connection.
2011 ... North Pole Engineering, Inc.

Programming Reference

4.6.7

79

Error Codes
System defined, intrinsic constants that are 32-bit, non-zero values returned by the system
variable, ERROR.
The table below defines the error code names and values. Within a program it is recommended
that the error name be used, as values may change between versions of WiFi-Basic.
Error Name
EOK

Error Value Error Description


0
The operation was successful.
BASIC operations capable of generating errors do not set the
value of ERROR to EOK on success. This allows error codes to
be maintained across multiple operations. Any read of the
ERROR keyword (while in passive error mode) sets it back to
EOK. To check an operation (or set of operations for success)
by checking the ERROR keyword, it should be cleared by
reading it beforehand.

EPREM

The operation is not allowed on the specified socket.\

EIO

The IO operation failed. Currently only used for ADC.

ENOMEM

12

There is not enough memory to complete the operation. This


error is most likely to occur with string operations or
keywords that return a string.

EINVAL

22

One of the parameters has an invalid value. For example: an


invalid IP address provided to the OPEN keyword or an
invalid starting index provided to the MID$ function.

EAGAIN

35

No data is ready or no clients are waiting.

EALREADY

37

The operation is already in progress, but is not yet


completed.

EMSGSIZE

40

The message is too long to be sent atomically. The message


should be separated into smaller packets before sending.

EOPNOTSUPP

45

This operation is not supported by the specified socket.

EADDRINUSE

48

A socket operation was attempted on an address that is


already in use. For example, an attempt was made to open a
receiving socket on a port that is already bound to another
socket.

EADDRNOTAVAIL

49

The specified address is not available on the remote/local


machine.

2011 ... North Pole Engineering, Inc.

80

WiFi-IT! Basic Language Reference

ECONNRESET

54

The connection was reset by the remote host (TCP only).

ENOTCONN

57

The operation is only valid while associated with a network


and the node is not currently connected.
Alternatively, a send or receive operation was attempted on
a TCP socket that is no longer in the connected state.

ESHUTDOWN

58

Send or receive operations are no longer allowed on this


connection (TCP only).
The operation timed out. There was no response from the
remote host.

ETIMEDOUT

60

ECONNREFUSED

61

The remote host refused the connection (TCP only).

ENAMETOOLONG

63

The operation could not be completed because the specified


name is too long. For example: SSIDs cannot be set to a string
longer than 32 characters.

EHOSTDOWN

64

The destination host is down.

EHOSTUNREACH

65

There is no route to the destination host.

ECONFIG

100

An operation was attempted on a peripheral that is not


currently enabled. OR An attempt was made to set the
node's IP address but the node is currently running with
DHCP enabled.

ECIDLIMIT

101

There are no more sockets (connection IDs) available.

EBADCID

102

A socket operation was attempted with an invalid CID.

ESLAVEADDRESS

103

An I2C or SPI operation was attempted and the interface


parameter is invalid.

ENORESP

104

No device responded at the specified I2C address.

ENOSENDER

105

GET_SENDER_PORT, GET_SENDER_IP, or GET_SENDER_CID was


called but data has not yet been received from any hosts.

ENODATA

106

An INPUT SPI operation was performed prior to any OUTPUT


operations and the SPI module is operating in full-duplex
mode. In full-duplex mode, both read and write operations
are performed simultaneously during the OUTPUT operation.
The read data is buffered until the INPUT statement is called.

EPROVEMODE

107

An operation was attempted on UART0 but the module is in


UART provisioning mode. BASIC programs using UART0 are
2011 ... North Pole Engineering, Inc.

Programming Reference

81

allowed to be compiled, loaded, and debugged in UART


provisioning mode, but they will be prevented from actually
accessing the UART when provisioning mode is being used.
ENONWFOUND

4.6.8

108

The LINK statement was executed in an attempt to connect


to one or more infrastructure networks, but WAP 1, WAP 2,
and/or provisioning SSIDs were not found.

ERRORFLAG
ERRORFLAG
System defined, intrinsic constant that is returned by some functions to indicate an error
codition.
Example:
DIM cid AS INTEGER
TASK
:
IF POLL(cid) = ERRORFLAG THEN
:
ENDIF
:
REPEAT_TASK
END

4.6.9

' Poll returns TRUE / FALSE or an ERRORFLAG.


' Only do this if an error was detected.

FALSE
FALSE
System defined, intrinsic constant that is returned by all comparison operators and functions
to indicate the opposite condition from TRUE.
Example:
TASK
:
IF LINKED? = FALSE THEN
:
ENDIF
:
REPEAT_TASK
END

4.6.10 INFRASTRUCTURE
INFRASTRUCTURE
EDK+ only
System defined, intrinsic constant that is used as a parameter to the SSID, CHANNEL, and LINK
functions.
INFRASTRUCTURE specifies that the node will connect to a Wireless Access Point (WAP).
2011 ... North Pole Engineering, Inc.

82

WiFi-IT! Basic Language Reference

When INFRASTRUCTURE is specified with the LINK command, the node will attempt to first
connect to WAP1, if that network is unavailable, WAP2 will be attempted. If neither WAP1 or
WAP2 are found the node will attempt to connect to the PROVISIONing network.
The PCP allows configuration of up to two different WAPs, WAP 1 and WAP 2. The
PROVISIONing network is predefined as SSID "NpeWiFiConfig" on CHANNEL 6, it can not be
changed by the programmer.
INFRSTRACTURE is also a network type returned by SCAN_ELEMENT(NETWORK).

4.6.11 NONE
NONE
EDK+ only
System defined, intrinsic constant that is one of the possible values used by SECURITY or
returned by SCAN_ELEMENT(SECURITY). NONE specifies the network is unsecured.

4.6.12 OFF
OFF
EDK+ only
System defined, intrinsic constant that is used as an assignment or comparison value for the
SLEEP_MODE and RECEIVER functions.

4.6.13 ON
ON
EDK+ only
System defined, intrinsic constant that is used as an assignment or comparison value for the
SLEEP_MODE and RECEIVER functions.

4.6.14 PRIMARY
PRIMARY
EDK+ only
System defined, intrinsic constant that is used as a parameter to the SSID, CHANNEL, and LINK
functions.
PRIMARY corresponds to the network configuration for WAP 1 in the Program Control Panel
(PCP).

4.6.15 PROVISION
PROVISION
EDK+ only
System defined, intrinsic constant that is used as a parameter to the SSID, CHANNEL, and LINK
functions.
PROVISION specifies the network configuration for the provisioning WAP. The provisioning
WAP is not user accessible through the Program Configuration Panel (PCP) and can not be
changed in WiFi-Basic. It is set to SSID "NpeWiFiConfig" on channel 6.
2011 ... North Pole Engineering, Inc.

Programming Reference

83

4.6.16 SECONDARY
SECONDARY
EDK+ only
System defined, intrinsic constant that is used as a parameter to the SSID, CHANNEL, and LINK
functions.
SECONDARY corresponds to the network configuration for WAP 2 in the Program Control Panel
(PCP).

4.6.17 TRUE
TRUE
System defined, intrinsic constant that is returned by all comparison operators and functions
to indicate the opposite condition from FALSE.
Intrinsic constants can only be used on the right side of an equal sign - in either an assignment
or relational comparison statement. Intrinsic constants may be used between TASK REPEAT_TASK, SUB - ENDSUB or ESUB - ENDESUB keywords.
Example:
DIM cid AS INTEGER
TASK
':
IF POLL(cid) = TRUE THEN
:
(TRUE).
ENDIF
:
REPEAT_TASK
END

' Poll returns TRUE / FALSE and an ERRORFLAG.


' Only do this if a message has been received

4.6.18 WEP_OPEN
WEP_OPEN
EDK+ only
System defined, intrinsic constant that is one of the possible values used by SECURITY or
returned by SCAN_ELEMENT(SECURITY). NONE specifies the network is unsecured.
WEP_OPEN specifies the network is secured using WEP Open key encryption.

4.6.19 WEP_SHARED
WEP_SHARED
EDK+ only
System defined, intrinsic constant that is one of the possible values used by SECURITY or
returned by SCAN_ELEMENT(SECURITY). NONE specifies the network is unsecured.
WEP_SHARED specifies the network is secured using WEP Shared key encryption.

2011 ... North Pole Engineering, Inc.

84

WiFi-IT! Basic Language Reference

4.6.20 WPA_ENTERPRISE
WPA_ENTERPRISE
EDK+ only
System defined, intrinsic constant that is one of the possible values used by SECURITY or
returned by SCAN_ELEMENT(SECURITY). NONE specifies the network is unsecured.
WPA_ENTERPRISE specifies the network is secured using WPA encryption and 802.1X
authentication.

4.6.21 WPA_PERSONAL
WPA_PERSONAL
EDK+ only
System defined, intrinsic constant that is one of the possible values used by SECURITY or
returned by SCAN_ELEMENT(SECURITY). NONE specifies the network is unsecured.
WPA_PERSONAL specifies the network is secured using WPA pre-shared key.

4.6.22 WPA2_ENTERPRISE
WPA2_ENTERPRISE
EDK+ only
System defined, intrinsic constant that is one of the possible values used by SECURITY or
returned by SCAN_ELEMENT(SECURITY). NONE specifies the network is unsecured.
WPA2_ENTERPRISE specifies the network is secured using WPA2 encryption and 802.1X
authentication.

4.6.23 WPA2_PERSONAL
WPA2_PERSONAL
EDK+ only
System defined, intrinsic constant that is one of the possible values used by SECURITY or
returned by SCAN_ELEMENT(SECURITY). NONE specifies the network is unsecured.
WPA2_PERSONAL specifies the network is secured using WPA2 pre-shared key.

4.7

Miscellaneous Functions
General statements, system variables and functions.

Comment
ABS
BYTECOPY
CBYTE
CINT
DELAY
EVENT
SERIAL_NUMBER
TIMER
UBOUND

Placing comments into a program


Absolute Function
Copy part of one byte array to another
Copy an int into a byte array
Extract an int out of a byte array
Delay Function
System variable
Return the serial number loaded at manufacturing
Returns the current timer count
Returns the highest index value of an array

2011 ... North Pole Engineering, Inc.

Programming Reference

4.7.1

85

Comment
'
The tic command forces the remainder of the line to be a comment. Comments are disregarded
by the compiler. A comment should never precede code on the same line that you want to
compile.
Example:
' This entire line is a comment and is disregarded by the compiler.
DIM MyVar AS INTEGER
' The rest of this line is a comment.

4.7.2

ABS
{i-variable =} ABS(x)
Return the absolute value (magnitude) of x.
Example:
DIM x AS INTEGER
DIM Xabs AS INTEGER
TASK
x = -5
Xabs = ABS(x)
:
REPEAT_TASK
END

4.7.3

'Xabs is equal to 5.

BYTECOPY
<b-array(index)> = BYTECOPY(<b-array(index)>, <i-value> )
Copies <i-value> bytes from one byte array into another. The source byte array is supplied
as an argument and the destination byte array goes to the left of the equals sign.
Example:
' Variables
DIM
dataPkt(63)
DIM
sendCid
DIM
inputIndex
DIM
inputArray(63)
DIM
bytesRcvd
DIM
readTime
DIM
buffer(15)

AS
AS
AS
AS
AS
AS
AS

' Constants
CONST
UART_DATA

= 1

BYTE
INTEGER
INTEGER
BYTE
INTEGER
INTEGER
BYTE

TASK
' Hypothetical data server
sendCid = OPEN UDP "192.168.89.2", 8000
' Hypothetical Type-Length-Value packet
GOSUB GetInput

2011 ... North Pole Engineering, Inc.

86

WiFi-IT! Basic Language Reference

IF inputIndex > 0 THEN


dataPkt(0) = UART_DATA
dataPkt(1) = inputIndex
dataPkt(2) = BYTECOPY inputArray(0), inputIndex
SEND sendCid, dataPkt(0), (2 + inputIndex)
ENDIF
REPEAT_TASK
' Read data from UART0. Once input starts,
' wait at least 500ms before returning.
' GPIO(30) ON while receiving characters.
SUB GetInput
inputIndex = 0
bytesRcvd = INPUT UART0 buffer
IF bytesRcvd > 0 THEN
GPIO(30) = 1
readTime = TIMER
WHILE( (bytesRcvd > 0) OR ((readTime + 500) > TIMER) )
inputArray(inputIndex) = BYTECOPY buffer(0), bytesRcvd
inputIndex = inputIndex + bytesRcvd
bytesRcvd = INPUT UART0 buffer
IF bytesRcvd > 0 THEN
readTime = TIMER
ENDIF
WEND
GPIO(30) = 0
ENDIF
RETURN
ENDSUB
END

4.7.4

CBYTE
<b-array(index)> = CBYTE(<i-value>)
Copies an integer into a byte array. Uses locations <b-array(index)> through <b-array
(index+3)>. Works at any offset. Integer is stored in little-endian format.
Example:
' Variables
DIM
dataPkt(23)
DIM
lightReading
DIM
sendCid

AS BYTE
AS INTEGER
AS INTEGER

' Constants
CONST
LIGHT_SENSOR

= 2

TASK
' Hypothetical data server
sendCid = OPEN UDP "192.168.3.200", 8000
' Hypothetical Type-Length-Value packet
GOSUB ReadLightSensor

2011 ... North Pole Engineering, Inc.

Programming Reference

87

dataPkt(0) = LIGHT_SENSOR
dataPkt(1) = 4
dataPkt(2) = CBYTE(lightReading)
SEND sendCid, dataPkt(0), 6
REPEAT_TASK
SUB ReadLightSensor
' Read a light sensor and store
' value in lightReading.
...
RETURN
ENDSUB
END

4.7.5

CINT
{i-variable =} CINT(<b-array(index)> )
Extracts an integer from a byte array. Reads locations <b-array(index)> through <b-array
(index+3)>. Works at any offset. Integer is assumed to be stored in little-endian format.
Example:
' Variables
DIM
dataPkt(23)
DIM
dataType
DIM
dataLen
DIM
dataValue
DIM
numBytes
DIM
recvCid

AS
AS
AS
AS
AS
AS

BYTE
INTEGER
INTEGER
INTEGER
INTEGER
INTEGER

TASK
recvCid = LISTEN UDP 8000
' Hypothetical Type-Length-Value packet
GOSUB ReceivePacket
dataType = dataPkt(0)
dataLen = dataPkt(1)
dataValue = CINT(dataPkt(2))
OUTPUT UART0 "Value received = " & STR$(dataValue) & CHR$(10)
REPEAT_TASK
SUB ReceivePacket
' Receive packet from sensor module
DO
DELAY 10
UNTIL(POLL(recvCid) = 1)
numBytes = RECEIVE recvCid, dataPkt
RETURN
ENDSUB
END

2011 ... North Pole Engineering, Inc.

88

4.7.6

WiFi-IT! Basic Language Reference

DELAY
DELAY(<i-value>)
The DELAY command is used to specify a period of time, in milliseconds, where the WiFi-IT!
processor waits until the specified time period expires. Execution is suspended during this
interval but all variables retain their values, so when the processor restarts, execution will
continue with the instruction following the DELAY instruction.
The parameter for DELAY is an unsigned integer, although a byte value may be used. This
means the maximum delay value is (2^32)/1000 seconds which is about 49.71 days. Although
you can specify a large value, it is not recommended because the device does not enter sleep
m ode during a DELA Y. This will have negative consequences on battery life.
NOTE: The DELAY function provides a best effort to meet the specified delay period. Since
WiFi-Basic runs in a multi-tasking environment, the DELAY function can be interrupted by
another task. Therefore, the delay specified will be the minimum amount of time that the
function delays.
Example:
DIM byLightData(1)
DIM byCmd(1)
DIM bytesRead

AS BYTE
AS BYTE
AS INTEGER

CONST SENSOR_ADRS = 0x1D


CONST LIGHT_RD_CMD = 0x82
TASK
byCmd(0) = LIGHT_RD_CMD
OUTPUT I2C SENSOR_ADRS, byCmd(0), 1
DELAY 50
' DELAY processing for 50 milliseconds.
bytesRead = INPUT I2C SENSOR_ADRS, byLightData, 2
REPEAT_TASK
END

4.7.7

EVENT
{i-variable =} EVENT
The EVENT system variable is read-only and contains flags to indicate specific events. Events
may occur during execution of the BASIC program or during sleep state. For example, an
alarm event will wake up the node and set the corresponding flag. Events occur
asynchronously to program execution, so an event flag can become set at any time. Reading
the EVENT variable clears all event flags. Multiple event flags can be set at the same time,
but WiFi-Basic will not register multiple occurrences of the same event.
The EVENT values and a descriptions are shown in the table below.
EVENT ID Value Description
COLD_BO 0x1 This event is signaled the first time the program runs after initial power on. It
OT
never occurs until the node is reset, a new WiFi-Basic program is loaded or a
power cycle occurs. It stays set until the first read of the EVENT system
2011 ... North Pole Engineering, Inc.

Programming Reference

ALARM1
ALARM2

89

variable.
0x2 The ALARM1 event occurs when an external trigger on the Alarm 1 input is
activated. If the node is sleeping it will wake up and begin processing.
0x4 The ALARM2 event occurs when an external trigger on the Alarm 2 input is
activated. If the node is sleeping it will wake up and begin processing.

Example:
STATIC
DIM

cidServer
eventVal

AS INTEGER
AS INTEGER

TASK
IF (EVENT AND COLD_BOOT) THEN
' Initialize wireless connection.
cidServer = OPEN UDP "192.168.3.2", 5889
ELSE
' Run standard program operation.
:
ENDIF
REPEAT_TASK
END

4.7.8

SERIAL_NUMBER
{i-variable =} SERIAL_NUMBER
The SERIAL_NUMBER system variable is read-only and returns the serial number loaded using
the Manufacturing Loader. It is written as part of the program flash in the manufacturing load
process. The serial number may be any unsigned 32-bit integer. You are free to subdivide
and use this field in any manner you wish. The Manufacturing Loader allows for serialization
by auto-incrementing this field on each module loaded.
Example:
' Variables
DIM
serialNumStr

AS STRING

' Constants
TASK
' Program statements here.
serialNumStr = STR$(SERIAL_NUMBER)
WHILE LEN$(serialNumStr) < 5
serialNumStr = "0" & serialNumStr
WEND
serialNumStr = "SN" & serialNumStr
OUTPUT UART0 "My serial number = " & serialNumStr & CHR$(10)
DELAY 5000
REPEAT_TASK
END

2011 ... North Pole Engineering, Inc.

90

4.7.9

WiFi-IT! Basic Language Reference

TIMER
{i-variable =} TIMER
The TIMER function returns a unsigned integer representing the number of milliseconds
elapsed since power on. Integers are 32-bit values giving a maximum measurement time of
4,294,967,296 milliseconds or approximately 49.71 days. After the maximum count has been
reached, the timer will rollover to zero. TIMER is the on-time since initial power-on. It is
based on the RTC and will continue counting through project loads and resets using
ext_reset. TIMER is not affected by changes to the RTC using the NOW keyword.
Example:
DIM StartTime
DIM EndTime
DIM RunTime

AS INTEGER
AS INTEGER
AS INTEGER

TASK
StartTime = TIMER
:
EndTime = TIMER
IF StartTime > EndTime THEN
' Take rollover into account.
RunTime = (4294967295 - StartTime) + EndTime
milliseconds.
ELSE
RunTime = EndTime - StartTime
ENDIF
REPEAT_TASK
END

' RunTime in

4.7.10 UBOUND
UBOUND(<array variable>,<dimension>)
Return the upper bound of the specified array dimension. The dimension parameter must be
a constant.
Note: The current version of WiFi-Basic only support single dimension variables therefore,
<dimension> must be set to 1.
Example:
DIM
DIM

byPacket(4)
iDimension

AS BYTE
AS INTEGER

CONST FST_DIMENSION = 1
TASK
iDimension = UBOUND(byPacket, 1)
iDimension = UBOUND(byPacket, FST_DIMENSION)
REPEAT_TASK
END

' iDimension holds the value 4.


' iDimension holds the value 4.

2011 ... North Pole Engineering, Inc.

Programming Reference

4.8

91

Power Management
This section describes power management in WiFi-Basic. There are two modes of operation.
Low-Power: Sleep mode is enabled. The module enters the sleep state upon hitting the
REPEAT_TASK statement. On wakeup, the module returns to the TASK statement.
Always-On: The module immediately returns to the TASK statement upon hitting the
REPEAT_TASK statement.
RECEIVER
SLEEP
SLEEP_MODE
UART_RX
XMIT_POWER

4.8.1

Power Configuration
Power settings for a project are set through the Project Configuration Panel (PCP). To edit the
power settings, select the Device tab in the PCP.

The Power section allows you to select whether Sleep mode is enabled or disabled. When
enabled a Sleep Time must be entered, which is at least 1000 milliseconds (1 second) and may
be as great as 32,000,000 milliseconds. The module will then enter the sleep state upon
reaching REPEAT_TASK. If sleep is disabled, the module immediately restarts execution at TASK
upon reaching REPEAT_TASK. For more detailed information, see Sleep Mode Operation.
NOTE: A minimum sleep period of 1000 milliseconds is required to ensure that the node
actually enters the sleep state. 1000 is the smallest value that will be accepted as a Sleep Time.

4.8.2

Sleep Mode Operation


When sleep is enabled, the sleep time specifies a timeout from the previous wake event. For
example, if a sleep time of 5 seconds is specified, and the module wakes and executes BASIC
code for half a second, the module would then sleep for 4 and a half seconds before the next
wake event.
The sleep timer is always running, even while BASIC code is executing. It resets itself at each

2011 ... North Pole Engineering, Inc.

92

WiFi-IT! Basic Language Reference

expiry. If BASIC code executes longer than the specified sleep time before executing
REPEAT_TASK, the module will sleep for the duration remaining on the current sleep timer. For
example, if a sleep time of 5 seconds is specified, and the module wakes and executes BASIC
code for 7 seconds, the module would then sleep for 3 seconds before the next wake event.
Also, an event on the alarm1 or alarm2 pins while in sleep mode will cause the WiFi-IT! module
to wake and begin executing code. The event will be recorded in the EVENT system variable.
Following are timing diagrams showing operation in sleep state.

This diagram shows a WiFi program executing for one-second with a three-second sleep
interval.
The module only sleeps for two seconds since one-second of the sleep interval was used used
for execution.

The top line in this diagram shows the ticks of the sleep timer. The bottom line shows
execution of the WiFi Program.
Since the WiFi program took longer than the sleep interval, one of the ticks is missed. When
the program enters the sleep state, it must now wait for the next tick of the sleep timer.

2011 ... North Pole Engineering, Inc.

Programming Reference

93

The top line in this diagram shows the ticks of the sleep timer. The bottom line shows the
module being woken by an alarm input independent of the sleep timer.

4.8.3

RECEIVER
RECEIVER = <ON | OFF>

EDK+ only

The intrinsic constants ON and OFF must be used with this statement. RECEIVER cannot be
assigned to a variable. RECEIVER can not be read unless it is used in a conditional statement
or comparison operation. When setting the value of RECEIVER it controls the state of the
radio receiver. It does not affect the transmitter, which is always off unless transmitting.
RECEIVER does not affect the LINK state of the module. Turning off the receiver does not
cause the module to disassociate from a network. While the receiver is off, the module will
not be able to receive packets. This is not an issue for modules that only wish to transmit
data. Normally, the access point (AP) will store packets destined for the module. If the
receiver is turned on, these packets could be delivered all at once. Note that TCP
operations require the RECEIVER to remain on.
The setting stored in RECEIVER corresponds to the "Radio RX On at Startup" setting in the
Project Configuration Panel. Assignments made to RECEIVER at run time are persistent
across sleep cycles, but not through a cold boot or module reset.
Important Note on joining/leaving networks:
UNLINK will always power off the radio receiver. The RECEIVER statement can still be used
while disconnected, although it will not change the actual power state of the receiver. The
WiFi-Basic Run Time Engine (RTE) will check this setting after joining a network to
determine whether the receiver should be on or off. The receiver is always on while
joining a network. The setting stored in RECEIVER is only applied to the radio receiver after
network association is complete.
Example:
TASK
:
IF RECEIVER = OFF THEN
RECEIVER = ON
ENDIF
:
REPEAT_TASK
END

4.8.4

SLEEP
SLEEP = <n-value>
<n-variable> = SLEEP

EDK+ only

SLEEP gets or sets the timeout value stored in the sleep timer. It overwrites the Sleep Time
value set in the Project Configuration Panel. This setting is persistent across sleep cycles,
cold boot, and loss of power. Assignment to SLEEP updates device settings in flash memory,
2011 ... North Pole Engineering, Inc.

94

WiFi-IT! Basic Language Reference

so use it sparingly. SLEEP time is specified in milliseconds.


Important Note:
The sleep timer is always running, regardless of whether sleep mode is enabled. A program
that uses SLEEP_MODE to switch between sleep enabled and disabled should recognize that
SLEEP_MODE does not reset the sleep timer. Thus, setting SLEEP_MODE to ON just before
REPEAT_TASK does not guarantee the full sleep duration. The SLEEP statement does reset
the sleep timer. See Sleep Mode Operation for more information.
Example:
TASK
:
IF SLEEP > 8000 THEN
' Set maximum sleep duration to 8 seconds
SLEEP = 8000
ENDIF
:
REPEAT_TASK
END

4.8.5

SLEEP_MODE
SLEEP_MODE = <ON | OFF>

EDK+ only

The intrinsic constants ON and OFF must be used with this statement. SLEEP_MODE cannot be
assigned to a variable. SLEEP_MODE can not be read unless it is used in a conditional
statement or comparison operation. SLEEP_MODE gets or sets the Enable Sleep setting in the
project configuration panel. ON means that the module will enter the sleep state upon
reaching REPEAT_TASK. OFF means the module will loop directly from REPEAT_TASK to TASK.
Important Note:
The sleep timer is always running, regardless of whether sleep mode is enabled. A program
that uses SLEEP_MODE to switch between sleep enabled and disabled should recognize that
SLEEP_MODE does not reset the sleep timer. Thus, setting SLEEP_MODE to ON just before
REPEAT_TASK does not guarantee the full sleep duration. The SLEEP statement does reset the
sleep timer. See Sleep Mode Operation for more information.
Example:
TASK
:
IF SLEEP_MODE = OFF THEN
SLEEP_MODE = ON
ENDIF
:
REPEAT_TASK
END

2011 ... North Pole Engineering, Inc.

Programming Reference

4.8.6

95

UART_RX
Refer to UART_RX under Interfaces -> UART.

4.8.7

XMIT_POWER
XMIT_POWER = <n-value>
<n-variable>= XMIT_POWER
Set or read the transmit power setting. The value ranges from 0 (highest) to 7 (lowest). If
the specified value is greater than 7, the transmit power will be set to 7. If the specified
value is less than 0 the transmit power will be set to 0. The value 0 is the highest power
level.
Example:
DIM byPower AS BYTE
CONST MID_POWER = 4
TASK
:
XMIT_POWER = MID_POWER
:
byPower = XMIT_POWER
:
REPEAT_TASK
END

4.9

' Set the radio output power.


' Read the radio power setting.

Networking
The Wi-Fi commands provide access to the 802.11 wireless capabilities of the WiFi-IT! module.
These commands consolidate many wireless protocol steps into simple functional commands.
Networking
Overview

Overview of networking operations in WiFi-Basic. All users should read


this section regardless of whether they are familiar with computer
networking, as it details aspects that are specific to WiFi-Basic.
Overview of wireless settings in the Project Configuration Panel.

Wireless
Configuration
IP and Port Ranges Standard ranges for IP addresses and port numbers.
Socket Operations Commands to open, close, and manage connections as well as send and
receive data.
Network
Commands to associate and disassociate from networks, change IP
Configuration
configuration, and so forth.

2011 ... North Pole Engineering, Inc.

96

4.9.1

WiFi-IT! Basic Language Reference

Networking Overview
WiFi-Basic supports two methods of wireless communication, User Datagram Protocol (UDP)
and Transmission Control Protocol (TCP). Each of these protocols provide data connections
between the module and a remote host (which may be another WiFi-IT! module).
Socket Types:
UDP - A connectionless protocol used to transfer data between two network endpoints. UDP
provides an unreliable service and packets may not reach their intended destination. There is
no indication if a packet does not reach its intended destination. UDP assumes that error
checking and correction is either not necessary or performed in the application. This avoids
the overhead of such processing, resulting in smaller data transfers than those of TCP. Since
UDP does not establish a connection with a single remote host, it can be used for broadcast
and multicast messages simply by sending to a broadcast or multicast IP address.
Notes on using UDP sockets in WiFi-Basic:
WiFi-Basic only supports unidirectional UDP sockets. Although associated with a remote
endpoint when created, no connection is actually made when a UDP sending socket is
created. The WiFi-Basic Run Time Engine (RTE) maintains the association and supplies the
correct IP address and port number when a SEND is performed. UDP receiving sockets are
bound to a local port at the time of creation. They are capable of receiving from any network
entity. To respond to a specific host, the GET_SENDER_CID command should be used.
TCP - A connection based protocol that establishes reliable, ordered delivery of a stream of
bytes. TCP should be used in any of the following scenarios. When supporting higher level
protocols that require it (HTTP, FTP, etc.). When reliable delivery is required and
mechanisms aren't provided for this in the WiFi-Basic program. Or when connections need to
be maintained with remote hosts on an ongoing basis (i.e. logging into a service).
Connection Management:
Note: Sockets are referred to in WiFi-Basic as Connection IDs.
Network commands are used to establish, maintain and close connections with devices on
the wireless network. The directives OPEN, LISTEN, and ACCEPT are used to establish
network connections. They return a Connection ID (CID) when successful. The Connection ID
is then used on all network commands to identify which network resource is being accessed.
The maximum number of open connections for UDP is 16 receive and 16 send, for a total of
32. The maximum number of open TCP connections is limited by available memory.
Although associated with a remote endpoint in WiFi-Basic, UDP sockets are connectionless.
Calling CLOSE on a UDP socket or entering the sleep state only closes the local endpoint.
There is no indication to a remote host that a connection was closed.
TCP connections require the CLOSE directive to close both the local connection and the
remote connection.
Connection IDs (CIDs) can not be saved in STATIC variables. This is because CIDs have

2011 ... North Pole Engineering, Inc.

Programming Reference

97

networking data structures associated with them which are invisible to WiFi-Basic programs.
The state of the network manager is not maintained across sleep cycles.
For UDP operations, instead of saving CIDs, store IP and port data in STATIC variables and use
this information to open the connection each time the TASK loop is run. STATIC variables
cannot contain string variables so IP addresses need to be stored as integers. See VALIP and
IP$.
For TCP operations, all CIDs should be closed using the CLOSE directive before entering the
sleep state and new connections created after the node wakes up. If the module never
enters the sleep state, then all CIDs remain valid through successive iterations of the REPEAT
- TASK loop and do not need to be reestablished.
Connection Lifetime:
Once a CID is created, it remains active until either a CLOSE command is issued or until the
node enters the sleep state.
If a module does not enter the sleep state, active CIDs remain valid on the next pass of the
TASK - REPEAT_TASK loop. Note that having sleep enabled does not guarantee a module will
sleep when it reaches REPEAT_TASK. The module may stay awake if some operation, such as
DHCP assignment, is incomplete. If the module has not entered the sleep state before the
TASK - REPEAT_TASK loop is reentered, any CIDs created during the previous pass will still be
valid.
For UDP operations, the WiFi-Basic program can simply reissue the OPEN statement to the
same remote endpoint on each pass of the TASK - REPEAT_TASK loop. If a CID to this
endpoint already exists, that CID is returned and no new socket is created. If it does not
exist, then a new socket is opened and that CID returned. This is designed as a convenience
when running in low-power mode. The programmer does not need to worry about duplicate
connections if the module does not enter the sleep state.
For TCP operations, when running in low-power, it is strongly recommended that the WiFiBasic program CLOSE all CIDs before reaching the REPEAT_TASK statement. New connections
should be created on the next pass of the TASK - REPEAT_TASK loop. If running in always-on,
CIDs only need to be established once and remain valid for multiple passes of the TASK REPEAT_TASK loop.
IP Address Format:
Internet Protocol (IP) addresses can be represented as formatted strings or 32-bit numbers in
WiFi-Basic. IP addresses use the industry standard IPv4 representation of four decimal octets
separated by periods ("dotted-string" format) e.g. IP Address 70.125.20.18 would be written
as "70.125.20.18".
WiFi-Basic supplies conversion commands that convert IP addresses between integers and
the standard dotted-string format data types. Converting a dotted- string format IP address to
integer allows it to be stored in STATIC memory. See VALIP and IP$. Most WiFi-Basic
commands work with both string and integer versions of IP addresses. Note that commands
that return an IP address in string format use HEAP space each time they are called.
2011 ... North Pole Engineering, Inc.

98

4.9.2

WiFi-IT! Basic Language Reference

Wireless Configuration
Default wireless settings for a project are set through the Project Configuration Panel (PCP), as
shown in the image below. To edit the wireless settings, select the Device tab in the PCP.

WAP 1 - The name of the first Wireless Access Point (WAP) that the WiFi-IT! module will
attempt to join at power on or when a LINK(INFRASTRUCTURE) command is issued. The
PRIMARY keyword specifies WAP 1 settings when used as a parameter to LINK, SSID, or
CHANNEL.
SSID - The Service Set Identifier that identifies the network. This is also sometimes referred
to by other utilities as the "Network Name"
Security - Selects the type of security used on the network. Only WEP and WPA are
supported at this point.
WPA security will connect to a network with WPA or WPA2 PSK authentication using
either TKIP or AES encryption. It will not connect to an unsecured network.
WEP security uses either a 40-bit or 104-bit key. For WEP, the Security Key must be either
a 10-digit or 26-digit hexadecimal string using the characters 0 through 9 and A through F.
The WEP Key ID is always set to 0. Setting Security to WEP also prevents connection to an
unsecured network.
Important Note: Currently, the IDE requires a 10-digit or 26-digit string for WEP
security. A length other than this will fail and result in a WEP key of all zeros.
Security Key - If WEP or WPA is chosing for Security, this is the network key. If Security is set
to None, this field has no effect.
SSID Channel - The channel on which the network is operating. All wireless networks must
select a channel. Only channels 1 through 11 may be selected.
WAP 2 - The name of the second Wireless Access Point that the WiFi-IT! module will attempt to
join. This is only done if the WiFi-IT! firmware fails to scan or join the network specified by
WAP 1. The SECONDARY keyword specifies WAP 2 settings when used as a parameter to LINK,
SSID, or CHANNEL.
2011 ... North Pole Engineering, Inc.

Programming Reference

99

ADHOC - The name of an adhoc network to create if "Network(s) to Join" is set to "Adhoc" or
LINK(ADHOC) statement is executed. The ADHOC keyword specifies adhoc settings when used
as a parameter to LINK, SSID, or CHANNEL.
Notes on adhoc networks in WiFi-Basic:
The WiFi-IT! module can either create or join an adhoc network. If the network already
exists, it will simply join the existing network.
Only WEP security is supported when creating a network. Adhoc security settings should
be set to WEP or NONE.
When creating an adhoc network, DHCP cannot be used. This is because the WiFi-IT!
module does not implement a DHCP server. If DHCP is enabled, the attempt to create the
network will fail after the module's DHCP request times out.
IP Settings - The IP Settings section applies to all network configurations. It specifies the IP
configuration to be used.
Enable DHCP - Specifies that the module should request IP address, Subnet Mask, and Default
Gateway from a DHCP server upon joining a network. If DHCP is enabled and the node
associates with a network, DHCP must complete successfully. If it does not, the node
disassociates and the network connection attempt fails.
Static IP - The IP address to use for the node if not using DHCP.
Subnet Mask - The Subnet Mask to use for the node if not using DHCP.
Gateway IP Address - The Default Gateway to use for the node if not using DHCP.
Radio Settings - The radio settings specify whether the module is linked and which network to
join at startup. These settings take effect after a new project is loaded or after a cold boot.
They do not take effect for the sleep/wake cycles that are part of normal operation.
Join Network on Startup - Specifies that the module should join a network at startup. If this
checkbox is cleared, the radio receiver will remain off and the module will not join any
networks until a LINK statement is issued. Note: This w ill a lso prevent connection to the
IDE.
Important Note: If "Join Network on Startup" is cleared, the next a ttem pt to loa d a
project into tha t m odule over W iFi w ill fa il a nd the m odule w ill be locked out. This is because
when "Join Network on Startup" is cleared, it is up to the WiFi-Basic code to establish the
connection. The IDE always resets the module and halts WiFi-Basic execution before loading
new code. Even if the node is connected when the "Project Load" is started, this will cause
the node to disconnect. Without WiFi-Basic code running the module will not rejoin the
network. It will be necessary to use the UART to reload a project. It is strong ly recom m ended
tha t a ll prototype desig ns bring out U A RT0, g pio27, a nd g pio25.
Network(s) to Join - Specifies which network to join at startup. If 'Join Network at Startup' is
cleared, then this setting will be applied if a LINK statement is issued without any
parameters.
Primary - Join WAP 1 only.
Secondary - Join WAP 2 only.
Provision - Join NpeWiFiConfig only.
Infrastructure - Try WAP 1, then WAP 2, then NpeWiFiConfig in order, until a connection
2011 ... North Pole Engineering, Inc.

100

WiFi-IT! Basic Language Reference

is established.
Adhoc - Only attempt to create or join the network specified in the Adhoc settings.
Important Note: If 'Join Network at Startup' is checked, the module will be continuously
attempting to join a network until it is successful. For 'Infrastructure', this means the module
will continuously cycle through the list WAP 1, WAP 2, NpeWiFiConfig.

4.9.3

IP and Port ranges


This section describes ranges for IP addresses and port numbers that are industry standard.
These addresses and ports not specific to WiFi-Basic and are only provided as a reference.
IP Address Ranges:
IP Addresses
10.0.0.0 - 10.255.255.255

Description
Private address range that may be used by a local area network.
Number of addresses provided: 16,777,216.
172.16.0.0 - 172.131.255.255 Private address range that may be used by a local area network.
Number of addresses provided: 1,048,576.
192.168.0.0 Private address range that may be used by a local area network.
192.168.255.255
Number of addresses provided: 65,536.
224.0.0.0 - 239.255.255.255 Reserved for multicasting. These addresses are not assigned to any
network entity. Instead, nodes wishing to receive multicast
packets all register for the same IP address. A node wishing to send
the same packet to all registered hosts then sends to that IP as
though it were performing a unicast transfer.
General Port Implementation
Port Number Description
0
Reserved and should not be used.
1 - 1023
Named ports that are used by many standard applications and should be
avoided (but can be used, if desired).
1024 - 49151 Registered Ports that are used by vendors for proprietary applications.
49152 - 65535 Tempory ports primarily used by clients to communicate with servers.
8255
Local port used by WiFi-IT! module firmware to communicate with the IDE. Not
available for use when the WiFi-IT! module is in Wireless provisioning mode.
Note: This is the same port value used in the GainSpan demo apps.
Some Standard Ports
Port Number Protocol
23
TCP
25
TCP
80
TCP, UDP
110
TCP

Description
Telnet
Simple Mail Transfer Protocol (SMTP)
World Wide Web (HTTP)
Post Office Protocol (POP3)

2011 ... North Pole Engineering, Inc.

Programming Reference

161

UDP

101

Simple Network Management Protocol (SNMP)

Unless your application is communicating with a standard application (such as a web browser),
it is best to use ports in the last range (49152 - 65525), although any port will operate in WiFiBasic.

4.9.4

Notes on using TCP


TCP Connection Establishment:
TCP connection IDs maintain an established connection between two endpoints. In order to
establish a connection, one machine must act as a server, and the other as a client. The
server opens a port on which will it will accept connections (i.e. port 80 for HTTP) using the
LISTEN statement. Any number of remote machines may connect to that port using the OPEN
statement. For each connection request, the network stack on the server will accept the
connection and assign it a connection ID (CID). The Wifi-Basic program on the server may
then execute ACCEPT to retrieve these CIDs. Once established, both client and server have a
connection ID in the connected state. There is no further need to specify IP address or port
number. Data sent through one socket will arrive at the other.
TCP Connection Maintenance:
Once established, the connection IDs on both machines will remain in the connected state.
The only condition that disconnects the socket is a close or reset message occurring either
locally, or from the remote host. A network outage will not cause the connection IDs to
change state. If the network is re-established, both sides will continue to be able to send
and receive data, provided both machines retained their IP addresses. If one end of the
connection is attempting to send data while the network is down, it will time out after a
maximum of eight minutes. At this point, the connection ID switches to a reset state. If the
network is re-established before the send operation times out, then the data will be sent
successfully, and the connection ID will not reset.
Both sides of a connection maintain their state independently. If one host resets or closes its
connection ID, it will send a notification to the other host. If communication is lost, this
packet will not reach its destination, and the other host will not know the connection is
terminated. If communication is re-established after one host has closed the connection, the
other host will find out once it attempts to send data, at which point it will receive a reset
notification.
TCP Message Delivery:
Delivery of data over TCP connections is handled automatically by the network stack. There
is no need for the WiFi-Basic program to intervene. If data is unable to be delivered, it is
stored in a local send buffer and periodically retried until successful. The network stack
continues attempting to resend until all data has been acknowledged by the remote host, or
the send attempt times out (approx eight minutes), at which point the socket is put in a reset
state. The status of the send buffer can be queried using POLL_SEND.
TCP Connection Reset:

2011 ... North Pole Engineering, Inc.

102

WiFi-IT! Basic Language Reference

Once a connection ID has been placed in a reset or shutdown state, it can no longer be used
to send data, and a new connection (and connection ID) should be established. A socket will
be reset if a send attempt times out, or if the remote host sends a reset notification. If
ETIMEDOUT, ECONNRESET, ESHUTDOWN, or ENOTCONN errors are ever returned on a SEND or
RECEIVE operation, that connection ID should be CLOSEd and a new connection established.
Stream vs. Datagram:
TCP sockets are by definition stream sockets, as opposed to UDP, which are datagram. If you
are familiar with the STDIO family of operations in C, then you are familiar with streams. No
distinction is made to how data is packetized at the source. If multiple SEND statements are
issued from a source module before the destination module issues a RECEIVE, then the
destination module will receive the data as though it were one packet. Note that even if
data is sent infrequently, this does not guarantee multiple packets will not be bundled
together at the destination. For example, if a network outage occurs long enough for 2 or
more packets to have been sent from the source, when the network is re-established, the
destination will receive this data all at once. UDP sockets will keep packets separate, even if
multiple packets arrive before they are read at the destination.
TCP and Low Power:
Since TCP is bi-directional, and requires hand-shaking in both directions, any WiFi-IT modules
using TCP must be running with their radio receivers enabled.
Also, state information for connection IDs is maintained in the network stack, and will be lost
if a module goes into the low-power sleep state. This effectively terminates the connection,
but does not inform the remote host that the connection has been closed. Any module
wishing to transition to low-power mode should close all TCP connections using the CLOSE
statement. If unacknowledged data is still waiting in the connection ID's send buffer or the
remote host does not acknowledge the close, the socket is in a close pending state. The
CLOSE statement is non-blocking and does not wait for these operations to complete. See
CLOSE for more details.
Important Note: If the WiFi-Basic program fails to CLOSE all TCP sockets before entering
sleep mode, the run time engine will attempt a force close on all sockets that remain open.
A FIN packet will go out to all servers (or clients) still maintaining connections with the
module. The module will not remain awake more than 4 or 5 milliseconds to accomplish this.
If there are several open connections, the RTE is not guaranteed to send a FIN packet for
every open connection. The purpose of the FIN packet is to allow remote servers to free
socket resources for connections that no longer exist. It is strongly recommended that WiFiBasic programs do their own cleanup and close all TCP sockets before entering sleep mode.

4.9.5

Socket Operations
These statements allow the creation and management of connections, as well as sending and
receiving data.
ACCEPT
CLOSE

2011 ... North Pole Engineering, Inc.

Programming Reference

103

GET_SENDER_CID
GET_SENDER_IP
GET_SENDER_PORT
LISTEN
OPEN
POLL
POLL_SEND
RECEIVE
SEND
4.9.5.1

ACCEPT

<server-side CID> = ACCEPT <listen CID>


ACCEPT is only intended to be used with TCP connection IDs created using the LISTEN
statement. ACCEPT checks the CID to see if any clients have waiting connection requests. If
so, a connection is established, the client's SYN packet is ACKed, and a connection ID is
returned representing the server side of the connection. ACCEPT is non-blocking and
returns -1 if no clients are waiting. ACCEPT only creates one connection at a time,
regardless of how many clients may be waiting.
Note that once a TCP listen socket is created on a port, the network stack will always be
accepting connections on that port, until the socket is closed. If a client requests a
connection, that is handled in the background to WiFi-Basic execution. When ACCEPT is
called, it returns the CID for the already existing connection.
Runtime Errors:
Error Code
EPREM
EAGAIN
EOPNOTSUPP
EBADCID

Error Description
<listen CID> is not a listen socket. See LISTEN.
There were no clients waiting connection.
<listen CID> is a UDP, not a TCP socket.
Not a valid Connection ID.

Example:
DIM ListenCID AS INTEGER
DIM ServerCID AS INTEGER
TASK
ListenCID = LISTEN TCP 9535
' Accept connections on port 9535
DO
ServerCID = ACCEPT ListenCID
' Wait for client to connect
UNTIL ServerCID >= 0
:
' Socket operations
:
CLOSE ServerCID
REPEAT_TASK
END

2011 ... North Pole Engineering, Inc.

104

4.9.5.2

WiFi-IT! Basic Language Reference

CLOSE

CLOSE UDP | TCP <connection ID>


Close the connection associated with the <connection ID>. Upon completion of this
command the <connection ID> becomes invalid.
For TCP connections, a FIN packet is sent to the remote host, instructing it to close its side of
the connection as well. CLOSE is non-blocking, but successful return does not mean the
socket is closed. This does not occur until the remote host has acknowledges the FIN packet
and any remaining data. During this period attempts to call SEND or RECEIVE will return
ESHUTDOWN. All commands return EBADCID once the socket is closed. The network stack
will retry the FIN packet for up to nine minutes before issuing a RST and closing the packet.
The CLOSE operation is non-blocking to allow the WiFi-Basic program to initiate the close
sequence on multiple sockets at the same time. The program can then decide how long to
wait before transitioning to standby. The program can check the status of a CLOSE operation
by issuing another CLOSE command and checking the ERROR value. EALREADY means it is
not complete. EBADCID means it is complete.
Runtime Errors for UDP:
Error Code Error Description
EBADCID
Not a valid Connection ID.
Runtime Errors for TCP:
Error Code Error Description
EALREADY Close was already called on this Connection ID but the remote host has not yet
acknowledged the close.
EBADCID
Not a valid Connection ID.
Example:
DIM ServerCID AS INTEGER
TASK
ServerCID = OPEN UDP "70.125.20.18", 9535
:
CLOSE ServerCID
REPEAT_TASK
END

4.9.5.3

GET_SENDER_CID

<i-variable> = GET_SENDER_CID
Opens a UDP connection to the remote sender of the last packet received using RECEIVE. On
successful completion a Connection ID (CID) is returned. The CID can then be used to reply to
the remote host that sent the packet.
Important Note:
GET_SENDER_CID is for use with UDP sockets only.

2011 ... North Pole Engineering, Inc.

Programming Reference

105

Runtime Errors:
Error Code
Error Description
ENOSENDER
No data has been received from a remote host on any UDP sockets since
the last wake/power-on event.
ENOMEM
Not enough memory.
ECIDLIMIT
Maximum number of send connections open.
Example:
DIM
DIM
DIM
DIM

CID
cidSender
iCount
byPacket(255)

AS
AS
AS
AS

INTEGER
INTEGER
INTEGER
BYTE

CONST DATA_AVAIL = 1
TASK
CID = LISTEN UDP 9000
IF CID <> -1 THEN
DO
UNTIL POLL(CID) = DATA_AVAIL

' Open a port to listen for messages.


' Connection is open!
' Wait to receive a message.

iCount = RECEIVE CID, byPacket


'Now we have the data but we don't know who it is from.
cidSender = GET_SENDER_CID
' Now we have a connection to respond to.
:
' Build a response message.
iCount = SEND cidSender, byPacket(100), 20 ' Send a response.
ENDIF
REPEAT_TASK
END

4.9.5.4

GET_SENDER_IP

<si-variable> = GET_SENDER_IP
Returns the IP address of the remote sender of the last packet received using RECEIVE.
Important Note:
GET_SENDER_IP is for use with UDP sockets only.
Runtime Errors:
Error Code
Error Description
ENOSENDER
No data has been received from a remote host on any UDP sockets since
the last wake/power-on event.
ENOMEM
Insufficient heap space to allocate string (when assigning to <s-variable>).
See example in GET_SENDER_PORT.

2011 ... North Pole Engineering, Inc.

106

4.9.5.5

WiFi-IT! Basic Language Reference

GET_SENDER_PORT

<n-variable> = GET_SENDER_PORT
Returns the port number of the remote sender of the last packet received using RECEIVE.
Important Note:
GET_SENDER_PORT is for use with UDP sockets only.
Runtime Errors:
Error Code
Error Description
ENOSENDER
No data has been received from a remote host on any UDP sockets since
the last wake/power-on event.
Example:
DIM
DIM
DIM
DIM
DIM
DIM

CID
cidSender
iCount
iPort
byPacket(255)
sIPadrs

AS
AS
AS
AS
AS
AS

INTEGER
INTEGER
INTEGER
INTEGER
BYTE
STRING

CONST DATA_AVAIL = 1
TASK
CID = LISTEN UDP 9000
IF CID <> -1 THEN
DO
UNTIL POLL(CID) = DATA_AVAIL
iCount = RECEIVE

'Open a port to listen for messages.


'Connection is open!
'Wait to receive a message.

CID, byPacket

'Now we have the data but we don't know who it is from.


sIPadrs = GET_SENDER_IP
iPort = GET_SENDER_PORT
cidSender = OPEN UDP sIPadrs, iPort
'Now we have a connection to remote
host.
:
'Build a response message.
iCount = SEND cidSender, byPacket(100), 20 'Send a response.
ENDIF
REPEAT_TASK
END

4.9.5.6

LISTEN

<i-variable> = LISTEN UDP | TCP <port#>


Open a receiving socket and bind it to a local port. If the socket is successfully opened a
connection ID is returned in <i-variable>. If the socket could not be opened, -1 is returned.
Connection IDs are integer values.
If a UDP connection was opened, the new connection is capable of receiving data using the
RECEIVE statement and will receive data from any host.
2011 ... North Pole Engineering, Inc.

Programming Reference

107

If a TCP connection was opened, the connection ID is a server side socket capable of
accepting new clients. It cannot be used to send or receive data. ACCEPT must be called on
the connection ID to accept any incoming connection requests.
Runtime Errors (errors are same for UDP and TCP):
Error Code
Error Description
ENOMEM
Not enough memory.
ECIDLIMIT
Maximum number of receive connections open.
EADDRINUSE
The requested port is already in use.
Important Note: The WiFi Basic Run Time Engine uses port 8255 to communicate with the
IDE. Attempting to open a socket on this port while in WiFi provisioning mode will result in an
EADDRINUSE error.
Example:
DIM ServerCID
DIM ClientCID

AS INTEGER
AS INTEGER

TASK
ClientCID = OPEN UDP "70.125.20.18", 9585
ServerCID = LISTEN UDP 9584
IF ClientCID <> -1 AND ServerCID <> -1 THEN
'A connection is open in both directions we can start communication
:
ENDIF
REPEAT_TASK
END

4.9.5.7

OPEN

<i-variable> = OPEN UDP | TCP <destination IP address>, <port#>


Open a UDP or TCP socket on the wireless interface, to send data to a specified <destination
address> and <port#>. The <destination IP address> (see VALIP) may be an integer variable or
a string value. Upon successful completion a connection ID is returned in <i-variable>. If the
command is unsuccessful, -1 is returned in <i- variable>. Connection IDs are integer values.
Once the connection has been successfully opened data may be sent to the specified
destination using the SEND command. To close the socket, issue the CLOSE command.
For UDP operations, OPEN may be called multiple times to the same destination. This will
return the same connection ID assigned during the first OPEN statement. This makes it easy
for low-power wireless sensor apps to simply call OPEN at the top of the TASK - REPEAT_TASK
loop without worrying whether the module actually went to sleep.
For TCP operations, OPEN always returns a unique connection ID, even if called on a
previously connected endpoint. Opening a TCP socket will attempt to establish a connection
to the remote host and wait for a handshake to occur. The remote host must be listening for
connections on the specified port. If the remote host is listening but declines the
2011 ... North Pole Engineering, Inc.

108

WiFi-IT! Basic Language Reference

connection, then OPEN will fail with an ECONNREFUSED error. OPEN TCP creates the client
side of a TCP connection.
Important Note: OPEN TCP is a blocking operation that will retry for up to 75 seconds.
The WiFi-Basic program remains blocked during this time period.
If the command fails <i-variable> will be equal to -1 (ERRORFLAG), and the system variable
ERROR will contain specific information about the failure.
Runtime Errors for UDP:
Error Code Error Description
ENOMEM
Not enough memory.
EINVAL
Invalid parameter.
ECIDLIMIT Maximum number of send connections open.
Runtime Errors for TCP:
Error Code
Error Description
ENOMEM
Not enough memory.
EINVAL
Invalid parameter.
EADDRNOTAVAIL
Invalid IP address.
ETIMEOUT
No response from remote host.
ECONNREFUSED
Remote host refused the connection.
EHOSTUNREACH
Remote host is unreachable.
ECIDLIMIT
Maximum number of connections open.
Example:
DIM cidClient AS INTEGER
TASK
cidClient = OPEN UDP "192.168.0.200", 8555
IF cidClient <> -1 THEN
' Connection is open!
:
ELSE
' Connection attempt failed!
:
ENDIF
REPEAT_TASK
END

4.9.5.8

POLL

{<n-variable> =} POLL <Connection ID>


Return a flag indicating the status of the specified Wi-Fi connection (CID). There are three
states in which a connection may exist; Data Available, No Data and Error. These three states
are enumerated below.
Note: This is equivalent to performing a select operation as defined by the BSD socket API to
check for read conditions on a socket.
2011 ... North Pole Engineering, Inc.

Programming Reference

109

Important Note:
POLL will return 1 on a TCP socket that has shutdown send and receive operations due to an
error such as ETIMEDOUT or ECONNRESET. In this case, RECEIVE will still return -1 and the
respective error code.
State
1
0
-1

Description
Data Available. A message has been received and is pending.
No Data Available.
Error. An error has occurred and the system variable ERROR contains the reason

Runtime Errors:
Error Code Error Description
EBADCID
Not a valid Connection ID.
Example:
DIM cidClient
DIM iCState
DIM bExitFlag

AS INTEGER
AS INTEGER
AS INTEGER

CONST DATA_AVAIL = 1
TASK
cidClient = OPEN UDP "192.168.0.200", 8555
IF cidClient <> -1 THEN
bExitFlag = 0
DO
'Connection is open! Wait to receive a message.
iCState = POLL(cidClient)
IF iCState = ERRORFLAG THEN
bExitFlag = -1
EXITDO
'An error occurred; exit wait loop.
ENDIF
UNTIL iCState = DATA_AVAIL
IF bExitFlag = 0 THEN
:
ELSE
:
ENDIF
ENDIF
REPEAT_TASK
END

4.9.5.9

'Receive data and handle it.


'Handle error.

POLL_SEND

{<n-variable> =} POLL_SEND <Connection ID>

TCP sockets only

Return the number of bytes in the connection ID's send queue still waiting
acknowledgment from the remote host.
Important Note: An error state on the socket will cause POLL_SEND to return 0, even if
2011 ... North Pole Engineering, Inc.

110

WiFi-IT! Basic Language Reference

data was not successfully sent. This is because certain error states, such as ETIMEDOUT and
ECONNRESET will cause the send buffer to empty. To verify an error has not occurred on the
socket, a dummy SEND or RECEIVE call should be issued to determine the socket's error
status.
Runtime Errors:
Error Code
EBADCID

Error Description
Not a valid Connection ID.

Example:
DIM
DIM
DIM
DIM
DIM

Status
Msg(9)
ClientCID
i
bytesUnsent

AS
AS
AS
AS
AS

INTEGER
BYTE
INTEGER
INTEGER
INTEGER

TASK
FOR i = 0 TO 9
Msg (i) = 100 + i
NEXT

' Build message.

ClientCID = OPEN TCP "70.125.20.18", 9585


IF ClientCID <> ERRORFLAG THEN
Status = SEND ClientCID, Msg(0), 10
(9).
DO
bytesUnsent= POLL_SEND ClientCID
UNTIL bytesUnsent = 0
CLOSE ClientCID
ENDIF
REPEAT_TASK
END

' Open connection.


' Send 10-bytes; Msg(0) to Msg

' Wait for data to send

4.9.5.10 RECEIVE

<n-variable> = RECEIVE UDP | TCP <connection ID>, <b-array>


This command is used to receive data from the WiFi connection specified by <connection ID>.
For UDP connections, a wireless connection must be created using LISTEN before calling
RECEIVE. The <connection ID> is the value returned by LISTEN.
For TCP connections, a wireless connection must be created using OPEN or ACCEPT before
calling RECEIVE.
RECEIVE is used to receive packets, so <b-array> is defined as an array of byte values. The
array should be sized so that the largest packet expected will fit. The actual number of bytes
received is returned in <n-variable>. You should not specify an index to <b-array>, only the
base name of the array should be specified.
Note that UDP receiving sockets are not associated with any remote endpoints. Thus they
2011 ... North Pole Engineering, Inc.

Programming Reference

111

will receive packets from all remote hosts addressed to the port to which they are bound.
NOTE: If a data packet has been received and is larger than the defined size of <b-array>, the
bytes beyond the length of the receive buffer will be lost.
This is a non-blocking call, so if no data is available the command returns immediately with
<n-variable> set to zero.
If <n-variable> contains -1 an error has occurred. To determine the error type, use the system
variable ERROR immediately after receiving the error indicator, when in passive error
handling mode (see Error Handling).
Runtime Errors for UDP:
Error Code
Error Description
EBADCID
Not a valid Connection ID.
Runtime Errors for TCP:
Error Code
Error Description
EBADCID
Not a valid Connection ID.
ECONNRESET
Connection has been reset either locally or by remote host.
ESHUTDOWN
Connection is no longer allowed to receive data.
ENOTCONN
This connection ID is no longer connected to a remote host.
Example:
DIM ByteCnt
AS INTEGER
DIM byData(127) AS BYTE
DIM cidTemp
AS INTEGER

' Largest message is 128 bytes long.

TASK
cidTemp = LISTEN UDP 9585
' Open a UDP port to receive messages.
IF cidTemp <> -1 THEN
DO
ByteCnt = RECEIVE cidTEMP, byData
' byData, has no index specified!
UNTIL ByteCnt <> 0
' Wait for a message to come in.
ENDIF
REPEAT_TASK
END

4.9.5.11 SEND

{<n-variable> =} SEND UDP | TCP <connection ID>, <b-array>, <n-value>


The SEND command is used to transmit data over the wireless network to the remote
endpoint associated with <connection ID>. SEND requires three parameters, a connection ID,
the data to send and the number of bytes of data to send.
Before calling SEND a connection must be created using the OPEN or ACCEPT statements. The
<connection ID> is the value returned by OPEN or ACCEPT. The data to send, <b-array>, must
be a byte array. The <n-value> field specifies the number of bytes of <b-array> to send.
When SEND competes, if <n-variable> contains -1, an error has occurred. To determine the
error type, use the system variable ERROR immediately after receiving the error indication.
2011 ... North Pole Engineering, Inc.

112

WiFi-IT! Basic Language Reference

SEND operations for TCP are non-blocking. Successful return from the SEND statement does
not mean all data has been delivered. Use the POLL_SEND statement to determine how
many unacknowledged bytes remain in the send buffer.
Runtime Errors for UDP:
Error Code
Error Description
EINVAL
Improper length argument.
EHOSTDOWN
Destination is unreachable.
EHOSTUNREACH
No route to destination host.
EMSGSIZE
Message is too long to be sent atomically.
EBADCID
Not a valid Connection ID.
Runtime Errors for TCP:
Error Code
Error Description
EINVAL
Improper length argument.
EHOSTUNREACH
No route to destination host.
ECONNRESET
Connection has been reset either locally or by remote host
ESHUTDOWN
Connection is no longer allowed to send data.
ETIMEDOUT
SEND failed to transmit previous TCP data.
EBADCID
Not a valid Connection ID.
Example:
DIM
DIM
DIM
DIM

Status
Msg(9)
ClientCID
i

AS
AS
AS
AS

INTEGER
BYTE
INTEGER
INTEGER

TASK
FOR i = 0 TO 9
Msg (i) = 100 + i
NEXT

' Build message.

ClientCID = OPEN UDP "70.125.20.18", 9585


IF ClientCID <> ERRORFLAG THEN
Status = SEND ClientCID, Msg(0), 10
(9).
ENDIF
:
REPEAT_TASK
END

4.9.6

' Open connection.


' Send 10-bytes; Msg(0) to Msg

Network Configuration
These statements allow updates to the network configuration and allow association and
disassociation with specific networks at runtime.
CHANNEL
DHCP
GATEWAY
2011 ... North Pole Engineering, Inc.

Programming Reference

113

IP$
IP_ADDRESS
LINK
LINKED?
MAC_ADDRESS
PASSPHRASE
RSSI
SECURITY
SCAN
SCAN_RESULT
SCAN_ELEMENT
SSID
SUBNET
UNLINK
VALIP
WEPKEY
4.9.6.1

CHANNEL

<n-value> = CHANNEL(n-value)
CHANNEL(n-value) = <n-value>

EDK+ only

The CHANNEL directive sets or returns the Wi-Fi channel of the specified wireless network
identifier. The CHANNEL Identifiers are defined as intrinsic constants in WiFi-Basic. It is best
to use the intrinsic constant, instead of the numeric value, since these values may change
between versions of WiFi-Basic.
WiFi-Basic supports four different SSIDs:
SSID
Identifier
CURRENT

nvalue
0

PRIMARY
SECONDARY
PROVISION

1
2
3

ADHOC

Read
Definition
Only
Yes Returns the channel number of the currently connected
wireless network.
No Return/Set the WAP 1 channel number.
No Return/Set the WAP 2 channel number.
Yes Return the value of the provisioning SSID channel number.
NOTE: The provisioning channel can not be changed.
No Return/Set the ADHOC channel number.

If the channel number for the currently connected network is changed, these changes do not
take effect until the node has disconnected and rejoined a network. For example, assume WAP
1 is set to SSID = "NpeDemo" on channel 2 and the node is connected on this network. If the
WiFi-Basic program executes CHANNEL(PRIMARY)=4, the node stays connected on channel 2.
The new setting for channel 4 only takes effect on the next rejoin attempt. The WiFi-Basic
program can force this by issuing an UNLINK, followed by LINK(PRIMARY). It would also occur if
the network connection was lost, at which point the node attempts to rejoin on channel 4.
Runtime Errors:
2011 ... North Pole Engineering, Inc.

114

WiFi-IT! Basic Language Reference

Error Code Error Description


EINVAL
Invalid parameter.
ENOTCONN Not connected to a network.
Example:
' This example assumes that each SSID uses a unique channel.
DIM iChannel
DIM priChannel

AS INTEGER
AS INTEGER

TASK
iChannel = CHANNEL(CURRENT)
' Get the currently connected channel number.
priChannel = CHANNEL(PRIMARY)
IF iChannel = priChannel THEN
'Connected to the primary WAP, UNLINK to change the channel.
UNLINK
IF LINKED? = 0 THEN
CHANNEL(PRIMARY) = 1
LINK(INFRASTRUCTURE)
ENDIF
ENDIF
REPEAT_TASK
END

4.9.6.2

DHCP

DHCP = <n-value>
<n-variable> = DHCP
Enables or disables use of the Dynamic Host Configuration Protocol (DHCP) when joining a
network. When enabled, the node will request an IP configuration from the DHCP server
upon joining a network. When DHCP is disabled (=0) the WiFi-IT module must be manually
configured with a static IP address that resides on the subnet in which the module will be
communicating.
NOTE: Default DHCP and IP configuration settings can be setup in the Wireless
Configuartion panel of the PCP.
NOTE: DHCP settings take effect on the next join attempt. If the module is already
associated with a network when the DHCP setting is modified, the module will not change
its IP configuration. If DHCP is turned off, and DHCP has already been completed, the
module will retain the IP address last assigned by DHCP, until changed by the IP_ADDRESS
command. A rejoin attempt will occur if the network connection is lost, or can be forced
using the UNLINK and LINK commands.
DHCP Setting n-value
ON
Nonzer
o
OFF
0

Description
The WiFi-IT! module will request an IP address from the local
DHCP server.
The WiFi-IT! module must be manually configured to
communicate on the associated network.
2011 ... North Pole Engineering, Inc.

Programming Reference

4.9.6.3

115

GATEWAY

<si-variable> = GATEWAY
GATEWAY = <si-value>

EDK+ only

The GATEWAY directive sets or returns the Internet Protocol address of the default
gateway. If DHCP is enabled and a set GATEWAY directive is issued an error will occur. DHCP
must be disabled before changing the GATEWAY setting.
NOTE: Changes to GATEWAY address take effect immediately. If GATEWAY is updated while
connected to a network, the network interface is reset. Resetting the network interface is
not the same as rejoining the network. It simply allows the IP configuration to be updated
to the network. The WiFi-IT! module stays associated to the current network during a
network interface reset.
The following tables describe the behavior of the WiFi-IT! module when reading or writing
GATEWAY.
Value returned by GATEWAY:
DHCP is enabled
DHCP is disabled

Node is connected
Currently assigned default
gateway
Currently assigned default
gateway

Behavior when assigning IP_ADDRESS:


Node is connected
DHCP is enabled
Error ECONFIG
DHCP is disabled
IP configuration updated.
Network interface reset.

Node is not connected


0.0.0.0
Last value assigned in the
PCP, or by the GATEWAY
command
Node is not connected
Error ECONFIG
IP configuration updated.

Runtime Errors:
Error Code Error Description
ECONFIG
GATEWAY cannot be changed while DHCP is enabled.
About Subnetting
See SUBNET for notes about subnetting.
4.9.6.4

IP$

<s-variable> = IP$ (<n-value>)


Return the IP address in dotted-string format. The <n-value> should be an IP address or the
returned string is meaningless. This function is generally used when the dotted-string format
of an IP address is required. VALIP reverses the operation, converting an IP address in dottedstring format to an integer value.
2011 ... North Pole Engineering, Inc.

116

WiFi-IT! Basic Language Reference

NOTE: Many of the commands that require IP addresses will use either dotted-decimal string
or numeric IP addresses.
Runtime Errors:
Error Code Error Description
ENOMEM
Insufficient heap space to allocate string.
EINVAL
Invalid parameter
4.9.6.5

IP_ADDRESS

<si-variable> = IP_ADDRESS
IP_ADDRESS = <si-value>
The IP_ADDRESS directive sets or returns the Internet Protocol address assigned to the
WiFi-IT! module. If DHCP is enabled and a set IP_ADDRESS directive is issued an error will
occur. DHCP must be disabled before changing the IP_ADDRESS setting.
NOTE: Changes to IP_ADDRESS take effect immediately. If IP_ADDRESS is updated while
connected to a network, the network interface is reset. Resetting the network interface is
not the same as rejoining the network. It simply allows the IP configuration to be updated
to the network. The WiFi-IT! module stays associated to the current network during a
network interface reset.
The following tables describe the behavior of the WiFi-IT! module when reading or writing
IP_ADDRESS.
Value returned by IP_ADDRESS:
DHCP is enabled
DHCP is disabled

Node is connected
Current IP address
Current IP address

Behavior when assigning IP_ADDRESS:


Node is connected
DHCP is enabled
Error ECONFIG
DHCP is disabled
IP configuration updated.
Network interface reset.

Node is not connected


0.0.0.0
Last value assigned in the
PCP, by the IP_ADDRESS
command, or by DHCP.
Node is not connected
Error ECONFIG
IP configuration updated.

Runtime Errors:
Error Code Error Description
ECONFIG
IP_ADDRESS cannot be changed while DHCP is enabled.
Example:
DIM
STATIC

sIP
iOldIP

AS STRING
AS INTEGER

TASK

2011 ... North Pole Engineering, Inc.

Programming Reference

117

IF DHCP = FALSE THEN


' It is ok to change our IP address.
iOldIP = IP_ADDRESS
' Save previous IP address.
IP_ADDRESS = "192.168.33.101"
' Set IP address to a prearranged value.
ENDIF
:
REPEAT_TASK
END

4.9.6.6

LINK

LINK
LINK (n-value)

EDK / EDK+
EDK+ only

There are two versions of the LINK statement: with and without a parameter. LINK with a
parameter is available in the EDK+ version only. It allows selection of a different network than
was selected in the Project Configuration Panel. LINK without a parameter will associate with
the network specified in the Project Configuration Panel. If a previous LINK statement has
changed the network selection, then the new setting will be used.
LINK associates or attempts to create the specified wireless network type. The parameter is
limited to the values shown in the table below. Values beyond those specified in the table will
cause a compiler and/or runtime error.
SSID Identifier n-value Definition
PRIMARY
1 Attempt to join the network specified by WAP 1. If that fails, stay
disconnected.
SECONDARY
2 Attempt to join the network specified by WAP 2. If that fails, stay
disconnected.
PROVISION
3 Attempt to join the provisioning network, which is always
"NpeWiFiConfig" on channel 6. If that fails, stay disconnected.
ADHOC
4 Attempt to join the network specified by the adhoc settings, or
create the network if it does not exist.
INFRASTRUCTU 5 First attempt to join WAP 1. If that fails, attempt to join WAP 2. If
RE
that fails, join the provisioning network. If that fails, stay
disconnected.
NOTE: LINK is a blocking operation. When LINK returns association, authentication, and IP
configuration (DHCP if enabled) are all complete. Or alternatively, one of the above steps has
failed and the node is no longer attempting to join a network. LINK can take anywhere from 10s
of milliseconds to several seconds to complete depending on what needs to be done. The
worst case scenario would be joining a WPA protected network for which the WiFi-Basic RTE has
the passphrase but has not yet calculated the pre-shared key (PSK).
Important Note:
Issuing a LINK command disconnects from the current network (if currently connected). Only
one attempt is made to join the network (or each network in the case of LINK(INFRASTRUCTURE)
). If the attempt fails, the module stays disconnected and no further attempts are made. If the
2011 ... North Pole Engineering, Inc.

118

WiFi-IT! Basic Language Reference

attempt succeeds, the module will attempt to maintain connection, even through disruptions in
network availability.
Runtime Errors:
Error Code
EINVAL
ENONWFOUND

Error Description
Invalid parameter.
The network connection attempt failed.

See the example in UNLINK.

4.9.6.7

LINKED?

{<n-variable> =} LINKED?
Leave a true flag if a wireless connection to an existing network is active or if an ad hoc
network has been successfully created. LINKED? may be used in a comparison operation to
execute code that depends on the linked network state.
NOTE: There are states besides connected and disconnected that represent a join operation
in progress. The node must complete association, authentication - if security is enabled,
and DHCP - if enabled, before LINKED? will return TRUE.
LINKED? returns the current state of the network. If the module was connected, but the
connection was lost, the module may be attempting to reconnect, but LINKED? will return
FALSE.
See Example: UNLINK
4.9.6.8

MAC_ADDRESS

{<sb-variable> =} MAC_ADDRESS
Return the local Media Access Control address as a string or as a byte array.
When assigned to a string, the MAC address is returned in the following format:
xx:xx:xx:xx:xx:xx
where xx represents two hexadecimal characters.
Each group of two hexadecimal characters is separated by a colon. There are six groups of
hexadecimal characters per MAC address.
When assigned to a byte array, the 6 consecutive bytes are overwritten in the byte array.
Runtime Errors:
Error Code Error Description
ENOMEM
No heap space memory available to build string.
Example1:
' Variables
DIM
sMyMacAdrs

AS STRING

TASK
2011 ... North Pole Engineering, Inc.

Programming Reference

119

sMyMacAdrs = MAC_ADDRESS
' Returns the local MAC address.
OUTPUT UART0 "My MAC Address = " & sMyMacAdrs & CHR$(10)
DELAY 5000
REPEAT_TASK
END

Example2:
' Variables
DIM
dataPkt(31)
DIM
sendCid

AS BYTE
AS INTEGER

TASK
' Send the MAC address as part of a data packet.
...
' Assign the MAC address to bytes 2 through 7
dataPkt(2) = MAC_ADDRESS
...
SEND sendCid, dataPkt(0), 32
...
REPEAT_TASK
END

4.9.6.9

PASSPHRASE

<s-variable> = PASSPHRASE(<n-value>)
PASSPHRASE(<n-value>) = <s-value>

EDK+ only

PASSPHRASE is used to read or modify the passphrase of a WPA protected network. The
passphrase of a network may be modified even if WPA encryption is not currently enabled
on that network. The passphrase is stored in non-volatile flash and will take effect the next
time a network join is performed on that network with WPA encryption enabled. This could
be from a LINK statement or from a power-cycle. If the passphrase is changed while
currently connected to a network, the new setting does not take effect until another
connection attempt is made. A passphrase must be between 8 and 63 characters in length.
All alphanumeric, punctuation, and space are allowed.
Important Note: The passphrase is not the PSK (pre-shared key). After setting a new
passphrase, the PSK must still be calculated. This will occur on the next connection
attempt. If this is during a LINK statement, the command will block for about 15 seconds
while generating the PSK. If this happens in the background due to network loss and
automatic reconnection attempt, or due to power-cycle, the run-time engine will divert
processor resources. This will cause the WiFi-Basic interpreter to become starved out for
about 15 seconds at a random point in code execution. Thus it is recommended to perform
an UNLINK before changing the passphrase and control generation of the PSK using the LINK
statement.
<n-value> must be one of the following intrinsic constants.
SSID
nRead
Definition
Identifier value Only

2011 ... North Pole Engineering, Inc.

120

WiFi-IT! Basic Language Reference

CURRENT

Yes

PRIMARY
SECONDARY
PROVISION

1
2
3

No
No
Yes

Runtime Errors:
Error Code
ENOMEM
EINVAL
ENAMETOOLONG
ENOTCONN
network.

Return the passphrase string value of the currently connected


wireless network.
Note: If the passphrase is modified while currently connected
to a WPA encrypted network, PASSPHRASE(CURRENT) will
continue to return the passphrase currently in use.
Return/Set the passphrase string for WAP 1.
Return/Set the passphrase string for WAP 2.
Return the passphrase string of the provisioning SSID.

Error Description
No heap space memory available to build string.
Invalid SSID Identifier or invalid character in passphrase string.
The passphrase string is too long.
Attempt to read PASSPHRASE(CURRENT) while not connected to a

Example:
' This example assumes the module is connected to WAP 1 and
' that security settings for WAP 1 are set to WPA-PSK.
' Variables
DIM
inputAryIdx
DIM
bytesRead
DIM
buffer(3)
DIM
inputAry(127)
DIM
inputStr
' Constants
CONST
ENTER
CONST
BACKSPACE

AS
AS
AS
AS
AS

INTEGER
INTEGER
BYTE
BYTE
STRING

= 0x0D
= 0x08

TASK
IF LINKED? = FALSE THEN
DELAY 1000
QUIT
ENDIF
OUTPUT UART0 "Current network passphrase = " & PASSPHRASE(CURRENT) & CHR$(10)
UNLINK
OUTPUT UART0 "Enter new passphrase"
GOSUB InputString
PASSPHRASE(PRIMARY) = inputStr
OUTPUT UART0 "Trying new passphrase. Allow 15 seconds to generate PSK." & CHR$
(10)
LINK(PRIMARY)
IF LINKED? THEN
OUTPUT UART0 "Passphrase accepted" & CHR$(10)
ELSE

2011 ... North Pole Engineering, Inc.

Programming Reference

121

OUTPUT UART0 "Passphrase rejected" & CHR$(10)


ENDIF
REPEAT_TASK
SUB InputString
OUTPUT UART0 "# "
inputAryIdx = 0
DO
DELAY 10
bytesRead = INPUT UART0 buffer
IF bytesRead <> 0 THEN
IF buffer(0) <> ENTER THEN
IF buffer(0) = BACKSPACE THEN
IF inputAryIdx > 0 THEN
inputAryIdx = inputAryIdx - 1
OUTPUT UART0 buffer(0), 1
ENDIF
ELSE
inputAry(inputAryIdx) = buffer(0)
inputAryIdx = inputAryIdx + 1
OUTPUT UART0 buffer(0), 1
ENDIF
ENDIF
ELSE
buffer(0) = 0
ENDIF
UNTIL(buffer(0) = ENTER)
inputStr = TOSTRING( inputAry, 0, inputAryIdx )
OUTPUT UART0 CHR$(10)
RETURN
ENDSUB
END

4.9.6.10 RSSI

<i-variable> = RSSI
Return the Received Signal Strength Indicator as an integer value. RSSI values are returned
as negative numbers. The more negative the number the weaker the signal. Generally, RSSI
values of -70 or less indicate a poor connection.
Example:
DIM RcvPower
AS INTEGER
DIM byRSSIvalue(4) AS BYTE
DIM CID
AS INTEGER
DIM I
AS INTEGER
TASK
:
RcvPower = RSSI
FOR I = 0 TO 3

2011 ... North Pole Engineering, Inc.

' We have setup a network connection.

122

WiFi-IT! Basic Language Reference

byRSSIvalue(i) = RcvPower
RcvPower = RcvPower SHR 8

' Shift next byte into position.

NEXT
SEND CID, byRSSIvalue(0), 4
REPEAT_TASK
END

' Send RSSI value to host.

4.9.6.11 SCAN

<i-variable> = SCAN
EDK+ only
Perform a passive scan for nearby networks. SCAN returns the number of networks found.
Use SCAN_RESULT to iterate through the results and SCAN_ELEMENT to read the elements
of each network.
Important Note: Active scanning is not supported at this time.
Example:
' Variables
DIM
numResults
DIM
bytesRead
DIM
inputAry(9)
DIM
i
DIM
inputVal
DIM
tempStr
DIM
tempVal
DIM
ssidStr
DIM
chan
DIM
rssiVal
DIM
nwType
DIM
secType
DIM
bssidStr

AS
AS
AS
AS
AS
AS
AS
AS
AS
AS
AS
AS
AS

INTEGER
INTEGER
BYTE
INTEGER
INTEGER
STRING
INTEGER
STRING
INTEGER
INTEGER
INTEGER
INTEGER
STRING

TASK
' Program statements here.
GOSUB ShowMenu
GOSUB GetInput
OUTPUT UART0 CHR$(10) & CHR$(10)
GOSUB HandleInput
REPEAT_TASK
SUB ShowMenu
OUTPUT UART0
OUTPUT UART0
OUTPUT UART0
OUTPUT UART0
OUTPUT UART0
RETURN
ENDSUB

"Select an option:" & CHR$(10)


" 1 - Perform scan" & CHR$(10)
" 2 - Get next scan result" & CHR$(10)
" 3 - Show elements" & CHR$(10)
"# "

SUB HandleInput
IF inputVal = 0x31 THEN

2011 ... North Pole Engineering, Inc.

Programming Reference

OUTPUT UART0
numResults =
OUTPUT UART0
OUTPUT UART0
ENDIF

"Starting scan" & CHR$(10)


SCAN
"Num results = "
STR$(numResults) & CHR$(10) & CHR$(10)

IF inputVal = 0x32 THEN


tempVal = SCAN_RESULT
OUTPUT UART0 "Index is "
IF tempVal = 1 THEN
OUTPUT UART0 "valid."
ELSE
OUTPUT UART0 "invalid."
ENDIF
OUTPUT UART0 CHR$(10) & CHR$(10)
ENDIF
IF inputVal = 0x33 THEN
GOSUB ShowElements
ENDIF
RETURN
ENDSUB
SUB ShowElements
ssidStr = SCAN_ELEMENT(SSID)
chan = SCAN_ELEMENT(CHANNEL)
rssiVal = SCAN_ELEMENT(RSSI)
nwType = SCAN_ELEMENT(NETWORK)
secType = SCAN_ELEMENT(SECURITY)
bssidStr = SCAN_ELEMENT(BSSID)
OUTPUT UART0 "SSID = " & ssidStr & CHR$(10)
OUTPUT UART0 "Channel = " & STR$(chan) & CHR$(10)
OUTPUT UART0 "RSSI = " & STR$(rssiVal) & CHR$(10)
OUTPUT UART0 "Network type = "
tempVal = nwType
GOSUB PrintNetworkType
OUTPUT UART0 CHR$(10)
OUTPUT UART0 "Security = "
tempVal = secType
GOSUB PrintNetworkSecurity
OUTPUT UART0 CHR$(10)
OUTPUT UART0 "BSSID = " & bssidStr & CHR$(10) & CHR$(10)
RETURN
ENDSUB
SUB GetInput
DO
bytesRead = INPUT UART0 inputAry
DELAY 20
UNTIL( bytesRead <> 0 )
inputVal = inputAry(0)
OUTPUT UART0 CHR$(inputVal)
2011 ... North Pole Engineering, Inc.

123

124

WiFi-IT! Basic Language Reference

RETURN
ENDSUB
SUB PrintNetworkType
OUTPUT UART0 " "
IF tempVal = ADHOC THEN
OUTPUT UART0 "Adhoc"
ELSE
OUTPUT UART0 "Infrastructure"
ENDIF
RETURN
ENDSUB
SUB PrintNetworkSecurity
OUTPUT UART0 " "
IF tempVal = NONE THEN
OUTPUT UART0 "None"
ENDIF
IF tempVal = WPA_PERSONAL THEN
OUTPUT UART0 "WPA Personal"
ENDIF
IF tempVal = WPA_ENTERPRISE THEN
OUTPUT UART0 "WPA Enterprise"
ENDIF
IF tempVal = WPA2_PERSONAL THEN
OUTPUT UART0 "WPA2 Personal"
ENDIF
IF tempVal = WPA2_ENTERPRISE THEN
OUTPUT UART0 "WPA2 Enterprise"
ENDIF
IF tempVal = WEP_OPEN THEN
OUTPUT UART0 "WEP Open"
ENDIF
IF tempVal = WEP_SHARED THEN
OUTPUT UART0 "WEP Shared"
ENDIF
RETURN
ENDSUB
END

4.9.6.12 SCAN_RESULT

<i-variable> = SCAN_RESULT

EDK+ only

Iterates to the next item in the SCAN results array. This directive must be used to iterate to
the first result after performing a SCAN. SCAN_ELEMENT can be used to get the individual
elements of a scan result before iterating to the next item. SCAN_RESULT returns 1 as long
as the next index is valid. It returns 0 once the WiFi-Basic program has iterated past the end
of the array. SCAN_RESULT can called again after returning 0 to return to the beginning of
the list.
2011 ... North Pole Engineering, Inc.

Programming Reference

125

See example in SCAN.


4.9.6.13 SCAN_ELEMENT

<sib-variable> = SCAN_ELEMENT(<i-value>)

EDK+ only

SCAN_ELEMENT is used to read the individual elements of a scan result after a scan is
performed. SCAN and SCAN_RESULT must be called first. If no scan has been performed or
SCAN_RESULT has not been used to iterate to a valid index, then SCAN_ELEMENT returns 0
or a null string for whatever element is being read.
The value passed into SCAN_ELEMENT should be one of the intrinsic constants listed in the
following table:
Scan
Can be assigned Description
Element
to
SSID
String
SSID of the discovered network
CHANNEL Integer
Channel of the discovered network
RSSI
Integer
Signal strength of the discovered network. Works similar
to the RSSI directive.
NETWORK Integer
Network type of the discovered network. Set equal to
ADHOC or INFRASTRUCTURE.
SECURITY Integer
Security setting of the discovered network. See table
below.
BSSID
String
BSSID of the discovered network. Returns either a 17character
string or 6 bytes of a byte-array.
Byte Array
Works similar to MAC_ADDRESS.
Security values returned by SCAN_ELEMENT(SECURITY). These are WiFi-Basic intrinsic
constants and may be compared directly in a comparison statement.
Constant
Description
NONE
The network is unsecured.
WPA_PERSON The network is secured using WPA pre-shared key.
AL
WPA_ENTERP The network is secured using WPA encryption and 802.1X authentication.
RISE
WPA2_PERSO The network is secured using WPA2 pre-shared key.
NAL
WPA2_ENTER The network is secured using WPA2 encryption and 802.1X authentication.
PRISE
WEP_OPEN
The network is secured using WEP Open key encryption.
WEP_SHARED The network is secured using WEP Shared key encryption.

2011 ... North Pole Engineering, Inc.

126

WiFi-IT! Basic Language Reference

See example in SCAN.


4.9.6.14 SECURITY

<i-variable> = SECURITY(<n-value>)
SECURITY(<n-value>) = <i-value>

EDK+ only

SECURITY is used to read or modify the security setting of the selected network. The
security setting is stored in non-volatile flash and will take effect the next time a network
join is performed on that network. This could be from a LINK statement or from a powercycle. If the security setting is changed while currently connected to a network, the new
setting does not take effect until another connection attempt is made.
<n-value> must be one of the following intrinsic constants.
SSID
nRead
Definition
Identifier value Only
CURRENT
0
Yes Returns the security setting of the currently connected
wireless network.
Note: If the security setting is modified while currently
connected to a network, SECURITY(CURRENT) will continue to
return the security setting currently in use.
Note: SECURITY(CURRENT) returns the setting actually in use.
If the security mode is set to AUTO and the module connects
to a WEP encrypted network, SECURITY(CURRENT) will return
WEP_OPEN or WEP_SHARED.
PRIMARY
1
No Return/Set the WAP 1 security setting.
SECONDARY 2
No Return/Set the WAP 2 security setting.
PROVISION
3
Yes ReturnReturn the security setting of the provisioning SSID.
NOTE: The provisioning channel can not be changed.
ADHOC
4
No Return/Set the ADHOC security setting.
The following intrinsic constants are valid when using SECURITY.
Constant
Description
NONE
The module will only connect to an unsecured network. This is equivalent
to the None setting in the IDEs Project Configuration Panel.
WPA_PERSON WPA security will connect to a network with WPA or WPA2 PSK
AL
authentication using either TKIP or AES encryption. The module will not
connect to an unsecured network. . This is equivalent to the WPA-PSK
setting in the IDEs Project Configuration Panel.
WPA_ENTERP WiFi-Basic does not support 802.1X authentication at this time. Setting
RISE
SECURITY to WPA_ENTERPRISE will cause an EINVAL error.
WPA2_PERSO WPA2 security will connect to a network with WPA2 PSK authentication
NAL
using either TKIP or AES encryption. The module will not connect to an
unsecured network or a network with WPA security.
WPA2_ENTER WiFi-Basic does not support 802.1X authentication at this time. Setting
2011 ... North Pole Engineering, Inc.

Programming Reference

127

PRISE
WEP_OPEN

SECURITY to WPA2_ENTERPRISE will cause an EINVAL error.


The module will join or create (in Adhoc mode) a network with WEP Open
key authentication. It will not join an unsecured network or a network with
WEP Shared key authentication.
WEP_SHARED The module will join a network with WEP Open key or WEP Shared key
authentication. If in Adhoc mode, it will create a network with WEP Shared
key encryption. It will not join an unsecured network. This is equivalent to
the WEP setting in the IDEs Project Configuration Panel.
AUTO
The module will connect to an open network, a network secured by WEP
Open key encryption, WPA pre-shared key, or WPA2 pre-shared key. It will
not connect to a network with WEP Shared key authentication.

Important Note: SECURITY may be assigned from and read into an integer variable.
Integer variables may be compared directly against the security type constants in a
comparison statement.
Runtime Errors:
Error Code
EINVAL
ENOTCONN

Error Description
Invalid network Identifier or invalid security setting.
Attempt to read SECURITY(CURRENT) while not connected to a network.

Example:
' Variables
DIM
securityType

AS INTEGER

' Constants
TASK
' Join a network with any type of security
UNLINK
SECURITY(PRIMARY) = AUTO
LINK(PRIMARY)
' Report security type actually in use on network
securityType = SECURITY(CURRENT)
OUTPUT UART0 "Primary network is using "
GOSUB DisplaySecurityType
OUTPUT UART0 " security." & CHR$(10)
DELAY 5000
REPEAT_TASK
SUB DisplaySecurityType
IF securityType = NONE THEN
OUTPUT UART0 "no"
ENDIF
IF securityType = WPA_PERSONAL THEN
OUTPUT UART0 "WPA Personal"
ENDIF
IF securityType = WPA_ENTERPRISE THEN
2011 ... North Pole Engineering, Inc.

128

WiFi-IT! Basic Language Reference

OUTPUT UART0 "WPA Enterprise"


ENDIF
IF securityType = WPA2_PERSONAL THEN
OUTPUT UART0 "WPA2 Personal"
ENDIF
IF securityType = WPA2_ENTERPRISE THEN
OUTPUT UART0 "WPA2 Enterprise"
ENDIF
IF securityType = WEP_OPEN THEN
OUTPUT UART0 "WEP Open"
ENDIF
IF securityType = WEP_SHARED THEN
OUTPUT UART0 "WEP Shared"
ENDIF
RETURN
ENDSUB
END

4.9.6.15 SSID

<s-variable> = SSID(n-value)
SSID(n-value) = <s-variable>

EDK+ only

The SSID directive sets or returns the Service Set Identifier (SSID) of the specified wireless
network. The SSID Identifiers are defined as intrinsic constants in WiFi-Basic. It is best to
use the intrinsic constant, instead of the numeric value, since these value may change
between version of WiFi-IT! Basic.
WiFi-Basic supports four different SSIDs:
SSID
Identifier
CURRENT

nvalue
0

PRIMARY
SECONDARY
PROVISION

1
2
3

ADHOC

Read
Definition
Only
Yes Returns the SSID string value of the currently connected
wireless network.
No Return/Set the SSID string for WAP 1.
No Return/Set the SSID string for WAP 2.
Yes Return the SSID string of the provisioning SSID (Always
"NpeWiFiConfig").
No Return/Set the adhoc SSID string.

If the SSID string for the currently connected network is changed, these changes do not take
effect until the node has disconnected and rejoined a network. For example, assume WAP 1 is
set to SSID = "NpeDemo" on channel 2 and the node is connected on this network. If the WiFiBasic program executes SSID(PRIMARY)="UserDemo", the node stays connected on
"NpeDemo". The new setting for "UserDemo" only takes effect on the next rejoin attempt.
The WiFi-Basic program can force this by issuing an UNLINK, followed by LINK(PRIMARY). It
would also occur if the network connection was lost, at which point the node would attempt to
rejoin on "UserDemo".

2011 ... North Pole Engineering, Inc.

Programming Reference

Runtime Errors:
Error Code
ENOMEM
EINVAL
ENAMETOOLONG
ENOTCONN

129

Error Description
No heap space memory available to build string.
Invalid parameter.
The string data is too long.
Not connected to a network.

Example:
DIM sConnectedNetwork
DIM ssidPrimary

AS STRING
AS STRING

TASK
sConnectedNetwork = SSID(CURRENT)
' Get the currently connected
network name.
ssidPrimary = SSID(PRIMARY)
IF sConnectedNetwork = ssidPrimary THEN
'Connected to the primary WAP, UNLINK to change the SSID.
UNLINK
DELAY(10000)
IF LINKED? = FALSE THEN
SSID(PRIMARY) = "NewSSID"
LINK(INFRASTRUCTURE)
ENDIF
ENDIF
REPEAT_TASK
END

4.9.6.16 SUBNET

<si-variable> = SUBNET
SUBNET = <si-value>

EDK+ only

The SUBNET directive sets or returns the SUBNET mask that is applied to IP addresses (see
About Subnetting below). If DHCP is enabled and a set SUBNET directive is issued an error
will occur. DHCP must be disabled before changing the SUBNET setting.
NOTE: Changes to SUBNET take effect immediately. If SUBNET is updated while connected
to a network, the network interface is reset. Resetting the network interface is not the
same as rejoining the network. It simply allows the IP configuration to be updated to the
network. The WiFi-IT! module stays associated to the current network during a network
interface reset.
The following tables describe the behavior of the WiFi-IT! module when reading or writing
SUBNET.
Value returned by SUBNET:
DHCP is enabled
DHCP is disabled
2011 ... North Pole Engineering, Inc.

Node is connected
Currently assigned subnet
mask
Currently assigned subnet

Node is not connected


0.0.0.0
Last value assigned in the

130

WiFi-IT! Basic Language Reference

mask

PCP, or by the SUBNET


command

Behavior when assigning SUBNET:


Node is connected
DHCP is enabled
Error ECONFIG
DHCP is disabled
IP configuration updated.
Network interface reset.

Node is not connected


Error ECONFIG
IP configuration updated.

Runtime Errors:
Error Code Error Description
ECONFIG
SUBNET cannot be changed while DHCP is enabled.
About Subnetting
Subnetting involves the separation of the network and subnet portion of an address from
the host identifier. This is performed by a bitwise AND operation between the destination
IP address and the subnet mask. The result yields the network address and the remainder is
the host identifier.
Example:
If we set the subnet mask as shown:
SUBNET = "255.255.255.0"
And send a packet to "192.168.89.5"
Then the network portion of the address is: 192.168.89.0
The host portion of the address is: 0.0.0.5
Each local area network has a network portion of the address that is the same for all nodes
on the network. The subnet mask is used to determine if the destination IP address is an
internal address, or external to the network, in which case the packet is forwarded to the
Default Gateway.
4.9.6.17 UNLINK

UNLINK
Disassociate from the current network. If not connected to a network, UNLINK performs no
action. If in the process of joining a network, the process is cancelled. The WiFi-IT! module
will not attempt to rejoin any networks until a LINK command is issued. UNLINK also turns
off the radio receiver.
NOTE: Unlink is a blocking operation that waits for network disconnection to complete.
Example:
'The Project Configuration Panel has been used to setup access two networks, WAP1
and WAP2.
TASK
:
IF LINKED? THEN
UNLINK
' Disassociate from both WAP1 and WAP2.
2011 ... North Pole Engineering, Inc.

Programming Reference

131

ENDIF
:
REPEAT_TASK
END

4.9.6.18 VALIP

<i-variable> = VALIP (<s-variable>)


Convert an IP address in dotted-string format to an integer. This command can be used when
saving IP addresses to STATIC variables, as static variables can not be declared as type string.
The command IP$ reverses the operation and returns the IP address in dotted-string format.
NOTE: Many of the commands that require IP addresses will use either dotted-decimal string
or numeric IP addresses.
Runtime Errors:
Error Code Error Description
EINVAL
Incorrectly formatted IP address string.
Example:
DIM
DIM
DIM
DIM

recvCid
bytesRcvd
senderIpStr
pkt(255)

STATIC savedIpVal
cycles.

AS
AS
AS
AS

INTEGER
INTEGER
STRING
BYTE

AS INTEGER

' Location to save IP address between sleep

TASK
recvCid = LISTEN UDP 9000
' Wait for data
DO
UNTIL( POLL(recvCid) = 1 )
' Receive data and get senders IP address
bytesRcvd = RECEIVE recvCid, pkt
senderIpStr = GET_SENDER_IP
' Could have stored this directly into an i-var,
' but then we wouldn't demonstrate VALIP.
' Save IP address for future use
savedIpVal = VALIP(senderIpStr)
:
REPEAT_TASK
END

4.9.6.19 WEPKEY

<s-variable> = WEPKEY(<n-value>)
WEPKEY(<n-value>) = <s-value>

EDK+ only

The WEPKEY directive sets or returns the WEP key of the specified wireless network. The
2011 ... North Pole Engineering, Inc.

132

WiFi-IT! Basic Language Reference

WEP key is a 40-bit or 104-bit key specified in hexadecimal. The key is combined with a 24bit initialization vector (IV) to create a 64-bit or 128-bit RC4 traffic key. You do not need to
be concerned about the 24-bit IV except to note WEP security using 64-bit encryption is
still using a 40-bit key and WEP security using 128-bit encryption is still using a 104-bit key.
The key is specified as a string of hexadecimal characters and must be either 10 digits or 26
digitis in length. The WEP key length will be set automatically based on this. Valid digits
are 0 through 9 and A through F (upper or lower-case). Space and dash characters may be
used for spacing, although they will not appear when reading the WEP key. Any other
character or a length other than 10 or 26 digits will result in an error and the WEP key not
being changed.
The WEP key can be changed for a specific network configuration regardless of whether its
security mode is set to WEP. The WEP key is maintained until the security mode is set to
WEP key.
<n-value> must be one of the following intrinsic constants.
SSID
nRead
Definition
Identifier value Only
CURRENT
0
Yes Returns the WEP key of the currently selected network.
Invalid if not connected.
Note: If the WEP key of the current network is modified after
joining, WEPKEY(CURRENT) still returns the WEP key currently
in use.
PRIMARY
1
No Sets or returns the WEP key of WAP 1.
SECONDARY 2
No Sets or returns the WEP key of WAP 2.
PROVISION
3
Yes Invalid.
ADHOC
4
No Sets or returns the WEP key of the Adhoc network.
Runtime Errors:
Error Code
EINVAL
ENOTCONN

Error Description
Invalid character in WEP key or improper WEP key length.
Attempt to read WEPKEY(CURRENT) while not connected to a network.

Example:
' Variables
' Constants
TASK
UNLINK
DHCP = 0
IP_ADDRESS = "192.168.3.100"
SECURITY(ADHOC) = WEP_SHARED
WEPKEY(ADHOC) = "11-22-33-44-55"
LINK(ADHOC)

2011 ... North Pole Engineering, Inc.

Programming Reference

133

OUTPUT UART0 "Current WEP key = " & WEPKEY(CURRENT) & CHR$(10)
DELAY 5000
REPEAT_TASK
END

4.10

Operators
Operator Precedence:
When several operations occur in a single expression, each operation is evaluated and resolved
in a predetermined order. Each of the operators, in the following sections, specifies the
precedence of the operator. If an operator in an expression has a higher precedence (a higher
number), it is evaluated before an operator of lower precedence. Operators of equal
precedence are evaluated and resolved in a left-to-right order. Parentheses can be used to
override operator precedence. Operations within parentheses are performed before other
operations. Within parentheses normal operator precedence is used.
Operator Precedence Table:
The table below shows the relative precedence of each operator when parentheses are not
used.
Operator

Precedence

Group

&

11

String

10

Arithmetic

Arithmetic

MOD

Arithmetic

SHL SHR

Bitwise

> < <= = >= <>

Comparison

NOT

Bitwise

AND

Bitwise

XOR

Bitwise

OR

Bitwise

4.10.1 Arithmetic Operators


The arithmetic operators only operate on numeric values.
Operator
*
/
+

Precedence
10
10
9

2011 ... North Pole Engineering, Inc.

Description
Multiply two 32-bit numeric values.
Divide two 32-bit numeric values.
Add two 32-bit numeric values.

134

WiFi-IT! Basic Language Reference

MOD

9
8

Subtract two 32-bit numeric values.


Returns the remainder of a divide operation.

When operators are combined in a single statement the higher precedence operators will be
evaluated first. Operators of the same precedence are interpreted in the order in which they
occur. The order of evaluation may be changed by using parenthesis.
Example:
Expression
MyVar = 17 * 29 + 88 / 11
MyVar = 15 + 6 MOD 2

Interpretation
MyVar = (17 * 29) + (88 / 11))
MyVar = (15 + 6) MOD 2

Result
MyVar = 501
MyVar = 1

4.10.2 Comparison Operators


The comparison operators perform comparisons between the values of two operands. Each
operator returns a boolean result that is true (1) if the relationship holds true, or false (0) if not.
The equality operators may be used with numeric or string values. All other operators require
numeric operands.
Operator
<=
<>
>=
>
<
=

Precedence
7
7
7
7
7
7

Description
Less than or equal
Not equal to
Greater than or equal
Greater than
Less than
Equal to

Operands
numeric
numeric / string
numeric
numeric
numeric
numeric / string

When operators are combined in a single statement the higher precedence operators will be
evaluate first. Operators of the same precedence are interpreted in the order in which they
occur.
Example:
Expression
IF x < 17 OR y >= 29 THEN

Interpretation
( x < 17) OR (y >= 29)

Result
For: x = 5, y = 5 : TRUE
For: x = 18, y =28 : FALSE

4.10.3 Bitwise Operators


The logical / bitwise operators only operate on numeric values.
Operato Precedenc Description
r
e
NOT
4
Bitwise Complement - operates on the immediately following
variable considered as a collection of 32 bits, changing 1's to 0's and 0's
to 1's.
AND
3
Bitwise AND - a bit of the result is 1 if and only if the corresponding

2011 ... North Pole Engineering, Inc.

Programming Reference

XOR

OR

SHL

SHR

135

bits in the operands are both 1.


Bitwise exclusive-OR - a bit of the result is 1 if and only if exactly 1 of
the corresponding bits in the operands are 1, that is, if the
corresponding bits differ.
Bitwise OR - a bit of the result is 1 if and only if at least 1 of the
corresponding bits in the operands is 1.
Bitwise Shift Left - Left shifts the operand on the left by the number
of bits specified by the operand on the right and returns the result.
Bitwise Shift Right - Right shifts the operand on the left by the
number of bits specified by the operand on the right and returns the
result.

When operators are combined in a single statement the higher precedence operators will be
evaluated first. Operators of the same precedence are interpreted in the order in which they
occur. Parenthesis may be used to changed the order of evaluation.
Example:
Expression
Result
M yV a r = 17 OR 29 XOR 91 AND 11
M yV a r = 23

Interpretation

M yV a r = 17 OR (29 XOR (91 AND 11))

4.10.4 String Operators


String Operators only operate on ASCII character strings.
Operat
or
"

Preceden
ce
N/A

&

11

<>
=

7
7

Description
Define text as constant string data until the next quote is encountered.
This operator must follow either an equal sign or the string
concatenation operator (&).
Concatenate two strings into one string. The strings are concatenated
sequentially.
Return true if strings are not equal, else return false.
Return true if strings are equal, else return false.

Runtime Errors:
Error Code Error Description
ENOMEM
Insufficient heap space to allocate string. (& operator only)
Example:
DIM String1 AS STRING
DIM String2 AS STRING
TASK
:
String1 = "Text for String1"
String2 = String1 & "/" & String1

2011 ... North Pole Engineering, Inc.

' Assigned the value "Text for String1".


' String2 contains the string
' "Text for String1/Text for String1"

136

WiFi-IT! Basic Language Reference

:
REPEAT_TASK
END

4.11

String Functions
The string functions convert numeric values to their ASCII equivalent, convert ASCII characters
to numeric values and parse strings. If the WiFi-Basic Run Time Engine (RTE) runs out of heap
space all string functions will return a null string and an ENOMEM error will be thrown. See
Heap Management.
CHR$
HEX$
HEX_VAL
INSTR$
LEFT$
LEN$
MID$
RIGHT$
STR$
TOBYTEARRAY
TOSTRING
VAL

4.11.1 Heap Management


There are two types of strings in WiFi-Basic: those that are defined directly in the program
source using quoted strings (i.e. "This is a string") and those that are created during runtime
using WiFi-Basic operations. A string variable can reference either type and management of
string types is handled invisibly to the program. Most WiFi-Basic operations that return a string
value do so by allocating heap space for that string at run-time. Note: There is no heap-space
reclamation until cycling around the TASK - REPEAT_TASK loop, at which point all heap is
reclaimed and all string variables become null strings. This happens regardless of whether the
module is in low-power or always-on mode.
Important Note:
Following is a list of WiFi-Basic operations that allocate heap space every time they are used. If
consideration is not taken to cycle back to the beginning of the TASK - REPEAT_TASK loop,
eventually these operations will cause heap space to become full. At this point, all of these
operations will return a null string and throw an ENOMEM error.
Networking related:
GET_SENDER_IP
IP_ADDRESS
(Heap space is only allocated when assigning IP_ADDRESS to a string
variable)
IP$
MAC_ADDRESS
2011 ... North Pole Engineering, Inc.

Programming Reference

SSID

137

(Heap space is only allocated when reading an SSID value)

String functions:
&
TOSTRING
CHR$
LEFT$
MID$
RIGHT$
STR$
HEX$
External interfaces:
INPUT UART
(Heap space is only allocated when reading into a string variable)
Static String Functions:
These functions return a string that is statically reserved by the Run-Time Engine. They do not
use hea p spa ce and may be called any number of times without cycling back to the beginning of
TASK - REPEAT_TASK.
MONTHNAME
WEEKDAYNAME
MAC_ADDRESS

4.11.2 CHR$
<s-variable> = CHR$(<char code>)
Return a string containing the character associated with the specified character code. If a
value greater than 255 or less than 0 is passed, CHR$ truncates the value to a positive value
between 0 and 255.
Runtime Errors:
Error Code Error Description
ENOMEM
Insufficient heap space to allocate string.
Example:
AsciiValue = CHR$(0x54)

' AsciiValue contains "T"

4.11.3 HEX$
<s-variable> = HEX$(expression, length)
Create an ASCII string of length leng th containing the hexadecimal representation of the
number from evaluating expression. Expression is interpreted as an unsigned integer and
can represent all values in the range 0 to FFFFFFFF. If leng th is less than the length of the
hexadecimal string, the most significant digits are truncated. If it is greater, the result string
is padded with 0s.
Runtime Errors:
2011 ... North Pole Engineering, Inc.

138

WiFi-IT! Basic Language Reference

Error Code
EINVAL
ENOMEM

Error Description
Invalid parameter.
Insufficient heap space to allocate string.

Example:
DIM MyString
DIM Value

AS STRING
AS INTEGER

TASK
:
MyString = "This is a test of the string functions."
Value = 28
Value = Value * 2
MyString = "0x" & HEX$(Value, 4)
:
REPEAT_TASK
END

' MyString contains "0x0038"

4.11.4 HEX_VAL
{i-variable =} HEX_VAL(<s-value>)
The HEX_VAL function treats <s-value> as a hexadecimal string and converts it to an unsigned
integer.
HEX_VAL first discards as many white-space characters as necessary until the first non-whitespace character is found. Then, starting from this character, it takes an optional initial plus or
minus sign followed by as many hexadecimal digits as possible, and interprets them as a
numerical value. Additional characters after those that form the integral number are
ignored. Hexadecimal digits may use uppercase or lowercase letters for digits A through F.
If a negative value is specified, the value is subtracted from 0x100000000 and the result
returned.
HEX_VAL will only process the first 15 characters of a string. Characters beyond this are
ignored. If the first sequence of non-white-space characters is not a valid integral number, or
if no such sequence exists, the behavior of HEX_VAL is undefined. If a sequence longer than
8 hexadecimal digits is provided, the last 8 characters will be used (i.e. the value is truncated
to fit into a 4-byte integer). If <s-value> is a null string, HEX_VAL returns 0.
Example:
DIM valString
DIM value

AS STRING
AS INTEGER

TASK
valString = "+89"
value = HEX_VAL valString
valString = " -63"
value = HEX_VAL valString
valString = "12345678ABCD"
value = HEX_VAL valString

' value = 137

(in decimal)

' value = 0xFFFFFFD9


' value = 0x5678ABCD
2011 ... North Pole Engineering, Inc.

Programming Reference

valString = "7F"
value = HEX_VAL valString
REPEAT_TASK
END

139

' value = 127

4.11.5 INSTR$
<i-variable> = INSTR$(<string>, <start>, "<substring>")
Search the specified string beginning at character position <start>, looking for the first
occurrence of the string <substring>. Return the character position of the start of the
substring. If the substring is not found, 0 is returned. Zero is returned if either of the
strings is null. The first character in a string is at index 1.
Example:
DIM MyString
DIM CharLoc
DIM ParseCharLoc

AS STRING
AS INTEGER
AS INTEGER

TASK
MyString = "This is a test of the string functions."
CharLoc = 6
' Start at the "i" in is.
ParseCharLoc = INSTR$(MyString, CharLoc, "test")
MyString = MID$(MyString,
"test".
REPEAT_TASK
END

ParseCharLoc, 4)

' ParseCharLoc contains 11.


' MyString will contain

4.11.6 LEFT$
<s-variable> = Left$ (<string>, <expression>)
Return a string whose length is the number of characters specified by <expression> starting
from the leftmost character in <string>. The first character position in a string is one (1). If the
value of expression is greater than the number of characters in the string, the return string is
truncated at the end of the input string.
Runtime Errors:
Error Code Error Description
ENOMEM
Insufficient heap space to allocate string.
Example:
DIM MyString
DIM SubString

AS STRING
AS STRING

TASK
:
MyString = "This is a test of the string functions."
SubString = LEFT$(MyString, 4)
' SubString contains "This"
:
REPEAT_TASK

2011 ... North Pole Engineering, Inc.

140

WiFi-IT! Basic Language Reference

END

4.11.7 LEN$
<i-varible> = Len$(<string>)
Return the number of characters in <string>. If <string> is null, a length of zero is returned. A
string is null prior to being assigned. It obtains a size after it is used in the program.
Example:
DIM MyString AS STRING
DIM iCharCnt AS INTEGER
TASK
:
MyString = "This is a test of the string functions."
iCharCnt = LEN$(MyString)
:
REPEAT_TASK
END

' iCharCnt contains 39

4.11.8 MID$
<s-variable> = Mid$ (<string>, expression1, expression2)
Return the characters of <string> starting at the character position returned by expression1
for the number of characters returned by expression2. If the value returned by expression2
exceeds the remaining characters in the string, the returned string is truncated at the last
character of <string>.
Runtime Errors:
Error Code Error Description
ENOMEM
Insufficient heap space to allocate string.
Example:
DIM MyString
DIM SubString

AS STRING
AS STRING

DIM StartIdx
DIM EndIdx

AS INTEGER
AS INTEGER

TASK
:
StartIdx = 6
EndIdx = 9
MyString = "This is a test of the string functions."
SubString = MID$(MyString, StartIdx, EndIdx)
:
REPEAT_TASK
END

' SubString contains "is a test"

2011 ... North Pole Engineering, Inc.

Programming Reference

141

4.11.9 RIGHT$
<s-variable> = RIGHT$(<string>, expression)
Return the number of characters specified by the value of the expression starting from the
tail of the string. The first character position in a string is at index one (1). If the value of
expression is greater than the number of characters in the string, the return string is
truncated at the beginning of the input string.
Runtime Errors:
Error Code Error Description
ENOMEM
Insufficient heap space to allocate string.
Example:
DIM MyString AS STRING
DIM SubString AS STRING
TASK
:
MyString = "This is a test of the string functions."
SubString = RIGHT$(MyString, 10)
:
REPEAT_TASK
END

' SubString contains "functions."

4.11.10 STR$
<s-variable> = STR$(expression)
Create an ASCII string containing the decimal representation of the number from evaluating
expression. Expression can represent all values of an integer; -231 to 231-1. The minus sign
(-) is printed for negative numbers.
Runtime Errors:
Error Code Error Description
ENOMEM
Insufficient heap space to allocate string.
Example:
DIM MyString AS STRING
DIM Value AS INTEGER
TASK
:
MyString = "This is a test of the string functions."
Value = 28
MyString = STR$(Value * 2)
:
REPEAT_TASK
END

2011 ... North Pole Engineering, Inc.

' MyString contains "56"

142

WiFi-IT! Basic Language Reference

4.11.11 TOBYTEARRAY
<b-array(index)> = TOBYTEARRAY(<s-value>)
Convert the string into a series of bytes, storing the bytes at the index and continuing for
the length of the string.
This function is generally used to move string data into a data packet that will be sent over
the wireless connection.
Example:
DIM MyString
DIM Packet(20)

AS STRING
AS BYTE

TASK
:
MyString = "TEST this out!"
Packet(4) = TOBYTEARRAY(LEFT$(MyString, 4))

'
'
'
'

Packet(4)
Packet(5)
Packet(6)
Packet(7)

=
=
=
=

0x54
0x45
0x53
0x54

ASCII
ASCII
ASCII
ASCII

'T'
'E'
'S'
'T'

:
REPEAT_TASK
END

4.11.12 TOSTRING
<s-variable> = TOSTRING(b-array, <expression1>, <expression2>)
Convert the byte array, starting at the byte position specified by expression1 (the start
index) for the number of bytes specified by expression2 (length), to the equivalent ASCII
string representation. This function only works only on byte arrays. If a non-ASCII character
is encountered it is copied into the string. This allows control characters to be converted
and used within a string.
This function is very similar to using the CHR$ function to convert bytes to strings and
concatenating the strings together.
Runtime Errors:
Error Code Error Description
ENOMEM
Insufficient heap space to allocate string.
Example:
DIM MyString
DIM Packet(20)

AS STRING
AS BYTE

TASK
:
Packet(4)
Packet(5)
Packet(6)
Packet(7)

0x54
0x45
0x53
0x54

=
=
=
=

'
'
'
'

Equivalent
Equivalent
Equivalent
Equivalent

to
to
to
to

ASCII
ASCII
ASCII
ASCII

'T'
'E'
'S'
'T'

2011 ... North Pole Engineering, Inc.

Programming Reference

143

MyString = TOSTRING(Packet,4,4) ' The contents of MyString = 'TEST'


:
REPEAT_TASK
END

4.11.13 VAL
{i-variable =} VAL(<s-value>)
The VAL function treats <s-value> as a decimal string and converts it to an integer.
VAL first discards as many whitespace characters as necessary until the first non-whitespace
character is found. Then, starting from this character, it takes an optional initial plus or minus
sign followed by as many numerical digits as possible, and interprets them as a numerical
value. Additional characters after those that form the integral number are ignored.
VAL will only process the first 15 characters of a string. Characters beyond this are ignored. If
the first sequence of non-whitespace characters is not a valid integral number, or if no such
sequence exists, VAL returns 0. If the correct return value is outside the range (-2,147,483,648
to 2,147,483,647), then the closest endpoint value will be returned. If <s-value> is a null
string, VAL returns 0.
Example:
DIM valString AS STRING
DIM value AS INTEGER
TASK
valString =
value = VAL
valString =
value = VAL
valString =
value = VAL
valString =
value = VAL
REPEAT_TASK
END

4.12

"+89"
valString
'
" -63"
valString
'
"4000000000"
valString
'
"%&*%)(*"
valString
'

value = 89
value = -63
value = 2147483647
value = 0

Variables and Datatypes


WiFi-Basic support 32-bit signed integer, 8-bit unsigned integer and string variables. Numeric
variables can be arranged as single-dimension arrays. All non-static numeric variables are
initialized at the TASK directive to zero, while string variables are initialized to the null string.
Numeric variables defined as STATIC retain their state between sleep cycles. At initial power-on
STATIC variables are set to zero.
WiFi-Basic also supports constants. All Constants are defined as 32-bit values but are
automatically coerced when used in a mathematical expression with 8-bit values.

2011 ... North Pole Engineering, Inc.

144

WiFi-IT! Basic Language Reference

4.12.1 Variable Naming and Limitations


1. All variables in WiFi-Basic are global.
2. Variable names must begin with an alpha-character.
3. Variable names may be up to 32 characters in length. If a variable name is longer than 32
characters only the first 32 characters are saved.
4. Variable names may contain numeric characters (0 through 9) and the underscore (_)
character.
5. Variable names are case insensitive.
6. Integer variables are 32-bit signed values.
7. Byte variables are 8-bit unsigned values (0 to 255). Byte variables are padded out to 32bits with zeros. This allows bytes to be compared to integers, but only through the range
of 0-255.
8. Variable arrays are zero-based therefore, declaring a variable as Var(3) creates an array of
four values; Var(0), Var(1), Var(2) and Var(3). Note that the declaration does not specify
the number of elements in the array. Instead, it specifies the upper bound of the array.
The lower bound of the array is zero by default.
9. The dimensions of arrays are statically defined. Their size may not be changed during
runtime.
10. Static variable data space is limited to 32 bytes.
11. Only integers and bytes may be stored in static variables, static string variables are not
supported.

4.12.2 Numeric Data Type Coercion


When two different data types are used in an operation, such as addition (+) or assignment (=),
the smaller data type (byte) is automatically promoted to the larger data type regardless of the
order in which the arguments are given.
The byte data type is unsigned and is always promoted as a positive integer with a value from
zero to 255. If the assignment is to a byte value, the integer result will be truncated to a value
from zero to 255; this may cause loss of precision and loss of sign!

4.12.3 CONST
CONST < na m e> = <va lue>
The CONST directive is used to create named numeric values used in a program. A constant is
a signed 32-bit value that cannot be changed after it is defined; it can only be used on the
right-side of the equal sign or in a logical expression. Constants are defined globally within a
program; meaning they are available in the main TASK and in any subroutines or error
handlers. Constants must be declared before they are used in the program. Constants are
declared before the TASK directive.
Naming constants improves program readability and helps create self documenting,
maintainable code.
Example:
DIM Force

AS INTEGER
2011 ... North Pole Engineering, Inc.

Programming Reference

DIM Mass

145

AS INTEGER

CONST ACCELERATION = 9

'Sets ACCELERATION equal to 9

TASK
Mass = 500
Force = Mass * ACCELERATION
REPEAT_TASK
END

'Force is equal to 4500 (500 x 9).

4.12.4 Variables
WiFi-Basic variables are composed of letters, numbers and the underscore character (_).
Variables must always start with a letter and have a maximum length of 32 characters. Variable
names are case insensitive. Therefore, variables with names like; 'MyVar' and 'myvar' will be
interpreted as referring to the same variable.
Variable Lifetime:
All variables in WiFi-Basic are transient and revert to their initialization value (0 for numeric's,
null for strings) after a sleep cycle or when the REPEAT_TASK directive is encountered.
Therefore, every time a WiFi-IT! node wakes up or encounters the REPEAT_TASK keyword, if
sleep mode is disabled; variable space is reinitialized to its default values. Only variables
defined as STATIC are carried through a sleep/REPEAT_TASK cycle.
Variable Types:
Three variable types are supported in WiFi-Basic; Integer, Byte and String. Integers are 32-bit
signed values ranging from 2,147,483,647 to -2,147,483,649. Bytes are 8-bit, unsigned values,
ranging from 0 to 255. String variables maybe up to 255 characters in length and are made up of
ASCII characters.
Array Variables:
Array variables of a single dimension are supported for the numeric data types. Array subscripts
are zero-based and run up to and including the specified subscript therefore, d+1 elements are
allocated when an array with last index of d is specified. The maximum size of an array is only
limited by available memory.
See Variable Naming and Limitations.
4.12.4.1 DIM

DIM <variable-name> { (d) } AS BYTE | INTEGER | STRING


Create a variable or variable array of the type specified. Because WiFi-Basic supports strong
type checking, all variables must be assigned a type. Only one variable maybe specified per
DIM statement.
Numeric Variables
All numeric variables are initialized to zero.

2011 ... North Pole Engineering, Inc.

146

WiFi-IT! Basic Language Reference

String Variables
All string variables are initialized to the null string, when defined. Strings are dynamically
allocated; therefore you do not have to declare their size. The maximum string size is
limited to 255 bytes.
Example:
DIM
DIM
DIM
DIM

Var_byte1 AS BYTE
Array(5) AS INTEGER
Temperature AS INTEGER
sIP AS STRING

'
'
'
'

Declares
Declares
Declares
Declares

a byte variable that can have values 0 - 255.


an integer array of six elements (0 - 5).
a single integer variable.
a string variable.

4.12.4.2 STATIC

STATIC <variable-name> { (d) } AS BYTE | INTEGER


The STATIC keyword is used in place of the DIM keyword when defining variables that
maintain their value across a sleep cycle, or when encountering the REPEAT_TASK directive.
STATIC variables must be numeric; static variables of type string are not supported. The
amount of STATIC memory is limited to 32-bytes on the WiFi-IT! module, so it should be
used only for information that must remain stable between sleep cycle executions of the
program.
STATIC variables maybe defined as arrays within the limited space available. The contents
of STATIC variables are initialized to zero only on power up.
Limitations of Static Variables:
There are only 32 bytes available for use as static variables. Only bytes and integers, or
arrays of bytes and integers may be declared static. Integer variables use four bytes of
static RAM and bytes use one. There is no support for storing static string variables.
Connection IDs (CIDs), such as returned by OPEN, LISTEN, and GET_SENDER_CID should not
be declared static. This is because the CID is a number that is only used to identify a socket.
Since the state of the networking stack is not saved when the module powers off, the CID
will be meaningless when the module powers back on. There is no run-time protection
against this and any attempt to use a CID in this fashion is likely to cause an EBADCID error.
To save a connection across sleep cycles, the IP address (in integer format) and port number
should be saved as static variables and an OPEN statement issued every pass through the
TASK loop. For receiving sockets, only the port number need be saved.
Important Note: It is strongly recommended that STATIC INTEGER variables be
declared before STATIC BYTE variables. This is because the compiler will pad any integer
declaration to the nearest 32-bit boundary. Five bytes followed by an integer will result in
three bytes of padding and thus three bytes of wasted STATIC ram space.
Example:
STATIC SafeVariable AS INTEGER
across a sleep cycle.
STATIC Temperature(8) AS BYTE

' Defines a variable that maintains it's contents


' Defines an array of byte variables
2011 ... North Pole Engineering, Inc.

Programming Reference

147

' that maintain their contents across


' a sleep cycle.

Guides
This section contains guides on specific topics. Some of the topics cover how the WiFi-IT system
operates. Others give examples for how to preform specific operations.

5.1

Regaining Access to a Device


If you are no longer able to access a WiFi-IT! module through a wireless network, these steps
can help restore access. Wireless access to a module may be lost for any of the following
reasons:
1. Incorrect network settings were entered for WAP 1 or WAP 2 in the project configuration
panel (PCP).
2. "Join Network on Startup" was cleared in the PCP
3. An incorrect IP configuration was entered in the PCP.
4. 'Join Network at Startup' under 'Radio Settings' in the PCP is not checked and you
attempted to load another project over WiFi. See note under "Join Network on Startup"
in Wireless Configuration.
5. The 'Network(s) to Join' setting is set to Adhoc.
6. The WiFi Basic program executed an UNLINK command.
7. The WiFi Basic program powered off the radio using the RECEIVER statement.
8. There is some other problem. For example the WiFi Basic program could have a long
sleep time and the IDE is timing out waiting for the module to wake up.
In any of these cases, the Override mode (see Modes of Operation) can be used to correct any
network settings or reload a project. Override mode guarantees on startup that the WiFi Basic
code is not executing and the Run Time Engine is listening for commands over UART0.
Important Note: You need physical access to a module to place it in override mode.
To place a module in Override Mode and edit its device settings or reload a project, perform the
following steps:
1. Connect the DCard serial interface to the PC that is running the IDE.

2011 ... North Pole Engineering, Inc.

148

WiFi-IT! Basic Language Reference

2. Plug the WiFi-IT! module into J2.

3. Place the FLASH DL switch in the up position and the L2 DBG switch in the down position. This
pla ces the device in override m ode. Note for prototype boards or custom hardware: Flipping
SW12 down is equivalent to tying GPIO25 to VDD_IO.

4. Turn on power to the DCard.


5. Start the WiFi-IT! Basic IDE if it is not already started.
2011 ... North Pole Engineering, Inc.

Guides

149

6. Select Device | Uart | Edit Device to edit the device settings loaded into the module. The
COM selection dialog is shown. Select the COM port connected to the DCard.

7. Device settings are loaded from the project configuration panel of the last project loaded.
You may modify them here without reloading a project. Press <Ctrl-S> to store modified
settings back into the device. See Wireless Configuration for correct setup of wireless
settings.
8. Select Device | Uart | Project Load if you wish to reload a project. The COM selection dialog
is shown followed by the project selection dialog.

2011 ... North Pole Engineering, Inc.

150

WiFi-IT! Basic Language Reference

If these steps fail, you can try a Device Firmware Update. This will restore a module to its
original state.

5.2

Updating the Device Firmware


In some cases it may be necessary to update the device firmware. If you have downloaded a
new version of the IDE, it may be built for a different version of the firmware. In this case, you
will need to perform a device firmware update from within the IDE for each module you wish to
program.
Also, if you are unable to access a module and followed all the steps in Regaining Access to a
Device, performing a firmware update will restore the module to its original state. This can
serve as a last resort.
Important Note: Loading the firmware can not be done over-the-air. The WiFi-IT! module
must be attached to the DCard and connected through the wired connection to a PC running the
IDE.
To load (or reload) the device firmware, follow the procedure below:
1. Connect the DCard serial interface to the PC that is running the IDE.

2011 ... North Pole Engineering, Inc.

Guides

151

2. Write down the WiFi-IT! module MAC address. You will need this in step 9. The M A C a ddress
is a 12-dig it hexa decim a l string ca n be found on a la bel on the m odule. If the label only has 6
digits, these are the last 6 digits and the first 6 are 001DC9.
3. Plug the WiFi-IT! module into J2.

4. Place the FLASH DL switch in the down position. This pla ces the device in firm w a re upda te
m ode.

2011 ... North Pole Engineering, Inc.

152

WiFi-IT! Basic Language Reference

5. Turn on power to the DCard.


6. Start the WiFi-IT! Basic IDE if it is not already started.
7. Select Device | Update Device Firmware from the IDE menu bar. A dialog box will open
listing the active COM ports.

8. Choose the COM port connected to the DCard and click OK. The IDE will check connectivity to
the WiFi-IT! module. In the event that the module is not found, an error message is
displayed as shown below.

2011 ... North Pole Engineering, Inc.

Guides

153

9. If the module is detected, the IDE will prompt to verify the module's MAC address. Enter or
verify the value recorded in step 2.

10.Click OK to begin loading the WiFi-IT! firmware. A new dialog will open to show download
progress.
11.If the operation completes successfully, the success dialog is displayed!

Important Note: If the firmware update fails during step 10 or later (after firmware
download has started), the module will be in an unusable state. You will need to restart the
firmware update process.

5.3

Setting Up an Ad Hoc Network


Ad hoc networks work much like infrastructure networks, but there are some special
considerations. Once a WiFi-IT! node is configured and connected on an ad hoc network, WiFiBasic network operations should work largely the same as with infrastructure networks. The
following steps will allow any user to create a functional ad hoc network.
Ad hoc networks are useful for creating direct connections between a WiFi-IT! module and a

2011 ... North Pole Engineering, Inc.

154

WiFi-IT! Basic Language Reference

tablet device or smart phone without use of an access point.


1.

Specify the SSID and Channel for the Ad Hoc Network


The WiFi-IT! node(s) and other stations (laptop, smart phone, etc.) must configure the
same SSID and channel. To configure the WiFi-IT! nodes, open the PCP for the project to be
loaded.

Set the SSID and SSID Channel. Remember the SSID is case-sensitive.
Important Note: Only no security or WEP may be chosen for adhoc networks. WPA is
not available.
2.

Specify a Static IP
In an infrastructure network, the access point (wireless router) typically serves as the DHCP
server. In an ad hoc network, no DHCP service will be available. The Device Settings panel
provides a checkbox to indicate DHCP is not in use, make sure Enable DHCP is not checked.
Next specify a static IP address. The static IP addresses for each of the stations must be
unique. The actual IP addresses specified do not matter, but they must be on the same
subnet (i.e. 192.168.3.x). Finally set the Gateway IP to 0.0.0.0.

3.

Set Network to Ad Hoc


Locate the "Network(s) to Join" setting in the PCP and set it to Adhoc. This will prevent the
module from joining any infrastructure networks.

4.

Startup the Ad Hoc Network


The WiFi-IT! module is capable of creating adhoc networks, or joining adhoc networks
create by other devices. If the adhoc network does not exist when the module is powered
on, it will create the network. Note that some devices, such as the iPhone, may not be
2011 ... North Pole Engineering, Inc.

Guides

155

able to create adhoc networks, and therefore the module may need to be powered on
first.

5.4

Data Monitor Protocol


The IDE's Data Monitor Perspective may be used to display variable and graph data from your
WiFi-Basic program in real time. Both the RSSI and Temp Sensor demos in the Quick Start Guide
demonstrate use of the Data Monitor Perspective. Following is the definition for the Data
Monitor Protocol.

Monitor Address:
Data Monitor packets must be sent to this address. This is a multicast address. The IDE registers
to receive packets sent to this address. All IDEs running on the same network will receive and
display Data Monitor packets.
The multicast address and port: 224.0.0.100:20000

Header Format:
1. Preamble ('W', 'B'): 2 bytes
2. Device MAC: 6 bytes
3. Packet Type: 1 byte (See below)
4. Number of Data Values (not number of bytes, byte count will be much larger): 1 byte
Total Header size: 10 bytes

Packet Types:
Variable (0x01):
This packet type expects pairs of data values, a String followed by another data value. It is
output in the data monitor perspective with each pair on it's own line, "String:Value". This
packet type is generally used to monitor wifi basic variables during execution.
Graph Data (0x02):
The Graph Data packet type is used to display graph data. The Graph Data packet is timestamped when received and plotted against time. A Graph packet type takes three data values,
as shown in the following chart:
Data #
Data Type
Description
1
String
Graph Title
2
String
Y-Axis Label (X-Axis is always time.)
3
Int or Byte
Y Value
Message (0x03):
The Message packet type is similar to the C-language printf function. It takes all of the data
values and concatenates them with a space between, and displays all of the values together on
a single line.
Raw(0x04):
The Raw packet type displays each data value on its own line.
2011 ... North Pole Engineering, Inc.

156

WiFi-IT! Basic Language Reference

Data Types:
Each packet consists of a certain number of data values. After the packet type and the number
of data values (bytes 8 and 9 of the header), come the data values. Each data value begins with
a single byte indicating its type.
String (0x00):
First byte is type string (0x00). Second byte is length, followed by that many bytes, each one a
character in the string. Total size will be length + 2 bytes.
Integer (0x01):
First byte is type integer (0x01). Second byte is number of integer values, followed by that
many integers. Total size will be (num values * 4) + 2 bytes.
Byte (0x02):
First byte is type byte (0x02). Second byte is number of byte values, followed by that many
bytes. Total size will be (num values) + 2 bytes.
Examples:

For an example of the Variable packet type, see the RSSI demo.
For an example of the Graph Data packet type, see the Temp Sensor demo.

5.5

SPI Timing Diagrams


The following diagrams show the SPI interface for the different settings of Clock Polarity (SPO)
and Clock Phase (SPH).

MSPI Master Mode, Clock Polarity = 0, Clock Phase = 0

2011 ... North Pole Engineering, Inc.

Guides

MSPI Master Mode, Clock Polarity = 0, Clock Phase = 1

2011 ... North Pole Engineering, Inc.

157

158

WiFi-IT! Basic Language Reference

MSPI Master Mode, Clock Polarity = 1, Clock Phase = 0

2011 ... North Pole Engineering, Inc.

Guides

MSPI Master Mode, Clock Polarity = 1, Clock Phase = 1

2011 ... North Pole Engineering, Inc.

159

160

WiFi-IT! Basic Language Reference

Programming Examples
The following example programs demonstrate how to use WiFi-IT! Basic functions and
statements. Most of the programs in this section require the WiFi-IT! EDK, as they assume either
an USB/RS232 interface on UART 0 or LEDs tied to specific GPIO pins. These programs can be
typed-in, compiled and loaded into a module to see how they operate.
SPI SRAM
UART0 INPUT / OUTPUT

6.1

SPI SRAM
'
'
'
'
'
'

Program Name: SpiSram.tb


Description: Test of Microchip 23K256 SPI SRAM.
- This example code uses the MSPI and UART interfaces. The SRAM
locations 100 - 500 are initialized to zero. The data written

2011 ... North Pole Engineering, Inc.

Programming Examples

'
'
'
'
'
'
'
'
'
'
'
'
'
dim
dim
dim
dim
dim
dim

161

is read back and printed through the UART port. Then an address
tag pattern is written. It is read back and printed through the
UART port.
- This device is connected to a GPIO as the chip select
instead of an SPI chip select (although we still need to
specify the SPI chip select, it isn't connected to anything.
- The reason an external GPIO was used as a chip select is because
the SPI chip selects deselect at the end of each operation. The
Microchip part needs multiple SPI operations with the chip select
remaining low through out all the operations.

msgStr
address
sramValue
numBytes
outPkt(9)
inPkt(9)

as
as
as
as
as
as

string
integer
integer
integer
byte
byte

const
SPI_READ
const
SPI_WRITE
const
RDSR
location.
const
WRSR
location.

=
=
=

0x03
0x02
0x05

' Read instruction opcode.


' Write instruction opcode.
' Read status register

0x01

' Write status register

const
IFACE
used by hardware.

0x01

' Default value - not really

CONST
SRAM_CS
= 18
chip select.
CONST
SRAM_HOLD = 16
hold pin.

' GPIO connected to SPI SRAM


' GPIO connected to SPI SRAM

TASK
GPIO(SRAM_CS) = 1
deselected.
GPIO(SRAM_HOLD) = 1
deselected.

' Initialize chip select to


' Initialize hold to

outPkt(0) = WRSR
outPkt(1) = 0x80
GPIO(SRAM_CS) = 0
OUTPUT MSPI IFACE, outPkt(0), 2
GPIO(SRAM_CS) = 1

' Select chip.


' Deselect chip.

DELAY 50
' Clear memory locations 100 through 500.
FOR address = 100 to 500
2011 ... North Pole Engineering, Inc.

162

WiFi-IT! Basic Language Reference

outPkt(0) = SPI_WRITE
outPkt(1) = address / 256

' Set high-byte of address.

outPkt(2) = address MOD 256


outPkt(3) = 0

' Set low-byte of address.


' Set data.

GPIO(SRAM_CS) = 0
OUTPUT MSPI IFACE, outPkt(0), 4
GPIO(SRAM_CS) = 1

' Clear specified address.

NEXT
' We only read back location 100 to 110 because reading all
' locations from 100 to 500 takes too long to output to the UART!
FOR address = 100 to 110
outPkt(0) = SPI_READ
outPkt(1) = address / 256
outPkt(2) = address MOD 256
outPkt(3) = 0x44
' Dummy data that will be
replace by read data.
GPIO(SRAM_CS) = 0
OUTPUT MSPI IFACE, outPkt(0), 4
GPIO(SRAM_CS) = 1
' Read the data pack and print the value read to UART0.
numBytes = INPUT MSPI IFACE, inPkt
sramValue = inPkt(3)
' This is the return data
value.
msgStr = "Value read = " & STR$(sramValue) & CHR$(10)
numBytes = OUTPUT UART0 msgStr
DELAY 20
NEXT
' Write incrementing pattern to locations 100 through 500.
FOR address = 100 to 500
outPkt(0) = SPI_WRITE
outPkt(1) = address / 256
outPkt(2) = address MOD 256
outPkt(3) = address - 100
GPIO(SRAM_CS) = 0
OUTPUT MSPI IFACE, outPkt(0), 4
GPIO(SRAM_CS) = 1
NEXT
' We only read back location 100 to 110 because reading all
' locations from 100 to 500 takes too long!
FOR address = 100 to 110
outPkt(0) = SPI_READ
outPkt(1) = address / 256
outPkt(2) = address MOD 256
outPkt(3) = 0x5A
' Dummy data that will be
replace by read data.

2011 ... North Pole Engineering, Inc.

Programming Examples

163

GPIO(SRAM_CS) = 0
OUTPUT MSPI IFACE, outPkt(0), 4
GPIO(SRAM_CS) = 1
numBytes = INPUT MSPI IFACE, inPkt
sramValue = inPkt(3)

' This is the return data

value.
msgStr = "Value read = " & STR$(sramValue) & CHR$(10)
numBytes = OUTPUT UART0 msgStr
DELAY 20
NEXT
REPEAT_TASK
END

6.2

UART0 Input / Output


'
'
'
'
'
'
'
'
'
DIM
DIM
DIM
DIM

UART Test Program


This program sends a string out UART0, then waits for input.
When the input is terminated with a CR, the input is echoed back,
Note: UART0 must be enabled in the project configuration panel
and the settings used must be the same as the terminal program
used to test.

sOut
sIn
sEcho
iCount

AS
AS
AS
AS

STRING
STRING
STRING
INTEGER

TASK
sOut = "Waiting for data: "
OUTPUT UART0 sOut

' Output Prompt.

DO
'Wait for some characters to be received on the UART.
DO
iCount = INPUT UART0 sIn
UNTIL iCount > 0
sEcho = sEcho & sIn
' Concatenate input characters.
UNTIL INSTR$(sEcho, 1, CHR$(13)) > 0
' Search the string for a CR,
exit loop if found.
OUTPUT UART0 CHR$(10)
OUTPUT UART0 sEcho
REPEAT_TASK
END

2011 ... North Pole Engineering, Inc.

' Output a Line Feed (LF).


' Output string input by user.

164

WiFi-IT! Basic Language Reference

Definitions
The following terms and acronyms are used throughout this manual.
Connection ID
(CID)
PCP

RTE

Subnet

Connection ID: In WiFi-Basic, this is synonymous with socket


Project Configuration Panel: The GUI used to setup Wi-Fi default values
and enable and initialize peripherals used in the program. To access the
PCP, right-click the project and select Edit Project Device Configuration.
Run Time Engine: The firmware that runs on the WiFi-IT! module and
provides the environment for running WiFi-Basic programs.
A sub-network, or subnet, is a logically visible, distinctly addressed part of
a single Internet Protocol network. The process of subnetting is the
division of a computer network into groups of computers that have a
common, designated IP address routing prefix.
The process of subnetting involves the separation of the network and
subnet portion of an address from the host identifier (see the example
below). This is performed by a bitwise AND operation between the IP
address and the (sub)network prefix. The result yields the network
address or prefix, and the remainder is the host identifier.
Binary form

IP address
Subnet mask
Network prefix
Host part
WAP

Dotted-decimal

11000000.10101000.00000101.10000010 192.168.5.130
11111111.11111111.11111111.11000000 255.255.255.192
11000000.10101000.00000101.10000000 192.168.5.128
00000000.00000000.00000000.00000010 0.0.0.2

Wireless Access Point: A device that allows wireless communication


devices to connect to a wireless network.

IP Address

An Internet Protocol (IP) address that uniquely identifies each node on a


network. The WiFi-IT! module should either be assigned an IP address via
DHCP when joining a network, or use have an IP address preconfigured in
the PCP.

Port

Both TCP and UDP use sockets to establish host-to-host communications.


Sockets bind the WiFi-Basic application to service ports that function as
the endpoints of data transmission. A port is a software structure that is
identified by the port number. Ports are maintained by the operating
system. When a socket is bound to a local port, other sockets may not be
bound to that port. When data is received from a remote host, that host
2011 ... North Pole Engineering, Inc.

Definitions

165

specifies the destination port. The application owning the socket bound
to that port can then receive the data by calling RECEIVE on the associated
socket. Port numbers are 16-bit integer values (0 - 65535). Unless your
application is communicating with a standard application (such as a web
browser), it is best to use ports in the last range (49152 - 65525), although
any port will operate in WiFi-Basic.
Endpoint

The term 'endpoint' refers to the combination of IP address and port


number. Sockets are always associated with endpoints and network
communications are always between endpoints.

Socket

A structure for sending and receiving data. When sending, a socket is


associated with a remote endpoint. When receiving, a socket is
associated with a local endpoint.

Gateway IP

The IP address of a node acting as a gateway between the Local Area


Network (LAN) to which this node is connected and a broader area
network, such as the internet. The Gateway IP is required for routing
outside of the local network.

Subnet Mask

Indicates the portion of the IP address that does not change for traffic
routed within the Local Area Network (LAN). I.e., if all IP addresses on the
LAN begin with "192.168.10" such as "192.168.10.3" or "192.168.10.4", the
subnet mask will be "255.255.255.0".

MAC address

An address that uniquely identifies the hardware interface which is used


to connect to the network. All physical adaptors, be they network
interface cards for a PC, smart-phones, or WiFi-IT! modules have a
globally unique MAC address assigned to them.
IP addresses are mapped to MAC addresses by the network infrastructure
for signal transmission.
The MAC address of the WiFi-IT! module can be read by a WiFi-Basic
program using MAC_ADDRESS.

DHCP

Dynamic Host Configuration Protocol: DHCP is a method for assigning IP


addresses on a local area network. If DHCP Enabled is checked in the PCP,
the WiFi-IT! module will automatically initiate the DHCP process upon
joining a network. A DHCP server must be present to respond and assign
an IP address to the node.

RSSI

Received Signal Strength Indication: An indication of the signal strength


of the wireless connection as seen by the WiFi-IT! module. RSSI is a
negative number between 0 and 255. -20 indicates a good connection
whereas -70 indicates a poor connection. The current value can be read
using RSSI.

2011 ... North Pole Engineering, Inc.

166

WiFi-IT! Basic Language Reference

SSID

Service Set Identifier: The name of the wireless network.

Broadcast

A message that is sent to all nodes on the network. This is usually done
by specifying an IP address of "255.255.255.255".

Multicast

A message that is sent to specific nodes on the network. To accomplish


this, nodes wishing to receive the message must register for a specific IP
address and port number that is in the range specifically designated for
multicasting. The sender, such as a WiFi-IT! module, simply sends a
packet to that IP address.

2011 ... North Pole Engineering, Inc.

Index

Index

-CCONST

---

-D-

133

DIM

-""

145

-F-

135

false

-&&

134

-L-

135

LINK

-**

81

-M-

133

MOD

-//

133

-N-

133

NOT

-++

134

-O-

133

OR

-<-

134

-S-

<
134
<=
134
<>
134

STATIC

146

-T-

->-

true
>
134
>=
134

134

-V-

-AAND
134
Array Variables

144

Variable Lifetime
145
Variable Types
145
145

2011 ... North Pole Engineering, Inc.

167

168

WiFi-IT! Basic Language Reference

-XXOR

134

2011 ... North Pole Engineering, Inc.

Back Cover

You might also like