B9X Basic GUI Module

B9X Basic — Complete User Reference

Learn the language, build touchscreen applications, and use audio, files, networking, and telephone features.
B9X Electronics • User Documentation

Beginner to Advanced • Updated 16 October 2026

This guide takes you from your first B9X Basic program to complete applications using touchscreens, files, networking, audio, and connected devices. Each function includes its purpose, calling syntax, and a practical example.
Includes peer-to-peer telephone calling, 255-character caller names, caller IP and listening port, callback examples, and the complete built-in icon gallery.

Contents

Getting Started Top ↑

B9X Basic helps you create ESP32-S3 applications using familiar BASIC programming concepts. Work with numbers, text, arrays, decisions, loops, functions, digital inputs and outputs, files, networking, touchscreens, audio, MQTT, VOIP, voice services, and LEDs.

Statements in the supplied language use a semicolon at the end of ordinary one-line statements. Block structures such as if...endif, while...wend, for...next, sub...end sub and function...end function organize larger programs.

Your first program

let message$="Hello from B9X Basic";
print message$;

let a=10;
let b=25;
print a+b;
Beginner tip: Start with small programs. Test variables, printing, and one hardware function at a time. Once each part works, combine them into the final application.

Comments

// This is a line comment
' This is also a line comment
/* This is a block comment.
   It can span multiple lines. */

Comments are ignored by the language and are strongly recommended for documenting pin assignments, element numbers, network settings and the purpose of each section of the program.

B9X Basic Language Top ↑

Numeric expressions use ordinary arithmetic operators. String variables and functions that return text end with $. You can create your own functions with numeric or string parameters and return either numbers or text.

Statement terminators

Ordinary assignments, function calls, print, call, and return statements end with a semicolon.

a=10;
print a;
call ShowStatus();

Case and names

Use clear, descriptive names. Names may contain letter sequences such as and, or, and to. These sequences within a name are not separate keywords.

Numeric and string expressions

Numeric expressions can contain variables, constants, arithmetic, comparisons, logical operators, arrays and numeric functions. String expressions can contain string literals, string variables, concatenation with +, built-in string functions and string-returning functions.

Variables & Data Top ↑

Numeric variables

let temperature=72.5;
counter=counter+1;
print temperature;

Numeric values are represented by the language numeric type and may contain whole or fractional values.

String variables

let name$="B9X";
let message$="Hello "+name$;
print message$;

A string variable ends in $. String literals are enclosed in double quotation marks.

Assignment

Both forms below are supported for numeric assignment:

let a=10;
a=20;

Use let for every string assignment, including when changing an existing string variable.

let status$="READY";
let status$="RUNNING";

Operators & Expressions Top ↑

CategoryOperatorsExample
Arithmetic+ - * / **power=2**8;
Comparison== != < <= > >=if temp>75 then
Logical ANDand or &&if a==1 and b==1 then
Logical ORor or ||if a==1 or b==1 then
Logical NOTnot or !if not ready then
String concatenation+msg$="A"+"B";

String equality and inequality are supported with == and !=. String comparison is exact and case-sensitive, so "Hello" and "hello" are different.

if response$!="done" then
  print "Waiting";
endif

Program Flow Top ↑

IF / ELSE / ENDIF

if temperature>80 then
  print "HOT";
else
  print "NORMAL";
endif

WHILE / WEND

counter=0;
while counter<5 do
  print counter;
  counter=counter+1;
wend

FOR / NEXT

Use FOR loops to repeat a section of your program a set number of times. The examples use do after the loop range.

for i=0 to 10 do
  print i;
next

for i=0 to 10 step 2 do
  print i;
next
Loop design: Add a short wait() inside a polling loop to keep displays, audio, and networking responsive.

Subs & Functions Top ↑

Subroutines

sub SayHello()
  print "Hello";
end sub

call SayHello();

Subroutines take no parameters. Define them with sub … end sub and invoke them with call.call.

User functions

User functions may accept numeric and/or string parameters. Numeric functions return a numeric expression; string-returning functions use a name ending in $ and return a string expression.

function add(a,b)
  return a+b;
end function

function greeting$(name$)
  return "Hello "+name$;
end function

print add(10,20);
print greeting$("Robert");

Function parameters are local to the function. You can pass numbers and strings and return either a number or a string.

Arrays Top ↑

Numeric arrays are declared with dim and indexed with square brackets.

dim values[100];

for i=0 to 10 do
  values[i]=i*10;
next

print values[5];
Tip: Keep array indexes inside the declared range. Give arrays names that describe what they store, such as samples, temperatures, or levels.

Practical Limits Top ↑

FeatureLimit or convention
Numeric variablesUp to 256
String variablesUp to 256
String valueUp to 512 bytes; use ASCII when counting visible characters
Numeric arraysUp to 64 arrays, each up to 1024 entries
Function argumentsUp to 16
Touchscreen elementsUp to 48 at once
Touchscreen textUp to 255 characters
Touch event textUp to 63 characters
Telephone caller nameUp to 255 printable ASCII characters
Online speech requestKeep to 255 characters or fewer

Keep array indexes inside the declared bounds, strings within their limits, and numeric inputs inside the range stated for each function. Online responses and file text may be shortened by the available string length; use small requests and files when you need the full result.

Strings Top ↑

B9X Basic includes the usual embedded string operations for building messages, parsing commands and formatting display text.

let name$="ROBERT";
print left$(name$,3);
print right$(name$,2);
print mid$(name$,2,3);
print len(name$);
print asc("A");
print chr$(65);
number=val("123.5");
let text$=str$(number);

instr() is useful for parsing messages. The two-argument form searches the whole string; the three-argument form starts at a supplied position.

Using the Function Reference Top ↑

Arguments are values inside parentheses. Their order matters: a function expecting (number,x,y,…) cannot accept the same values in a different order. A name ending in $ is text; other parameters are numeric. Every ordinary statement ends with a semicolon.

let title$="Kitchen";
retVal=displaySetText(20,title$);
let caller$=p2pCallerID$();
let callerPort=p2pCallerPort();

Success values differ between function families. Many telephone and file commands return 1 for success. VOIP and many display commands return 0 for success. Read the Returns line for each function; a nonzero result is not universally success.

Result styleMeaningExample
1/0 command1 accepted/success; 0 failedp2pStart(), mp3Play(), sdWriteText()
0/error command0 success; nonzero errorvoipInit(), displaySetText()
State/valueA value, rather than a command resultp2pStatus(), batteryVoltage()
TextReturned string; often empty when no result is readygetDisplayMessage$(), vrxGetTranscript$()

A request being accepted does not mean it has finished. Dialing, online answers, transcription, and speech playback take time. Poll their state or result while using short wait() calls. Test with small examples before combining features.

Complete Function Reference Top ↑

Example return-value convention used throughout this reference: Numeric/status-returning functions are shown as retVal=funct();. String-returning functions are shown as let s$=funct$();. Every function entry below includes an example using this convention.

This reference describes the functions available to your B9X Basic programs. Use the spelling and argument order shown for each function.

System & timing

wait(milliseconds)

Pauses your program for the requested number of milliseconds, then returns that number.

Returns: The requested delay value in milliseconds.

ParameterTypeMeaning
millisecondsNumberDelay or AEC reference lag in milliseconds; see the function’s allowed range.
retVal=wait(250);

Note: Use short waits in polling loops to keep your device responsive.

getTicks(mode)

Returns elapsed time since boot. mode 0=seconds, 1=milliseconds, 2=microseconds.

Returns: Elapsed time: mode 0 seconds, 1 milliseconds, 2 microseconds.

ParameterTypeMeaning
modeNumber0 seconds, 1 milliseconds, 2 microseconds.
retVal=getTicks(1);

Note: Useful for elapsed-time measurements and non-blocking timing.

memx()

Returns currently available 8-bit-capable heap memory.

Returns: Available memory in bytes.

retVal=memx();

Note: Useful while diagnosing memory-heavy applications.

restart()

Restarts the controller.

Returns: Does not normally return because the device restarts.

retVal=restart();

Note: Use when an application intentionally needs a software reboot.

wifiIsConnected()

Returns a nonzero value when Wi-Fi is connected.

Returns: 1 when connected, otherwise 0.

retVal=wifiIsConnected();

Note: Network functions require a working Wi-Fi connection.

Variables, conversion & strings

len(text$)

Returns the number of characters in a string.

Returns: Length of the text in bytes; ASCII characters occupy one byte each.

ParameterTypeMeaning
text$StringText in double quotes or a string variable ending in $.
retVal=len("B9X");

Note: Built into the language.

asc(text$)

Returns the character code of the first character.

Returns: Character code of the first character.

ParameterTypeMeaning
text$StringText in double quotes or a string variable ending in $.
retVal=asc("A");

Note: Built into the language.

chr$(number)

Returns a one-character string for a character code.

Returns: Text. See the description for the empty-result behavior.

ParameterTypeMeaning
numberNumberNumeric value to convert; chr$ uses a character code.
let s$=chr$(65);

Note: Built into the language.

left$(text$, count)

Returns the leftmost count characters.

Returns: Text. See the description for the empty-result behavior.

ParameterTypeMeaning
text$StringText in double quotes or a string variable ending in $.
countNumberNumber of characters, or number of LEDs when initializing a strip.
let s$=left$("ROBERT",3);

Note: Returns “ROB”.

right$(text$, count)

Returns the rightmost count characters.

Returns: Text. See the description for the empty-result behavior.

ParameterTypeMeaning
text$StringText in double quotes or a string variable ending in $.
countNumberNumber of characters, or number of LEDs when initializing a strip.
let s$=right$("ROBERT",2);

Note: Returns “RT”.

mid$(text$, start, count)

Returns a substring beginning at start for count characters.

Returns: Text. See the description for the empty-result behavior.

ParameterTypeMeaning
text$StringText in double quotes or a string variable ending in $.
startNumberOne-based starting position.
countNumberNumber of characters, or number of LEDs when initializing a strip.
let s$=mid$("ROBERT",2,3);

Note: Use for parsing fixed-format strings.

str$(number)

Converts a numeric value to a string.

Returns: Text. See the description for the empty-result behavior.

ParameterTypeMeaning
numberNumberNumeric value to convert; chr$ uses a character code.
let s$=str$(25);

Note: Useful when building messages or display text.

val(text$)

Converts a numeric string to a number.

Returns: Numeric conversion of the supplied text.

ParameterTypeMeaning
text$StringText in double quotes or a string variable ending in $.
retVal=val("18000");

Note: Use only with text that represents a number.

instr(text$, find$)

Returns the position of one string inside another.

Returns: One-based position of a match, or 0 if not found.

ParameterTypeMeaning
text$StringText in double quotes or a string variable ending in $.
find$StringText to search for.
retVal=instr("B9X BASIC","BASIC");

Note: A three-argument form also accepts a starting position.

instr(start, text$, find$)

Searches for find$ beginning at start.

Returns: One-based position of a match, or 0 if not found.

ParameterTypeMeaning
startNumberOne-based starting position.
text$StringText in double quotes or a string variable ending in $.
find$StringText to search for.
retVal=instr(5,"B9X BASIC BASIC","BASIC");

Note: Useful when parsing repeated fields.

fmt$(number, format$)

Formats a number as text using a VB-style format pattern.

Returns: Text. See the description for the empty-result behavior.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
format$StringNumeric format pattern, such as “0.00”.
let s$=fmt$(12.345,"0.00");

Note: Useful for display labels and reports.

trim$(text$)

Returns a copy with leading and trailing ASCII space characters removed.

Returns: Text. See the description for the empty-result behavior.

ParameterTypeMeaning
text$StringText in double quotes or a string variable ending in $.
let s$=trim$("  B9X Basic  ");

Removes leading and trailing space characters only. Tabs and line endings remain.

Math

abs(x)

Returns the absolute value of x.

Returns: Absolute value of x.

ParameterTypeMeaning
xNumberNumeric input. Angles for sin/cos/tan are in radians; asin/acos require -1 through 1. log/log10 require positive input; sqrt requires zero or greater.
retVal=abs(-12);
log(x)

Returns the natural logarithm.

Returns: Natural logarithm; x must be positive.

ParameterTypeMeaning
xNumberNumeric input. Angles for sin/cos/tan are in radians; asin/acos require -1 through 1. log/log10 require positive input; sqrt requires zero or greater.
retVal=log(10);
log10(x)

Returns the base-10 logarithm.

Returns: Base-10 logarithm; x must be positive.

ParameterTypeMeaning
xNumberNumeric input. Angles for sin/cos/tan are in radians; asin/acos require -1 through 1. log/log10 require positive input; sqrt requires zero or greater.
retVal=log10(100);
round(x)

Rounds x to the nearest integral value.

Returns: Nearest integer; halfway values round away from zero.

ParameterTypeMeaning
xNumberNumeric input. Angles for sin/cos/tan are in radians; asin/acos require -1 through 1. log/log10 require positive input; sqrt requires zero or greater.
retVal=round(12.6);
exp(x)

Returns e raised to x.

Returns: e raised to x.

ParameterTypeMeaning
xNumberNumeric input. Angles for sin/cos/tan are in radians; asin/acos require -1 through 1. log/log10 require positive input; sqrt requires zero or greater.
retVal=exp(1);
sqrt(x)

Returns the square root.

Returns: Square root; x must be zero or greater.

ParameterTypeMeaning
xNumberNumeric input. Angles for sin/cos/tan are in radians; asin/acos require -1 through 1. log/log10 require positive input; sqrt requires zero or greater.
retVal=sqrt(144);
sin(x)

Returns the sine of an angle in radians.

Returns: Sine of x, with x in radians.

ParameterTypeMeaning
xNumberNumeric input. Angles for sin/cos/tan are in radians; asin/acos require -1 through 1. log/log10 require positive input; sqrt requires zero or greater.
retVal=sin(0.5);
cos(x)

Returns the cosine of an angle in radians.

Returns: Cosine of x, with x in radians.

ParameterTypeMeaning
xNumberNumeric input. Angles for sin/cos/tan are in radians; asin/acos require -1 through 1. log/log10 require positive input; sqrt requires zero or greater.
retVal=cos(0.5);
tan(x)

Returns the tangent of an angle in radians.

Returns: Tangent of x, with x in radians.

ParameterTypeMeaning
xNumberNumeric input. Angles for sin/cos/tan are in radians; asin/acos require -1 through 1. log/log10 require positive input; sqrt requires zero or greater.
retVal=tan(0.5);
asin(x)

Returns the inverse sine in radians.

Returns: Inverse sine in radians; x must be -1 through 1.

ParameterTypeMeaning
xNumberNumeric input. Angles for sin/cos/tan are in radians; asin/acos require -1 through 1. log/log10 require positive input; sqrt requires zero or greater.
retVal=asin(0.5);
acos(x)

Returns the inverse cosine in radians.

Returns: Inverse cosine in radians; x must be -1 through 1.

ParameterTypeMeaning
xNumberNumeric input. Angles for sin/cos/tan are in radians; asin/acos require -1 through 1. log/log10 require positive input; sqrt requires zero or greater.
retVal=acos(0.5);
atan(x)

Returns the inverse tangent in radians.

Returns: Inverse tangent in radians.

ParameterTypeMeaning
xNumberNumeric input. Angles for sin/cos/tan are in radians; asin/acos require -1 through 1. log/log10 require positive input; sqrt requires zero or greater.
retVal=atan(0.5);
sinh(x)

Returns the hyperbolic sine.

Returns: Hyperbolic sine of x.

ParameterTypeMeaning
xNumberNumeric input. Angles for sin/cos/tan are in radians; asin/acos require -1 through 1. log/log10 require positive input; sqrt requires zero or greater.
retVal=sinh(0.5);
cosh(x)

Returns the hyperbolic cosine.

Returns: Hyperbolic cosine of x.

ParameterTypeMeaning
xNumberNumeric input. Angles for sin/cos/tan are in radians; asin/acos require -1 through 1. log/log10 require positive input; sqrt requires zero or greater.
retVal=cosh(0.5);
rnd(min, max)

Returns a random integer in the inclusive range min through max.

Returns: Random integer between min and max inclusive. Use min less than or equal to max.

ParameterTypeMeaning
minNumberLower inclusive bound.
maxNumberUpper inclusive bound.
retVal=rnd(1,6);
modulo(a, b)

Returns the integer remainder of a divided by b.

Returns: Integer remainder a divided by b. b must not be zero. Fractional arguments are converted to integers.

ParameterTypeMeaning
aNumberDividend, converted to an integer.
bNumberNonzero divisor, converted to an integer.
retVal=modulo(17,5);

GPIO & sensors

makeInput(gpio)

Configures a GPIO as an input with pull-down.

Returns: The GPIO number supplied. Choose a suitable free GPIO greater than 0.

ParameterTypeMeaning
gpioNumberSuitable free GPIO number.
retVal=makeInput(13);

Note: The GPIO number must be appropriate for the board and not already reserved.

getInput(gpio)

Reads a digital input and returns its logic level.

Returns: 0 for low or 1 for high. Configure the input first.

ParameterTypeMeaning
gpioNumberSuitable free GPIO number.
retVal=getInput(13);

Note: Returns the current digital level.

makeOutput(gpio)

Configures a GPIO as an output.

Returns: The GPIO number supplied. Choose a suitable free GPIO greater than 0.

ParameterTypeMeaning
gpioNumberSuitable free GPIO number.
retVal=makeOutput(12);
setHigh(gpio)

Drives an output high.

Returns: The GPIO number supplied. Choose a suitable free GPIO greater than 0.

ParameterTypeMeaning
gpioNumberSuitable free GPIO number.
retVal=setHigh(12);
setLow(gpio)

Drives an output low.

Returns: The GPIO number supplied. Choose a suitable free GPIO greater than 0.

ParameterTypeMeaning
gpioNumberSuitable free GPIO number.
retVal=setLow(12);
readTemperature(gpio)

Initializes/reads the supported DS18B20 temperature sensor on the specified GPIO and returns Celsius.

Returns: Temperature in degrees Celsius.

ParameterTypeMeaning
gpioNumberSuitable free GPIO number.
retVal=readTemperature(4);

Note: Allow for sensor conversion time in application design.

motionInit(uartPort,receiveGPIO)

Starts the supported RD-03 motion/distance sensor on a UART port and receive GPIO.

Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.

ParameterTypeMeaning
uartPortNumberUnused UART port number supported by the board.
receiveGPIONumberFree GPIO receiving the sensor TX signal.
retVal=motionInit(2,freeRxGPIO);

Connect the sensor TX to the selected receive GPIO and share ground. Choose an unused UART and pin.

motionGetDistance()

Returns the latest distance value reported by the initialized motion sensor.

Returns: The latest sensor-reported distance value.

retVal=motionGetDistance();

Call motionInit() first and allow time for sensor reports. This is the sensor-reported value; verify the scale against your sensor documentation.

batteryVoltage()

Returns the measured battery voltage in volts.

Returns: Measured battery voltage in volts.

retVal=batteryVoltage();

Note: Use with the battery connected to the device’s battery input.

batteryLevel()

Returns the estimated battery charge level.

Returns: Estimated charge percentage from 0 to 100.

retVal=batteryLevel();

Note: Intended as a convenient battery percentage/level indication.

NVS & logging

setNVS(key$, value$)

Stores a string value under a string key in nonvolatile storage.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
key$StringStorage key name, up to 15 characters. Choose a consistent name such as “host”.
value$StringText to store under the specified storage key.
retVal=setNVS("fHost","192.168.1.130");

Note: Use for configuration that should survive restart.

getNVS$(key$)

Returns the stored string for a key.

Returns: Text. See the description for the empty-result behavior.

ParameterTypeMeaning
key$StringStorage key name, up to 15 characters. Choose a consistent name such as “host”.
let s$=getNVS$("fHost");

Note: Check for an empty string when a value may not exist.

logData(name$, data$)

Records application data under the supplied log name.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
name$StringName string; see the function’s length and character rules.
data$StringText to publish or log.
retVal=logData("temperature","72.5");

Note: Both arguments are strings.

SD card files

sdMounted()

Returns 1 when the SD card is mounted, otherwise 0.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

retVal=sdMounted();

Note: The SD card must be mounted before you use file functions. Check sdMounted() first.

sdExists(path$)

Returns 1 if the path exists.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
path$StringComplete file or directory path, such as “/sdcard/config.txt”.
retVal=sdExists("/sdcard/config.txt");

Note: Use complete mounted paths.

sdFileSize(path$)

Returns file size.

Returns: The file size in bytes, or -1 if the file cannot be examined.

ParameterTypeMeaning
path$StringComplete file or directory path, such as “/sdcard/config.txt”.
retVal=sdFileSize("/sdcard/config.txt");
sdReadText$(path$)

Reads text from a file into a BASIC string.

Returns: Text. See the description for the empty-result behavior.

ParameterTypeMeaning
path$StringComplete file or directory path, such as “/sdcard/config.txt”.
let s$=sdReadText$("/sdcard/config.txt");

Note: Use for small text files such as configuration files. Large files may exceed the supported text length.

Use small text files. The returned BASIC string can hold at most 512 bytes.

sdList$(path$)

Returns a directory listing string.

Returns: Text. See the description for the empty-result behavior.

ParameterTypeMeaning
path$StringComplete file or directory path, such as “/sdcard/config.txt”.
let s$=sdList$("/sdcard");

Large directory listings can be shortened. Use sdFindFirst$()/sdFindNext$() to process names one at a time.

sdFindFirst$(pattern$)

Starts a file search and returns the first matching name, without its parent directory.

Returns: Text. See the description for the empty-result behavior.

ParameterTypeMeaning
pattern$StringDirectory plus wildcard pattern, such as “/sdcard/*.mp3”.
let s$=sdFindFirst$("/sdcard/*.mp3");

Use * for any sequence and ? for one character. Matching is case-insensitive. Empty text means no match. A new search replaces the previous search.

sdFindNext$()

Returns the next name in the active file search, or empty text at the end.

Returns: Text. See the description for the empty-result behavior.

let s$=sdFindNext$();

Start with sdFindFirst$(). Add the directory path before passing a returned filename to mp3Play() or another file function.

sdFindPrevious$()

Returns the previous name in the active file search, or empty text when no previous match exists.

Returns: Text. See the description for the empty-result behavior.

let s$=sdFindPrevious$();

After moving past the end with sdFindNext$(), this returns the final matching name.

sdWriteText(path$, text$)

Writes text to a file, replacing its contents.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
path$StringComplete file or directory path, such as “/sdcard/config.txt”.
text$StringText in double quotes or a string variable ending in $.
retVal=sdWriteText("/sdcard/test.txt","Hello");

Note: Returns 1 on success.

sdAppendText(path$, text$)

Appends text to a file.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
path$StringComplete file or directory path, such as “/sdcard/config.txt”.
text$StringText in double quotes or a string variable ending in $.
retVal=sdAppendText("/sdcard/log.txt","Next line");
sdDelete(path$)

Deletes a file/path.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
path$StringComplete file or directory path, such as “/sdcard/config.txt”.
retVal=sdDelete("/sdcard/old.txt");
sdRename(old$, new$)

Renames a file/path.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
old$StringExisting full path.
new$StringNew full path.
retVal=sdRename("/sdcard/a.txt","/sdcard/b.txt");
sdMakeDir(path$)

Creates a directory.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
path$StringComplete file or directory path, such as “/sdcard/config.txt”.
retVal=sdMakeDir("/sdcard/data");

MP3 audio

mp3Play(path$)

Starts MP3 playback from the specified path.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
path$StringComplete file or directory path, such as “/sdcard/config.txt”.
retVal=mp3Play("/sdcard/music.mp3");

Note: Playback runs while your BASIC program continues.

mp3Stop()

Stops MP3 playback.

Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.

retVal=mp3Stop();
mp3Pause()

Pauses playback.

Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.

retVal=mp3Pause();
mp3Resume()

Resumes paused playback.

Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.

retVal=mp3Resume();
mp3IsPlaying()

Returns 1 while MP3 playback is active.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

retVal=mp3IsPlaying();
mp3SetVolume(level)

Sets the MP3 playback volume.

Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.

ParameterTypeMeaning
levelNumberA level from 0 through 100.
retVal=mp3SetVolume(50);
mp3LastResult()

Returns the last MP3 result/status value.

Returns: The last playback result; 0 indicates success. Use mp3LastError$() for explanatory text.

retVal=mp3LastResult();
mp3LastError$()

Returns text describing the last MP3 error.

Returns: Text. See the description for the empty-result behavior.

let s$=mp3LastError$();

Note: Useful for troubleshooting failed playback.

MQTT

initMQTTClient(broker$, user$, password$)

Starts the MQTT client using broker and credential strings.

Returns: 0 on successful client startup; a nonzero error value on failure.

ParameterTypeMeaning
broker$StringMQTT broker URI, such as “mqtt://192.168.1.10”.
user$StringBroker username, or empty text when not required.
password$StringPassword string; use matching settings on communicating devices.
retVal=initMQTTClient("mqtt://192.168.1.10","user","password");

Note: Wi-Fi must be connected.

mqttClientSubscribe(topic$)

Subscribes to a topic.

Returns: A message ID, or -1 if the request fails.

ParameterTypeMeaning
topic$StringMQTT topic name.
retVal=mqttClientSubscribe("shop/temp");
mqttClientUnsubscribe(topic$)

Removes a subscription.

Returns: A message ID, or -1 if the request fails.

ParameterTypeMeaning
topic$StringMQTT topic name.
retVal=mqttClientUnsubscribe("shop/temp");
mqttClientPublish(topic$, data$)

Publishes a string payload.

Returns: A message ID, or a negative value if publishing fails.

ParameterTypeMeaning
topic$StringMQTT topic name.
data$StringText to publish or log.
retVal=mqttClientPublish("shop/temp","72.5");

Note: Publishes with MQTT quality of service level 1 (at least once).

mqttClientGetMessage$()

Returns the next queued MQTT event/message as a bracketed string.

Returns: Text. See the description for the empty-result behavior.

let s$=mqttClientGetMessage$();

Note: Messages include event type, message id, topic and data. An empty string means no queued message.

VOIP / UDP radio audio

voipInit(localPort, txBclk, txWs, txData, rxBclk, rxWs, rxData)

Initializes VOIP UDP audio with encryption, an audio sample rate of 11025 Hz, a 5-second connection-check interval, and a 120-second connection timeout.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
localPortNumberThis device’s UDP listening port, 1–65535.
txBclkNumberTransmit bit-clock GPIO; -1 selects the onboard defaults.
txWsNumberTransmit word-select GPIO; -1 selects the onboard defaults.
txDataNumberTransmit data GPIO; -1 selects the onboard defaults.
rxBclkNumberReceive bit-clock GPIO; -1 selects the onboard defaults.
rxWsNumberReceive word-select GPIO; -1 selects the onboard defaults.
rxDataNumberReceive data GPIO; -1 selects the onboard defaults.
retVal=voipInit(24000,-1,-1,-1,-1,-1,-1);

Note: Use -1 for audio pin arguments to select the device’s default audio connections.

voipConnect(host$, port, password$, node$, key$)

Sends a connection request to B9X Voice Server and stores the server/session information.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
host$StringDestination IPv4 address or DNS hostname.
portNumberDestination network port.
password$StringPassword string; use matching settings on communicating devices.
node$StringName identifying this device to B9X Voice Server.
key$StringSecret key; see the function-specific requirements.
retVal=voipConnect("192.168.1.130",18000,password$,"MYNODE",key$);

Note: Wait until voipIsConnected()==1 before starting listening.

voipIsConnected()

Returns 1 after the server connection has been established.

Returns: 1 when connected, otherwise 0.

retVal=voipIsConnected();

Note: Use this to wait for CONNECT_OK.

voipClose()

Requests that B9X Voice Server connection be closed.

Returns: 0 on success; a nonzero error value on failure.

retVal=voipClose();
voipStartListening()

Starts receiving/playing server audio.

Returns: 0 on success; a nonzero error value on failure.

retVal=voipStartListening();

Note: Important: call only after voipIsConnected() confirms the connection.

voipHaltListening()

Stops VOIP receive/playback.

Returns: 0 on success; a nonzero error value on failure.

retVal=voipHaltListening();
voipStartSending()

Starts microphone audio transmission.

Returns: 0 on success; a nonzero error value on failure.

retVal=voipStartSending();
voipHaltSending()

Stops microphone audio transmission.

Returns: 0 on success; a nonzero error value on failure.

retVal=voipHaltSending();
voipIsSending()

Returns the current sending state.

Returns: 1 while sending is enabled, otherwise 0.

retVal=voipIsSending();
voipSetVolume(level)

Sets received speaker volume from 0 through 100.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
levelNumberA level from 0 through 100.
retVal=voipSetVolume(20);

Note: 100 preserves full PCM amplitude; 0 mutes.

voipSetMicGain(level)

Sets microphone gain from 0 through 100.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
levelNumberA level from 0 through 100.
retVal=voipSetMicGain(100);
voipGetMicLevel()

Returns the instantaneous/recent microphone audio level on a 0-100 scale.

Returns: Recent microphone peak on a 0–100 scale.

retVal=voipGetMicLevel();
voipGetSpeakerLevel()

Returns the instantaneous/recent speaker audio level on a 0-100 scale.

Returns: Recent speaker peak on a 0–100 scale.

retVal=voipGetSpeakerLevel();
voipEnableVOX(sensitivity)

Enables voice-operated transmit monitoring using the supplied sensitivity threshold.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
sensitivityNumberVOX audio threshold; lower values trigger on quieter audio.
retVal=voipEnableVOX(700);

Note: Lower threshold values trigger transmission on quieter sounds.

voipDisableVOX()

Disables VOX.

Returns: 0 on success; a nonzero error value on failure.

retVal=voipDisableVOX();
voipIsVOXActive()

Returns whether VOX is currently active/open.

Returns: 1 while voice detection is triggered, otherwise 0.

retVal=voipIsVOXActive();

P2P telephone & direct-peer audio

p2pSetCallerID(name$)

Sets the name this device sends with outgoing telephone calls.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
name$StringName string; see the function’s length and character rules.
retVal=p2pSetCallerID("Kitchen Telephone");

Accepts 0–255 printable ASCII characters including spaces. Returns 1 when accepted, 0 when invalid. An empty name selects IP-address display at the receiver. Set before dialing. Set again after reboot; it is not saved automatically. Both devices need the current version for long caller names.

p2pCallerID$()

Returns the last incoming caller’s name, or its source IP address when no name is supplied.

Returns: Text. See the description for the empty-result behavior.

let s$=p2pCallerID$();

Available as soon as p2pStatus()==2. Remains available after the call ends until another incoming call replaces it or the telephone service is reopened or closed. Names are selected by the calling device.

p2pCallerIP$()

Returns the source IPv4 address of the last incoming caller.

Returns: Text. See the description for the empty-result behavior.

let s$=p2pCallerIP$();

Empty before an incoming call. For an Internet call this is normally the public address of the caller’s router; on a LAN it is the caller’s LAN address. Save it with p2pCallerPort() to call back.

p2pCallerPort()

Returns the listening port advertised by the last incoming caller.

Returns: Listening port 1–65535; 0 when no caller port is available.

retVal=p2pCallerPort();

Returns 0 before a call or after caller information is cleared. Older senders may supply only their observed source port. Update both devices for an explicitly advertised listening port. For Internet callbacks, forward the same external and internal UDP port.

The command functions below return 1 when successful or when a request is accepted, and 0 on failure, unless stated otherwise. Dialing and call-control requests finish after the function returns. Check p2pStatus() to follow a call. P2P telephone calling and server-based VOIP have separate setup procedures.

p2pStart(localPort,key$,password$)

Starts the telephone service on a local UDP port without dialing a peer. Returns 1 on success, 0 on failure.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
localPortNumberThis device’s UDP listening port, 1–65535.
key$StringSecret key; see the function-specific requirements.
password$StringPassword string; use matching settings on communicating devices.
retVal=p2pStart(24000,key$,password$);

Notes: Call after Wi-Fi connects. Port: 1–65535. key$ must contain exactly 32 ASCII characters, used directly as the AES-256 key, not hexadecimal text to decode. password$ may be empty or contain 8–127 bytes. Both peers must use matching keys and password settings. Call once at startup. Manual answering is the default. Key precedes password in BASIC.

p2pDial(host$,remotePort)

Queues an outgoing call. Returns 1 if the request is accepted, 0 if invalid or the service is already handling a call.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
host$StringDestination IPv4 address or DNS hostname.
remotePortNumberDestination UDP listening port, 1–65535.
retVal=p2pDial("192.168.1.131",24000);

Notes: Use p2pStatus() to follow progress; a successful return does not mean the other device answered. Host may be an IP address or resolvable hostname. Start the service first.

p2pAnswer()

Queues acceptance of an incoming call. Returns 1 on acceptance, otherwise 0.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

retVal=p2pAnswer();

Notes: Valid only while p2pStatus()==2. Call processing is asynchronous. Playback starts when the call is accepted; in default PTT mode, use p2pSend(1) to transmit.

p2pReject()

Queues rejection of an incoming call. Returns 1 on acceptance, otherwise 0.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

retVal=p2pReject();

Notes: Valid only while status is 2. The local service returns to idle after the request is completed.

p2pHangup()

Queues termination or cancellation of the current call while keeping the telephone service available.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

retVal=p2pHangup();

Notes: Returns 1 when telephone mode is enabled, otherwise 0. Status changes asynchronously. Prefer this to p2pClose() between telephone calls.

p2pStatus()

Returns the telephone call state: 0 idle, 1 dialing, 2 incoming, 3 in call, 4 busy, 5 unavailable.

Returns: 0 idle, 1 dialing, 2 incoming, 3 in call, 4 busy, 5 unavailable.

retVal=p2pStatus();

Notes: Poll with a short wait. Busy/unavailable may remain visible until another dial or hangup resets the state. A call can be authenticated before it is answered; use status 3 to identify an accepted call.

p2pAutoAnswer(enabled)

Enables automatic answering for subsequent incoming calls when enabled is nonzero; 0 selects manual answering. Returns 1.

Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.

ParameterTypeMeaning
enabledNumber0 disables; any nonzero value enables.
retVal=p2pAutoAnswer(0);

Notes: Call after p2pStart(), which resets automatic answering to off. This function does not report connection state.

p2pOpen(host$,localPort,remotePort,key$,password$)

Initializes the direct-peer connection and starts asynchronous authentication. Returns 1 if initialization and connection request succeed, otherwise 0.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
host$StringDestination IPv4 address or DNS hostname.
localPortNumberThis device’s UDP listening port, 1–65535.
remotePortNumberDestination UDP listening port, 1–65535.
key$StringSecret key; see the function-specific requirements.
password$StringPassword string; use matching settings on communicating devices.
retVal=p2pOpen("192.168.1.131",24000,24000,key$,password$);

Notes: Both ports must be 1–65535. Uses encrypted 16000 Hz audio, a 2-second connection-check interval, and a 15-second timeout. Match the key and password on both devices. Wait for p2pConnected()==1 before starting audio. Choose either this direct-peer setup or the p2pStart()/p2pDial() telephone setup.

p2pListen(enabled)

Starts received-audio playback when enabled is nonzero; 0 stops playback. Returns 1 on success, 0 on failure.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
enabledNumber0 disables; any nonzero value enables.
retVal=p2pListen(1);

Notes: For direct-peer use, wait for p2pConnected()==1 first. Telephone mode starts listening when the call is accepted.

p2pSend(enabled)

Starts microphone transmission when enabled is nonzero; 0 stops transmission. Returns 1 on success, 0 on failure.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
enabledNumber0 disables; any nonzero value enables.
retVal=p2pSend(1);

Notes: Use as the press/release control for push-to-talk: send(1) when pressed and send(0) when released. In telephone mode transmit only while status is 3.

p2pConnected()

Returns 1 when the peer has authenticated, otherwise 0.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

retVal=p2pConnected();

Notes: In telephone mode this is not an answered-call indicator. Use p2pStatus()==3 for that.

p2pVolume(level)

Sets received-speech speaker volume, clamped to 0–100. Returns 1 on success, 0 on failure.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
levelNumberA level from 0 through 100.
retVal=p2pVolume(60);

Notes: 100 preserves PCM amplitude; 0 mutes received speech. Initialization resets this setting to 100. Call-progress tones have their own volume control.

p2pToneVolume(level)

Sets local ringing, ringback, and busy-tone volume independently of received speech. Clamps to 0–100.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
levelNumberA level from 0 through 100.
retVal=p2pToneVolume(35);

Notes: Returns 1 on success, 0 on failure. Initialization default is 80. Setting p2pVolume() does not replace this control.

p2pMicGain(level)

Sets microphone software gain, clamped to 0–100. Returns 1 on success, 0 on failure.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
levelNumberA level from 0 through 100.
retVal=p2pMicGain(100);

Notes: 100 preserves amplitude and 0 mutes capture. Initialization resets the setting to 100. This is not a hardware preamplifier gain in decibels.

p2pSidetone(level)

Sets local microphone monitoring mixed into the speaker, clamped to 0–100. Returns 1 on success, 0 on failure.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
levelNumberA level from 0 through 100.
retVal=p2pSidetone(0);

Notes: 0 disables local monitoring and is the default; 100 is unity monitoring. This does not remove echo returned by the remote device.

p2pMicLevel()

Returns the most recent processed microphone-block peak on a 0–100 scale.

Returns: Recent microphone peak on a 0–100 scale.

retVal=p2pMicLevel();

Notes: Returns 0 while capture is inactive or before the first block. It is an audio peak indicator, not a calibrated sound-pressure measurement.

p2pSpeakerLevel()

Returns the most recent processed speaker-block peak on a 0–100 scale.

Returns: Recent speaker peak on a 0–100 scale.

retVal=p2pSpeakerLevel();

Notes: Returns 0 while playback is inactive or before the first block. It does not measure physical speaker loudness.

p2pMode(mode)

Selects 0 for push-to-talk or 1 for full-duplex operation using ESP-SR acoustic echo cancellation. Returns 1 on success, 0 on failure.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
modeNumber0 push-to-talk or 1 full-duplex AEC.
retVal=p2pMode(1);

Notes: Initialize P2P first. Mode 1 requires 16000 Hz audio and starts listening and sending together. Check the return value. For telephone calls, select this mode after p2pStatus()==3. Mode 0 stops both directions; call p2pListen(1) to resume listening. Echo reduction depends on speaker volume, microphone position, and the enclosure.

p2pGetMode()

Returns 0 for PTT or 1 for full-duplex AEC mode.

Returns: 0 PTT or 1 full-duplex AEC.

retVal=p2pGetMode();

Notes: This is an operating-mode value, not a call or connection status.

p2pAECDelay(milliseconds)

Sets AEC reference delay from 0 through 250 ms and resets the reference history. Returns 1 for a valid value, otherwise 0.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
millisecondsNumberDelay or AEC reference lag in milliseconds; see the function’s allowed range.
retVal=p2pAECDelay(20);

Notes: The default is 20 ms. Adjust the delay for your speaker, microphone placement, and enclosure to improve echo reduction.

p2pClose()

Stops audio, closes the connection, clears the encryption key, and leaves telephone mode. Returns 1 on success, 0 on failure.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

retVal=p2pClose();

Notes: Use p2pHangup() to end one call while remaining available. Reopen the service before further telephone calls after closing.

Display, touchscreen & optional OLED

Use B9X Screen Designer to create the layout visually and generate screen-element addition code, or call the displayAdd…() functions yourself. Keep element numbers consistent between the layout and the code that responds to touches.

displayInit(sdaGPIO,sclGPIO)

Initializes an optional external SSD1306 OLED display. This function does not initialize the built-in color touchscreen.

Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.

ParameterTypeMeaning
sdaGPIONumberFree GPIO wired to the external OLED SDA signal.
sclGPIONumberFree GPIO wired to the external OLED SCL signal.
retVal=displayInit(sdaGPIO,sclGPIO);

Use only when an external OLED is connected to suitable free GPIOs. For the built-in touchscreen, start with displaySetOrientation(0), displayRemoveAllElements(), and displayClear().

displaySetOrientation(orientation)

Selects 0 for portrait (320 × 480) or 1 for landscape (480 × 320).

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
orientationNumber0 portrait or 1 landscape.
retVal=displaySetOrientation(0);

Changing orientation clears existing elements and pending touch events. Set orientation before creating your screen.

displaySetBrightness(level)

Sets display brightness.

Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.

ParameterTypeMeaning
levelNumberA level from 0 through 100.
retVal=displaySetBrightness(80);
displaySetColors(number,foreground,background)

Changes the text/foreground and background colors of one existing element.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
foregroundNumberRGB565 foreground/text color.
backgroundNumberRGB565 background color.
retVal=displaySetColors(10,65535,31);

number is the element ID, not a color. Colors use RGB565. Create the element before changing its colors.

displayClear(color)

Clears the display using a numeric color.

Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.

ParameterTypeMeaning
colorNumberRGB565 color value.
retVal=displayClear(0);
displayRefresh()

Forces a display refresh/redraw.

Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.

retVal=displayRefresh();
displayRemoveAllElements()

Removes all UI elements and associated icon state.

Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.

retVal=displayRemoveAllElements();

Note: Useful when changing screens.

displayText(text$)

Shows text on the optional external OLED initialized with displayInit().

Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.

ParameterTypeMeaning
text$StringText in double quotes or a string variable ending in $.
retVal=displayText("Ready");

For text on the color touchscreen, use displayAddLabel() and displaySetText().

displayAddButton(number,x,y,width,height,caption$,font)

Adds a touchable pushbutton.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
xNumberLeft position in pixels, measured from the screen’s left edge.
yNumberTop position in pixels, measured from the screen’s top edge.
widthNumberElement width in pixels. Keep it inside the current screen.
heightNumberElement height in pixels. Keep it inside the current screen.
caption$StringVisible caption in double quotes or a string variable.
fontNumberFont size 1–6; see the touchscreen font table.
retVal=displayAddButton(10,20,30,100,40,"START",1);

Note: Element numbers should be unique on the active screen.

displayAddRoundedButton(number,x,y,width,height,caption$,font,radius)

Adds a pushbutton with rounded corners.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
xNumberLeft position in pixels, measured from the screen’s left edge.
yNumberTop position in pixels, measured from the screen’s top edge.
widthNumberElement width in pixels. Keep it inside the current screen.
heightNumberElement height in pixels. Keep it inside the current screen.
caption$StringVisible caption in double quotes or a string variable.
fontNumberFont size 1–6; see the touchscreen font table.
radiusNumberCorner radius in pixels; at least 2.
retVal=displayAddRoundedButton(10,10,10,140,48,"START",2,10);

radius is measured in pixels and must be at least 2. Width and height must each be at least 12 pixels.

displayAddLabel(number,x,y,width,height,text$,font,textColor)

Adds a text label with the specified text color.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
xNumberLeft position in pixels, measured from the screen’s left edge.
yNumberTop position in pixels, measured from the screen’s top edge.
widthNumberElement width in pixels. Keep it inside the current screen.
heightNumberElement height in pixels. Keep it inside the current screen.
text$StringText in double quotes or a string variable ending in $.
fontNumberFont size 1–6; see the touchscreen font table.
textColorNumberRGB565 text color, such as 65535 for white or 0 for black.
retVal=displayAddLabel(20,10,10,280,32,"Ready",2,65535);

Use displaySetColors() afterward to set both the foreground and background colors. A label is used for output rather than editable input.

displayAddCheckBox(number,x,y,width,height,caption$,checked,font)

Adds a checkbox. Touching it changes its checked state.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
xNumberLeft position in pixels, measured from the screen’s left edge.
yNumberTop position in pixels, measured from the screen’s top edge.
widthNumberElement width in pixels. Keep it inside the current screen.
heightNumberElement height in pixels. Keep it inside the current screen.
caption$StringVisible caption in double quotes or a string variable.
checkedNumberInitial state: 0 unchecked or 1 checked.
fontNumberFont size 1–6; see the touchscreen font table.
retVal=displayAddCheckBox(21,10,60,200,32,"Enable",0,2);

checked comes BEFORE font. Use 0 for unchecked and 1 for checked; font selects the text size.

displayAddTextBox(number,x,y,width,height,text$,maxLen,font)

Adds an editable text field.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
xNumberLeft position in pixels, measured from the screen’s left edge.
yNumberTop position in pixels, measured from the screen’s top edge.
widthNumberElement width in pixels. Keep it inside the current screen.
heightNumberElement height in pixels. Keep it inside the current screen.
text$StringText in double quotes or a string variable ending in $.
maxLenNumberMaximum editable length, up to 255 characters.
fontNumberFont size 1–6; see the touchscreen font table.
retVal=displayAddTextBox(30,10,10,280,40,"Kitchen",63,2);

maxLen is at most 255. Add one keyboard per screen. Touching the textbox selects it for editing.

displayAddPasswordTextBox(number,x,y,width,height,text$,maxLen,font)

Adds an editable textbox whose displayed characters are masked.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
xNumberLeft position in pixels, measured from the screen’s left edge.
yNumberTop position in pixels, measured from the screen’s top edge.
widthNumberElement width in pixels. Keep it inside the current screen.
heightNumberElement height in pixels. Keep it inside the current screen.
text$StringText in double quotes or a string variable ending in $.
maxLenNumberMaximum editable length, up to 255 characters.
fontNumberFont size 1–6; see the touchscreen font table.
retVal=displayAddPasswordTextBox(31,10,60,280,40,"",63,2);

maxLen is at most 255. Add a keyboard to edit it. displayGetText$() and relevant text events contain the actual text, so avoid printing password fields.

displayAddSlider(number,x,y,width,height,min,max,value)

Adds a touch slider with an initial value and visible numeric value.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
xNumberLeft position in pixels, measured from the screen’s left edge.
yNumberTop position in pixels, measured from the screen’s top edge.
widthNumberElement width in pixels. Keep it inside the current screen.
heightNumberElement height in pixels. Keep it inside the current screen.
minNumberMinimum permitted numeric value.
maxNumberMaximum permitted numeric value.
valueNumberInitial or replacement numeric value.
retVal=displayAddSlider(22,10,110,280,42,0,100,50);

The final three arguments are minimum, maximum, then initial value. Read changes with displayGetValue() or display events.

displayAddListBox(number,x,y,width,height,items$,selected,font)

Adds a scrollable list. Separate items with the | character.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
xNumberLeft position in pixels, measured from the screen’s left edge.
yNumberTop position in pixels, measured from the screen’s top edge.
widthNumberElement width in pixels. Keep it inside the current screen.
heightNumberElement height in pixels. Keep it inside the current screen.
items$StringItems separated by |, for example “One|Two|Three”.
selectedNumberInitial selection index, starting at 0.
fontNumberFont size 1–6; see the touchscreen font table.
retVal=displayAddListBox(23,10,170,280,110,"Kitchen|Workshop|Office",0,2);

Selection indexes start at 0. Read the index with displayGetValue(); selection-change events also carry the selected text. Drag to scroll a list that is taller than its visible area.

displayAddAnalogMeter(number,x,y,width,height,min,max,value)

Adds a needle meter with its numeric value displayed.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
xNumberLeft position in pixels, measured from the screen’s left edge.
yNumberTop position in pixels, measured from the screen’s top edge.
widthNumberElement width in pixels. Keep it inside the current screen.
heightNumberElement height in pixels. Keep it inside the current screen.
minNumberMinimum permitted numeric value.
maxNumberMaximum permitted numeric value.
valueNumberInitial or replacement numeric value.
retVal=displayAddAnalogMeter(24,10,10,200,100,0,100,25);

Use displaySetValue(number,value) to move the needle. Choose min less than max.

displayAddVerticalBarMeter(number,x,y,width,height,min,max,value)

Adds a vertical level meter with a visible numeric value.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
xNumberLeft position in pixels, measured from the screen’s left edge.
yNumberTop position in pixels, measured from the screen’s top edge.
widthNumberElement width in pixels. Keep it inside the current screen.
heightNumberElement height in pixels. Keep it inside the current screen.
minNumberMinimum permitted numeric value.
maxNumberMaximum permitted numeric value.
valueNumberInitial or replacement numeric value.
retVal=displayAddVerticalBarMeter(25,230,10,60,180,0,100,25);

Use displaySetValue() to update the level. Values are constrained to the meter range.

displayAddLamp(number,x,y,width,height,caption$,font,on)

Adds an on/off indicator that can also be toggled by touch.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
xNumberLeft position in pixels, measured from the screen’s left edge.
yNumberTop position in pixels, measured from the screen’s top edge.
widthNumberElement width in pixels. Keep it inside the current screen.
heightNumberElement height in pixels. Keep it inside the current screen.
caption$StringVisible caption in double quotes or a string variable.
fontNumberFont size 1–6; see the touchscreen font table.
onNumberInitial state: 0 off or 1 on.
retVal=displayAddLamp(26,10,230,150,32,"RUN",2,0);

Use displaySetChecked() to set it from your program. Minimum size is 20 × 20 pixels.

displayAddSwitch(number,x,y,width,height,caption$,font,on)

Adds an on/off switch display that can be toggled by touch or changed by your program.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
xNumberLeft position in pixels, measured from the screen’s left edge.
yNumberTop position in pixels, measured from the screen’s top edge.
widthNumberElement width in pixels. Keep it inside the current screen.
heightNumberElement height in pixels. Keep it inside the current screen.
caption$StringVisible caption in double quotes or a string variable.
fontNumberFont size 1–6; see the touchscreen font table.
onNumberInitial state: 0 off or 1 on.
retVal=displayAddSwitch(27,10,280,200,36,"AUTO",2,0);

Use displaySetChecked() and displayGetChecked() for its state. Minimum size is 40 × 24 pixels.

displayAddToggleSwitch(number,x,y,width,height,caption$,font,on)

Adds a touchable switch that toggles between on and off.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
xNumberLeft position in pixels, measured from the screen’s left edge.
yNumberTop position in pixels, measured from the screen’s top edge.
widthNumberElement width in pixels. Keep it inside the current screen.
heightNumberElement height in pixels. Keep it inside the current screen.
caption$StringVisible caption in double quotes or a string variable.
fontNumberFont size 1–6; see the touchscreen font table.
onNumberInitial state: 0 off or 1 on.
retVal=displayAddToggleSwitch(28,10,330,200,36,"PUMP",2,0);

A change generates checked or unchecked events. Minimum size is 40 × 24 pixels.

displayAddFlipSwitch(number,x,y,width,height,caption$,font,on)

Adds a touchable toggle switch using the flip-switch function name.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
xNumberLeft position in pixels, measured from the screen’s left edge.
yNumberTop position in pixels, measured from the screen’s top edge.
widthNumberElement width in pixels. Keep it inside the current screen.
heightNumberElement height in pixels. Keep it inside the current screen.
caption$StringVisible caption in double quotes or a string variable.
fontNumberFont size 1–6; see the touchscreen font table.
onNumberInitial state: 0 off or 1 on.
retVal=displayAddFlipSwitch(29,10,380,200,36,"LIGHT",2,0);

Its checked state and event behavior match displayAddToggleSwitch().

displayAddKeyboard(number,targetElement)

Adds an alphanumeric keyboard linked initially to a textbox.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
targetElementNumberID of an existing editable textbox.
retVal=displayAddKeyboard(40,30);

Create the target textbox first. The keyboard starts hidden and appears when an editable textbox is touched. Use one keyboard per screen.

displayAddIcon(number,x,y,iconNumber)

Adds a touchable built-in icon.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
xNumberLeft position in pixels, measured from the screen’s left edge.
yNumberTop position in pixels, measured from the screen’s top edge.
iconNumberNumberBuilt-in icon number, 1–121.
retVal=displayAddIcon(31,20,20,17);
displaySetIcon(number,iconNumber)

Changes an existing icon element.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
iconNumberNumberBuilt-in icon number, 1–121.
retVal=displaySetIcon(31,18);
displayAddBmpFromFile(number,x,y,path$,touchable)

Adds a BMP image from a file path.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
xNumberLeft position in pixels, measured from the screen’s left edge.
yNumberTop position in pixels, measured from the screen’s top edge.
path$StringComplete file or directory path, such as “/sdcard/config.txt”.
touchableNumber0 for display only; 1 to generate touch events.
retVal=displayAddBmpFromFile(32,10,10,"/sdcard/photo.bmp",1);
displayAddBMPFromSD(number,x,y,path$,touchable)

Adds a BMP stored on the mounted SD card.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
xNumberLeft position in pixels, measured from the screen’s left edge.
yNumberTop position in pixels, measured from the screen’s top edge.
path$StringComplete file or directory path, such as “/sdcard/config.txt”.
touchableNumber0 for display only; 1 to generate touch events.
retVal=displayAddBMPFromSD(33,10,10,"/sdcard/photo.bmp",1);

Note: Supports the BMP formats described in the “Display Events” section. The SD card must be mounted first.

displaySetText(number,text$)

Changes an element’s text.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
text$StringText in double quotes or a string variable ending in $.
retVal=displaySetText(14,"New text");
displayGetText$(number)

Returns text from an element.

Returns: Text. See the description for the empty-result behavior.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
let s$=displayGetText$(14);
displaySetValue(number,value)

Sets an element’s numeric value/state.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
valueNumberInitial or replacement numeric value.
retVal=displaySetValue(16,75);

Note: Used by sliders, meters and other value-driven elements.

displayGetValue(number)

Returns an element’s numeric value.

Returns: The element’s numeric value. A list returns a zero-based selection index.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
retVal=displayGetValue(16);
displaySetChecked(number,state)

Sets a checkbox checked state.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
stateNumber0 false/off or 1 true/on.
retVal=displaySetChecked(13,1);
displayGetChecked(number)

Returns checkbox state.

Returns: 1 for checked/on, 0 for unchecked/off.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
retVal=displayGetChecked(13);
displaySetEnabled(number,state)

Enables or disables user interaction with an element.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
stateNumber0 false/off or 1 true/on.
retVal=displaySetEnabled(10,0);
displaySetVisible(number,state)

Shows or hides an element.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
numberNumberUnique element ID on the current screen; use this ID to read or change the element later.
stateNumber0 false/off or 1 true/on.
retVal=displaySetVisible(10,1);
getDisplayMessage$()

Returns the next queued display interaction message, or an empty string when none is queued.

Returns: Text. See the description for the empty-result behavior.

let s$=getDisplayMessage$();

Note: Format: [DMSG][element][type][activity][value][x][y][text].

Text-to-speech, voice recognition & AI

ttsInit(uartPort,busyGPIO,txGPIO,rxGPIO)

Initializes an optional external SYN6988 serial speech module.

Returns: 1 after initializing the external serial speech module.

ParameterTypeMeaning
uartPortNumberUnused UART port number supported by the board.
busyGPIONumberFree GPIO connected to the speech module BUSY output.
txGPIONumberFree GPIO connected to the speech module RX input.
rxGPIONumberFree GPIO connected to the speech module TX output.
retVal=ttsInit(uartPort,busyGPIO,txGPIO,rxGPIO);

This is separate from online ttsx speech. Connect the external module using suitable unused GPIO pins.

ttsSpeak(text$)

Starts speaking the supplied text.

Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.

ParameterTypeMeaning
text$StringText in double quotes or a string variable ending in $.
retVal=ttsSpeak("Hello from B9X Basic");
ttsIsBusy()

Returns nonzero while TTS is active.

Returns: The busy state reported by the external module; use to wait for speech to finish.

retVal=ttsIsBusy();
ttsxInit(bclkGPIO,wsGPIO,dataGPIO,key$,voice$,instructions$)

Prepares online text-to-speech playback.

Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.

ParameterTypeMeaning
bclkGPIONumberAudio bit-clock GPIO for the selected board.
wsGPIONumberAudio word-select GPIO for the selected board.
dataGPIONumberAudio data GPIO for the selected board.
key$StringSecret key; see the function-specific requirements.
voice$StringVoice name supported by the speech service.
instructions$StringInstructions describing the desired speaking style.
retVal=ttsxInit(18,21,15,key$,"alloy","Speak clearly.");

Provide your own API key and a voice supported by your speech service. instructions$ describes how the voice should speak. Call once before queuing speech.

ttsxSpeak(text$)

Queues text for online speech playback.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
text$StringText in double quotes or a string variable ending in $.
retVal=ttsxSpeak("The telephone is ready.");

Returns 1 when queued and 0 when the queue is full. Keep each speech request to 255 characters or fewer. Stop conflicting audio use before speech playback.

ttsxSetVolume(level)

Sets extended TTS output volume.

Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.

ParameterTypeMeaning
levelNumberA level from 0 through 100.
retVal=ttsxSetVolume(70);
vrxInit(bclkGPIO,wsGPIO,dataGPIO,recordSeconds,key$)

Prepares voice recording and online transcription.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
bclkGPIONumberAudio bit-clock GPIO for the selected board.
wsGPIONumberAudio word-select GPIO for the selected board.
dataGPIONumberAudio data GPIO for the selected board.
recordSecondsNumberRecording duration in seconds.
key$StringSecret key; see the function-specific requirements.
retVal=vrxInit(18,21,16,5,key$);

Connect Wi-Fi first and provide your own API key. For the supported onboard microphone use the board’s audio settings; do not run another recording or playback feature at the same time.

vrxTranscribe(requestID)

Requests a recording and transcription using an application-chosen numeric request ID.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
requestIDNumberApplication-chosen number used to identify a submitted request.
retVal=vrxTranscribe(1);

Returns 1 if queued, 0 if the request cannot be queued. Poll vrxGetTranscript$() with a short wait for nonempty text.

vrxGetTranscript$()

Returns the next available transcription, or empty text when no result is ready.

Returns: Text. See the description for the empty-result behavior.

let s$=vrxGetTranscript$();

Save the returned text if you need to use it again; each call checks for a new result.

oaixInit(key$)

Initializes access to the online text-answer service.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
key$StringSecret key; see the function-specific requirements.
retVal=oaixInit(key$);

Wi-Fi and a valid API key are required. Returns 1 when initialization succeeds, otherwise 0.

oaixAskQuestion(requestID,question$)

Queues a text question for the online AI service.

Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.

ParameterTypeMeaning
requestIDNumberApplication-chosen number used to identify a submitted request.
question$StringQuestion text.
retVal=oaixAskQuestion(1,"Explain what a relay does.");

requestID is an application-chosen number, not a model or operating mode. Returns 1 when queued, 0 when not queued. Poll oaixGetAnswer$() for nonempty text.

oaixGetAnswer$()

Returns the next available answer as text, or empty text when no answer is ready.

Returns: Text. See the description for the empty-result behavior.

let s$=oaixGetAnswer$();

Keep your polling loop responsive with wait(). Do not assume an answer is ready immediately after submitting a question.

Infrared & WS2812

irInit(gpio)

Initializes the infrared receiver on a GPIO.

Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.

ParameterTypeMeaning
gpioNumberSuitable free GPIO number.
retVal=irInit(7);
irGetCode()

Returns a received infrared code, or -1 when no sufficiently confident code is available.

Returns: A received numeric code; -1 when no qualifying code is available.

retVal=irGetCode();

Call irInit() first. Compare this numeric code with values captured from your remote. It combines the protocol identifier and command.

ws2812Init(gpio,count)

Initializes a WS2812/NeoPixel-style LED strip.

Returns: A strip handle greater than 0 on success; 0 if initialization fails. Save this handle for later LED calls.

ParameterTypeMeaning
gpioNumberSuitable free GPIO number.
countNumberNumber of characters, or number of LEDs when initializing a strip.
retVal=ws2812Init(48,8);
ws2812SetPixel(handle,index,r,g,b)

Sets one pixel’s RGB values.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
handleNumberStrip handle previously returned by ws2812Init().
indexNumberLED position starting at 0; must be less than the configured count.
rNumberRed intensity, 0–255.
gNumberGreen intensity, 0–255.
bNumberBlue intensity, 0–255.
retVal=ws2812SetPixel(0,2,255,0,0);

Note: Use the LED-strip handle returned by ws2812Init(); pixel positions start at 0.

ws2812Fill(handle,r,g,b)

Sets all pixels to one RGB color.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
handleNumberStrip handle previously returned by ws2812Init().
rNumberRed intensity, 0–255.
gNumberGreen intensity, 0–255.
bNumberBlue intensity, 0–255.
retVal=ws2812Fill(0,0,0,255);
ws2812Show(handle)

Updates the physical LEDs with the colors you have set.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
handleNumberStrip handle previously returned by ws2812Init().
retVal=ws2812Show(0);
ws2812Clear(handle)

Sets all LEDs in the strip to off.

Returns: 0 on success; a nonzero error value on failure.

ParameterTypeMeaning
handleNumberStrip handle previously returned by ws2812Init().
retVal=ws2812Clear(0);
ws2812IsBusy(handle)

Returns whether the LED subsystem is busy.

Returns: 1 while an LED update is queued or being sent; otherwise 0.

ParameterTypeMeaning
handleNumberStrip handle previously returned by ws2812Init().
retVal=ws2812IsBusy(0);

Date & time

hour()

Returns the current hour from the configured system clock.

Returns: Hour from 0 to 23.

retVal=hour();
minute()

Returns the current minute.

Returns: Minute from 0 to 59.

retVal=minute();
second()

Returns the current second.

Returns: Second from 0 to 59.

retVal=second();
month()

Returns the current month number.

Returns: Month from 1 to 12.

retVal=month();
day()

Returns the current day of month.

Returns: Day of month from 1 to 31.

retVal=day();
year()

Returns the current year.

Returns: Four-digit calendar year.

retVal=year();
weekDay()

Returns the day of the week: 0 Sunday through 6 Saturday.

Returns: 0 Sunday, 1 Monday, …, 6 Saturday.

retVal=weekDay();

The device clock must be set or synchronized first.

Built-In Icon Reference Top ↑

B9X Basic includes 121 built-in icons. Each icon has a fixed number from 1 through 121. Use that number with displayAddIcon() or displaySetIcon().

Important: The first argument is the display element number; the icon number selects the built-in graphic. Element numbers should be unique on the active screen.

Adding a built-in icon

retVal=displayAddIcon(31,20,20,17);

This example creates display element 31 at X=20, Y=20 and uses built-in icon 17 — Play.

Changing an existing icon

retVal=displaySetIcon(31,18);

This changes element 31 to built-in icon 18 — Pause. This is useful for controls whose appearance changes with state.

Built-In Icon Graphics

The gallery below shows all 121 built-in icons. Each image is labeled with the icon number to use in your program.

Complete icon number list

No.IconNo.IconNo.Icon
1Home
home
11Check
check
21Volume Up
volume_up
31Temperature
temperature
2Back
back
12Close
close
22Volume Down
volume_down
32Humidity
humidity
3Forward
forward
13Plus
plus
23Mute
mute
33Light
light
4Up
up
14Minus
minus
24Brightness
brightness
34Fan
fan
5Down
down
15Power
power
25Wifi
wifi
35Pump
pump
6Menu
menu
16Refresh
refresh
26Bluetooth
bluetooth
36Valve
valve
7Settings
settings
17Play
play
27Lock
lock
37Motor
motor
8Information
information
18Pause
pause
28Unlock
unlock
38Heater
heater
9Warning
warning
19Stop
stop
29User
user
39Cooling
cooling
10Error
error
20Record
record
30Users
users
40Battery
battery
41Plug
plug
42Clock
clock
43Calendar
calendar
44Camera
camera
45Folder
folder
46Save
save
47Upload
upload
48Download
download
49Edit
edit
50Trash
trash
51Lamp Off
lamp_off
52Lamp On
lamp_on
53Lamp Dim
lamp_dim
54Switch Off
switch_off
55Switch On
switch_on
56Selector Left
selector_left
57Selector Center
selector_center
58Selector Right
selector_right
59Door Closed
door_closed
60Door Open
door_open
61Door Locked
door_locked
62Garage Closed
garage_closed
63Garage Open
garage_open
64Window Closed
window_closed
65Window Open
window_open
66Blinds Closed
blinds_closed
67Blinds Half
blinds_half
68Blinds Open
blinds_open
69Thermostat Heat
thermostat_heat
70Thermostat Cool
thermostat_cool
71Thermostat Auto
thermostat_auto
72Thermostat Off
thermostat_off
73Motion Idle
motion_idle
74Motion Detected
motion_detected
75Alarm Disarmed
alarm_disarmed
76Alarm Armed
alarm_armed
77Alarm Triggered
alarm_triggered
78Water Dry
water_dry
79Water Leak
water_leak
80Smoke Clear
smoke_clear
81Smoke Alarm
smoke_alarm
82Security Camera On
security_camera_on
83Security Camera Off
security_camera_off
84Machine Stop
machine_stop
85Machine Run
machine_run
86Machine Fault
machine_fault
87Machine Maintenance
machine_maintenance
88Conveyor Stop
conveyor_stop
89Conveyor Run
conveyor_run
90Conveyor Reverse
conveyor_reverse
91Pump Off
pump_off
92Pump On
pump_on
93Pump Fault
pump_fault
94Valve Closed
valve_closed
95Valve Open
valve_open
96Valve Half
valve_half
97Tank Empty
tank_empty
98Tank Quarter
tank_quarter
99Tank Half
tank_half
100Tank Three Quarter
tank_three_quarter
101Tank Full
tank_full
102Motor Off
motor_off
103Motor Forward
motor_forward
104Motor Reverse
motor_reverse
105Motor Fault
motor_fault
106Traffic Red
traffic_red
107Traffic Yellow
traffic_yellow
108Traffic Green
traffic_green
109Mode Auto
mode_auto
110Mode Manual
mode_manual
111Mode Off
mode_off
112Emergency Stop
emergency_stop
113Pressure Low
pressure_low
114Pressure Normal
pressure_normal
115Pressure High
pressure_high
116Level Low
level_low
117Level Normal
level_normal
118Level High
level_high
119Temperature Cold
temperature_cold
120Temperature Normal
temperature_normal
121Temperature Hot
temperature_hot

Useful multistate icon groups

PurposeIcon numbers
Lamp51 Off, 52 On, 53 Dim
Switch54 Off, 55 On
Selector56 Left, 57 Center, 58 Right
Door59 Closed, 60 Open, 61 Locked
Garage62 Closed, 63 Open
Window64 Closed, 65 Open
Blinds66 Closed, 67 Half, 68 Open
Thermostat69 Heat, 70 Cool, 71 Auto, 72 Off
Motion73 Idle, 74 Detected
Alarm75 Disarmed, 76 Armed, 77 Triggered
Water78 Dry, 79 Leak
Smoke80 Clear, 81 Alarm
Security camera82 On, 83 Off
Machine84 Stop, 85 Run, 86 Fault, 87 Maintenance
Conveyor88 Stop, 89 Run, 90 Reverse
Pump91 Off, 92 On, 93 Fault
Valve94 Closed, 95 Open, 96 Half
Tank97 Empty, 98 Quarter, 99 Half, 100 Three Quarter, 101 Full
Motor102 Off, 103 Forward, 104 Reverse, 105 Fault
Traffic light106 Red, 107 Yellow, 108 Green
Mode109 Auto, 110 Manual, 111 Off
Emergency stop112 Emergency Stop
Pressure113 Low, 114 Normal, 115 High
Level116 Low, 117 Normal, 118 High
Temperature state119 Cold, 120 Normal, 121 Hot

Example: changing an icon with equipment state

// Element 50 is a pump status icon.
result=displayAddIcon(50,20,20,91);

if pumpRunning==1 then
  result=displaySetIcon(50,92);
else
  result=displaySetIcon(50,91);
endif

The same technique can be used for lamps, doors, alarms, tanks, motors, valves, traffic lights and the other multistate icon groups.

Touchscreen Design Guide Top ↑

The color touchscreen is ready when your application starts. Select the orientation first, clear old elements, and then create controls with unique numeric IDs. Use the same IDs in your event handling. Coordinates are measured from the top-left corner, with x increasing rightward and y downward.

B9X Screen Designer lets you arrange screen elements visually and generate the B9X Basic code that adds them to your screen. Use it to position and size controls and set their captions and appearance, then use the generated element numbers when writing your event handling. The displayAdd…() functions below are also available when you prefer to add or adjust elements directly in BASIC.

retVal=displaySetOrientation(0);
retVal=displayRemoveAllElements();
retVal=displayClear(0);
retVal=displayAddLabel(20,10,10,280,32,"Ready",2,65535);
retVal=displayAddRoundedButton(10,10,60,140,48,"START",2,10);
retVal=displaySetColors(10,65535,31);
retVal=displayRefresh();
OrientationValueLogical screen
Portrait0320 × 480 pixels
Landscape1480 × 320 pixels

Changing orientation removes the current controls and pending events. Recreate your screen afterward. Clearing the screen color is different from removing controls: use displayRemoveAllElements() when changing pages.

Font numberUse
1Small: compact captions and dense information
2Medium: standard labels and buttons
3Large
4Extra large
5Huge
6Tall condensed

Choose a control large enough for its text and font. The screen supports up to 48 elements at once; the on-screen keyboard also occupies one element. Ordinary element text is limited to 255 characters, and event text is limited to 63 characters. Use displayGetText$() when you need the full contents of a textbox.

ColorRGB565 decimal
Black0
White65535
Red63488
Green2016
Blue31
Yellow65504
Cyan2047
Magenta63519

displaySetColors(number,foreground,background) changes an existing element. displayClear(color) changes the screen background. For labels, the last displayAddLabel() argument is the text color. For checkboxes, checked comes before font. For sliders, the final arguments are minimum, maximum, value.

Text entry and passwords

retVal=displayAddTextBox(30,10,120,280,40,"",63,2);
retVal=displayAddPasswordTextBox(31,10,175,280,40,"",63,2);
retVal=displayAddKeyboard(40,30);

Touch a textbox to open the keyboard for it. Password masking affects the screen only: reading its text returns the actual password. Avoid printing password text or including it in ordinary logs.

Display Events Top ↑

getDisplayMessage$() returns empty text when no event is waiting. Otherwise it returns eight bracketed fields:

[DMSG][elementNumber][elementType][activity][value][x][y][text]
FieldMeaning
1DMSG marker
2Your numeric element ID
3Element type from the table below
4Activity/event code
5Numeric value or state
6Touch x position
7Touch y position
8Event text, up to 63 characters
ActivityCodeTypical use
Pressed1Start push-to-talk or a press action
Released2Stop push-to-talk
Clicked3Perform a single button action
Value changed4Slider/list/meter value update
Checked5On/checked
Unchecked6Off/unchecked
Focused7Textbox selected
Text changed8Edited text
Key pressed9Keyboard input
Keyboard done10User completed entry
Keyboard cancelled11User cancelled entry
Queue overflow12Drain pending events more promptly
Element typeCode
Button1
Textbox2
Password textbox3
Label4
Checkbox5
BMP/icon6
Slider7
Keyboard8
Listbox9
Analog meter10
Vertical bar11
Lamp12
Switch13
Toggle/flip switch14
Rounded button15

Use Clicked (3) for one action per button tap. Use Pressed and Released for controls that must stay active only while held. Do not handle both Pressed and Clicked as the same dialing action or you may submit it twice.

Read events frequently. The event queue holds 32 messages. A short polling wait such as 20–50 ms is a useful starting point. The simple bracket-field reader in the examples assumes field text does not contain [ or ]; avoid those characters in labels or messages you plan to parse this way.

BMP images

Use complete paths such as /sdcard/photo.bmp or /spiffs/photo.bmp. Supported images are uncompressed 24-bit Windows BMP and supported 16-bit RGB565 BMP. Set touchable to 1 to receive image touch events. The image supplies its own width and height; position it with x and y.

retVal=displayAddBMPFromSD(50,10,10,"/sdcard/photo.bmp",1);

VOIP Guide — B9X Voice Server Top ↑

VOIP uses encrypted UDP audio to communicate with B9X Voice Server. The audio sample rate is 11025 Hz.

B9X Voice Server is the server used by the VOIP functions in this guide. Configure voipConnect() with your B9X Voice Server address, listening port, password, node name, and encryption key. The direct P2P telephone functions use a separate device-to-device calling setup.

Important connection order: Call voipConnect(), wait until voipIsConnected()==1, and then call voipStartListening(). Starting listening before the connection is confirmed can leave you without received audio.
result=voipInit(24000,-1,-1,-1,-1,-1,-1);

result=voipConnect(host$,18000,password$,"MYNODE",key$);

for connectWait=0 to 40 do
  result=voipIsConnected();
  if result==1 then
    result=voipStartListening();
    result=voipSetVolume(20);
    result=voipSetMicGain(100);
    connectWait=41;
  else
    x=wait(250);
  endif
next

Push-to-talk example

result=voipStartSending();

// Keep sending while PTT is active.

result=voipHaltSending();

Closing and reconnecting

Use voipClose() to close the server session. On a new connection, repeat the successful connection sequence: connect, wait for voipIsConnected(), then start listening.

VOX

VOX starts transmission when your voice exceeds a threshold. Lower threshold values respond to quieter sounds. Use voipIsVOXActive() to check whether VOX is currently triggered.

P2P Telephone Guide Top ↑

Use P2P telephone functions to call another B9X device directly. Start the telephone service once on each device, set a caller name, and dial the other device’s host and listening port. No central telephone server is required for a reachable direct connection.

First test: two devices on the same Wi-Fi network

  1. Connect both devices to the same local network and find each device’s LAN IP.
  2. Use the same 32-character key and matching password settings on both devices.
  3. Start each device with p2pStart(). Each can use port 24000 because it has its own LAN IP.
  4. Set a different p2pSetCallerID() name on each device.
  5. On the calling device, dial the other device’s LAN IP and listening port.
  6. When the receiver shows incoming status 2, read caller ID and answer.
  7. Use push-to-talk or enable full-duplex AEC after the call reaches status 3.
let key$="0123456789ABCDEF0123456789ABCDEF";
let password$="testpass123";
retVal=p2pStart(24000,key$,password$);
retVal=p2pSetCallerID("Kitchen");
retVal=p2pAutoAnswer(0);
retVal=p2pDial("192.168.1.131",24000);

The example key and password are for learning only. Replace them on both devices before normal use. The key is exactly 32 ASCII characters, not a password to be expanded into a key. A password may be empty or 8–127 bytes; matching password settings are required on both devices.

StatusMeaningWhat your program should do
0IdleAllow dial or wait for a call.
1DialingShow progress; cancel with p2pHangup().
2IncomingRead caller information, then answer or reject.
3In callRun PTT or enable hands-free AEC once.
4BusyShow the result; allow another dial or hangup.
5UnavailableCheck destination, credentials, network, and remote service.

Caller ID and calling back

Caller ID has three parts: a name, the observed source IPv4 address, and the caller’s advertised listening port. The name may contain up to 255 printable ASCII characters, including spaces. Read all three when incoming status 2 first appears; save them if you want a callback or missed-call display.

let savedName$=p2pCallerID$();
let savedIP$=p2pCallerIP$();
let savedPort=p2pCallerPort();
// After the current call has ended:
if savedPort>0 then
    retVal=p2pDial(savedIP$,savedPort);
endif

Read the saved values only after an incoming call has supplied them. p2pCallerPort() returns 0 before a call. Caller information remains after hangup, rejection, or timeout until another incoming call replaces it or the telephone service is reopened or closed. Outgoing calls do not replace the last incoming caller ID.

Set your outgoing name before dialing. It remains set across hangup and reopening the service but must be set again after reboot. An empty name makes the receiver display the source IP. Older devices may show an IP instead of a name; install the current telephone version on both devices for 255-character names and a reliable advertised callback port. Caller names are chosen by the calling device, rather than supplied by a telephone carrier.

Push-to-talk and hands-free audio

PTT is the starting mode. After an accepted call begins, listening starts automatically. Call p2pSend(1) on your talk button’s Pressed event and p2pSend(0) on Released. Do not use Clicked to hold a transmission open.

For hands-free calling, wait for status 3, then call p2pMode(1) once and check for a return of 1. Do this on both devices. It enables simultaneous microphone transmission and playback with acoustic echo cancellation (AEC). Start with a moderate speaker volume, sidetone off, and the default 20 ms AEC delay. Tune the delay for your speaker, microphone, and enclosure if needed.

if p2pStatus()==3 then
    retVal=p2pAECDelay(20);
    retVal=p2pMode(1);
    if retVal==0 then
        print "Hands-free mode could not start";
    endif
endif

Run that setup once when entering a call, not in every loop iteration. To return to PTT call p2pMode(0), which stops both directions, then p2pListen(1). p2pSidetone() controls hearing your own microphone locally; it does not remove echo coming back from the other device. Use p2pVolume() for received speech and p2pToneVolume() for local ringing, ringback, and busy tones.

Ending calls and staying available

Use p2pReject() only for an incoming call. Use p2pHangup() to end a call or cancel dialing while keeping the service available. p2pClose() closes the service; call p2pStart() again before making or receiving further telephone calls. Requests complete after the function returns, so let p2pStatus() confirm the resulting state.

Internet calls, DNS, and callback ports

For Internet calls, use a reachable public IP or dynamic DNS hostname. Forward the chosen UDP port from the destination router to its telephone. For callbacks using the advertised port, use the same external and internal port. If two telephones share one public IP, give them different listening ports and forward each port to the correct local device.

Dynamic DNS keeps a hostname pointed at an address; it does not open a router or bypass carrier-grade NAT. Phone hotspots and many cellular connections may block incoming calls. A public connection path, supported NAT traversal, or a relay service is needed in those situations. These telephone functions do not by themselves provide a relay service.

If a public IP changes during a call, audio can stop and the call may need to be redialed once the new address is available. A saved callback IP can also become outdated. Save a known DNS hostname in your contacts when you need a long-lived destination.

An unanswered call times out after about 30 seconds. p2pStart() uses a 15-second connection-check interval and a 45-second connection timeout. p2pOpen(), the direct-peer setup, uses a 2-second interval and 15-second timeout. Choose one setup method; use p2pStart()/p2pDial() when you want ringing, answer, reject, and callback behavior.

Complete touchscreen telephone example

Use this program on both devices. Change myName$ and peerHost$ for each telephone. Set handsFree to 1 for AEC hands-free operation or 0 for the Hold to Talk button. The Call Back button uses the last incoming caller’s saved IP and listening port. The example keeps its most recent caller only; add your own file-based history if needed.

// Set these differently on each telephone.
let myName$="Kitchen";
let peerHost$="192.168.1.131";
let myPort=24000;
let peerPort=24000;
// Replace the sample key on BOTH devices with the same 32-character key.
let key$="0123456789ABCDEF0123456789ABCDEF";
let password$="testpass123";
let handsFree=1;

function field$(fieldIndex,record$)
    let pos=1;
    for item=1 to fieldIndex do
        pos=instr(pos,record$,"[");
        if pos==0 then
            return "";
        endif
        let finish=instr(pos+1,record$,"]");
        if finish==0 then
            return "";
        endif
        if item==fieldIndex then
            return mid$(record$,pos+1,finish-pos-1);
        endif
        pos=finish+1;
    next
    return "";
end function

while wifiIsConnected()==0 do
    retVal=wait(100);
wend
retVal=displaySetOrientation(0);
retVal=displayRemoveAllElements();
retVal=displayClear(0);
retVal=displayAddRoundedButton(1,10,10,140,48,"DIAL",2,10);
retVal=displayAddRoundedButton(2,170,10,140,48,"ANSWER",2,10);
retVal=displayAddRoundedButton(3,10,70,140,48,"HANG UP",2,10);
retVal=displayAddRoundedButton(4,170,70,140,48,"CALL BACK",2,10);
retVal=displayAddLabel(10,10,135,300,32,"Starting",2,65535);
retVal=displayAddLabel(11,10,180,300,70,"",2,65535);
retVal=displayAddRoundedButton(5,10,280,300,70,"HOLD TO TALK",2,10);
retVal=displayRefresh();

let savedIP$="";
let savedPort=0;
let savedName$="";
let lastState=-1;
let ready=p2pStart(myPort,key$,password$);
if ready==0 then
    print "Telephone service could not start";
    retVal=displaySetText(10,"Startup failed");
else
    retVal=p2pSetCallerID(myName$);
    retVal=p2pAutoAnswer(0);
    retVal=p2pVolume(40);
    retVal=p2pToneVolume(35);
    retVal=p2pMicGain(100);
    retVal=p2pSidetone(0);
endif

while ready==1 do
    let state=p2pStatus();
    let evt$=getDisplayMessage$();
    if len(evt$)>0 then
        let fieldValue$=field$(2,evt$);
        let element=val(fieldValue$);
        let fieldValue$=field$(4,evt$);
        let activity=val(fieldValue$);
        if activity==3 then
            if element==1 then
                if state==0 or state==4 or state==5 then
                    retVal=p2pDial(peerHost$,peerPort);
                endif
            endif
            if element==2 and state==2 then
                retVal=p2pAnswer();
            endif
            if element==3 then
                retVal=p2pHangup();
            endif
            if element==4 then
                if state==0 or state==4 or state==5 then
                    if savedPort>0 then
                        retVal=p2pDial(savedIP$,savedPort);
                    endif
                endif
            endif
        endif
        if handsFree==0 and state==3 then
            if element==5 and activity==1 then
                retVal=p2pSend(1);
            endif
            if element==5 and activity==2 then
                retVal=p2pSend(0);
            endif
        endif
    endif
    let state=p2pStatus();
    if state!=lastState then
        if state==0 then
            retVal=displaySetText(10,"Ready");
        endif
        if state==1 then
            retVal=displaySetText(10,"Dialing");
        endif
        if state==2 then
            let savedName$=p2pCallerID$();
            let savedIP$=p2pCallerIP$();
            savedPort=p2pCallerPort();
            retVal=displaySetText(10,"Incoming call");
            retVal=displaySetText(11,savedName$);
            print savedName$;
            print savedIP$;
            print savedPort;
        endif
        if state==3 then
            retVal=displaySetText(10,"In call");
            if handsFree==1 then
                retVal=p2pAECDelay(20);
                retVal=p2pMode(1);
                if retVal==0 then
                    print "Hands-free audio could not start";
                endif
            endif
        endif
        if state==4 then
            retVal=displaySetText(10,"Busy");
        endif
        if state==5 then
            retVal=displaySetText(10,"Unavailable");
        endif
        lastState=state;
    endif
    retVal=wait(25);
wend

For a first test, use LAN addresses. Check command return values when adapting this example to a finished application, and show a useful message when a dial or answer request is rejected. Keep online speech, MP3 playback, and voice recording stopped during a telephone call.

MQTT Guide Top ↑

MQTT exchanges messages through a broker, such as Mosquitto. Connect Wi-Fi first, then initialize the client with the broker URI, username, and password. Use empty credential strings only when the broker permits anonymous access. Broker installation is outside this guide.

A topic is a named message channel, such as b9x/temperature. Subscribe to topics you want to receive and publish text payloads to topics you want to send. Initialization starts a connection attempt; wait for the CONNECT event before subscribing or publishing. Subscribe again after a reconnect.

// A compatible broker such as Mosquitto must already be running.
retVal=initMQTTClient("mqtt://192.168.1.10","user","password");
while 1 do
    let msg$=mqttClientGetMessage$();
    if len(msg$)>0 then
        print msg$;
        if instr(msg$,"[CONNECT]")==1 then
            retVal=mqttClientSubscribe("b9x/command");
            let temperature=72.5;
            let payload$=str$(temperature);
            retVal=mqttClientPublish("b9x/temperature",payload$);
        endif
    endif
    retVal=wait(50);
wend

mqttClientGetMessage$() returns empty text when no event is ready. Otherwise its fields are [eventType][messageID][topic][data]. Events include CONNECT, DISCONNECT, DATA, SUBSCRIBED, UNSUBSCRIBED, PUBLISHED, and ERROR. DATA carries the topic and message text. Keep messages short; large event records may be shortened.

Publishing uses quality of service 1, which can deliver a message more than once. Design commands so a repeated message does not cause an unwanted second action. Separate function calls into named variables when converting or combining values; this also makes errors easier to diagnose.

Complete Examples Top ↑

Each example below is a separate BASIC program. Do not paste several complete programs into one file without combining their initialization and main loops. Use suitable free GPIOs for external hardware and keep sample credentials out of published applications.

Touchscreen controls

Demonstrates checkbox argument order, a 0–100 slider, a scrollable list, textbox input, and a keyboard. Prints events so you can inspect them.

retVal=displaySetOrientation(0);
retVal=displayRemoveAllElements();
retVal=displayClear(0);
retVal=displayAddLabel(20,10,10,280,32,"Control Panel",2,65535);
retVal=displayAddCheckBox(21,10,60,200,32,"Enable",0,2);
retVal=displayAddSlider(22,10,110,280,42,0,100,50);
retVal=displayAddListBox(23,10,170,280,100,"Kitchen|Workshop|Office",0,2);
retVal=displayAddTextBox(30,10,290,280,40,"",63,2);
retVal=displayAddKeyboard(40,30);
retVal=displayRefresh();
while 1 do
    let eventText$=getDisplayMessage$();
    if len(eventText$)>0 then
        print eventText$;
        let level=displayGetValue(22);
        let enabled=displayGetChecked(21);
        let chosen=displayGetValue(23);
        let inputText$=displayGetText$(30);
    endif
    retVal=wait(25);
wend

SD text and MP3 playback

Checks the SD card, writes and reads a small text file, searches for an MP3, then starts playback. Playback continues after the call returns.

if sdMounted()==1 then
    retVal=sdWriteText("/sdcard/test.txt","Hello from B9X Basic");
    if retVal==1 then
        let fileText$=sdReadText$("/sdcard/test.txt");
        print fileText$;
    endif
    let fileName$=sdFindFirst$("/sdcard/*.mp3");
    if len(fileName$)>0 then
        let fullPath$="/sdcard/"+fileName$;
        retVal=mp3SetVolume(40);
        retVal=mp3Play(fullPath$);
        if retVal==0 then
            let errorText$=mp3LastError$();
            print errorText$;
        endif
    endif
else
    print "SD card is not mounted";
endif

Online question and answer

Initializes with your own key, submits a question, and polls for a result with a two-minute timeout. The timeout ends the example’s wait; it does not cancel a previously submitted online request.

// Replace with your own API key. Do not publish it with your program.
let key$="YOUR_API_KEY";
while wifiIsConnected()==0 do
    retVal=wait(100);
wend
let ready=oaixInit(key$);
if ready==1 then
    let accepted=oaixAskQuestion(1,"What does a relay do?");
    if accepted==1 then
        let answer$="";
        let began=getTicks(1);
        while len(answer$)==0 and getTicks(1)-began<120000 do
            let answer$=oaixGetAnswer$();
            retVal=wait(100);
        wend
        if len(answer$)>0 then
            print answer$;
        else
            print "No answer received before timeout";
        endif
    endif
endif

The complete calling, answering, caller-ID, callback, and hands-free example is in the P2P Telephone Guide above.

Troubleshooting Top ↑

SymptomWhat to check
Unexpected character in a programCheck semicolons, matching block endings, function argument types, quotes, and whether a string function name ends in $.
String comparison behaves unexpectedlyComparisons are case-sensitive. Verify spelling and capitalization.
FOR loop errorUse for i=0 to 10 do … next, following the examples in this guide.
Display event never arrivesConfirm the element is touchable/enabled/visible and that the program is polling getDisplayMessage$().
BMP does not displayConfirm SD is mounted, use the complete path, and use a supported uncompressed 16/24-bit BMP format.
VOIP connects but there is no audioWait until voipIsConnected()==1 before calling voipStartListening().
Network function failsCheck wifiIsConnected(), host/port values, credentials and network reachability.
MP3 fails to playCheck the SD path and inspect mp3LastResult() and mp3LastError$().
Application becomes sluggishAdd a short wait() in polling loops so displays, audio, and networking remain responsive.
Unexpected = in a string assignmentWrite let savedIP$=address$; use let for every string assignment.
Caller name is missingSet p2pSetCallerID() before dialing and update both devices for long-name support.
Callback failsSave both p2pCallerIP$() and p2pCallerPort(); verify matching credentials and reachable UDP forwarding.
Command returned 0Check that function’s Returns line. For several display and VOIP commands, 0 means success.
Touch fields seem wrongField 2 is the element ID; field 3 is element type; field 4 is activity; field 5 is value.
Slider starts at the wrong valueUse (…,min,max,value), for example (…,0,100,50).
Checkbox uses the wrong font/stateUse (…,caption$,checked,font).
Color change affects the wrong controlThe first displaySetColors() argument is the element ID.
No incoming calls on cellular/hotspotDynamic DNS does not bypass carrier-grade NAT. A publicly reachable path, NAT traversal, or relay is needed.
Using several features: Choose GPIO pins that are free for your application. Stop one audio feature before starting another. For example, stop music playback before starting a telephone call.

Quick Reference Top ↑

Look up a function’s exact argument order here, then consult its full entry for return values, ranges, and examples.

FunctionPurpose
wait(milliseconds)Pauses your program for the requested number of milliseconds, then returns that number.
getTicks(mode)Returns elapsed time since boot. mode 0=seconds, 1=milliseconds, 2=microseconds.
memx()Returns currently available 8-bit-capable heap memory.
restart()Restarts the controller.
wifiIsConnected()Returns a nonzero value when Wi-Fi is connected.
len(text$)Returns the number of characters in a string.
asc(text$)Returns the character code of the first character.
chr$(number)Returns a one-character string for a character code.
left$(text$, count)Returns the leftmost count characters.
right$(text$, count)Returns the rightmost count characters.
mid$(text$, start, count)Returns a substring beginning at start for count characters.
str$(number)Converts a numeric value to a string.
val(text$)Converts a numeric string to a number.
instr(text$, find$)Returns the position of one string inside another.
instr(start, text$, find$)Searches for find$ beginning at start.
fmt$(number, format$)Formats a number as text using a VB-style format pattern.
trim$(text$)Returns a copy with leading and trailing ASCII space characters removed.
abs(x)Returns the absolute value of x.
log(x)Returns the natural logarithm.
log10(x)Returns the base-10 logarithm.
round(x)Rounds x to the nearest integral value.
exp(x)Returns e raised to x.
sqrt(x)Returns the square root.
sin(x)Returns the sine of an angle in radians.
cos(x)Returns the cosine of an angle in radians.
tan(x)Returns the tangent of an angle in radians.
asin(x)Returns the inverse sine in radians.
acos(x)Returns the inverse cosine in radians.
atan(x)Returns the inverse tangent in radians.
sinh(x)Returns the hyperbolic sine.
cosh(x)Returns the hyperbolic cosine.
rnd(min, max)Returns a random integer in the inclusive range min through max.
modulo(a, b)Returns the integer remainder of a divided by b.
makeInput(gpio)Configures a GPIO as an input with pull-down.
getInput(gpio)Reads a digital input and returns its logic level.
makeOutput(gpio)Configures a GPIO as an output.
setHigh(gpio)Drives an output high.
setLow(gpio)Drives an output low.
readTemperature(gpio)Initializes/reads the supported DS18B20 temperature sensor on the specified GPIO and returns Celsius.
motionInit(uartPort,receiveGPIO)Starts the supported RD-03 motion/distance sensor on a UART port and receive GPIO.
motionGetDistance()Returns the latest distance value reported by the initialized motion sensor.
batteryVoltage()Returns the measured battery voltage in volts.
batteryLevel()Returns the estimated battery charge level.
setNVS(key$, value$)Stores a string value under a string key in nonvolatile storage.
getNVS$(key$)Returns the stored string for a key.
logData(name$, data$)Records application data under the supplied log name.
sdMounted()Returns 1 when the SD card is mounted, otherwise 0.
sdExists(path$)Returns 1 if the path exists.
sdFileSize(path$)Returns file size.
sdReadText$(path$)Reads text from a file into a BASIC string.
sdList$(path$)Returns a directory listing string.
sdFindFirst$(pattern$)Starts a file search and returns the first matching name, without its parent directory.
sdFindNext$()Returns the next name in the active file search, or empty text at the end.
sdFindPrevious$()Returns the previous name in the active file search, or empty text when no previous match exists.
sdWriteText(path$, text$)Writes text to a file, replacing its contents.
sdAppendText(path$, text$)Appends text to a file.
sdDelete(path$)Deletes a file/path.
sdRename(old$, new$)Renames a file/path.
sdMakeDir(path$)Creates a directory.
mp3Play(path$)Starts MP3 playback from the specified path.
mp3Stop()Stops MP3 playback.
mp3Pause()Pauses playback.
mp3Resume()Resumes paused playback.
mp3IsPlaying()Returns 1 while MP3 playback is active.
mp3SetVolume(level)Sets the MP3 playback volume.
mp3LastResult()Returns the last MP3 result/status value.
mp3LastError$()Returns text describing the last MP3 error.
initMQTTClient(broker$, user$, password$)Starts the MQTT client using broker and credential strings.
mqttClientSubscribe(topic$)Subscribes to a topic.
mqttClientUnsubscribe(topic$)Removes a subscription.
mqttClientPublish(topic$, data$)Publishes a string payload.
mqttClientGetMessage$()Returns the next queued MQTT event/message as a bracketed string.
voipInit(localPort, txBclk, txWs, txData, rxBclk, rxWs, rxData)Initializes VOIP UDP audio with encryption, an audio sample rate of 11025 Hz, a 5-second connection-check interval, and a 120-second connection timeout.
voipConnect(host$, port, password$, node$, key$)Sends a connection request to B9X Voice Server and stores the server/session information.
voipIsConnected()Returns 1 after the server connection has been established.
voipClose()Requests that B9X Voice Server connection be closed.
voipStartListening()Starts receiving/playing server audio.
voipHaltListening()Stops VOIP receive/playback.
voipStartSending()Starts microphone audio transmission.
voipHaltSending()Stops microphone audio transmission.
voipIsSending()Returns the current sending state.
voipSetVolume(level)Sets received speaker volume from 0 through 100.
voipSetMicGain(level)Sets microphone gain from 0 through 100.
voipGetMicLevel()Returns the instantaneous/recent microphone audio level on a 0-100 scale.
voipGetSpeakerLevel()Returns the instantaneous/recent speaker audio level on a 0-100 scale.
voipEnableVOX(sensitivity)Enables voice-operated transmit monitoring using the supplied sensitivity threshold.
voipDisableVOX()Disables VOX.
voipIsVOXActive()Returns whether VOX is currently active/open.
p2pSetCallerID(name$)Sets the name this device sends with outgoing telephone calls.
p2pCallerID$()Returns the last incoming caller’s name, or its source IP address when no name is supplied.
p2pCallerIP$()Returns the source IPv4 address of the last incoming caller.
p2pCallerPort()Returns the listening port advertised by the last incoming caller.
p2pStart(localPort,key$,password$)Starts the telephone service on a local UDP port without dialing a peer. Returns 1 on success, 0 on failure.
p2pDial(host$,remotePort)Queues an outgoing call. Returns 1 if the request is accepted, 0 if invalid or the service is already handling a call.
p2pAnswer()Queues acceptance of an incoming call. Returns 1 on acceptance, otherwise 0.
p2pReject()Queues rejection of an incoming call. Returns 1 on acceptance, otherwise 0.
p2pHangup()Queues termination or cancellation of the current call while keeping the telephone service available.
p2pStatus()Returns the telephone call state: 0 idle, 1 dialing, 2 incoming, 3 in call, 4 busy, 5 unavailable.
p2pAutoAnswer(enabled)Enables automatic answering for subsequent incoming calls when enabled is nonzero; 0 selects manual answering. Returns 1.
p2pOpen(host$,localPort,remotePort,key$,password$)Initializes the direct-peer connection and starts asynchronous authentication. Returns 1 if initialization and connection request succeed, otherwise 0.
p2pListen(enabled)Starts received-audio playback when enabled is nonzero; 0 stops playback. Returns 1 on success, 0 on failure.
p2pSend(enabled)Starts microphone transmission when enabled is nonzero; 0 stops transmission. Returns 1 on success, 0 on failure.
p2pConnected()Returns 1 when the peer has authenticated, otherwise 0.
p2pVolume(level)Sets received-speech speaker volume, clamped to 0–100. Returns 1 on success, 0 on failure.
p2pToneVolume(level)Sets local ringing, ringback, and busy-tone volume independently of received speech. Clamps to 0–100.
p2pMicGain(level)Sets microphone software gain, clamped to 0–100. Returns 1 on success, 0 on failure.
p2pSidetone(level)Sets local microphone monitoring mixed into the speaker, clamped to 0–100. Returns 1 on success, 0 on failure.
p2pMicLevel()Returns the most recent processed microphone-block peak on a 0–100 scale.
p2pSpeakerLevel()Returns the most recent processed speaker-block peak on a 0–100 scale.
p2pMode(mode)Selects 0 for push-to-talk or 1 for full-duplex operation using ESP-SR acoustic echo cancellation. Returns 1 on success, 0 on failure.
p2pGetMode()Returns 0 for PTT or 1 for full-duplex AEC mode.
p2pAECDelay(milliseconds)Sets AEC reference delay from 0 through 250 ms and resets the reference history. Returns 1 for a valid value, otherwise 0.
p2pClose()Stops audio, closes the connection, clears the encryption key, and leaves telephone mode. Returns 1 on success, 0 on failure.
displayInit(sdaGPIO,sclGPIO)Initializes an optional external SSD1306 OLED display. This function does not initialize the built-in color touchscreen.
displaySetOrientation(orientation)Selects 0 for portrait (320 × 480) or 1 for landscape (480 × 320).
displaySetBrightness(level)Sets display brightness.
displaySetColors(number,foreground,background)Changes the text/foreground and background colors of one existing element.
displayClear(color)Clears the display using a numeric color.
displayRefresh()Forces a display refresh/redraw.
displayRemoveAllElements()Removes all UI elements and associated icon state.
displayText(text$)Shows text on the optional external OLED initialized with displayInit().
displayAddButton(number,x,y,width,height,caption$,font)Adds a touchable pushbutton.
displayAddRoundedButton(number,x,y,width,height,caption$,font,radius)Adds a pushbutton with rounded corners.
displayAddLabel(number,x,y,width,height,text$,font,textColor)Adds a text label with the specified text color.
displayAddCheckBox(number,x,y,width,height,caption$,checked,font)Adds a checkbox. Touching it changes its checked state.
displayAddTextBox(number,x,y,width,height,text$,maxLen,font)Adds an editable text field.
displayAddPasswordTextBox(number,x,y,width,height,text$,maxLen,font)Adds an editable textbox whose displayed characters are masked.
displayAddSlider(number,x,y,width,height,min,max,value)Adds a touch slider with an initial value and visible numeric value.
displayAddListBox(number,x,y,width,height,items$,selected,font)Adds a scrollable list. Separate items with the | character.
displayAddAnalogMeter(number,x,y,width,height,min,max,value)Adds a needle meter with its numeric value displayed.
displayAddVerticalBarMeter(number,x,y,width,height,min,max,value)Adds a vertical level meter with a visible numeric value.
displayAddLamp(number,x,y,width,height,caption$,font,on)Adds an on/off indicator that can also be toggled by touch.
displayAddSwitch(number,x,y,width,height,caption$,font,on)Adds an on/off switch display that can be toggled by touch or changed by your program.
displayAddToggleSwitch(number,x,y,width,height,caption$,font,on)Adds a touchable switch that toggles between on and off.
displayAddFlipSwitch(number,x,y,width,height,caption$,font,on)Adds a touchable toggle switch using the flip-switch function name.
displayAddKeyboard(number,targetElement)Adds an alphanumeric keyboard linked initially to a textbox.
displayAddIcon(number,x,y,iconNumber)Adds a touchable built-in icon.
displaySetIcon(number,iconNumber)Changes an existing icon element.
displayAddBmpFromFile(number,x,y,path$,touchable)Adds a BMP image from a file path.
displayAddBMPFromSD(number,x,y,path$,touchable)Adds a BMP stored on the mounted SD card.
displaySetText(number,text$)Changes an element’s text.
displayGetText$(number)Returns text from an element.
displaySetValue(number,value)Sets an element’s numeric value/state.
displayGetValue(number)Returns an element’s numeric value.
displaySetChecked(number,state)Sets a checkbox checked state.
displayGetChecked(number)Returns checkbox state.
displaySetEnabled(number,state)Enables or disables user interaction with an element.
displaySetVisible(number,state)Shows or hides an element.
getDisplayMessage$()Returns the next queued display interaction message, or an empty string when none is queued.
ttsInit(uartPort,busyGPIO,txGPIO,rxGPIO)Initializes an optional external SYN6988 serial speech module.
ttsSpeak(text$)Starts speaking the supplied text.
ttsIsBusy()Returns nonzero while TTS is active.
ttsxInit(bclkGPIO,wsGPIO,dataGPIO,key$,voice$,instructions$)Prepares online text-to-speech playback.
ttsxSpeak(text$)Queues text for online speech playback.
ttsxSetVolume(level)Sets extended TTS output volume.
vrxInit(bclkGPIO,wsGPIO,dataGPIO,recordSeconds,key$)Prepares voice recording and online transcription.
vrxTranscribe(requestID)Requests a recording and transcription using an application-chosen numeric request ID.
vrxGetTranscript$()Returns the next available transcription, or empty text when no result is ready.
oaixInit(key$)Initializes access to the online text-answer service.
oaixAskQuestion(requestID,question$)Queues a text question for the online AI service.
oaixGetAnswer$()Returns the next available answer as text, or empty text when no answer is ready.
irInit(gpio)Initializes the infrared receiver on a GPIO.
irGetCode()Returns a received infrared code, or -1 when no sufficiently confident code is available.
ws2812Init(gpio,count)Initializes a WS2812/NeoPixel-style LED strip.
ws2812SetPixel(handle,index,r,g,b)Sets one pixel’s RGB values.
ws2812Fill(handle,r,g,b)Sets all pixels to one RGB color.
ws2812Show(handle)Updates the physical LEDs with the colors you have set.
ws2812Clear(handle)Sets all LEDs in the strip to off.
ws2812IsBusy(handle)Returns whether the LED subsystem is busy.
hour()Returns the current hour from the configured system clock.
minute()Returns the current minute.
second()Returns the current second.
month()Returns the current month number.
day()Returns the current day of month.
year()Returns the current year.
weekDay()Returns the day of the week: 0 Sunday through 6 Saturday.

B9X Basic • Complete User Reference • Beginner to Advanced • B9X Electronics

References And Disclaimer

B9X Electronics

Website: https://b9xelectronics.com

B9X Voice Server™ and B9X Voice Client™ are trademarks of B9X Electronics.

Windows™ is a trademark of Microsoft Corporation.

Xojo™ is a trademark of Xojo.

B4A™ is a trademark of Anywhere Software.

Android™ and Google™ are trademarks of Google.

Yaesu™ and products mentioned are trademarks of Yaesu/Vertex Standard.

Icom™ and products mentioned are trademarks of Icom.

All other references are trademarks and copyrights of their respective holders.

The specifications in this document are only given to provide information, without any guarantee in regards to either mistakes or omissions. B9X Electronics reserves the right to make changes to the products contained in this publication for any reason.

IN NO EVENT WILL B9X ELECTRONICS BE LIABLE TO YOU OR ANYONE FOR ANY DAMAGES, INCLUDING BUT NOT LIMITED TO INJURY TO PERSON OR PRODUCT, LOST PROFITS, LEGAL COSTS, LOST SAVINGS, OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THIS AND ANY OF OUR PRODUCTS.