

B9X Basic — Complete User Reference
Beginner to Advanced • Updated 16 October 2026
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;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 ↑
| Category | Operators | Example |
|---|---|---|
| Arithmetic | + - * / ** | power=2**8; |
| Comparison | == != < <= > >= | if temp>75 then |
| Logical AND | and or && | if a==1 and b==1 then |
| Logical OR | or or || | if a==1 or b==1 then |
| Logical NOT | not 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";
endifProgram Flow Top ↑
IF / ELSE / ENDIF
if temperature>80 then
print "HOT";
else
print "NORMAL";
endifWHILE / WEND
counter=0;
while counter<5 do
print counter;
counter=counter+1;
wendFOR / 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;
nextSubs & 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];samples, temperatures, or levels.Practical Limits Top ↑
| Feature | Limit or convention |
|---|---|
| Numeric variables | Up to 256 |
| String variables | Up to 256 |
| String value | Up to 512 bytes; use ASCII when counting visible characters |
| Numeric arrays | Up to 64 arrays, each up to 1024 entries |
| Function arguments | Up to 16 |
| Touchscreen elements | Up to 48 at once |
| Touchscreen text | Up to 255 characters |
| Touch event text | Up to 63 characters |
| Telephone caller name | Up to 255 printable ASCII characters |
| Online speech request | Keep 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 style | Meaning | Example |
|---|---|---|
| 1/0 command | 1 accepted/success; 0 failed | p2pStart(), mp3Play(), sdWriteText() |
| 0/error command | 0 success; nonzero error | voipInit(), displaySetText() |
| State/value | A value, rather than a command result | p2pStatus(), batteryVoltage() |
| Text | Returned string; often empty when no result is ready | getDisplayMessage$(), 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 ↑
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
Pauses your program for the requested number of milliseconds, then returns that number.
Returns: The requested delay value in milliseconds.
| Parameter | Type | Meaning |
|---|---|---|
| milliseconds | Number | Delay 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.
Returns elapsed time since boot. mode 0=seconds, 1=milliseconds, 2=microseconds.
Returns: Elapsed time: mode 0 seconds, 1 milliseconds, 2 microseconds.
| Parameter | Type | Meaning |
|---|---|---|
| mode | Number | 0 seconds, 1 milliseconds, 2 microseconds. |
retVal=getTicks(1);Note: Useful for elapsed-time measurements and non-blocking timing.
Returns currently available 8-bit-capable heap memory.
Returns: Available memory in bytes.
retVal=memx();Note: Useful while diagnosing memory-heavy applications.
Restarts the controller.
Returns: Does not normally return because the device restarts.
retVal=restart();Note: Use when an application intentionally needs a software reboot.
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
Returns the number of characters in a string.
Returns: Length of the text in bytes; ASCII characters occupy one byte each.
| Parameter | Type | Meaning |
|---|---|---|
| text$ | String | Text in double quotes or a string variable ending in $. |
retVal=len("B9X");Note: Built into the language.
Returns the character code of the first character.
Returns: Character code of the first character.
| Parameter | Type | Meaning |
|---|---|---|
| text$ | String | Text in double quotes or a string variable ending in $. |
retVal=asc("A");Note: Built into the language.
Returns a one-character string for a character code.
Returns: Text. See the description for the empty-result behavior.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Numeric value to convert; chr$ uses a character code. |
let s$=chr$(65);Note: Built into the language.
Returns the leftmost count characters.
Returns: Text. See the description for the empty-result behavior.
| Parameter | Type | Meaning |
|---|---|---|
| text$ | String | Text in double quotes or a string variable ending in $. |
| count | Number | Number of characters, or number of LEDs when initializing a strip. |
let s$=left$("ROBERT",3);Note: Returns “ROB”.
Returns the rightmost count characters.
Returns: Text. See the description for the empty-result behavior.
| Parameter | Type | Meaning |
|---|---|---|
| text$ | String | Text in double quotes or a string variable ending in $. |
| count | Number | Number of characters, or number of LEDs when initializing a strip. |
let s$=right$("ROBERT",2);Note: Returns “RT”.
Returns a substring beginning at start for count characters.
Returns: Text. See the description for the empty-result behavior.
| Parameter | Type | Meaning |
|---|---|---|
| text$ | String | Text in double quotes or a string variable ending in $. |
| start | Number | One-based starting position. |
| count | Number | Number of characters, or number of LEDs when initializing a strip. |
let s$=mid$("ROBERT",2,3);Note: Use for parsing fixed-format strings.
Converts a numeric value to a string.
Returns: Text. See the description for the empty-result behavior.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Numeric value to convert; chr$ uses a character code. |
let s$=str$(25);Note: Useful when building messages or display text.
Converts a numeric string to a number.
Returns: Numeric conversion of the supplied text.
| Parameter | Type | Meaning |
|---|---|---|
| text$ | String | Text in double quotes or a string variable ending in $. |
retVal=val("18000");Note: Use only with text that represents a number.
Returns the position of one string inside another.
Returns: One-based position of a match, or 0 if not found.
| Parameter | Type | Meaning |
|---|---|---|
| text$ | String | Text in double quotes or a string variable ending in $. |
| find$ | String | Text to search for. |
retVal=instr("B9X BASIC","BASIC");Note: A three-argument form also accepts a starting position.
Searches for find$ beginning at start.
Returns: One-based position of a match, or 0 if not found.
| Parameter | Type | Meaning |
|---|---|---|
| start | Number | One-based starting position. |
| text$ | String | Text in double quotes or a string variable ending in $. |
| find$ | String | Text to search for. |
retVal=instr(5,"B9X BASIC BASIC","BASIC");Note: Useful when parsing repeated fields.
Formats a number as text using a VB-style format pattern.
Returns: Text. See the description for the empty-result behavior.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| format$ | String | Numeric format pattern, such as “0.00”. |
let s$=fmt$(12.345,"0.00");Note: Useful for display labels and reports.
Returns a copy with leading and trailing ASCII space characters removed.
Returns: Text. See the description for the empty-result behavior.
| Parameter | Type | Meaning |
|---|---|---|
| text$ | String | Text 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
Returns the absolute value of x.
Returns: Absolute value of x.
| Parameter | Type | Meaning |
|---|---|---|
| x | Number | Numeric 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);Returns the natural logarithm.
Returns: Natural logarithm; x must be positive.
| Parameter | Type | Meaning |
|---|---|---|
| x | Number | Numeric 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);Returns the base-10 logarithm.
Returns: Base-10 logarithm; x must be positive.
| Parameter | Type | Meaning |
|---|---|---|
| x | Number | Numeric 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);Rounds x to the nearest integral value.
Returns: Nearest integer; halfway values round away from zero.
| Parameter | Type | Meaning |
|---|---|---|
| x | Number | Numeric 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);Returns e raised to x.
Returns: e raised to x.
| Parameter | Type | Meaning |
|---|---|---|
| x | Number | Numeric 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);Returns the square root.
Returns: Square root; x must be zero or greater.
| Parameter | Type | Meaning |
|---|---|---|
| x | Number | Numeric 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);Returns the sine of an angle in radians.
Returns: Sine of x, with x in radians.
| Parameter | Type | Meaning |
|---|---|---|
| x | Number | Numeric 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);Returns the cosine of an angle in radians.
Returns: Cosine of x, with x in radians.
| Parameter | Type | Meaning |
|---|---|---|
| x | Number | Numeric 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);Returns the tangent of an angle in radians.
Returns: Tangent of x, with x in radians.
| Parameter | Type | Meaning |
|---|---|---|
| x | Number | Numeric 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);Returns the inverse sine in radians.
Returns: Inverse sine in radians; x must be -1 through 1.
| Parameter | Type | Meaning |
|---|---|---|
| x | Number | Numeric 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);Returns the inverse cosine in radians.
Returns: Inverse cosine in radians; x must be -1 through 1.
| Parameter | Type | Meaning |
|---|---|---|
| x | Number | Numeric 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);Returns the inverse tangent in radians.
Returns: Inverse tangent in radians.
| Parameter | Type | Meaning |
|---|---|---|
| x | Number | Numeric 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);Returns the hyperbolic sine.
Returns: Hyperbolic sine of x.
| Parameter | Type | Meaning |
|---|---|---|
| x | Number | Numeric 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);Returns the hyperbolic cosine.
Returns: Hyperbolic cosine of x.
| Parameter | Type | Meaning |
|---|---|---|
| x | Number | Numeric 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);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.
| Parameter | Type | Meaning |
|---|---|---|
| min | Number | Lower inclusive bound. |
| max | Number | Upper inclusive bound. |
retVal=rnd(1,6);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.
| Parameter | Type | Meaning |
|---|---|---|
| a | Number | Dividend, converted to an integer. |
| b | Number | Nonzero divisor, converted to an integer. |
retVal=modulo(17,5);GPIO & sensors
Configures a GPIO as an input with pull-down.
Returns: The GPIO number supplied. Choose a suitable free GPIO greater than 0.
| Parameter | Type | Meaning |
|---|---|---|
| gpio | Number | Suitable free GPIO number. |
retVal=makeInput(13);Note: The GPIO number must be appropriate for the board and not already reserved.
Reads a digital input and returns its logic level.
Returns: 0 for low or 1 for high. Configure the input first.
| Parameter | Type | Meaning |
|---|---|---|
| gpio | Number | Suitable free GPIO number. |
retVal=getInput(13);Note: Returns the current digital level.
Configures a GPIO as an output.
Returns: The GPIO number supplied. Choose a suitable free GPIO greater than 0.
| Parameter | Type | Meaning |
|---|---|---|
| gpio | Number | Suitable free GPIO number. |
retVal=makeOutput(12);Drives an output high.
Returns: The GPIO number supplied. Choose a suitable free GPIO greater than 0.
| Parameter | Type | Meaning |
|---|---|---|
| gpio | Number | Suitable free GPIO number. |
retVal=setHigh(12);Drives an output low.
Returns: The GPIO number supplied. Choose a suitable free GPIO greater than 0.
| Parameter | Type | Meaning |
|---|---|---|
| gpio | Number | Suitable free GPIO number. |
retVal=setLow(12);Initializes/reads the supported DS18B20 temperature sensor on the specified GPIO and returns Celsius.
Returns: Temperature in degrees Celsius.
| Parameter | Type | Meaning |
|---|---|---|
| gpio | Number | Suitable free GPIO number. |
retVal=readTemperature(4);Note: Allow for sensor conversion time in application design.
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.
| Parameter | Type | Meaning |
|---|---|---|
| uartPort | Number | Unused UART port number supported by the board. |
| receiveGPIO | Number | Free 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.
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.
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.
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
Stores a string value under a string key in nonvolatile storage.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| key$ | String | Storage key name, up to 15 characters. Choose a consistent name such as “host”. |
| value$ | String | Text to store under the specified storage key. |
retVal=setNVS("fHost","192.168.1.130");Note: Use for configuration that should survive restart.
Returns the stored string for a key.
Returns: Text. See the description for the empty-result behavior.
| Parameter | Type | Meaning |
|---|---|---|
| key$ | String | Storage 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.
Records application data under the supplied log name.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| name$ | String | Name string; see the function’s length and character rules. |
| data$ | String | Text to publish or log. |
retVal=logData("temperature","72.5");Note: Both arguments are strings.
SD card files
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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| path$ | String | Complete file or directory path, such as “/sdcard/config.txt”. |
retVal=sdExists("/sdcard/config.txt");Note: Use complete mounted paths.
Returns file size.
Returns: The file size in bytes, or -1 if the file cannot be examined.
| Parameter | Type | Meaning |
|---|---|---|
| path$ | String | Complete file or directory path, such as “/sdcard/config.txt”. |
retVal=sdFileSize("/sdcard/config.txt");Reads text from a file into a BASIC string.
Returns: Text. See the description for the empty-result behavior.
| Parameter | Type | Meaning |
|---|---|---|
| path$ | String | Complete 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.
Returns a directory listing string.
Returns: Text. See the description for the empty-result behavior.
| Parameter | Type | Meaning |
|---|---|---|
| path$ | String | Complete 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.
Starts a file search and returns the first matching name, without its parent directory.
Returns: Text. See the description for the empty-result behavior.
| Parameter | Type | Meaning |
|---|---|---|
| pattern$ | String | Directory 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.
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.
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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| path$ | String | Complete file or directory path, such as “/sdcard/config.txt”. |
| text$ | String | Text in double quotes or a string variable ending in $. |
retVal=sdWriteText("/sdcard/test.txt","Hello");Note: Returns 1 on success.
Appends text to a file.
Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.
| Parameter | Type | Meaning |
|---|---|---|
| path$ | String | Complete file or directory path, such as “/sdcard/config.txt”. |
| text$ | String | Text in double quotes or a string variable ending in $. |
retVal=sdAppendText("/sdcard/log.txt","Next line");Deletes a file/path.
Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.
| Parameter | Type | Meaning |
|---|---|---|
| path$ | String | Complete file or directory path, such as “/sdcard/config.txt”. |
retVal=sdDelete("/sdcard/old.txt");Renames a file/path.
Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.
| Parameter | Type | Meaning |
|---|---|---|
| old$ | String | Existing full path. |
| new$ | String | New full path. |
retVal=sdRename("/sdcard/a.txt","/sdcard/b.txt");Creates a directory.
Returns: 1 on success or request acceptance; 0 on failure. For asynchronous calls, check the relevant state function afterward.
| Parameter | Type | Meaning |
|---|---|---|
| path$ | String | Complete file or directory path, such as “/sdcard/config.txt”. |
retVal=sdMakeDir("/sdcard/data");MP3 audio
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.
| Parameter | Type | Meaning |
|---|---|---|
| path$ | String | Complete file or directory path, such as “/sdcard/config.txt”. |
retVal=mp3Play("/sdcard/music.mp3");Note: Playback runs while your BASIC program continues.
Stops MP3 playback.
Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.
retVal=mp3Stop();Pauses playback.
Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.
retVal=mp3Pause();Resumes paused playback.
Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.
retVal=mp3Resume();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();Sets the MP3 playback volume.
Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.
| Parameter | Type | Meaning |
|---|---|---|
| level | Number | A level from 0 through 100. |
retVal=mp3SetVolume(50);Returns the last MP3 result/status value.
Returns: The last playback result; 0 indicates success. Use mp3LastError$() for explanatory text.
retVal=mp3LastResult();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
Starts the MQTT client using broker and credential strings.
Returns: 0 on successful client startup; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| broker$ | String | MQTT broker URI, such as “mqtt://192.168.1.10”. |
| user$ | String | Broker username, or empty text when not required. |
| password$ | String | Password string; use matching settings on communicating devices. |
retVal=initMQTTClient("mqtt://192.168.1.10","user","password");Note: Wi-Fi must be connected.
Subscribes to a topic.
Returns: A message ID, or -1 if the request fails.
| Parameter | Type | Meaning |
|---|---|---|
| topic$ | String | MQTT topic name. |
retVal=mqttClientSubscribe("shop/temp");Removes a subscription.
Returns: A message ID, or -1 if the request fails.
| Parameter | Type | Meaning |
|---|---|---|
| topic$ | String | MQTT topic name. |
retVal=mqttClientUnsubscribe("shop/temp");Publishes a string payload.
Returns: A message ID, or a negative value if publishing fails.
| Parameter | Type | Meaning |
|---|---|---|
| topic$ | String | MQTT topic name. |
| data$ | String | Text to publish or log. |
retVal=mqttClientPublish("shop/temp","72.5");Note: Publishes with MQTT quality of service level 1 (at least once).
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
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.
| Parameter | Type | Meaning |
|---|---|---|
| localPort | Number | This device’s UDP listening port, 1–65535. |
| txBclk | Number | Transmit bit-clock GPIO; -1 selects the onboard defaults. |
| txWs | Number | Transmit word-select GPIO; -1 selects the onboard defaults. |
| txData | Number | Transmit data GPIO; -1 selects the onboard defaults. |
| rxBclk | Number | Receive bit-clock GPIO; -1 selects the onboard defaults. |
| rxWs | Number | Receive word-select GPIO; -1 selects the onboard defaults. |
| rxData | Number | Receive 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.
Sends a connection request to B9X Voice Server and stores the server/session information.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| host$ | String | Destination IPv4 address or DNS hostname. |
| port | Number | Destination network port. |
| password$ | String | Password string; use matching settings on communicating devices. |
| node$ | String | Name identifying this device to B9X Voice Server. |
| key$ | String | Secret key; see the function-specific requirements. |
retVal=voipConnect("192.168.1.130",18000,password$,"MYNODE",key$);Note: Wait until voipIsConnected()==1 before starting listening.
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.
Requests that B9X Voice Server connection be closed.
Returns: 0 on success; a nonzero error value on failure.
retVal=voipClose();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.
Stops VOIP receive/playback.
Returns: 0 on success; a nonzero error value on failure.
retVal=voipHaltListening();Starts microphone audio transmission.
Returns: 0 on success; a nonzero error value on failure.
retVal=voipStartSending();Stops microphone audio transmission.
Returns: 0 on success; a nonzero error value on failure.
retVal=voipHaltSending();Returns the current sending state.
Returns: 1 while sending is enabled, otherwise 0.
retVal=voipIsSending();Sets received speaker volume from 0 through 100.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| level | Number | A level from 0 through 100. |
retVal=voipSetVolume(20);Note: 100 preserves full PCM amplitude; 0 mutes.
Sets microphone gain from 0 through 100.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| level | Number | A level from 0 through 100. |
retVal=voipSetMicGain(100);Returns the instantaneous/recent microphone audio level on a 0-100 scale.
Returns: Recent microphone peak on a 0–100 scale.
retVal=voipGetMicLevel();Returns the instantaneous/recent speaker audio level on a 0-100 scale.
Returns: Recent speaker peak on a 0–100 scale.
retVal=voipGetSpeakerLevel();Enables voice-operated transmit monitoring using the supplied sensitivity threshold.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| sensitivity | Number | VOX audio threshold; lower values trigger on quieter audio. |
retVal=voipEnableVOX(700);Note: Lower threshold values trigger transmission on quieter sounds.
Disables VOX.
Returns: 0 on success; a nonzero error value on failure.
retVal=voipDisableVOX();Returns whether VOX is currently active/open.
Returns: 1 while voice detection is triggered, otherwise 0.
retVal=voipIsVOXActive();P2P telephone & direct-peer audio
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.
| Parameter | Type | Meaning |
|---|---|---|
| name$ | String | Name 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.
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.
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.
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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| localPort | Number | This device’s UDP listening port, 1–65535. |
| key$ | String | Secret key; see the function-specific requirements. |
| password$ | String | Password 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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| host$ | String | Destination IPv4 address or DNS hostname. |
| remotePort | Number | Destination 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.
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.
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.
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.
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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| enabled | Number | 0 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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| host$ | String | Destination IPv4 address or DNS hostname. |
| localPort | Number | This device’s UDP listening port, 1–65535. |
| remotePort | Number | Destination UDP listening port, 1–65535. |
| key$ | String | Secret key; see the function-specific requirements. |
| password$ | String | Password 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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| enabled | Number | 0 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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| enabled | Number | 0 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.
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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| level | Number | A 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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| level | Number | A 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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| level | Number | A 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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| level | Number | A 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.
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.
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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| mode | Number | 0 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.
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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| milliseconds | Number | Delay 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.
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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| sdaGPIO | Number | Free GPIO wired to the external OLED SDA signal. |
| sclGPIO | Number | Free 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().
Selects 0 for portrait (320 × 480) or 1 for landscape (480 × 320).
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| orientation | Number | 0 portrait or 1 landscape. |
retVal=displaySetOrientation(0);Changing orientation clears existing elements and pending touch events. Set orientation before creating your screen.
Sets display brightness.
Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.
| Parameter | Type | Meaning |
|---|---|---|
| level | Number | A level from 0 through 100. |
retVal=displaySetBrightness(80);Changes the text/foreground and background colors of one existing element.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| foreground | Number | RGB565 foreground/text color. |
| background | Number | RGB565 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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| color | Number | RGB565 color value. |
retVal=displayClear(0);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();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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| text$ | String | Text in double quotes or a string variable ending in $. |
retVal=displayText("Ready");For text on the color touchscreen, use displayAddLabel() and displaySetText().
Adds a touchable pushbutton.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| x | Number | Left position in pixels, measured from the screen’s left edge. |
| y | Number | Top position in pixels, measured from the screen’s top edge. |
| width | Number | Element width in pixels. Keep it inside the current screen. |
| height | Number | Element height in pixels. Keep it inside the current screen. |
| caption$ | String | Visible caption in double quotes or a string variable. |
| font | Number | Font 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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| x | Number | Left position in pixels, measured from the screen’s left edge. |
| y | Number | Top position in pixels, measured from the screen’s top edge. |
| width | Number | Element width in pixels. Keep it inside the current screen. |
| height | Number | Element height in pixels. Keep it inside the current screen. |
| caption$ | String | Visible caption in double quotes or a string variable. |
| font | Number | Font size 1–6; see the touchscreen font table. |
| radius | Number | Corner 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.
Adds a text label with the specified text color.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| x | Number | Left position in pixels, measured from the screen’s left edge. |
| y | Number | Top position in pixels, measured from the screen’s top edge. |
| width | Number | Element width in pixels. Keep it inside the current screen. |
| height | Number | Element height in pixels. Keep it inside the current screen. |
| text$ | String | Text in double quotes or a string variable ending in $. |
| font | Number | Font size 1–6; see the touchscreen font table. |
| textColor | Number | RGB565 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.
Adds a checkbox. Touching it changes its checked state.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| x | Number | Left position in pixels, measured from the screen’s left edge. |
| y | Number | Top position in pixels, measured from the screen’s top edge. |
| width | Number | Element width in pixels. Keep it inside the current screen. |
| height | Number | Element height in pixels. Keep it inside the current screen. |
| caption$ | String | Visible caption in double quotes or a string variable. |
| checked | Number | Initial state: 0 unchecked or 1 checked. |
| font | Number | Font 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.
Adds an editable text field.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| x | Number | Left position in pixels, measured from the screen’s left edge. |
| y | Number | Top position in pixels, measured from the screen’s top edge. |
| width | Number | Element width in pixels. Keep it inside the current screen. |
| height | Number | Element height in pixels. Keep it inside the current screen. |
| text$ | String | Text in double quotes or a string variable ending in $. |
| maxLen | Number | Maximum editable length, up to 255 characters. |
| font | Number | Font 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.
Adds an editable textbox whose displayed characters are masked.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| x | Number | Left position in pixels, measured from the screen’s left edge. |
| y | Number | Top position in pixels, measured from the screen’s top edge. |
| width | Number | Element width in pixels. Keep it inside the current screen. |
| height | Number | Element height in pixels. Keep it inside the current screen. |
| text$ | String | Text in double quotes or a string variable ending in $. |
| maxLen | Number | Maximum editable length, up to 255 characters. |
| font | Number | Font 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.
Adds a touch slider with an initial value and visible numeric value.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| x | Number | Left position in pixels, measured from the screen’s left edge. |
| y | Number | Top position in pixels, measured from the screen’s top edge. |
| width | Number | Element width in pixels. Keep it inside the current screen. |
| height | Number | Element height in pixels. Keep it inside the current screen. |
| min | Number | Minimum permitted numeric value. |
| max | Number | Maximum permitted numeric value. |
| value | Number | Initial 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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| x | Number | Left position in pixels, measured from the screen’s left edge. |
| y | Number | Top position in pixels, measured from the screen’s top edge. |
| width | Number | Element width in pixels. Keep it inside the current screen. |
| height | Number | Element height in pixels. Keep it inside the current screen. |
| items$ | String | Items separated by |, for example “One|Two|Three”. |
| selected | Number | Initial selection index, starting at 0. |
| font | Number | Font 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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| x | Number | Left position in pixels, measured from the screen’s left edge. |
| y | Number | Top position in pixels, measured from the screen’s top edge. |
| width | Number | Element width in pixels. Keep it inside the current screen. |
| height | Number | Element height in pixels. Keep it inside the current screen. |
| min | Number | Minimum permitted numeric value. |
| max | Number | Maximum permitted numeric value. |
| value | Number | Initial 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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| x | Number | Left position in pixels, measured from the screen’s left edge. |
| y | Number | Top position in pixels, measured from the screen’s top edge. |
| width | Number | Element width in pixels. Keep it inside the current screen. |
| height | Number | Element height in pixels. Keep it inside the current screen. |
| min | Number | Minimum permitted numeric value. |
| max | Number | Maximum permitted numeric value. |
| value | Number | Initial 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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| x | Number | Left position in pixels, measured from the screen’s left edge. |
| y | Number | Top position in pixels, measured from the screen’s top edge. |
| width | Number | Element width in pixels. Keep it inside the current screen. |
| height | Number | Element height in pixels. Keep it inside the current screen. |
| caption$ | String | Visible caption in double quotes or a string variable. |
| font | Number | Font size 1–6; see the touchscreen font table. |
| on | Number | Initial 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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| x | Number | Left position in pixels, measured from the screen’s left edge. |
| y | Number | Top position in pixels, measured from the screen’s top edge. |
| width | Number | Element width in pixels. Keep it inside the current screen. |
| height | Number | Element height in pixels. Keep it inside the current screen. |
| caption$ | String | Visible caption in double quotes or a string variable. |
| font | Number | Font size 1–6; see the touchscreen font table. |
| on | Number | Initial 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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| x | Number | Left position in pixels, measured from the screen’s left edge. |
| y | Number | Top position in pixels, measured from the screen’s top edge. |
| width | Number | Element width in pixels. Keep it inside the current screen. |
| height | Number | Element height in pixels. Keep it inside the current screen. |
| caption$ | String | Visible caption in double quotes or a string variable. |
| font | Number | Font size 1–6; see the touchscreen font table. |
| on | Number | Initial 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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| x | Number | Left position in pixels, measured from the screen’s left edge. |
| y | Number | Top position in pixels, measured from the screen’s top edge. |
| width | Number | Element width in pixels. Keep it inside the current screen. |
| height | Number | Element height in pixels. Keep it inside the current screen. |
| caption$ | String | Visible caption in double quotes or a string variable. |
| font | Number | Font size 1–6; see the touchscreen font table. |
| on | Number | Initial state: 0 off or 1 on. |
retVal=displayAddFlipSwitch(29,10,380,200,36,"LIGHT",2,0);Its checked state and event behavior match displayAddToggleSwitch().
Adds an alphanumeric keyboard linked initially to a textbox.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| targetElement | Number | ID 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.
Adds a touchable built-in icon.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| x | Number | Left position in pixels, measured from the screen’s left edge. |
| y | Number | Top position in pixels, measured from the screen’s top edge. |
| iconNumber | Number | Built-in icon number, 1–121. |
retVal=displayAddIcon(31,20,20,17);Changes an existing icon element.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| iconNumber | Number | Built-in icon number, 1–121. |
retVal=displaySetIcon(31,18);Adds a BMP image from a file path.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| x | Number | Left position in pixels, measured from the screen’s left edge. |
| y | Number | Top position in pixels, measured from the screen’s top edge. |
| path$ | String | Complete file or directory path, such as “/sdcard/config.txt”. |
| touchable | Number | 0 for display only; 1 to generate touch events. |
retVal=displayAddBmpFromFile(32,10,10,"/sdcard/photo.bmp",1);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.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| x | Number | Left position in pixels, measured from the screen’s left edge. |
| y | Number | Top position in pixels, measured from the screen’s top edge. |
| path$ | String | Complete file or directory path, such as “/sdcard/config.txt”. |
| touchable | Number | 0 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.
Changes an element’s text.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| text$ | String | Text in double quotes or a string variable ending in $. |
retVal=displaySetText(14,"New text");Returns text from an element.
Returns: Text. See the description for the empty-result behavior.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
let s$=displayGetText$(14);Sets an element’s numeric value/state.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| value | Number | Initial or replacement numeric value. |
retVal=displaySetValue(16,75);Note: Used by sliders, meters and other value-driven elements.
Returns an element’s numeric value.
Returns: The element’s numeric value. A list returns a zero-based selection index.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
retVal=displayGetValue(16);Sets a checkbox checked state.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| state | Number | 0 false/off or 1 true/on. |
retVal=displaySetChecked(13,1);Returns checkbox state.
Returns: 1 for checked/on, 0 for unchecked/off.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
retVal=displayGetChecked(13);Enables or disables user interaction with an element.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| state | Number | 0 false/off or 1 true/on. |
retVal=displaySetEnabled(10,0);Shows or hides an element.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| number | Number | Unique element ID on the current screen; use this ID to read or change the element later. |
| state | Number | 0 false/off or 1 true/on. |
retVal=displaySetVisible(10,1);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
Initializes an optional external SYN6988 serial speech module.
Returns: 1 after initializing the external serial speech module.
| Parameter | Type | Meaning |
|---|---|---|
| uartPort | Number | Unused UART port number supported by the board. |
| busyGPIO | Number | Free GPIO connected to the speech module BUSY output. |
| txGPIO | Number | Free GPIO connected to the speech module RX input. |
| rxGPIO | Number | Free 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.
Starts speaking the supplied text.
Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.
| Parameter | Type | Meaning |
|---|---|---|
| text$ | String | Text in double quotes or a string variable ending in $. |
retVal=ttsSpeak("Hello from B9X Basic");Returns nonzero while TTS is active.
Returns: The busy state reported by the external module; use to wait for speech to finish.
retVal=ttsIsBusy();Prepares online text-to-speech playback.
Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.
| Parameter | Type | Meaning |
|---|---|---|
| bclkGPIO | Number | Audio bit-clock GPIO for the selected board. |
| wsGPIO | Number | Audio word-select GPIO for the selected board. |
| dataGPIO | Number | Audio data GPIO for the selected board. |
| key$ | String | Secret key; see the function-specific requirements. |
| voice$ | String | Voice name supported by the speech service. |
| instructions$ | String | Instructions 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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| text$ | String | Text 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.
Sets extended TTS output volume.
Returns: 1 after issuing the operation. This return value does not confirm a later network or playback result.
| Parameter | Type | Meaning |
|---|---|---|
| level | Number | A level from 0 through 100. |
retVal=ttsxSetVolume(70);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.
| Parameter | Type | Meaning |
|---|---|---|
| bclkGPIO | Number | Audio bit-clock GPIO for the selected board. |
| wsGPIO | Number | Audio word-select GPIO for the selected board. |
| dataGPIO | Number | Audio data GPIO for the selected board. |
| recordSeconds | Number | Recording duration in seconds. |
| key$ | String | Secret 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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| requestID | Number | Application-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.
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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| key$ | String | Secret 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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| requestID | Number | Application-chosen number used to identify a submitted request. |
| question$ | String | Question 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.
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
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.
| Parameter | Type | Meaning |
|---|---|---|
| gpio | Number | Suitable free GPIO number. |
retVal=irInit(7);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.
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.
| Parameter | Type | Meaning |
|---|---|---|
| gpio | Number | Suitable free GPIO number. |
| count | Number | Number of characters, or number of LEDs when initializing a strip. |
retVal=ws2812Init(48,8);Sets one pixel’s RGB values.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| handle | Number | Strip handle previously returned by ws2812Init(). |
| index | Number | LED position starting at 0; must be less than the configured count. |
| r | Number | Red intensity, 0–255. |
| g | Number | Green intensity, 0–255. |
| b | Number | Blue intensity, 0–255. |
retVal=ws2812SetPixel(0,2,255,0,0);Note: Use the LED-strip handle returned by ws2812Init(); pixel positions start at 0.
Sets all pixels to one RGB color.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| handle | Number | Strip handle previously returned by ws2812Init(). |
| r | Number | Red intensity, 0–255. |
| g | Number | Green intensity, 0–255. |
| b | Number | Blue intensity, 0–255. |
retVal=ws2812Fill(0,0,0,255);Updates the physical LEDs with the colors you have set.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| handle | Number | Strip handle previously returned by ws2812Init(). |
retVal=ws2812Show(0);Sets all LEDs in the strip to off.
Returns: 0 on success; a nonzero error value on failure.
| Parameter | Type | Meaning |
|---|---|---|
| handle | Number | Strip handle previously returned by ws2812Init(). |
retVal=ws2812Clear(0);Returns whether the LED subsystem is busy.
Returns: 1 while an LED update is queued or being sent; otherwise 0.
| Parameter | Type | Meaning |
|---|---|---|
| handle | Number | Strip handle previously returned by ws2812Init(). |
retVal=ws2812IsBusy(0);Date & time
Returns the current hour from the configured system clock.
Returns: Hour from 0 to 23.
retVal=hour();Returns the current minute.
Returns: Minute from 0 to 59.
retVal=minute();Returns the current second.
Returns: Second from 0 to 59.
retVal=second();Returns the current month number.
Returns: Month from 1 to 12.
retVal=month();Returns the current day of month.
Returns: Day of month from 1 to 31.
retVal=day();Returns the current year.
Returns: Four-digit calendar year.
retVal=year();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().
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.
Home
Check
Volume Up
Temperature
Back
Close
Volume Down
Humidity
Forward
Plus
Mute
Light
Up
Minus
Brightness
Fan
Down
Power
Wifi
Pump
Menu
Refresh
Bluetooth
Valve
Settings
Play
Lock
Motor
Information
Pause
Unlock
Heater
Warning
Stop
User
Cooling
Error
Record
Users
Battery
Plug
Clock
Calendar
Camera
Folder
Save
Upload
Download
Edit
Trash
Lamp Off
Lamp On
Lamp Dim
Switch Off
Switch On
Selector Left
Selector Center
Selector Right
Door Closed
Door Open
Door Locked
Garage Closed
Garage Open
Window Closed
Window Open
Blinds Closed
Blinds Half
Blinds Open
Thermostat Heat
Thermostat Cool
Thermostat Auto
Thermostat Off
Motion Idle
Motion Detected
Alarm Disarmed
Alarm Armed
Alarm Triggered
Water Dry
Water Leak
Smoke Clear
Smoke Alarm
Security Camera On
Security Camera Off
Machine Stop
Machine Run
Machine Fault
Machine Maintenance
Conveyor Stop
Conveyor Run
Conveyor Reverse
Pump Off
Pump On
Pump Fault
Valve Closed
Valve Open
Valve Half
Tank Empty
Tank Quarter
Tank Half
Tank Three Quarter
Tank Full
Motor Off
Motor Forward
Motor Reverse
Motor Fault
Traffic Red
Traffic Yellow
Traffic Green
Mode Auto
Mode Manual
Mode Off
Emergency Stop
Pressure Low
Pressure Normal
Pressure High
Level Low
Level Normal
Level High
Temperature Cold
Temperature Normal
Temperature Hot
Complete icon number list
| No. | Icon | No. | Icon | No. | Icon | |||
|---|---|---|---|---|---|---|---|---|
| 1 | Homehome | 11 | Checkcheck | 21 | Volume Upvolume_up | |||
| 31 | Temperaturetemperature | 2 | Backback | 12 | Closeclose | |||
| 22 | Volume Downvolume_down | 32 | Humidityhumidity | 3 | Forwardforward | |||
| 13 | Plusplus | 23 | Mutemute | 33 | Lightlight | |||
| 4 | Upup | 14 | Minusminus | 24 | Brightnessbrightness | |||
| 34 | Fanfan | 5 | Downdown | 15 | Powerpower | |||
| 25 | Wifiwifi | 35 | Pumppump | 6 | Menumenu | |||
| 16 | Refreshrefresh | 26 | Bluetoothbluetooth | 36 | Valvevalve | |||
| 7 | Settingssettings | 17 | Playplay | 27 | Locklock | |||
| 37 | Motormotor | 8 | Informationinformation | 18 | Pausepause | |||
| 28 | Unlockunlock | 38 | Heaterheater | 9 | Warningwarning | |||
| 19 | Stopstop | 29 | Useruser | 39 | Coolingcooling | |||
| 10 | Errorerror | 20 | Recordrecord | 30 | Usersusers | |||
| 40 | Batterybattery | 41 | Plugplug | 42 | Clockclock | |||
| 43 | Calendarcalendar | 44 | Cameracamera | 45 | Folderfolder | |||
| 46 | Savesave | 47 | Uploadupload | 48 | Downloaddownload | |||
| 49 | Editedit | 50 | Trashtrash | 51 | Lamp Offlamp_off | |||
| 52 | Lamp Onlamp_on | 53 | Lamp Dimlamp_dim | 54 | Switch Offswitch_off | |||
| 55 | Switch Onswitch_on | 56 | Selector Leftselector_left | 57 | Selector Centerselector_center | |||
| 58 | Selector Rightselector_right | 59 | Door Closeddoor_closed | 60 | Door Opendoor_open | |||
| 61 | Door Lockeddoor_locked | 62 | Garage Closedgarage_closed | 63 | Garage Opengarage_open | |||
| 64 | Window Closedwindow_closed | 65 | Window Openwindow_open | 66 | Blinds Closedblinds_closed | |||
| 67 | Blinds Halfblinds_half | 68 | Blinds Openblinds_open | 69 | Thermostat Heatthermostat_heat | |||
| 70 | Thermostat Coolthermostat_cool | 71 | Thermostat Autothermostat_auto | 72 | Thermostat Offthermostat_off | |||
| 73 | Motion Idlemotion_idle | 74 | Motion Detectedmotion_detected | 75 | Alarm Disarmedalarm_disarmed | |||
| 76 | Alarm Armedalarm_armed | 77 | Alarm Triggeredalarm_triggered | 78 | Water Drywater_dry | |||
| 79 | Water Leakwater_leak | 80 | Smoke Clearsmoke_clear | 81 | Smoke Alarmsmoke_alarm | |||
| 82 | Security Camera Onsecurity_camera_on | 83 | Security Camera Offsecurity_camera_off | 84 | Machine Stopmachine_stop | |||
| 85 | Machine Runmachine_run | 86 | Machine Faultmachine_fault | 87 | Machine Maintenancemachine_maintenance | |||
| 88 | Conveyor Stopconveyor_stop | 89 | Conveyor Runconveyor_run | 90 | Conveyor Reverseconveyor_reverse | |||
| 91 | Pump Offpump_off | 92 | Pump Onpump_on | 93 | Pump Faultpump_fault | |||
| 94 | Valve Closedvalve_closed | 95 | Valve Openvalve_open | 96 | Valve Halfvalve_half | |||
| 97 | Tank Emptytank_empty | 98 | Tank Quartertank_quarter | 99 | Tank Halftank_half | |||
| 100 | Tank Three Quartertank_three_quarter | 101 | Tank Fulltank_full | 102 | Motor Offmotor_off | |||
| 103 | Motor Forwardmotor_forward | 104 | Motor Reversemotor_reverse | 105 | Motor Faultmotor_fault | |||
| 106 | Traffic Redtraffic_red | 107 | Traffic Yellowtraffic_yellow | 108 | Traffic Greentraffic_green | |||
| 109 | Mode Automode_auto | 110 | Mode Manualmode_manual | 111 | Mode Offmode_off | |||
| 112 | Emergency Stopemergency_stop | 113 | Pressure Lowpressure_low | 114 | Pressure Normalpressure_normal | |||
| 115 | Pressure Highpressure_high | 116 | Level Lowlevel_low | 117 | Level Normallevel_normal | |||
| 118 | Level Highlevel_high | 119 | Temperature Coldtemperature_cold | 120 | Temperature Normaltemperature_normal | |||
| 121 | Temperature Hottemperature_hot |
Useful multistate icon groups
| Purpose | Icon numbers |
|---|---|
| Lamp | 51 Off, 52 On, 53 Dim |
| Switch | 54 Off, 55 On |
| Selector | 56 Left, 57 Center, 58 Right |
| Door | 59 Closed, 60 Open, 61 Locked |
| Garage | 62 Closed, 63 Open |
| Window | 64 Closed, 65 Open |
| Blinds | 66 Closed, 67 Half, 68 Open |
| Thermostat | 69 Heat, 70 Cool, 71 Auto, 72 Off |
| Motion | 73 Idle, 74 Detected |
| Alarm | 75 Disarmed, 76 Armed, 77 Triggered |
| Water | 78 Dry, 79 Leak |
| Smoke | 80 Clear, 81 Alarm |
| Security camera | 82 On, 83 Off |
| Machine | 84 Stop, 85 Run, 86 Fault, 87 Maintenance |
| Conveyor | 88 Stop, 89 Run, 90 Reverse |
| Pump | 91 Off, 92 On, 93 Fault |
| Valve | 94 Closed, 95 Open, 96 Half |
| Tank | 97 Empty, 98 Quarter, 99 Half, 100 Three Quarter, 101 Full |
| Motor | 102 Off, 103 Forward, 104 Reverse, 105 Fault |
| Traffic light | 106 Red, 107 Yellow, 108 Green |
| Mode | 109 Auto, 110 Manual, 111 Off |
| Emergency stop | 112 Emergency Stop |
| Pressure | 113 Low, 114 Normal, 115 High |
| Level | 116 Low, 117 Normal, 118 High |
| Temperature state | 119 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();| Orientation | Value | Logical screen |
|---|---|---|
| Portrait | 0 | 320 × 480 pixels |
| Landscape | 1 | 480 × 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 number | Use |
|---|---|
| 1 | Small: compact captions and dense information |
| 2 | Medium: standard labels and buttons |
| 3 | Large |
| 4 | Extra large |
| 5 | Huge |
| 6 | Tall 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.
| Color | RGB565 decimal |
|---|---|
| Black | 0 |
| White | 65535 |
| Red | 63488 |
| Green | 2016 |
| Blue | 31 |
| Yellow | 65504 |
| Cyan | 2047 |
| Magenta | 63519 |
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]| Field | Meaning |
|---|---|
| 1 | DMSG marker |
| 2 | Your numeric element ID |
| 3 | Element type from the table below |
| 4 | Activity/event code |
| 5 | Numeric value or state |
| 6 | Touch x position |
| 7 | Touch y position |
| 8 | Event text, up to 63 characters |
| Activity | Code | Typical use |
|---|---|---|
| Pressed | 1 | Start push-to-talk or a press action |
| Released | 2 | Stop push-to-talk |
| Clicked | 3 | Perform a single button action |
| Value changed | 4 | Slider/list/meter value update |
| Checked | 5 | On/checked |
| Unchecked | 6 | Off/unchecked |
| Focused | 7 | Textbox selected |
| Text changed | 8 | Edited text |
| Key pressed | 9 | Keyboard input |
| Keyboard done | 10 | User completed entry |
| Keyboard cancelled | 11 | User cancelled entry |
| Queue overflow | 12 | Drain pending events more promptly |
| Element type | Code |
|---|---|
| Button | 1 |
| Textbox | 2 |
| Password textbox | 3 |
| Label | 4 |
| Checkbox | 5 |
| BMP/icon | 6 |
| Slider | 7 |
| Keyboard | 8 |
| Listbox | 9 |
| Analog meter | 10 |
| Vertical bar | 11 |
| Lamp | 12 |
| Switch | 13 |
| Toggle/flip switch | 14 |
| Rounded button | 15 |
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.
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
nextPush-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
- Connect both devices to the same local network and find each device’s LAN IP.
- Use the same 32-character key and matching password settings on both devices.
- Start each device with p2pStart(). Each can use port 24000 because it has its own LAN IP.
- Set a different p2pSetCallerID() name on each device.
- On the calling device, dial the other device’s LAN IP and listening port.
- When the receiver shows incoming status 2, read caller ID and answer.
- 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.
| Status | Meaning | What your program should do |
|---|---|---|
| 0 | Idle | Allow dial or wait for a call. |
| 1 | Dialing | Show progress; cancel with p2pHangup(). |
| 2 | Incoming | Read caller information, then answer or reject. |
| 3 | In call | Run PTT or enable hands-free AEC once. |
| 4 | Busy | Show the result; allow another dial or hangup. |
| 5 | Unavailable | Check 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);
endifRead 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
endifRun 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 ↑
| Symptom | What to check |
|---|---|
| Unexpected character in a program | Check semicolons, matching block endings, function argument types, quotes, and whether a string function name ends in $. |
| String comparison behaves unexpectedly | Comparisons are case-sensitive. Verify spelling and capitalization. |
| FOR loop error | Use for i=0 to 10 do … next, following the examples in this guide. |
| Display event never arrives | Confirm the element is touchable/enabled/visible and that the program is polling getDisplayMessage$(). |
| BMP does not display | Confirm SD is mounted, use the complete path, and use a supported uncompressed 16/24-bit BMP format. |
| VOIP connects but there is no audio | Wait until voipIsConnected()==1 before calling voipStartListening(). |
| Network function fails | Check wifiIsConnected(), host/port values, credentials and network reachability. |
| MP3 fails to play | Check the SD path and inspect mp3LastResult() and mp3LastError$(). |
| Application becomes sluggish | Add a short wait() in polling loops so displays, audio, and networking remain responsive. |
| Unexpected = in a string assignment | Write let savedIP$=address$; use let for every string assignment. |
| Caller name is missing | Set p2pSetCallerID() before dialing and update both devices for long-name support. |
| Callback fails | Save both p2pCallerIP$() and p2pCallerPort(); verify matching credentials and reachable UDP forwarding. |
| Command returned 0 | Check that function’s Returns line. For several display and VOIP commands, 0 means success. |
| Touch fields seem wrong | Field 2 is the element ID; field 3 is element type; field 4 is activity; field 5 is value. |
| Slider starts at the wrong value | Use (…,min,max,value), for example (…,0,100,50). |
| Checkbox uses the wrong font/state | Use (…,caption$,checked,font). |
| Color change affects the wrong control | The first displaySetColors() argument is the element ID. |
| No incoming calls on cellular/hotspot | Dynamic DNS does not bypass carrier-grade NAT. A publicly reachable path, NAT traversal, or relay is needed. |
Quick Reference Top ↑
Look up a function’s exact argument order here, then consult its full entry for return values, ranges, and examples.
| Function | Purpose |
|---|---|
| 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.

