Pocket FORTH

Stack-based programming on iOS, macOS and embedded hardware

Pocket FORTH

Pocket FORTH is a compact FORTH environment for iPhone, iPad and Mac, with a remote terminal for compatible ESP8266 and ESP32 boards. Type commands directly, define and edit new words, inspect the stack, save programs as .4th files and move them between the app and embedded hardware over Wi-Fi.

✓ iOS & macOS
✓ ESP8266 & ESP32
✓ Remote terminal
✓ .4th & QR sharing

Think in stacks

Values go on the stack, words consume and produce values. 5 DUP * . prints the square of 5.

Build your language

Use colon definitions to create new words: : SQUARE DUP * ;. Small words combine into larger programs.

Documentation

Reference for the Pocket FORTH 2.0 feature set.

Introduction

FORTH is interactive and stack-based. You type words separated by spaces. Numbers are pushed on the stack; words operate on the stack.

2 3 + .        \ prints 5
5 DUP * .      \ prints 25
.S             \ inspect the stack
Truth values: Pocket FORTH follows the classic convention: TRUE is -1, FALSE is 0.

Stack and arithmetic

WordMeaningStack effect
+ - * /integer arithmetica b -- result
MODremaindera b -- rem
/MODremainder and quotienta b -- rem quot
1+ 1- 2+ 2- 2* 2/small integer shortcutsn -- n'
ABS NEGATE MIN MAXnumeric helpers...

Stack manipulation

WordStack effect
DUPa -- a a
DROPa --
SWAPa b -- b a
OVERa b -- a b a
ROTa b c -- b c a
NIPa b -- b
TUCKa b -- b a b
2DROP 2DUP 2OVER 2SWAPdouble-cell stack helpers
?DUPduplicate only if non-zero
DEPTH PICKstack depth and deep stack access

Definitions and comments

Create new words with : and ;. Comments use backslash to the end of the line or parenthesized comments.

: SQUARE DUP * ;
9 SQUARE .

\ comment to end of line
( stack comment )

RECURSE can be used inside a definition to call the current word. EXIT exits the current word early.

Variables, constants and memory

WordMeaning
VARIABLE namecreates a variable; executing it leaves its address
value CONSTANT namecreates a constant; executing it leaves its value
@fetch value from address
!store value to address
?print value stored at address
+!add to value stored at address
HERE ALLOT , CREATE CELLS CELL+basic dictionary/memory words
VARIABLE A
10 A !
A @ .
5 A +!
A ?

Control flow

Implemented control words include IF ELSE THEN, BEGIN AGAIN UNTIL, DO ?DO LOOP +LOOP, I, J, LEAVE and UNLOOP.

: SIGN
  DUP 0< IF ." NEGATIVE" CR EXIT THEN
  DUP 0= IF ." ZERO" CR EXIT THEN
  ." POSITIVE" CR
;

: COUNT10
  10 0 DO I . LOOP
;

Comparison and logic

Available words: = < > 0= 0< 0> 0<> <> TRUE FALSE AND OR XOR INVERT <= >=

Output and strings

WordMeaning
.print top stack value
.Rright-aligned numeric output: value width .R
." text"print literal text immediately
S" text" TYPEcompiled string/address+length, then output
EMITprint character code
CR SPACE SPACES BLformatting helpers
." HELLO" CR
65 EMIT CR
S" POCKET FORTH" TYPE CR

System commands

CommandDescription
WORDSlist the dictionary
.S or STACKshow stack contents
SEE wordshow a word definition
EDIT wordedit a colon definition
HELPquick help in the console
DIRlist saved programs
SAVE namesave current source as name.4th
INCLUDE nameload a saved .4th program
RUNexecute the loaded program
NEWreset the current session and clear source/output
PAGEclear console output
COPYWORD old newduplicate a user colon definition
FORGET wordremove a user word
FORGET *remove all user-defined words

Limits

ResourceLimit
Data stack128 cells
Return stack128 cells
Dictionary256 words
Input line512 characters
Source lines per colon definition64
Cell memory1024 cells
String space4096 bytes

Timing and compatibility

MS, MILLIS and MICROS are available in the local interpreter. The constants INPUT, OUTPUT, HIGH and LOW are also defined for compatibility with embedded programs.

Sharing and persistence

  • Save and export plain-text .4th files containing user colon definitions, constants, variables and CREATE data.
  • Import/export QR codes; larger programs can be split across multiple QR parts.
  • Run saved programs from Apple Shortcuts using the Run FORTH Program action.
  • On Mac, saved programs can also be launched through the pocketforth://run?program=Name URL scheme.

Remote Terminal

Use the Pocket FORTH app as a Wi-Fi console for a compatible ESP8266 or ESP32 board running the Pocket FORTH firmware.

Connection

Turn on the board, open Pocket FORTH and tap TERMINAL. The app joins the board access point and opens a TCP connection automatically.

SettingValue
Wi-Fi networkPOCKETFORTH
Address192.168.1.1
TCP port2323
Direct control: commands entered in remote mode are executed by the board, not by the local iOS interpreter.

Remote controls

ControlAction
CONSOLEreturn to the local interpreter
WORDSshow the remote dictionary
STACKshow the remote data stack
UPLOADreplace the board user program with the current local .4th program
DOWNLOADimport the board user program into the app
RESETrestart the board
HELPshow the firmware quick help

After a reset or a temporary Wi-Fi interruption, the app attempts to restore the remote session. Hardware output and available words depend on the selected board.

Embedded Firmware

Run Pocket FORTH directly on supported ESP8266 and ESP32 boards, using serial or the built-in Wi-Fi terminal.

Read before downloading: installing firmware changes the contents of the board flash memory. Make sure the selected image matches your hardware and read the firmware disclaimer below.

ESP8266 firmware

Precompiled Pocket FORTH binary for compatible ESP8266 boards.

Download ESP8266 .bin

ESP32 firmware

Precompiled Pocket FORTH binary for compatible ESP32 boards.

Download ESP32 .bin

Hardware words

WordStack effect / meaning
PINMODEpin mode --
DIGITAL!value pin --, write a digital output
DIGITAL@pin -- value, read a digital input
PWM!duty pin --, set PWM output
ANALOG@pin -- value, read an analog input where supported
MSmilliseconds --, delay execution
MILLIS MICROSreturn elapsed time since startup
: BLINK
  2 OUTPUT PINMODE
  5 0 DO
    LOW 2 DIGITAL!
    500 MS
    HIGH 2 DIGITAL!
    500 MS
  LOOP
;

Pin numbering, active-high or active-low behavior, analog capabilities and safe voltage levels vary by board. Check the documentation for your exact hardware before connecting anything.

Read the complete firmware disclaimer

Examples

Small programs you can type, save as .4th, export or convert to QR code from the app.

1
Square / Quadrato — first custom word
Defines SQUARE, duplicates the number and multiplies it.
FORTH Code
\ PROGRAMMA QUADRATO
: SQUARE DUP * ;
9 SQUARE .
2
Integer square root / Radice intera — Newton method
Pocket FORTH currently uses integers, so this version adapts the pseudocode to an integer Newton iteration and stops when the improvement is 1 or less.
FORTH Code
\ RADICE QUADRATA INTERA CON METODO DI NEWTON
\ funzione radice(N): m=N/2; ripeti m=(m+N/m)/2

VARIABLE N
VARIABLE M
VARIABLE D

: RADICE ( n -- m )
  DUP 2 < IF EXIT THEN
  N !
  N @ 2/ M !
  BEGIN
    N @ M @ / M @ - ABS D !
    M @ N @ M @ / + 2/ M !
    D @ 1 > 0=
  UNTIL
  M @
;

81 RADICE .
3
Fibonacci — variables, DO LOOP, stack operations
Small program for Fibonacci sequence, with ASSEGNA defined before MAIN for VARIABLEs settings.
FORTH Code
\ PROGRAMMA FIBONACCI
\ BLOCCO DEFINIZIONI
VARIABLE START ( INIZIO SEQUENZA )
VARIABLE END   ( FINE SEQUENZA )

: ASSEGNA
  10 END !
  0 START !
;

\ BLOCCO MAIN
: MAIN
  ASSEGNA
  0 1       \ PRIMI DUE NUMERI DELLA SEQUENZA
  END @ START @ DO
    OVER .
    TUCK +
  LOOP
  2DROP
;

MAIN

Disclaimer

Pocket FORTH is intended for learning, experimentation and hobby use. Software and firmware are provided “as is”, without warranties.

Firmware and hardware warning
Downloading, installing or using Pocket FORTH firmware is entirely at the user’s own risk.

The author makes no warranty, express or implied, regarding compatibility, fitness for a particular purpose, reliability or safety. The author shall not be held liable for any direct or indirect damage, including damage to microcontrollers, development boards, computers, connected electronics, peripherals, power supplies or other equipment; loss or corruption of data; interruption of service; financial loss; or personal injury arising from installation, connection, configuration or use of the firmware.

The user is solely responsible for selecting the correct binary, flashing method, board configuration, pin mapping, voltage level, power supply and any connected circuit. Incorrect firmware, wiring or electrical levels may permanently damage hardware or create unsafe conditions.

Pocket FORTH is not certified and must not be used in safety-critical, medical, automotive, industrial control, security, life-support or other mission-critical systems. By downloading or using a firmware image, the user acknowledges and accepts these conditions and assumes full responsibility for all consequences.

Privacy

Pocket FORTH programs are stored locally on your device unless you explicitly export or share them. QR and file sharing are user-initiated actions.

Email: support@pocketbasic.it