ANNEX32 WI-FI RDS
User Manual
Version beta
1.70.2
© ciccioCB
2024
COPYRIGHT
The Annex firmware, including the AnnexToolKit
and this manual, are Copyright 2017-2024 by Francesco Ceccarella
(ciccioCB).
The compiled object code (the .bin file) for
the Annex firmware is free software: you can use or redistribute it
as you please except for commercial purposes. It is not allowed to distribute or embed it into
products that are sold or for any other activity making or intended
to make a profit.
The compiled object code (the .exe file) for
the AnnexToolKit utility is free software: you can use or
redistribute it as you please except for commercial purposes.
It is not allowed to distribute or
embed it into products that are sold or for any other activity
making or intended to make a profit.
This program is distributed in the hope that
it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.
This manual is distributed under a Creative
Commons Attribution-NonCommercial-ShareAlike 3.0 France license
(CC BY-NC-SA 3.0)
The above copyright notice and this permission
notice shall be included in all copies or redistributions of the
Software in any form.
License and
credits
The base of the interpreter
comes from the original project "MiniBasic" by Malcom
Mclean.
Adafruit BNO055 Orientation
Sensor library is written by KTOWN is Copyright © Adafruit
Industries. It is released under MIT license.
TFT_eSPI display Library is
Copyright © 2017 Bodmer. It is released under FreeBSD
license.
Adafruit PWM Servo Driver
Library is Copyright © Adafruit. It is released under MIT
license.
Arduino Library for Dallas
Temperature ICs is Copyright © Miles Burton
<miles@mnetcs.com>. It is released under LGPL
license.
OneWire Library is Copyright
1999-2006 Dallas Semiconductor Corporation and Copyright © 2007,
Jim Studt.
Adafruit DHT Humidity &
Temperature Sensor Library is Copyright © Adafruit. It is released
under MIT license.
ESP8266 and ESP32 Oled Driver
for SSD1306 display is Copyright © 2016 by Daniel Eichhorn and
Copyright © 2016 by Fabrice Weinberg
NeoPixelBus library is
Copyright © Michael C. Miller. It is released under LGPL
license.
ESP AsyncTCP library is
Copyright © 2016 Hristo Gochkov. It is released under LGPL
license.
ESP AsyncWebServer library is
Copyright © 2016 Hristo Gochkov. It is released under LGPL
license.
IRremote library is Copyright ©
Sebastien Warin, Mark Szabo, Ken Shirriff, David Conran. It is
released under LGPL license.
uRTCLib is is Copyright © 2015
Naguissa (naguissa.com@gmail.com). It is released under LGPL
license.
BME280 library is written by
Limor Fried/Ladyada for Adafruit Industries. It is released under
BSD license,
APDS9960 library is written by
Shawn Hymel for Sparkfun Electronics. It is released under Beerware
license.
PID Library is written by Brett
Beauregard (br3ttb@gmail.com). It is released under MIT
license.
The Javascript Editor
EditArea is Copyright © 2008 Christophe Dolivet. It is
released under BSD license.
The M5Stack library is
copyright © 2017 by M5Stack. It is released under MIT
license.
The MPU9250 driver is part of
the M5Stack Library.
The VL53L0X driver is Copyright
© 2017 Pololu. It contains code © 2016
STMicroelectronics.
Some GUI objects come from the
library GUIslice Copyright © Calvin Hass that is released under MIT
license.
The MFRD522 library is written
by Miguel Balboa and is released as free and unencumbered software
released into the public domain.
Contributions
A very big thank you to Robin Baker
(Electroguard) for his great involvement in the project by
supporting all the tests on the real hardware (bought with his
money), and all the advices that allowed me to add a lot of
functionality, not to mention the Huge work he did while
documenting the project on the website.
Content :
Introduction: 33
Interpreter: 36
Branch labels.
36
Variables: 37
Arrays: 38
OPTION.BASE 1. 38
LBOUND(array() [, dimension]) :
Returns the lower bound of the specified array dimension.
39
UBOUND(array() [, dimension]) :
Returns the upper bound of the specified array dimension.
39
Scope of the variables: 40
Bases of the language.
41
OPERATORS AND PRECEDENCE..
41
Basic internal keywords: 43
IF command : 43
FOR loop.
44
WHILE WEND loop.
45
DO LOOP loop.
46
SELECT CASE..
47
GOTO..
48
GOSUB..
48
DATA..
49
END..
50
EXIT.
50
SUB..
50
Logical / boolean Operations.
52
ERRORS HANDLING..
53
ONERROR ABORT.
54
ONERROR IGNORE.
54
ONERROR SKIP [nn].
54
ONERROR CLEAR.
54
ONERROR GOTO [label |
OFF].
54
BAS.ERRLINE.
54
BAS.ERRNUM.
54
BAS.ERRMSG$.
54
HOW the interpreter works with the HTML
code and Objects : 55
HTML Objects.
59
TIMERS..
64
EVENTS..
64
Button Event 65
OnHtmlChange Event 65
OnHtmlReloadEvent 65
OnInfrared Event 66
OnSerial Event 66
OnSerial2 Event 66
OnTouch Event 67
OnUDP Event 67
OnWgetAsync Event 67
OnUrlMessage Event 68
OnEspNowMsg Event 71
OnEspNowError Event 72
OnMQTT Event 72
OnPlay Event 72
WiFI CONNECTIONS..
72
PROGRAM AUTORUN..
74
RECOVERY MODE..
75
SLEEP mode (low energy) and RTC
memory.
75
DATE - TIME timekeeper 76
Unix Time functions.
77
FAT32 File System..
77
FILE.COPY(filename$,
newfile$).
79
FILE.DELETE(filename$).
79
FILE.EXISTS(filename$).
79
FILE.RENAME(oldname$,
newname$).
79
FILE.SIZE(filename$).
79
FILE.MKDIR(dirname$).
79
FILE.RMDIR(dirname$).
79
FILE.DIR$(path$).
79
FILE.READ$(filename$, [line_num] | [start,
length]).
79
FILE.APPEND filename$,
content$.
79
FILE.SAVE filename$,
content$.
80
FILE.WRITE filename$,
content$.
80
FILE.FROMBASE64 source$,
dest$.
80
FILE.TOBASE64 source$,
dest$.
80
FILE.SAVE_IOBUFF.
80
FILE.WRITE_IOBUFF.
80
FILE.APPEND_IOBUFF.
80
FILE.READ_IOBUFF.
80
Download files from another module or WEB
server 81
FILE.DOWNLOAD url$,
file_path$.
81
Notes: 81
I/O BUFFERS..
82
Define the Size of an I/O Buffer
82
IOBUFF.DIM(buff_num,
size).
82
Fill a Buffer with Predefined
Data.
82
IOBUFF.DIM(buff_num, size) =
data_list.
82
Release a Buffer 83
IOBUFF.DESTROY(buff_num,
size).
83
Get the Size of a Buffer 83
IOBUFF.LEN(buff_num).
83
Read Data from a Buffer 84
IOBUFF.READ(buff_num,
position).
84
Write Data to a Buffer 84
IOBUFF.WRITE(buff_num, position,
value).
84
Read Operations.
85
Write Operations.
86
Special operations.
87
Advanced operations.
87
IOBUFF.FROMSTRING(buff_num, var$ [,
pos]).
87
IOBUFF.TOSTRING$(buff_num, [, start [,
size]]).
88
IOBUFF.FROMHEX(buff_num, var$ [,
pos]).
89
IOBUFF.TOHEX$(buff_num, [, start [,
size]]).
89
Base64 conversion.
90
IOBUFF.TOBASE64(buff_num).
90
IOBUFF.FROMBASE64(buff_num,
Base64String$).
91
Cryptography.
91
IOBUFF.ENCRYPT(buff_num,
key$).
91
IOBUFF.DECRYPT(buff_num,
key$).
92
CRC Function: 92
IOBUFF.CRC(buff_num, nb_bits, polynom,
initial_value, ref_in, ref_out, xor_out).
92
Bit Operations on Buffer Data.
96
IObuff.bit(buff_num, position,
bit).
96
IObuff.setbit(buff_num, position,
bit).
96
IObuff.clearbit(buff_num, position,
bit).
97
IObuff.togglebit(buff_num, position,
bit).
97
Buffer copy.
98
IObuff.copy(dest_buff_num [,pos]) ,
(source_buff_num, [, start [, size]]).
98
Code examples : 99
WIRING..
101
DIGITAL I/O..
102
PIN.STRENGTH 15, 2.
103
PIN SERIAL SHIFTING..
103
PIN.SHIFTOUT pin_data, pin_clk, data [,
bit_order] [, nb_bits] [, delay_us].
104
PIN.SHIFTIN( pin_data, pin_clk [, bit_order]
[, nb_bits] [, delay_us] ).
105
PIN INTERRUPTS..
106
Analog inputs.
107
TOUCH inputs.
107
Analog outputs.
108
Hardware interfaces: 108
PWM..
108
PWM.SETUP pin, channel, default_value,
[,frequency] [,resolution].
109
PWM.OUT channel,
value.
109
SERVO..
110
I2S BUS..
111
SPEAKER OUTPUT.
113
I2C BUS..
114
PCF8574 Module.
115
ADS1115 Module.
116
MCP23017 Module.
119
SPI BUS..
120
74HC595 Module.
123
MCP23S17 Module.
124
CAN BUS..
126
CAN.SETUP..
127
CAN.INIT.
128
CAN.STOP..
128
CAN.WRITE..
128
CAN.WRITE_IOBUFF.
129
ONCANBUS..
129
CANBUS BUFFERS..
131
RMT Module.
133
Key Features.
133
Memory Management and Synchronisation
of RMT Channels.
134
Clock Divider.
134
RMT RAM Composition.
135
Memory Block Extension.
136
RMT Transmit
Synchronisation.
137
TX Transmitter Mode.
137
RX Reception Mode.
138
RX Reception Event 138
RMT Command Functions.
138
RMT.SETUP_TX channel, pin [, clk_div] [,
mem_block_num] [, idle_level] [, loop_en] [, carrier_en] [,
carrier_freq_hz] [, carrier_duty_percent] [,
carrier_level].
138
RMT.WRITE channel, num_items, name [,
wait].
139
RMT.ENCODE channel, num_items, array() [,
wait].
139
RMT.SETUP_RX channel, pin [, clk_div] [,
mem_block_num] [, invert] [, filter_en] [, filter_ticks_thresh] [,
idle_threshold] [, rm_carrier] [, carrier_freq_hz] [,
carrier_duty_percent] [, carrier_level].
139
RMT.READ array().
140
RMT.DECODE array().
140
RMT.ADD_GROUP channel.
140
RMT.DEL_GROUP channel.
140
RMT.END channel.
141
Synchronisation in
Groups.
141
Example 1: RMT Transmission of a Pulse
Sequence.
141
Example 2: RMT Transmission of a
Sinusoidal Pattern.
143
Example 3: Synchronized RMT
Transmission of Sinusoidal Patterns.
145
Example 4: Infrared Signal Reception
and Decoding with RMT on ESP32.
147
COUNTERS..
149
PID controllers.
150
SOUND PLAYER..
152
Metadata Decoding from Mp3 and
streaming.
154
SPEECH SYNTHESIS with vintage C64 SAM
speaker 155
SPEECH SYNTHESIS using google
translate.
156
SPEECH SYNTHESIS using voiceRSS free
service.
157
VS1053B Audio Decoder 158
VS1053.SETUP XCS_pin, XDCS_pin, DREQ_pin
[,info_enabled] [,SPIfreq] [SCI_CLOCKF].
160
VS1053.PLAY file$.
160
VS1053.STREAM
streaming_url$.
161
VS1053.VOICE "message",
"language".
161
VS1053.STOP.
161
VS1053.VOLUME vol.
161
VS1053.RESET.
161
VS1053.INIT patchFile$.
162
VS1053.INIT
"/patches/vs1053b-patches-flac.cmd".
162
VS1053.WRITE register,
value.
162
VS1053.READ register.
162
VS1053.MIDI_CMD cmd, data1,
data2.
162
VS1053.NOTE_ON channel, note,
velocity.
162
VS1053.NOTE_OFF channel, note,
velocity.
162
LCD DISPLAY USING I2C..
162
OLED DISPLAY..
167
ST7920 LCD DISPLAY..
169
RTC module.
171
PCA9685 (PWM / Servo) Module.
173
TM1637 display module.
174
TM1638 display module.
176
MAX7219 8-Digits 7-segment
display.
178
MAX7219 Dot Matrix Display.
179
NeoPixel WS2812B led strips.
181
NEO.SETUP pin,
[nb_led].
183
NEO.STRIP led_start_pos, led_end_pos, R, G,
B [, disable].
183
NEO.STRIP led_start_pos, led_end_pos, COLOR
[, disable].
183
NEO.PIXEL led_pos, R, G, B [,
disable].
183
NEO.PIXEL led_pos, COLOR [,
disable].
183
NEO.RGB(R, G, B).
183
NEO.GETPIXEL(led_pos).
183
NEO.ROTATELEFT num_steps, [led_end_pos,
led_end_pos, disable].
183
NEO.ROTATERIGHT num_steps, [led_end_pos,
led_end_pos, disable].
183
NEO.SHIFTLEFT num_steps, [led_end_pos,
led_end_pos, disable].
183
NEO.SHIFTRIGHT num_steps, [led_end_pos,
led_end_pos, disable].
184
NEO.REFRESH.
184
NEO.DIM(COLOR , Gain).
184
NEO.LIGHTEN(COLOR ,
Gain).
184
NEO.DARKEN(COLOR ,
Gain).
184
NEO.LINEARBLEND(COLOR1, COLOR2,
progress).
184
NEO.BILINEARBLEND(.
184
Upper_Left_COLOR, Upper_Right_COLOR,
Lower_Left_COLOR, Lower_Right_COLOR, x, y).
184
NeoPixel based WS2812b Dot Matrix
DIsplay.
185
NEOSCROLL.SETUP nb_devices, nb_lines, pin
[,layout] [,width, height, orientation].
189
NEOSCROLL.DELETE.
189
NEOSCROLL.FILL color, [x, y, width,
height].
189
NEOSCROLL.TEXT.POS x,
y.
189
NEOSCROLL.TEXT.FONT
font.
189
NEOSCROLL.SHOW x, y.
189
NEOSCROLL.TEXT.BRIGHTNESS
brightness.
189
NEOSCROLL.BRIGHTNESS
brightness.
189
NEOSCROLL.PRINT text$,
color$.
190
NEOSCROLL.SPRITESHEET
image$.
190
NEOSCROLL.SPRITE x, y, width, height,
x_in_bmp, y_in_bmp.
191
Copy a portion of the SPRITESHEET image into the canvas
using the parameters given.
191
NEOSCROLL.LIMITS [x1,] [x2], [y1],
[y2].
191
NEOSCROLL.SYNC.
191
NEOSCROLL.MODE mode.
191
NEOSCROLL.SCROLL.
191
NEOSCROLL.SCROLL.
191
Scroll the image using the current
MODE and within
the current LIMITS.c.
191
NEOSCROLL.OSCILLATE.
191
NEOSCROLL.OSCILLATE.
191
Oscillate the image using the current
MODE and within
the current LIMITS.c.
191
NEOSCROLL.X.
191
NEOSCROLL.Y.
191
HUB75 Matrix Displays -
DMAMATRIX..
195
DMAMATRIX.INIT R1, G1, B1, R2, G2, B2, A, B,
C, D, E, LAT, OE, CLK [,freq_DMA]
[,resolution].
196
DMAMATRIX.SETUP nb_devices, nb_lines
[,layout] [,width, height, orientation].
196
DMAMATRIX.DELETE.
196
DMAMATRIX.FILL color, [x, y, width,
height].
196
DMAMATRIX.TEXT.POS x,
y.
196
DMAMATRIX.TEXT.FONT
font.
197
DMAMATRIX.TEXT.COLOR
color.
197
DMAMATRIX.SHOW [x, y].
197
DMAMATRIX.TEXT.BRIGHTNESS
brightness.
197
DMAMATRIX.BRIGHTNESS
brightness.
197
DMAMATRIX.PRINT text$ [, color$ |
color].
198
DMAMATRIX.SPRITESHEET
image$.
198
DMAMATRIX.SPRITE x, y, width, height,
x_in_bmp, y_in_bmp.
199
Copy a portion of the SPRITESHEET image into the canvas
using the parameters given.
199
DMAMATRIX.LIMITS [x1,] [x2], [y1],
[y2].
199
DMAMATRIX.SYNC.
199
DMAMATRIX.MODE mode.
199
DMAMATRIX.SCROLL.
199
DMAMATRIX.SCROLL.
199
Scroll the image using the current
MODE and within
the current LIMITS.c.
199
DMAMATRIX.OSCILLATE.
199
DMAMATRIX.OSCILLATE.
199
Oscillate the image using the current
MODE and within
the current LIMITS.c.
199
DMAMATRIX.PIXEL x, y,
color.
199
DMAMATRIX.LINE x1, y1, x2, y1,
color.
199
DMAMATRIX.CIRCLE x, y, radius, color
[,fill].
199
DMAMATRIX.RECT x, y, w, h, color
[,fill].
199
DMAMATRIX.X.
199
DMAMATRIX.Y.
200
DMAMATRIX.POSX.
200
DMAMATRIX.POSY.
200
DMAMATRIX.PLAYGIF gif$ [,x ,
y].
200
DMAMATRIX.LOADGIF gif$ [,x ,
y].
200
DMAMATRIX.FRAMEGIF [do_not_show
[,loop]].
200
SD CARD ADAPTER..
200
TFT DISPLAY ILI9341.
202
TFT DISPLAY ILI9163.
206
TFT DISPLAY ILI9486.
207
TFT DISPLAY ILI9481.
210
TFT DISPLAY ILI9488.
211
TFT DISPLAY ST7735.
212
TFT DISPLAY ST7796.
213
TFT DISPLAY ST7789.
216
OLED DISPLAY SSD1351 RGB..
217
TFT DISPLAY GC9A01.
218
TouchScreen - Resistive.
218
TouchScreen - Capacitive.
219
TFT FONTS..
220
QR CODES..
224
GRAPHIC GUI for TFT.
224
GUI Objects.
225
gui.TextLine.
225
gui.Button.
225
gui.Image.
226
gui.ButtonImage.
226
gui.CheckBox.
227
gui.Slider.
228
gui.ProgressBar.
228
gui.Ramp.
228
gui.Gauge.
229
gui.Box.
229
gui.Circle.
230
gui.Rect 230
gui.Line.
231
GUI Functions.
231
gui.GetValue.
231
gui.Target 231
GUI Commands.
231
gui.INIT..
231
gui.REDRAW...
232
gui.REFRESH..
232
gui.AUTOREFRESH..
232
gui.SETVALUE..
232
gui.SETTEXT..
232
gui.SETIMAGE..
232
gui.SETCOLOR..
232
gui.SETRANGE..
233
gui.SETEVENT..
233
gui.SETSTYLE..
234
LCD RGB DISPLAY INTERFACE (module
ESP32-8048S070C) 235
VGA.PINOUT R0, R1, R2, R3, R4, G0, G1, G2,
G3, G4, G5, B0, B1, B2, B3, B4, HSYNC, VSYNC, DE,
pCLK.
235
VGA DISPLAY INTERFACE..
235
VGA.PINOUT R0, R1, R2, G0, G1, G2, B0, B1,
HSYNC, VSYNC.
238
VGA.PINOUT R0, R1, R2, R3, R4, G0, G1, G2,
G3, G4, G5, B0, B1, B2, B3, B4, HSYNC, VSYNC, DE,
pCLK.
238
VGA.SETUP hFront,hSync, hBack, hRes, vFront,
vSync, vBack, vRes, frequency [,vClones=1] [,nb_pages=1]
[,outSize=1] [,aligned].
238
VGA.INIT mode
[,nb_pages=1].
238
VGA.DELETE.
238
VGA.STOP.
238
VGA.START.
238
VGA.SHOW.
238
VGA.SHOWPAGE page.
239
VGA.WRITEPAGE page.
239
VGA.SAVE file$.
239
VGA.FILL color.
239
VGA.COPY src, dest [x, y, w, h [dest_x,
dest_y].
239
VGA.PIXEL x, y, color.
239
VGA.LINE x1, y1, x2, y2, color
[,thickness=1].
239
VGA.CIRCLE x, y, radius, color
[,fill].
239
VGA.RECT x, y, w, h, color
[,fill].
239
VGA.TRIANGLE x1, y1, x2, y2, x3, y3, color
[,fill=1].
239
VGA.NEEDLE x, y, length, angle, color
[,thickness=1].
239
VGA.NEXT x, y, length, angle, color
[,thickness=1].
239
VGA.TEXT.POS x, y.
239
VGA.TEXT.FONT font.
240
VGA.TEXT.COLOR color
[,background].
240
VGA.TEXT.SIZE size.
240
VGA.PRINT var
[var$].
240
VGA.TEXT.ALIGN align.
240
VGA.TEXT.PADDING width.
240
VGA.TEXT.DRAW "text", x, y
[,font].
240
VGA.IMAGE file$ [, x,
y].
240
VGA.SPRITESHEET
image$.
241
VGA.SPRITE x, y, width, height, x_in_bmp,
y_in_bmp.
241
VGA.SETSPRITE id, width, height, x_in_bmp,
y_in_bmp [, nextframe_delta_x,
nextframe_delta_y].
241
VGA.DRAWSPRITE id, x, y,
[frame=0].
241
VGA.REMOVESPRITE id, src,
dest.
241
VGA.HIDESPRITE id,
visibility.
241
VGA GUI (experimental) 241
VGAGUI.SETSPRITE x_in_bmp, y_in_bmp, width, height,
nextframe_delta_x, nextframe_delta_y.
243
VGAGUI.SPRITE(x, y, width, height, frame_on,
frame_off, [,toggle=0] [,group]).
243
VGAGUI.ARC(x, y, width, height, value
[,thickness=10]).
244
VGAGUI.TEXTAREA(x, y, width, height, "text",
[,font] [,alignment] [,color_text] [,color_back] [,color_frame]
[,margin] ).
245
VGAGUI.IGNORE obj.
245
VGAGUI.GETTEXT obj,
var$.
246
VGAGUI.SETVALUE obj,
value.
246
VGAGUI.SETTEXT obj,
text$.
246
VGAGUI.SETCOLOR object, col1 [,col2 [,col3
[,col4]]].
246
VGAGUI.SETSTYLE object, prop1 [,prop2
[,prop3 [,prop4]]].
247
USB HID INTERFACE (Mouse, Keyboard,
Gamepad) - ESP32-S3 only.
248
How use the USB devices.
249
INFRARED INTERFACE..
251
ULTRASONIC DISTANCE SENSOR
HC-SR04.
255
DHT xx Temperature / Humidity
Sensors.
256
DS18B20 Temperature Sensors.
257
TEMPR$(pin_number, [ID],
[resolution]).
258
BNO055 Absolute Orientation Sensor
259
BME280 Combined humidity and pressure
sensor 261
BME680 Combined gas, pressure,
temperature & humidity sensor 263
FUNCTIONS / COMMANDS..
265
BME680.BEGIN(address).
266
BME680.SETUP(rate,
filename).
266
BME680.SAVE_STATE(filename).
266
BME680.LOAD_STATE(filename).
266
BME680.SET_OFFSET(offset).
266
BME680.RUN.
266
BME680.TEMP.
266
BME680.RAW_TEMP.
266
BME680.HUM.
266
BME680.RAW_HUM.
266
BME680.PRESS.
266
BME680.IAQ.
267
BME680.STATIC_IAQ.
267
BME680.IAQ_ACCURACY.
267
BME680.CO2.
267
BME680.BREATH_VOC.
267
BME680.GAS.
267
BME680.GAS_RES.
267
BME680.BME_STATUS.
267
BME680.BSEC_STATUS.
267
BME680.STAB_STATUS.
267
BME680.RUN_STATUS.
267
HDC1080 High Accuracy Digital Humidity
Sensor with Temperature Sensor 268
CCS811 Air Quality Sensor 269
APDS9960 Digital Proximity, Ambient
Light, RGB and Gesture Sensor 272
RFID MFRC522 RFID cards reader
275
Writing NUID for UID changeable card (4 byte UID version)
279
VL53L0X TOF (Time Of Flight) Distance
Sensor 279
HX711 - Weight Measurement
Module.
281
SI5351 Clock Generator Module.
283
SI5351.INIT [capacitor
[,crystal]].
285
SI5351.CALIB
correction.
285
SI5351.SETFREQ out_nb,
frequency.
285
SI5351.SETFREQ_MAN out_nb, frequency,
pll.
285
SI5351.STRENGTH out_nb,
strength.
285
SI5351.PHASE out_nb,
phase.
285
SI5351.RESET_PLL
pll_nb.
285
SI5351.ENABLE out_nb,
enable.
285
SI5351.INVERT out_nb,
invert.
285
SI5351.LOAD filename$.
286
STEP MOTOR..
286
STEPPER.SETUP stepper_id, pin_step,
pin_dir.
288
STEPPER.SETPARAM stepper_id, speed,
acceleration.
288
STEPPER.SETPOSITION stepper_id,
position.
288
STEPPER.MOVE stepper_id,
position.
288
STEPPER.MOVETO stepper_id,
position.
288
STEPPER.STOP
stepper_id.
288
STEPPER.FORCESTOP
stepper_id.
288
STEPPER.RUNFWD
stepper_id.
288
STEPPER.RUNBKD
stepper_id.
288
STEPPER.GETPOSITION(stepper_id).
289
STEPPER.GETTARGET(stepper_id).
289
MPU9250.
289
MPU6500 / MPU6050.
291
MPU6886 (For M5 Atom) 293
IMU FUSION FUNCTIONS..
295
ETHERNET Module W5500.
297
FTP..
301
BAS.FTP$.
301
Server data requests (GET, POST and
PUT) 302
-
WGET$(server$, port, [,header]
[,content_type$]).
303
-
WGET$(url$ [,header]
[,content_type$]).
303
-
WPOST$(server$, body$, port
[,header] [,content_type$] ).
303
-
WPOST$(url$, body$ [,header]
[,content_type$]).
303
-
WPUT$(server$, body$, port
[,header] [,content_type$] ).
303
-
WPUT$(url$, body$ [,header]
[,content_type$]).
303
-
WGETASYNC[(] server$, port,
[,header] [)].
303
-
WGETASYNC[(] url$,[,header]
[)].
303
MQTT Client 305
MQTT.Setup(server$
[,debug]).
307
MQTT.Certif(cert_pem$ [,client_cert_pem$]
[,client_key_pem$]).
307
MQTT.PSK(psk_hint_key$).
307
MQTT.LWT(topic$, message$ [,Qos]
[,retain]).
307
MQTT.Connect(login$, pass$
[,id$]).
307
MQTT.Connect("", ""
[,id$]).
307
MQTT.Disconnect[()].
307
MQTT.Publish(topic$, message$ [,Qos]
[,retain]).
307
MQTT.Subscribe(topic$
[,Qos]).
307
MQTT.UnSubscribe(topic$).
307
MQTT.Connected[()].
307
MQTT.Status[()].
308
MQTT Broker 310
MqttBroker.Setup(port, login$, password$ [,
debug]).
311
MqttBroker.Start(ramsize).
311
MqttBroker.Stop.
312
MqttBroker.Restart.
312
MqttBroker.Publish(topic, payload[, qos[,
retain]]).
312
MqttBroker.Subscribe(topic$).
312
MqttBroker.UnSubscribe(topic$).
313
MqttBroker.ListTopics[(list$)].
313
MqttBroker.ClearTopics.
314
MqttBroker.ListClients[(list$)].
314
OnMQTT Event Handler 314
OnMQTT label.
314
Event Information Variables.
315
Special Event Topics.
315
Disabling ONMQTT.
315
ESP-NOW...
318
EspNow.Begin.
319
EspNow.Stop.
319
EspNow.Add_Peer(MAC_add$ [,interface]
[,channel]).
319
EspNow.Del_Peer.
319
EspNow.Write(msg$).
319
EspNow.Write(msg$,
MAC_add$).
319
EspNow.READ$.
319
ESPNow.REMOTE$.
319
ESPNow.ERROR$.
319
OnEspNowMsg label.
320
OnEspNowError label.
320
BLUETOOTH Low Energy (BLE) 328
Overview..
328
Operating Modes.
328
Server Mode.
329
Communication Details.
329
BLE Commands / Functions.
329
BLUETOOTH.SETUP "devicename" [,
code].
329
BLUETOOTH.CLEAR.
330
BLUETOOTH.DELETE.
330
BLUETOOTH.POWER pow.
330
BLUETOOTH.WRITE
"text".
330
BLUETOOTH.READ$.
330
BLUETOOTH.LEN.
330
BLUETOOTH.CONNECTED.
330
BLUETOOTH.STATUS.
330
BLUETOOTH.WRITE_IOBUFF(buff_num [, start [,
size]]).
330
BLUETOOTH.READ_IOBUFF(buff_num).
330
BLUETOOTH.SCAN time.
330
BLUETOOTH.SCANRESULT$.
330
Client Mode Functions.
331
BLUETOOTH.CLIENT mac, service_UUID,
characteristic_UUID.
331
BLUETOOTH.CLWRITE characteristic_UUID,
"text".
331
BLUETOOTH.CLWRITE_IOBUFF
characteristic_UUID, (buff_num [, start [,
size]]).
331
Event Handling.
331
ONBLUETOOTH label.
331
TELEGRAM (messenger) support 335
LORA..
337
LoRa.Setup ss, reset,
dio0.
340
LoRa.Begin(freq).
340
LoRa.End.
340
LoRa.BeginPacket.
340
LoRa.Print.
340
LoRa.EndPacket.
340
LoRa.Receive.
340
LoRa.RSSI.
340
LoRa.SNR.
340
LoRa.Idle.
340
LoRa.Sleep.
340
LoRa.TXpower pow.
340
LoRa.SyncWord word.
341
LoRa.EnableCRC enable.
341
OnLora.
341
LoRa.Message$.
341
Modbus.
343
MODBUS.CONNECT IP$, [port] [,timeout]
[,idleTimeout].
343
MODBUS.DISCONNECT.
344
MODBUS.REQUEST token, serverID, functionCode [,p1] [,p2]
[,p3].
344
Modbus RTU Support 347
MODBUS.SetupRTU RX_pin, TX_pin, RE_DE_pin,
["BBBB,P,D,S"].
347
MODBUS.requestRTU ….. (see the
details in the chapter above) 347
MODBUS RTU wiring.
349
Regular Expressions (RegEx) 350
Patterns.
351
Magic characters.
351
Repetition.
352
Anchor to start and/or end of
string.
353
Captures.
353
Frontier patterns.
354
Multiple matches.
354
M5 Tough.
355
M5Tough.BatLevel.
357
M5Tough.BatVoltage.
357
M5Tough.BatCurrent.
357
M5Tough.VinVoltage.
357
M5Tough.VinCurrent.
357
M5Tough.VBusVoltage.
357
M5Tough.VBusCurrent.
357
M5Tough.BatChgCurrent.
357
M5Tough.BatPower.
357
M5Tough.AxpTemp.
357
M5Tough.ApsVoltage.
357
M5Tough.AxpState.
357
M5Tough.TftPower
power.
357
M5Tough.SpeakerPower
power.
357
M5Tough.SetBusPowerMode
mode.
358
M5Tough.PowerOff sec.
358
M5Tough.LightSleep
sec.
358
M5Tough.DeepSleep sec.
358
ANNEXCAM..
358
Functionalities enabled in the ANNEXCAM
version.
361
Camera Functions / commands.
362
Using AnnexCam in output page.
365
Control of the camera using
URL.
366
Face Recognition.
367
Image / video reception from
Annex.
368
ANNEXEPAPER for LILYGO T5 4.7” E-paper
module.
370
.........................................................................................................................................
371
GRAPHIC GUI for E-PAPER..
373
Functionalities enabled in the E-PAPER
version.
380
PEEK and POKE FUNCTIONS..
382
BAS.PEEK(addr).
382
BAS.PEEK16(addr).
382
BAS.PEEK8(addr).
382
BAS.POKE addr, data.
382
BAS.POKE16 addr, data.
382
BAS.POKE8 addr, data.
382
CONVERSION FUNCTIONS..
383
CONVERT.DEGC_TO_F(degC).
384
CONVERT.F_TO_DEGC(degF).
384
CONVERT.TO_IEEE754(num).
384
CONVERT.FROM_IEEE754(iee754_bin).
384
CONVERT.MAP(number, fromLow, fromHigh,
toLow, toHigh).
384
CONVERT.TO_BCD(number).
384
CONVERT.FROM_BCD(number).
384
CONVERT.LIMITS(number, min,
max).
384
BAS CONSTANTS..
384
BAS.VER.
385
BAS.VER$.
385
BAS.ERRLINE.
385
BAS.ERRNUM.
385
BAS.ERRMSG$.
385
BAS.FILENAME$.
385
BAS.RTCMEM$.
385
BAS.SSID$.
385
BAS.PASSWORD$.
385
BAS.LOAD.
385
BAS.RESETREASON.
386
BAS.WAKEUPREASON.
387
BAS.DEVICE.
388
BAS.TFT.
389
OPTION COMMANDS..
389
OPTION.BASE 0 | 1.
390
OPTION.CPUFREQ
80|160|240.
390
OPTION.ES8388.
390
OPTION.MAC mac$.
390
OPTION.LOWRAM value.
390
OPTION.NTPSYNC.
390
OPTION.WDT time.
390
OPTION.WDTRESET.
390
OPTION.WLOG value.
390
OPTION.TOUCH value.
391
OPTION.I2S BCLK_pin, WSEL_pin,
DOUT_pin.
391
OPTION.PSRAM limit.
391
HALL Sensor (Internal): 391
BAS.HALL.
391
FUNCTIONS: 391
NUMERICAL FUNCTIONS..
391
ABS(number) 392
ACOS(number) 392
ADC(pin) 392
APDS9960.SETUP (mode) 392
APDS9960.READGESTURE..
392
APDS9960.AMBIENT.
392
APDS9960.RED..
392
APDS9960.GREEN..
392
APDS9960.BLUE..
393
APDS9960.PROXIMITY..
393
APDS9960.GESTUREGAIN (gain) 393
APDS9960.GESTURELED (intensity)
393
ASC(string$) 393
ASIN(number) 393
ATAN(number) 393
ATAN2(x, y) 393
BAS.VER..
393
BAS.ERRLINE..
394
BAS.ERRNUM..
394
BME280.SETUP(address) 394
BME280.ALT(qnh) 394
BME280.HUM..
394
BME280.QFE..
394
BME280.QNH(altitude) 394
BME280.TEMP..
394
BNO055.SETUP( address) 394
BNO055.HEADING..
394
BNO055.PITCH..
394
BNO055.ROLL.
394
BNO055.VECTOR ( param, axis) 395
BNO055.CALIB [(param)] 395
CINT(number) 396
CONVERT.DEGC_TO_F(degC) 396
CONVERT.F_TO_DEGC(degF) 396
CONVERT.TO_IEEE754(num) 396
CONVERT.FROM_IEEE754(ieee754_bin)
396
CONVERT.MAP(number, fromLow, fromHigh,
toLow, toHigh) 396
CONVERT.TO_BCD(number) 396
CONVERT.FROM_BCD(number) 396
COS(number) 396
COUNTER.COUNT (cnt) 396
COUNTER.PERIOD (cnt) 396
DATEUNIX(date$) 396
DHT.TEMP..
397
DHT.HUM..
397
DHT.HEATINDEX..
397
DISTANCE(pin_trig, pin_echo) 397
EMAIL from$, to$, subject$,
message$.
397
ESPNOW.ADD_PEER(MAC_add$ [,interface]
[,channel]) 397
ESPNOW.BEGIN..
397
ESPNOW.DEL_PEER(MAC_add$) 397
ESPNOW.STOP..
397
ESPNOW.WRITE( msg$) 397
ESPNOW.WRITE( msg$,MAC_add$) 397
EXP(number) 397
FIX(number) 398
FILE.DELETE(filename$) 398
FILE.EXISTS(filename$) 398
FILE.SIZE(filename$) 398
FLASHFREE..
398
FUSION.ANGLE(axis) 398
INSTR([start], string$, pattern$)
398
I2C.LEN..
398
I2C.READ..
398
I2C.READREGBYTE (i2c_address, register)
399
I2C.END..
399
INT(number) 399
LEN(string$) 399
LOG(number) 399
MILLIS..
399
MQTT.Setup(server$ [,debug]) 399
MQTT.Certif(cert_pem$ [,client_cert_pem$]
[,client_key_pem$]) 400
MQTT.PSK(psk_hint_key$) 400
MQTT.LWT(topic$, message$ [,Qos,
[,retain]) 400
MQTT.Connect(login$, pass$ [,id$])
400
MQTT.Connect("", "" [,id$]) 400
MQTT.Disconnect[()] 400
MQTT.Publish(topic$, message$ [,Qos]
[,retain]) 400
MQTT.Subscribe(topic$ [,Qos])
400
MQTT.UnSubscribe(topic$) 400
MQTT.Connected[()] 400
MQTT.Status[()] 400
NEO.GETPIXEL(pos) 401
NEO.RGB(R, G, B) 401
PI 401
PID1.COMPUTE( current_value,
target_value) 401
PIN(pin_number) 401
PIN.TOUCH(pin_number) 401
PING(host$) 401
POW(x, y) 401
RAMFREE..
401
RFID.SETUP(CS_pin, RST_pin) 402
RFID.SETGAIN(gain) 402
RFID.SETKEY(key$) 402
RFID.RESET.
402
RFID.AWAKE..
402
RFID.SETNUID(NUID$) 402
RFID.WRITE(block, data$) 403
RND(number) 403
SERIAL.LEN..
403
SERIAL2.LEN..
403
SGN(number) 403
SIN(number) 403
SPI.BYTE(byte) 403
SQR(number) 403
TAN(number) 403
TFT.RGB(r,g,b) 403
TIMEUNIX(time$) 403
TM1638.BUTTONS..
404
TOUCH.X..
404
TOUCH.Y..
404
VAL(string$) 404
WIFI.CHANNEL.
404
WIFI.MODE..
404
WIFI.NETWORKS ( network$ )
404
WIFI.RSSI 405
WIFI.STATUS..
405
WORD.COUNT( string$ [,delimiter$])
405
WORD.FIND( string$, find$ [,delimiter$])
405
STRING FUNCTIONS..
406
BAS.ERRMSG$.
407
BAS.FILENAME$.
407
BAS.FTP$( host$, login$, password$,
file$, folder$) 407
BAS.PASSWORD$.
407
BAS.RTCMEM$.
407
BAS.SSID$.
407
BAS.VER$.
407
BIN$(number) 407
BUTTON$(name$, label [, id] )
407
CHECKBOX$( variable [,id]) 407
CHR$(number) 408
CSSID$(object_id, object_style)
408
DATE$[(format)] 408
ESPNOW.ERROR$.
408
ESPNOW.READ$.
408
ESPNOW.REMOTE$.
408
FILE.DIR$[(path$)] 408
FILE.READ$(filename$,[line_num] | [start,
length]) 408
HEX$(number) 408
HtmlEventButton$.
408
HtmlEventVar$.
409
IMAGE$(path [,id]) 409
IMAGEBUTTON$(path, label [,id])
409
IP$.
409
IR.GET$[ (param) ] 409
JSON$(string$, field$) 409
LCASE$(string$) 409
LED$(variable [,id]) 410
LEFT$(string$, num) 410
LISTBOX$(variable$, "option1, option2,
option3, ..." [, height] [,id]) 410
MAC$[ (id) ] 410
METER$(variable, min, max [,id])
410
MID$(string$, start [,num]) 410
MQTT.Message$.
411
MQTT.Topic$.
411
OCT$(number) 411
PASSWORD$(variable [, id] ) 411
REPLACE$(expression$, find$,
replacewith$) 411
RFID.NUID$.
411
RFID.TYPE$.
412
RFID.READ$(block [,key_b]) 412
RIGHT$(string$, num) 412
RTC.DATE$[(format)] 412
RTC.TIME$.
413
SERIAL.CHR$.
413
SERIAL.INPUT$.
413
SERIAL2.CHR$.
413
SERIAL2.INPUT$.
413
SLIDER$(variable, min, max [,step] [,id])
413
SPACE$(number) 413
SPI.STRING$(data$, len) 413
SPI.HEX$(datahex$, len) 413
STR$ (number [,format$ [,toint]])
414
STRING$(num, char$) 416
TEMPR$(pin_number [,ID]) 416
TEXTAREA$(variable [, id] ) 417
TEXTBOX$(variable [, id] ) 417
TRIM$(string$) 417
TIME$.
417
UCASE$(string$) 417
UDP.READ$.
417
UDP.REMOTE$.
417
UNIXDATE$(value [,format]) 417
UNIXTIME$(value) 417
URLMSGGET$ ([arg$]) 418
WGET$( http_server$, port [,header] )
418
WGET$( url$, [,header] ) 418
WGETRESULT$.
418
WORD$(string$, position [,delimiter$])
418
WORD.DELETE$(string$, position
[delimiter$]) 418
WORD.EXTRACT$(string$, lead$, trail$)
419
WORD.GETPARAM$( setting$,
parameter$ [,separator$]) 419
WPOST$(server$, body$, port [,header])
419
WPOST$(url$, body$, [,header])
419
COMMANDS: 419
AUTOREFRESH interval 420
BAS.LOAD filename$.
420
BAS.RTCMEM$ = val$.
420
CLS..
420
CSS style_code$.
420
COMMAND cmd$.
420
COUNTER.RESET cnt 420
COUNTER.SETUP cnt, pin [,mode]
420
CSSEXTERNAL file$.
421
DATA const1 [,const2] ... 421
DHT.SETUP pin, model 422
EMAIL.SETUP server$, port, user_name$,
password$ [, debug] 422
EMAILASYNC from$, to$, subject$,
message$.
422
FILE.FROMBASE64 source$,
dest$.
422
FILE.SAVE filename$, content$.
422
FILE.TOBASE64 source$, dest$.
422
FUSION.INIT.
422
FUSION.MADGWICK ax, ay, az, gx, gy,
gz.
423
FUSION.MADGWICK ax, ay, az, gx, gy, gz,
mx, my, mz.
423
FUSION.MAHONY ax, ay, az, gx, gy, gz, mx,
my, mz.
424
FUSION.BETA =.
424
FUSION.ZETA =.
424
FUSION.KI =.
424
FUSION.KP =.
424
HTML code$.
424
I2C.SETUP sda_pin, scl_pin [,freq ]
424
I2C.BEGIN address.
424
I2C.END..
425
I2C.REQFROM address, length.
425
I2C.READREGARRAY i2c_address, register,
nb_of_bytes, Array() 425
I2C.WRITE value.
425
I2C.WRITEREGBYTE i2c_address,register,
value.
426
I2C.WRITEREGARRAY i2c_address, register,
nb_of_bytes, Array() 426
INCR var [, increment] 426
INPUT.TIMEOUT timeout 426
INPUT["prompt$";] variable.
426
INTERRUPT pin_no, {OFF | label} [, mode]
427
IR.INIT pin_rx | OFF [, pin_tx]
427
IR.SEND type, code$, bits.
427
JSCALL javaCode$.
427
JSCRIPT script$.
427
JSEXTERNAL file$.
427
LCD.INIT address, cols, rows.
428
LCD.CLS..
428
LCD.PRINT x, y, text$.
428
LOCAL var1 [,var2], ... 428
MAXDISPLAY.SETUP CS_pin.
428
MAXDISPLAY.PRINT msg$ [,‘brightness]
428
MAXSCROLL.SETUP nb_devices,
CS_pin.
428
MAXSCROLL.PRINT msg$.
428
MAXSCROLL.NEXT msg$.
429
MAXSCROLL.TEXT msg$.
429
MAXSCROLL.SHOW pos [, brightness]
429
MAXSCROLL.SCROLL [brightness]
429
MAXSCROLL.OSCILLATE [brightness]
429
NEO.PIXEL led_pos, R, G, B [, disable]
429
NEO.PIXEL led_pos, COLOR [, disable]
429
NEO.SETUP pin [,nb_led] 429
NEO.STRIP led_start_pos, led_end_pos, R,
G, B [, disable] 429
NEO.STRIP led_start_pos, led_end_pos,
COLOR [, disable] 430
NEOSCROLL.SETUP nb_devices, pin
[,serpentine] 430
NEOSCROLL.PRINT msg$.
430
NEOSCROLL.NEXT msg$.
430
NEOSCROLL.COLORS col$.
430
NEOSCROLL. NEXTCOLORS col$.
430
NEOSCROLL.SHOW pos [, brightness]
430
NEOSCROLL.TEXT msg$.
430
NEOSCROLL.SCROLL [‘brightness]
430
NEOSCROLL.OSCILLATE [‘brightness]
430
OLED.CLS..
431
OLED.INIT orientation [,model]
431
OLED.REFRESH fmt 431
OLED.COLOR color 431
OLED.PIXEL x, y.
431
OLED.LINE x1, y1, x2, y2.
431
OLED.RECT x,y, width, height [,fill]
431
OLED.CIRCLE x, y, radius [, fill]
431
OLED.FONT font_num..
432
OLED.PRINT x, y, text$ [background]
432
OLED.IMAGE x, y, image$.
432
OLED.BMP x, y, image$.
432
ONERROR ABORT or ONERROR IGNORE or
ONERROR SKIP [nn] or ONERROR CLEAR or ONERROR GOTO label
432
ONESPNOWERROR [label | OFF] 432
ONESPNOWMSG [label | OFF] 432
ONGESTURE [label | OFF] 432
ONHTMLCHANGE [label | OFF] 433
ONHTMLRELOAD [label | OFF] 433
ONINFRARED label 433
ONMQTT label 433
ONRFID label 433
ONSERIAL [label | OFF] 433
ONSERIAL2 [label | OFF] 433
ONTOUCH [label | OFF] 433
ONUDP [label | OFF] 433
ONURLMESSAGE [label | OFF] 433
ONWGETASYNC [label | OFF] 433
OPTION.CPUFREQ 80|160|240.
433
OPTION.LOWRAM value.
434
PAUSE delay.
434
PCA9685.SETUP addr 434
PCA9685.SETFREQ freq.
434
PCA9685.PWM pin, value.
434
PID1.INIT Kp, Ki, Kd.
434
PID1.LIMITS min, max.
434
PID1.PERIOD msec.
434
PID1.PARAMS Kp, Ki, Kd.
434
PID1.SETMODE mode.
434
PIN(pin_number) = val 434
PIN.DAC pin_number, value.
435
PIN.MODE pin_number, mode [,PULLUP |
PULLDOWN ] 435
PLAY.MP3 mp3$.
435
PLAY.STREAM stream$ [,buffer]
435
PLAY.SETUP dest [,buffer] [,mono]
435
PLAY.SPEAK message$ [, phonetic]
436
PLAY.STOP..
436
PLAY.VOICE "message", "language" [,
"filename"] [, action] 436
PLAY.VOLUME volume.
436
PLAY.WAV..
436
PRINT expression[[,; ]expression] ...
436
PRINT2 expression [[,; ]expression] ...
436
PWM.SETUP pin, chan, default,
[,freq] [,resol] 437
PWM.SETUP pin, OFF.
437
PWM.OUT chan, value.
437
READ var1 [,var2] ... 437
REBOOT.
437
REFRESH..
437
RESTORE [label] 437
RTC.SETTIME Year, Month, Day, Hours,
Minutes, Seconds.
437
SERIAL.BYTE ch1 [,ch2] . . . 437
SERIAL2.BYTE ch1 [,ch2] . . .
438
SERIAL.MODE baudrate [, bits, parity,
stop] 438
SERIAL2.MODE baudrate, pin_tx, pin
rx [, bits, parity, stop] [, TXbuffer, RXbuffer] 438
SETTIME Year, Month, Day, Hours, Minutes,
Seconds.
438
SLEEP value [,pin, level] 438
SOCKET client, msg$.
438
SPI.CSPIN pin [, polarity] 438
SPI.SETUP speed [,data_mode [,
bit_order]] 439
SPI.STOP..
439
ST7920.INIT CS_pin.
439
ST7920.CLS..
439
ST7920.REFRESH fmt 439
ST7920.COLOR color 439
ST7920.PIXEL x, y.
439
ST7920.LINE x1, y1, x2, y2.
439
ST7920.RECT x,y, width, height [,fill]
439
ST7920.CIRCLE x, y, radius [, fill]
439
ST7920.FONT font_num..
440
ST7920.PRINT x, y, text$ [background]
440
ST7920.IMAGE x, y, image$.
440
ST7920.BMP x, y, image$.
440
TM1637.PRINT msg$ [, brightness ]
440
TM1637.SETUP data_pin, clock_pin [,
bit_delay] [, display_type] 440
TM1638.PRINT msg$ [, brightness ]]
440
TM1638.SETUP data_pin, clock_pin,
strobe_pin.
440
TM1638.LEDS val 440
TFT.BMP filename$, [x, y [, back_color] ]
441
TFT.BRIGHTNESS val 441
TFT.CIRCLE x, y, radius,color [, fill]
441
TFT.FILL color 441
TFT.IMAGE filename$, [x, y [, back_color]
] 441
TFT.INIT orientation.
442
TFT.JPG filename$, [x, y [, scale] ]
442
TFT.LINE x1, y1, x2, y2, col 442
TFT.PIXEL x, y, col 442
TFT.PRINT expression [[,; ]expression]
... 443
TFT.RECT x, y, width, height, color [
[,fill] ,[round_radius] ] 443
TFT.SETFREQ freq.
443
TFT.TEXT.COLOR color [,backcolor]
443
TFT.TEXT.POS x, y.
443
TFT.TEXT.SIZE size.
443
TIMER0 interval, label 443
TIMER1 interval, label 443
TOUCH.CALIB..
444
UDP.BEGIN port 444
UDP.REPLY msg$ [,port] 444
UDP.STOP..
444
UDP.WRITE ip, port, msg$.
444
URLMSGRETURN msg$ [,content_type$]
444
WAIT.
444
WGETASYNC server$, port [,header]
444
WGETASYNC url$, port [,header]
445
WIFI.APMODE SSID$, password$ [, channel]
[, IP$ , MASK$] 445
WIFI.AWAKE..
445
WIFI.CONNECT SSID$, password$ [, BSSID$]
[, IP$ , MASK$ [, GATEWAY$]] 445
WIFI.POWER pow..
445
WIFI.SCAN..
445
WIFI.SLEEP..
445
WLOG [text$ | num] 446
WORD.DELPARAM setting$, parameter$,
[,separator$] 446
WORD.SETPARAM setting$, parameter$,
value$ [,separator$] 447
BASIC KEYWORDS..
447
CASE..
448
DIM array(size) [, …] 448
DO..
448
ELSE..
448
ELSEIF.
448
END [IF | SELECT | SUB] 448
ENDIF.
448
EXIT {DO | FOR | SUB} 448
FOR..
448
GOSUB [label | lab$] 448
GOTO [label | lab$] 448
IF.
448
LET var = expression.
448
LOOP..
448
NEXT.
448
OFF.
449
OUTPUT.
449
PULLUP..
449
PULLDOWN..
449
REM..
449
RETURN..
449
SELECT.
449
SPECIAL.
449
STEP..
449
SUB..
449
THEN..
449
TO..
449
UNTIL.
449
WEND..
449
WHILE..
449
Annex32 WI-Fi RDS (Rapid Development Suite) is
a version of the "BASIC" language developed to run on low cost
ESP-32 WIFI devices.
Annex32 is specifically for the ESP32 range of
devices, whose implemented features can vary greatly.
To offer some standardisation, Annex32 caters
in particular to M5stack devices, which include a micro-SD card
slot, TFT display, speaker, 3 user buttons plus a reset button, and
a lipo battery, all self-contained in a plastic case offering
expansion pin access and designed to accept ‘stackable’ expansion
modules.
All drivers needed for the M5stack features
are already included in the Annex32 firmware, and pre-configured
for the M5stack so that features such as TFT display and SDcard
work by default.
Similar functionality could be built using
alternative TFT display and SD card reader etc, if preferred.
Please refer to the original
M5Stack schematics for more details.
However, M5stack and its hardware features
merely offer a convenient standardised feature set, they are not
mandatory - Annex32 works with any ESP32 devices, with or without
hardware expansion modules.
Obviously appropriate hardware is needed for
any required features - eg: an OLED display could be used, but
scripts written for TFT displays will need modifying for the
different display.
Annex32 can use the internal flash disk space,
or an external SD card.
The internal and the external (SDcard) space
are mutually exclusive and cannot be accessed at the same time.
By default Annex32 will use the SD, if
available, otherwise it will use the internal flash disk space
(FATFS).
Both use the same type file system (FAT32),
enabling the use of long file names and directories.
Depending on the module flash memory size (4,
8 or 16MB), the internal disk space can be from ~1MB to 13MB.
Using the ESP32 partition scheme it is
possible to freely define this space, but modifying it will wipe
out all existing files already stored.
Annex32 Wi-Fi RDS takes from the original
concept of Annex WI-FI RDS for ESP8266 from which it shares
essentially the IDE interface and the same command syntax as much
as possible.
It should be straightforward switching to
Annex32 if coming from Annex, and the same programs should run
without (or with minimum) modifications (eg: pin numbers).
Annex32 Wi-Fi RDS benefits from the powerful
H/W architecture of the ESP32 using both cores and the RAM memory
available. In addition, for modules equipped with PSRAM memory
extension, Annex32 can make available to the users this additional
RAM space (up to 4MBytes).
Functionalities:
-
Includes an internal IDE so can be programmed directly using your
web browser (even from your phone/tablet) without any additional
utility.
-
Syntax highlighting with context-sensitive Help
-
A programmable web server which includes a file server
-
Supports OTA (over the air) update.
-
Support async events (interrupts, timers, web access, UDP, ….)
-
Breakpoints, immediate execution of commands, display of variables,
single step.
-
A basic interpreter with floating point variables (double
precision) and string variables, multi-dimensional arrays (float
and string), user defined subroutines.
-
Access to any available I/O pin for input/output, PWM and
Servo.
-
Errors Handling .
-
Support TCP (HTTP) GET and POST for communications
-
Support for UDP for communications.
-
Support for sending Emails using SMTP SSL servers
-
Support for AJAX communications (GET, POST, PUT) Synchronous and
Asynchronous
-
Support for ESP-NOW communications
-
Support for MQTT communications
-
Support for MODBUS communications
-
Support for FTP communications
-
Support for Bluetooth Low Energy (BLE) communications
-
Support for Telegram communications
-
Support for RJ45 wired ethernet using W5500 module
-
Accompanying utility suite includes Flasher, File Manager, HTML
Converter, Backup/Restore to bin or zip, integrated Serial Port
Monitor, OTA (over the air) update server and UDP Console.
-
IMU / AHRS Fusion algorithms 6 DOF and 9 DOF (Madgwick and
Mahony)
-
Play MP3 or WAV sound files or streaming using a speaker or an
external I2S DAC
-
Text to Speech using a speaker or an external I2S DAC
-
Support for regular expressions (regex)
The following
devices are supported directly with dedicated commands / functions
:
-
DHT11, DHT21 or DHT22 Temperature / Humidity Sensors
-
DS18B20 Temperature sensor
-
LCD HD44780 with I2C interface module (1, 2 or 4 lines with 16 or
20 chars per line)
-
LCD Display based on chipset ST7920 with 128x64 pixels
monochrome
-
OLED Display based on chipset SSD1306 or SH1106 with 128x64 pixels
monochrome
-
TFT Display at 16 bits colors based on the following chipset:
-
ILI9341 with 320x240 pixels
-
ILI9163 with several resolutions
-
ST7735 with several resolutions
-
ST7796 with 480x320 pixels
-
ILI9481 with 480x320 pixels
-
ILI9486 with 480x320 pixels
-
ILI9488 with 480x320 pixels
-
ILI7789 with several resolutions
-
SSD1351 with 128x128 pixels
-
GC9A01 with 240x240 pixels
-
TM1637 4 and 6 digits 7-segments display
-
TM1638 8 digits 7-segments display including 8 leds and 8
buttons
-
MAX7219 8 digits 7-segments display
-
MAX7219 8x8 dot matrix display modules
-
Neopixel WS2812 led strips
-
Neopixel WS2812 8x8 dot matrix display
-
PCA9685 PWM/SERVO module
-
Infrared interface with many RC protocols (transmission and
reception)
-
RTC module (DS1307 or DS3231)
-
HC-SR04 ultrasonic sensor for distance measurement
-
BNO055 Absolute Orientation Sensor
-
MPU9250 / MPU6500 IMU units
-
MPU6886 IMU unit
-
BME280 Combined humidity and pressure sensor
-
BME680 Combined gas, pressure, temperature & humidity sensor /
Air Quality Sensor
-
HDC1080 High Accuracy Digital Humidity Sensor with Temperature
Sensor
-
CCS811 Air Quality Sensor
-
APDS9960 Digital Proximity, Ambient Light, RGB and Gesture
Sensor
-
W5500 RJ45 wired Ethernet interface
-
VL53L0X TOF (Time Of Flight) Distance Sensor
-
RFID MFRC522 cards reader
-
HX711 - Weight Measurement Module
-
SI5351 Clock Generator Module
-
Any compatible I2S DAC
-
Lora SX127x modules
-
STEP Motors
-
VGA output for ESP32–S3
-
RGB TFT output for ESP32-S3
Many ESP32 modules
/ units are supported and can be configured using the
“CONFIG” menu:
-
Almost all the ESP32 modules including ESP32 devkit, ESP32 wemos
mini, ESP32 lolin lite, ...
-
M5Stack
-
M5 Atom
-
M5 Atom matrix
-
M5 Atom Echo
-
ESP32-CAM
-
M5CAMERA
-
ODROID GO
-
M5Tough
-
WIFI LORA 32
-
ESP32-2432S028 (module with a 240x320 2.8” TFT with resistive
touchscreen)
-
ESP32-3248S035R (module with 320x480 3.5” TFT with resistive
touchscreen)
ESP32-3248S035C (module with 320x480 3.5” TFT with capacitive
touchscreen)
In addition to
the ESP32, Annex now extends its support to other family members,
including the ESP32-C3, ESP32-S2, and ESP32-S3. This support
encompasses both direct USB connection and variants with USB to
serial chip. For all of these modules, Annex offers compatibility
across different versions, considering the specific type of flash
memory installed, including DIO, QIO, and OPI, as well as the
presence of PSRAM, with* options for QIO and OPI configurations. As
a result of this diverse range of variants, Annex provides distinct
firmware releases tailored to each particular configuration. This
ensures optimal performance and seamless integration across the
ESP32 series.
The following
modules equipped with ESP32-S3 are also supported and can be
configured using the “CONFIG” menu:
-
ESP32-4848S040 (module with a 480x480 4” RGB TFT with capacitive
touchscreen)
-
ESP32-8048S070C (module with a 800x480 7” RGB TFT with
capacitive touchscreen)
The basic interpreter works by reading a
script file saved to the esp local disk filing system.
This is the default mode if no external
SDcard(s) are connected to the ESP32.
In addition, Annex32 can use an external
SDcard as file system permitting up to 16Gbytes of disk space.
During the startup, if an external SDcard is
detected it will be automatically connected and used as the default
file system, in which case the internal filing system will not be
used.
Because the ESP32 contains a good quantity of
RAM, the user script is copied from the disk into a dedicated
area in the RAM memory where it is executed, together with the list
of the program lines, the branch labels and the list of the user
defined subroutines..
This uses more RAM compared to other
approaches, but allows faster program execution.
Another performance consideration is that the
ESP32 must be capable of executing several activities in the
background (web server, file server, etc..) so needs sufficient
free memory for running such tasks, and those parallel tasks will
obviously have an impact on script performance..
So performance-wise, the interpreter is not
particularly fast, but it should be fast enough for most tasks you
may require. In particular it is around 2 times faster than Annex
for ESP8266, considering that many tasks can run in parallel
without any appreciable performance impact (such as playing music
in the background).
Basic program lines :
A typical script line should comply with the
following syntax :
[label:]
command [argument1 [,argument2 …..]]
Script lines may contain several commands on
the same line if separated by the colon character ":".
[label:]
command1 [argument1 [,argument2 …..]]: command2 [argument1
[,argument2 …..]]
It must be noted that use of several commands on the same line is
not recommended and will cause program errors if the line contains
GOSUB or user defined subroutine calls.
All program jumps (eg: GOTO, GOSUB) are
referenced by their branch label names - line numbers are not
referenced in scripts, they are merely available in the editor as a
programming convenience if wished, and for error references.
NOTE : The gosub and the call to user
defined subroutines must be used alone on the script line.
Branch labels should not be named the same as
a command name, and must follow the same format as variables (see
below).
A branch label definition must begin the line,
and a colon (":") must terminate the label definition.
Any references to the defined label (GOTOs and
GOSUBs etc) do not use a colon.
Example :
b
= 10
a
= 20 : c = 30
GOSUB LABEL1
END
LABEL1:
print "Label1"
RETURN
|
The interpreter has 2 types of variables:
-
Floating Point (double precision)
-
String
Floating point variables can store numbers
with decimal points; they can also store integer numbers with a
precision equivalent to 32bits.
Strings contain sequences of characters
(example "my program") and must be terminated by "$".
The strings are not limited in size, they are
only limited by the amount of memory available.
NOTE: The string variables cannot contain
the character with ASCII code 0 (zero) because it is used
internally as an end of string delimiter.
The variables are defined as any name starting
with an alpha character (a, b, ..z) followed by any alphanumeric
character (a..z, 0..9); it can also include the "_"
(underscore).
The case is don’t care, so ‘’Num"
is equivalent to "nuM".
The variable name length is limited to 31
characters maximum, including the "$" for the strings.
There are no limits in terms of number of
variables; the only limit is the RAM memory available.
Example:
NUM = 10.56
myString$ = "this is My
String"
this_is_my_value$
= "ESP8266"
number = 8826621
|
Numeric variables and string variables are
managed separately so the same name can be used; this means that
A and A$ are different variables that can coexist at
the same time (even if this could lead to confusion).
Constants:
The numeric constants can have the following
format :
A =
5 : Z = 1.5
B =
1.23456E5 -> same as 123456
C =
1.23456E+5 -> same as 123456
D =
1.23456E-3 -> same as 0.00123456
The string constants are simply defined as a
text between quotes:
A$
= "This
is my string" : B$ =
"another string"
The strings can include the character "
(quote) simply typing it two times :
A$
= "this
is ""MY"" string"
The | (vertical bar) can also be used
as a string literal.
This permit to include the " (quote) easily
inside a string constant :
A$
= |this
is a "string" constant|
The hexadecimal constants can be defined
simply prefixing it with &h :
E
= &hABCD -> equivalent of decimal
43981 (hexadecimal constant)
F
= &hA0 -> equivalent of decimal
160
The binary constants can be defined simply
prefixing it with &b :
E
= &b00000101 -> equivalent of decimal
5 (binary constant)
F
= &b10000001 -> equivalent of
decimal 129
The octal constants can be defined simply
prefixing it with &o :
E
= &o377 -> equivalent of decimal 255
(octal constant)
F
= &o17 -> equivalent of decimal
15
Arrays are defined using the DIM
command.
Their names follow the same rules as the
regular variables and are followed by parenthesis (brackets)
containing the index. The subscript starts from 0, but you can
adjust the lower limit using
The scope of the Arrays is always global (see
next paragraph).
Example:
DIM
A(100)
define a floating point array with 101 elements (index
from 0 to 100)
DIM
ABC$(50)
define a string array with 51 elements
(index from 0 to 50)
A(15) = 1234.5678
ABC$(49) = "Hi friend!"
The arrays can have up to 5 subscripts
(dimensions), examples:
DIM
A(50,50) -> create a floating point array with
51*51 elements (2601)
DIM
J$(4, 4, 4) -> create a string array with 5 * 5
* 5 elements (125)
If the command
OPTION.BASE 1
is executed the subscripts start from 1 and an error will be raised
when trying to use the index 0.
This line
OPTION.BASE 1
must be present in the code before array declaration.
In this case
DIM
A(100)
define a floating point array with 100 elements (index
from 1 to 100)
DIM
ABC$(50)
define a string array with 50 elements
(index from 1 to 50)
Notice that declaring a multi-dimensional
array with multiple subscripts uses elements for every
possible[1] [2] [3] combination of
subscripts, whereas in practice it may be preferable to declare
multiple arrays with the same subscript, eg:
users=4
DIM Name$(users)
DIM Address$(users)
DIM Tel$(users)
Which only uses 5 + 5 + 5 elements
(15)
NOTE:
The numerical Arrays are always
initialised at 0 with the command DIM.
The string Arrays are always initialised
as null string with the command DIM.
There are no limits to the number of
arrays or their size, the only restriction is the RAM memory
available.
The arrays can be re-dimensioned using the
same command DIM.
In this case all the existing elements will
maintain the previous value except the new elements that will be
initialised at 0 or null string.
Example :
DIM A(5)
' all the elements are initialised at
0
A(0)
= 123
Print A(0)
' print 123
Dim A(10)
Print A(0)
' print the same value
123
Print A(10)
' print 0
|
In addition the elements of the arrays can be
initialised with a given value during the command DIM.
Example :
DIM
A(5) = 0, 1, 2,
3, 4, 5 ' set A(0)= 0,
A(1)= 1, A(2)=2, ….
If the command
OPTION.BASE 1
is executed before
DIM
A(5) = 0, 1, 2,
3, 4, 5 ' set A(1)= 0,
A(2)= 1, A(3)=2, ….
The same can be done with string arrays.
Example :
DIM
A$(5) =
"zero", "one", "two", "three", "four", "five"
Two additional functions can be used to determine the bound limits
of arrays:
LBOUND(array()
[, dimension]) : Returns the lower bound of the
specified array dimension.
UBOUND(array()
[, dimension]) : Returns the upper bound of the
specified array dimension.
Example :
OPTION.BASE 0
DIM A(100)
print
LBOUND(a()) ' print 0
(option.base 0)
print
UBOUND(a()) ' print
100
OPTION.BASE 1
DIM A(10,
20)
print
LBOUND(a(), 1)
' print 1 (option.base
1)
print
LBOUND(a(), 1)
' print 1 (option.base
1)
print
UBOUND(a(), 1)
' print 10
print
UBOUND(a(), 2)
' print 20
|
Variables and arrays defined in the main code
are global, therefore any variable is accessible from any part of
the code after it has been previously defined there.
Variables and arrays defined inside
“user defined” subroutine (SUB) are visible only inside that sub
and inside all the code called by that subroutine; their content
(and their memory space) is removed at the end of the SUB
The LOCAL command permits defining local
variables inside of "user defined" subroutines; this permits to use
the same name of an “already existing” variable locally without
modifying the original.
As for all the variables defined inside SUB,
they will disappear at the end of the subroutine.
Example:
A
= 10
B
= 20
C
= 30
mysub
"Hello"
PRINT A,B,
C
END
SUB mysub(a$)
LOCAL A,B
A
= 123
B
= 456
C
= 789
D
= 8888
PRINT A$, D
END
SUB
|
In this example, calling the user-defined
subroutine "mysub" will not modify the content of the global
variables A and B (defined locally) but will modify the content of
the variable C (not defined locally) and the variable D will
disappear at the end of the SUB.
The keywords recognized by the interpreter can
be defined into 3 classes:
●
Operators
●
Commands
●
Functions
The Operators are symbols that tell the
compiler to perform specific mathematical or logical
manipulations.
Commands and Functions both execute an action,
but functions also return a data value.
For example
PRINTis a command and
SIN()
is a function whereas the ‘+’ in a = b
+ 5 is an operator.
The string functions are always followed by
the "$" symbol if they return a string value.
In addition to commands and functions there
are all the internal interpreter internal commands that are part of
the language itself.
The following operators are available. These
are listed in the following tables by order of precedence.
Operators on the same line are processed with a left to right
precedence.
Arithmetic operators:
^
|
Power
|
* / \ MOD
|
Multiplication,
division, integer division and modulo (remainder of the
division)
|
+ -
|
Addition and
subtraction
|
Shift operators:
x <<
y
x >> y
|
These operate in a
special way. << means that the value returned will be the
value of x shifted by y bits to the left while >> means the
same only right shifted. They are integer functions and any bits
shifted off are discarded and any bits introduced are set to
zero.
For more
information about the kinds of bitwise shifts, see Bitwise shifts.
|
Logical operators:
<> <
> <=
>=
=
|
Not Equal, less
than, greater than, less than or equal to,
greater than or
equal to, equal
|
AND OR NOT XOR
|
Conjunction,
disjunction, negation, Exclusive OR
|
String operators:
<> <
> <=
>=
=
|
Not Equal, less
than, greater than, less than or equal to,
greater than or
equal to, equal
|
+ &
|
Add strings
together
|
Bitwise operators:
AND OR XOR NOT
|
Binary AND, binary
OR, binary exclusive OR, binary negation
For more
information about the bitwise operators, see
Bitwise Operators
|
The operators AND, OR and XOR are integer
bitwise operators. For example PRINT (3 AND 6) will output 2.
Expressions beginning with open parenthesis
‘(‘ are always considered numerical but the parser is able to
determine if an expression is true or false even if the expression
represents a string.
Each expression representing a comparison,
returns a numerical value of 1 if the expression is true or 0 if
false.
For example 10 = 10 represents a value of 1
whereas 10 = 5
represents a value of 0.
The same logic is applied for string
expressions where "abc" =
"abc" represents a value of 1 and "abc" = "def" represents a
value of 0.
This is very useful in the IF command and also
in other expressions.
For example the following code :
A$ = "on"
If
A$ = "on"
then
pin(4)
= 1
Else
pin(4)
= 0
End
if
|
Can be replaced by
pin(4)
= (a$ =
"on")
The strings can also be compared to determine
the alphabetical order.
To see whether a string is greater than
another, Annex uses the so-called “ASCII” order.
In other words, strings are compared
letter-by-letter.
For example:
("Z"
> "A") is true
("Glow"
> "Glee") is true
("Bee"
> "Be") is true
("Bas"
> "Bat") is false
The algorithm to compare two strings is
simple:
Compare the first character of both
strings.
If the first character from the first string
is greater (or less) than the other string, then the first string
is greater (or less) than the second. We’re done.
Otherwise, if both strings’ first characters
are the same, compare the second characters the same way.
Repeat until the end of either string.
If both strings end at the same length, then
they are equal. Otherwise, the longer string is greater.
In the examples above, the comparison
"Z" > "A" gets
to a result at the first step while the strings"Glow" and "Glee" are compared
character-by-character:
-
G is the same as G.
-
l is the same as l.
-
o is greater than e. Stop here. The first string is greater.
The comparison algorithm given above is
roughly equivalent to the one used in dictionaries or phone books,
but it’s not exactly the same.
For instance, case matters. A capital letter
"A" is not equal to the lowercase "a". Which one is greater?
The lowercase "a". Why? Because the lowercase
character has a greater index in the ASCII table.
The IF can have the following syntax :
1) IF
expression THEN statement
2) IF
expression THEN statement1 ELSE statement 2
3) IF
expression THEN
Statements
ELSE
Statements
END IF
4) IF
expression THEN
Statements
ELSEIF expression THEN
Statements
ELSEIF ……..
………
ELSE
Statements
END IF
Example:
IF a
> 100 THEN print
"a"
IF b
<a THEN print
"b" ELSE print
"a"
IF c
> d THEN
print "C"
print "is greater"
ELSE
print "D"
print "is greater"
END
IF ' (can also be ENDIF
without space between END and IF)
IF d
= a THEN
print "d"
print "is like a"
ELSEIF d
= b
print "d"
print "is like b"
ELSEIF d
= c
print "d"
print "is like c"
ELSE
print "d"
print "is unknown"
END
IF ' (can also be ENDIF
without space between END and IF)
|
When the conditional is all on one line it
does not need terminating with an END IF
Example
IFa=2
THEN
PRINT "ok"
ELSE PRINT "not
ok"
The AND ,
OR keywords can be used
between the expressions as long as they are in
parenthesis.
Example:
IF
(a=1)
AND (b=2)
THEN PRINT "ok"
Or
IF
((a=2)
AND (b=3)
AND (c =
3)) OR (d=4)
THEN PRINT "ok"
The IF can be nested
Example:
IF
a=2 THEN
IF b = 2
THEN
IF c = 3 THEN
PRINT "ok"
END IF
END IF
END
IF
|
The “THEN” keyword can eventually be
removed, even if this is not recommended.
Example:
IF
a > 100 print
"a" else print
"b"
The FOR loop can
have the following syntax :
FOR
variable=init_value to end_value [step
value]
Statements
NEXT
variable
The ‘step’ value can be positive or
negative
Example:
FOR
i=1 to
5
Print i
NEXT
i
Will print 1, 2, 3, 4, 5
FOR
i=1 to 3
step 0.5
Print i
NEXT
i
Will print 1, 1.5, 2, 2.5, 3
FOR
i=3 to 1
step -0.5
Print i
NEXT
i
Will print 3, 2.5, 2, 1.5, 1
The command
EXIT
FOR can be
used to exit from the loop at any time:
FOR
i=1 to
50
IF
i=10 THEN
EXIT FOR
Print i
NEXT
i
Print
"end of loop"
Optionally, the variable in the
NEXT statement
can be omitted.
This means that this program is valid :
FOR
i=1 to
5
Print i
NEXT
The WHILE
WEND loop can have the following
syntax :
WHILE
expression
Statements
WEND
The loop is iterated as long as the expression
is true
Example:
i
= 0
WHILE
i < 3
Print i
i = i +
1
WEND
Will print 0, 1, 2
The DOLOOP
can have one of the following 4 syntax :
DO
WHILE expression
Statements
LOOP
DO
UNTIL expression
Statements
LOOP
DO
Statements
LOOP
WHILE expression
DO
Statements
LOOP
UNTIL expression
The command
EXIT
DO can be used to exit from the
loop at any time
Example
i
= 0
DO
Print
i
i = i
+ 0.5
LOOP
UNTIL i >3
Will print 0, 0.5, 1, 1.5, 2, 2.5, 3
i
= 0
DO
Print
i
i = i
+ 0.5
IF
i > 2 THEN
EXIT DO
LOOP
UNTIL i >3
Will print 0, 0.5,
1, 1.5, 2
The SELECTcan
have the following syntax:
SELECT
CASE expression
CASE exp1 [: Statements]
Statements
CASE exp2 TO exp3 [: Statements]
Statements
CASE exp4 [,exp5],
... [: Statements]
Statements
CASE ELSE
Statements
END
SELECT
Example:
a =
4
SELECT
CASE a
CASE 1
PRINT "case
1"
CASE 2 :
PRINT "case 2"
CASE 3 :
PRINT "case 3" : PRINT "can continue
on same line"
CASE 4 :
PRINT "case 4"
PRINT "can continue
also on next line"
CASE ELSE:
PRINT "case
else"
END
SELECT
Multiple cases:
a =
4
SELECT
CASE a
CASE1 :
PRINT "case 1"
CASE 2, 3, 5
: PRINT "case 2 or 3 or 5"
CASE4 :
PRINT "case 4"
CASE 6 TO
8 : PRINT "case 6 to 8"
CASE 9 TO 20
: PRINT "case 9 to 20"
CASE ELSE:
PRINT "case
else"
END
SELECT
The SELECT CASE can
also handle string content:
SELECT
CASE a$
CASE "a"
:
PRINT "case
a"
CASE "a",
"b", "c",
"d" :
PRINT "case a, b,
c, or d"
CASE "e"
TO "h" :
PRINT "case e to
h"
CASE ELSE:
PRINT "case
else"
END
SELECT
The GOTOcan have
the following syntax :
GOTO
[LABEL | LAB$]
Example
a =
5
IF a
> 5 THEN GOTO
LABEL1
END
....
LABEL1:
PRINT
"This is label1"
....
The goto must be
considered as an obsolete command and is provided just for backward
compatibility with old style Basic programs.
The GOSUBcan have
the following syntax :
GOSUB
[LABEL | LAB$]
The called function
must terminate with the command RETURN
Example
a =
5
IF a
> 5 THEN GOSUB LABEL1
END
....
LABEL1:
PRINT
"This is label1"
RETURN
The command DATA is used to store constant
information in the program code, and is associated with the command
READ. Each
DATA-line can contain one or more constants separated by commas.
Expressions containing variables will be also evaluated
here.
The goal of the DATA is to avoid repetitive
variable assignation lines, in particular for arrays.
The DATA values will be read from left to right, beginning with the
first line containing a DATA statement. Each time a READ
instruction is executed the saved DATA position of the last READ is
advanced to the next value. Strings must be written in quotes like
string constants. The command
RESTORE resets the pointer of the current DATA
position, so the next READ will read from the first DATA found from
the beginning of the program.
In case READ uses the wrong variable type the error message
"Type mismatch" appears while referring to the line number
containing the READ statement that triggered the condition.
DATA lines may be scattered throughout the
whole program code, but for the sake of clarity they would be
better kept together at the beginning of the program.
The DATA can have
the following syntax :
DATA const1
[,const2] …..
The constants can
be Numerical or String.
Example :
DATA 1, 55.88,
"constant", 99
READ A, B, C$,
D
PRINT A, B, C$,
D
Example without
DATA:
dim colors$(5)
colors$(1)
= "Red"
colors$(2)
= "Green"
colors$(3)
= "Blue"
colors$(4)
= "Yellow"
colors$(5)
= "Magenta"
Same example but
using DATA:
DATA
"Red", "Green",
"Blue", "Yellow", "Magenta"
dim colors$(5)
For i=1
to 5
Read colors$(i)
Next i
The command
RESTORE can optionally define a label to set the DATA
pointer to a specific point
Example
data 0, 1, 2,
3, 4, 5
block2:
data 10, 11,
12, 13, 14, 15
block3:
data 20, 21,
22, 23, 24, 25
block4:
data 30, 31,
32, 33, 34, 35
restore block3
for z
= 0 to 5
read a
print a,
next z
restore block2
print
" "
for z
= 0 to 5
read a
print a,
next z
print
"----------"
Define the end of
the program. With this command the program stops.
It can also be
:
END IF -> close the IF command
END SELECT -> closes the SELECT CASE command
END SUB -> closes the user defined SUB
Permit to exit from
a loop or a user defined SUB.
The syntax is :
EXIT
DO -> exit from a DO loop
EXIT
FOR
-> exit from a FOR loop
EXIT
SUB
-> exit from a user defined SUB.
Define a
user-defined subroutine, which the script can use like a command or
function.
User-defined
subroutines are effectively additional commands, so cannot be used
as branch labels.
Permit to create a
user defined command with optional parameters.
The syntax is SUB
subname[(arg1 [,arg2] …)]
The variables are
passed by reference; this means that the arguments, if modified
inside the subroutine, will modify the original variable. This can
be useful to return values from the subroutine (acting like a
function).
It is possible to
pass arrays using the syntax array_name().
Using the
LOCAL command will permit to define local variables (useful
to avoid to modify existing global variables).
Example 1 :
routine cube
SUB
cube(x)
PRINT X ^3
END
SUB
cube 3 ' will print 27
|
Example 2:
routine cube with returning argument
SUB
cube(x,y)
y = x ^3 ' the value is returned using the 2nd
argument
END
SUB
ret
= 0
cube 5,
ret
PRINT
ret
' will print 125
|
Example 3:
routine with local variables and returning argument
SUB left_trim(s$,
ret$)
LOCAL i
i
= 1
DO UNTIL i =
len(s$)
IF
mid$(s$, i, 1) <>
" " THEN EXIT
DO
i = i + 1
LOOP
ret$ = mid$(s$,
i)
END
SUB
z$
= ""
FOR i
= 1 to 3
left_trim " remove space from
left ", z$
PRINT z$ + "--"
NEXT i
|
Will print
remove space from
left --
remove space from
left --
remove space from
left --
As you can see in
this example, the variable i in the FOR loop is not modified by the
LOCAL variable i in the subroutine.
Example 4:
pass arrays
SUB pass_array(f(),
c$())
Dim myArray(10)
myArray(0)
= 456
Print f(0),
c$(0), myArray(0)
f(1) =
123
c$(1) =
"myText"
END
SUB
Dim alpha(10)
Dim beta$(10)
alpha(0)
= 456
beta$(0)
= "testme"
Pass_array
alpha(), beta$()
Print alpha(1),
beta$(1)
|
In this example,
the array alfa() is passed locally to the array f()
and the array beta$() is passed locally to the array
c$().
Modifying locally
these arrays change the value of the original one as their content
is passed by reference.
The array
“myArray” will disappear at the end of the SUB
As the numerical
variables are stored internally as double precision floating
numbers, it is possible to store numbers with a precision
equivalent to 32 bits.
Several boolean
operators are available to manipulate these numbers..
The first operator
is the bit shift; it can be shift left
<< or shift right >>
This operator
permits to shift the number of a specified number of positions to
left or right.
Example
A
= 1
Print A
<< 3 ' will print 8
A
= 16
Print A
>> 2 ' will print 4
The operators
AND
,
OR ,
XOR are also available :
A
= 24
A
= 15
Print A
AND B '
will print 8
A
= 24
A
= 15
Print A
OR B '
will print 31
A
= 24
A
= 15
Print A
XOR B '
will print 23
The unary operator
NOT
is also available. It inverts all the bits from 0 to 1:
A
= 0
Print
Hex$(NOT A)
' will print
FFFFFFFF
For a 32 bits
number, assuming 4 bytes ABCD where A is the MSB and D the LSB, the
bytes can be extracted as follows :
VAR
= &h12345678 ' this is a 32 bits variable
D = VAR
AND &hFF
C = (VAR
>> 8) AND
&hFF
B = (VAR
>> 16) AND
&hFF
A = (VAR
>> 24) AND
&hFF
For more
information, see
Bitwise
Operators
Annex allows to control and manage errors that
occur during the execution of the code.
This is managed with the command ONERROR.
This command defines what action is taken when
an error occurs, and applies to all errors, including syntax
errors.
It can be used in different ways, as specified
in the table below:
FUNCTIONS / COMMANDS
|
DESCRIPTION
|
|
Displays the error message then aborts the
program.
This is the normal behaviour and is the
default when a program starts running.
|
|
Any error will be simply ignored.
As this can make it very difficult to debug a
program it should be used wisely.
|
|
Ignore an error in the next command(s)
executed after the current command (the number of skipped commands
depends on whether the number ‘nn’ is specified).
'nn' is optional, the default is 1
if not specified.
After the number of skipped commands has
completed (with an error or not) the behaviour will revert to
ONERROR ABORT.
|
|
Reset the eventual pending error
|
ONERROR
GOTO [label
| OFF]
|
Jumps to the error handling routine defined by
the label.
It can be removed (hence reverting to ONERROR
ABORT) replacing the label with OFF.
Using RETURN inside the error handling routine
will continue the execution on the line following the error.
|
When an error occurs, the following constants
are available :
CONSTANT
|
DESCRIPTION
|
|
Returns the line
number where the error happened. Value of 0 means no error.
It is reset to 0
with the command ONERROR CLEAR or running the program or with
the command ONERROR IGNORE or ONERROR SKIP.
|
|
Returns a number
where non zero means that there was an error.
It is reset to 0
with the command ONERROR CLEAR or running the program or with
the command ONERROR IGNORE or ONERROR SKIP.
|
|
Return a string
representing the error message that would have normally been
displayed on the console. It is reset to “No Error” running the
program or with the command ONERROR CLEAR or ONERROR IGNORE or
ONERROR SKIP.
|
Example of error handling using the command
ONERROR GOTO :
ONERROR
GOTO
Error_Handler
Print
"start"
Print
3/0
' this generates a divide by zero
error
Print
space$(60000)
' this generates an out of memory
error
End
Error_Handler:
Print
"Error text
"; BAS.ErrMsg$
Print
"Error
num "; BAS.ErrNum
Print
"Error line
"; BAS.ErrLine
Return
' returns to
the line following the error
|
When a client
connects to the module using its IP address, the module will
redirect automatically to the url ‘/output?menu’, which sends an
empty html page present on the module.
That page contains
a bunch of javascript code permitting to interface the page with
the module using javascript.
This page will
automatically open a websocket connection with the module; the
"squared led" indicates if the connection was successful (green) or
not (red).
A mechanism of ping
- pong has been implemented into the javascript in order to hold
the connection alive all the time. If the connection is lost, the
page will try to reconnect automatically without any manual
action.
The button
"reconnect" permits to force the reconnection if the automatic
reconnection fails.
As soon as the
connection is done with the module, the html page is ready to send
and receive messages to / from the module.
Initially the page
is empty but its content can be easily filled.
To send HTML code
to the page, the command HTML is used.
The syntax is :
HTML HTML code.
For example the
line
HTML
"Hello, world <br>This is my first html
content<br>"
Will give this
result :
Continuing with the
HTML command, the content can be improved :
HTML
"Textbox: <input
type='text'><br>"
Continuing
again:
HTML
"Button: <button type='button'>Click
Here</button>"
All the html code
can be combined and sent with just one HTML command; this is much
faster:
a$ =
"Hello, world <br>This is my
first html content<br>"
a$ = a$
+ "Textbox: <input
type='text'><br>"
a$ = a$
+ "Button: <button type='button'>Click
Here</button>"
HTML
a$
|
To clear the
content of the page, the command is:
CLS
Now we can try
another example
CLS
a$ =
"Now style me,
please<br>"
a$ = a$
+ "Button1: <button id='but1'
type='button'>ON</button> "
a$ = a$
+ "Button2: <button id='but2'
type='button'>OFF</button>"
HTML
a$
Now we will try to
style the buttons using css.
This can be done
using command CSS CSSID$()
For example the
line
CSS
CSSID$("but1",
"background-color:
red;")
Will give this
result :
Combining with the
style for the other button:
a$ = a$
+ cssid$("but1",
"background-color:
red;")
a$ = a$
+ cssid$("but2",
"background-color:
green;")
CSS
a$
A set of functions
is included to simplify the creation of HTML pages as we will see
later, so no need to worry if you are not familiar with writing
HTML code.
Now we will mention
an important ‘event’ that can be used to automatically fill the
content of the page each time a client connects to the module :
OnHtmlReload.
This ‘event’
defines a place where the program will jump to as soon as a
Websocket connection request is accepted.
Let’s clarify with
an example :
OnHtmlReload
Fill_Page
‘will jump to Fill_Page when the
page is reloaded
gosub
Fill_Page
'load the page for the first
time
Wait
‘pause waiting for the event
Fill_Page:
‘place where the page begins to
be created
CLS
a$ = "Now style me,
please<br>"
a$ = a$ +
"Button1: <button id='but1'
type='button'>ON</button> "
a$ = a$ +
"Button2: <button id='but2'
type='button'>OFF</button>"
HTML
a$
a$ = cssid$("but1",
"background-color:
red;")
a$ = a$ +
cssid$("but2",
"background-color:
green;")
HTML
a$
RETURN
|
The result will
be:
Now try to play
with the button "Reconnect"; you’ll see that, at each time the page
reconnects to the module, the HTML content is built and sent again.
This ensures that each time a client connects to the module it will
receive the correct content. At the same time, if other clients are
already connected, the content of all the pages will be refreshed
simultaneously. This ensures a synchronized content between all the
clients.
As said previously,
in order to simplify the creation of HTML pages there are several
functions available which can generate the html code
automatically.
Let’s start with
the button.
A button is an
object that is used to trigger an action each time it is pressed on
the web page.
The function is
BUTTON$.
Let’s explain with
an example:
CLS
HTML
BUTTON$("Button1", jump1)
Wait
'pause waiting for the
event
Jump1:
PRINT
"Clicked on Button1"
Return
|
The result will
be:
Try clicking on the
button then checking the result in the terminal console; the
message "Clicked on Button1" will be shown at each click.
To style the
button, we need to modify the syntax of the BUTTON$
command slightly; in fact we need to add another parameter to give
the button an ID:
CLS
HTML
BUTTON$("Button1", jump1, "but1") '
"but1" is the ID
Wait
'pause waiting for the
event
Jump1:
PRINT
"Clicked on Button1"
CSS
cssid$("but1",
"background-color:
red;") 'the same ID is used here
Return
|
Clicking on the
button now will change its color to red
Now we can now
introduce the LED object. The LED object is a circle that can be
filled in red or green depending on the content of a variable. The
function is LED$
As usual, let’s
start with an example:
CLS
led = 1 ‘this is the variable
associated with the LED. With 0 the led is red, with 1 the led is
green
HTML
LED$(led)
|
The result will
be:
Let’s also add a
button :
CLS
led
= 0
a$
= BUTTON$("Button1", jump1, "but1") '
"but1" is the ID
a$
= a$ + LED$(led)
HTML
a$
Wait
'pause waiting for the
event
Jump1:
PRINT
"Clicked on Button1"
led
= 1 -
led ' invert the
variable
REFRESH
' refresh (update) the variables between the code
and the html
Return
|
The result will
be:
Clicking on the
button will toggle the led between red and green colors.
The command
REFRESH
permits to update (synchronize) the variables in the code with the
corresponding objects variables on the web page. It should be run
each time a variable is modified.
As a simpler
alternative, the command AUTOREFRESH
will regularly sync the variables.
The command must be
run with the desired refresh timing.
Example
AutoRefresh
500 will refresh the variables each 500
milliseconds.
The interval
should not be less than 300 milliseconds (otherwise the module will
be too busy).
The example :
CLS
led = 0
a$ = BUTTON$("Button1", jump1, "but1") '
"but1" is the ID
a$ = a$ +
LED$(led)
HTML
a$
AutoRefresh
300
'sync each 300
milliseconds
Wait
'pause waiting for the
event
Jump1:
PRINT
"Clicked on Button1"
led = 1 - led
' invert the
variable
Return
|
The result will be
the same as the previous example.
Now it’s time to
introduce another object; the TEXTBOX with the corresponding
function TEXTBOX$.
The TEXTBOX will
display a ‘text box’ on the web page which is linked with a
variable. When the variable is modified in the code, the TEXTBOX
content will be updated on the web page, and vice-versa.
This lets us
introduce another ‘event’, the OnHtmlChange
command.
This ‘event’
defines a branch for the program to jump to whenever a variable is
modified inside the web page.
As usual, let’s
start with an example:
CLS
text$ = "Change me,
please"
HTML
TEXTBOX$(text$)
OnHtmlChange
Jump1
'will jump to Jump1 when a variable
changes on the web page
Wait
'pause waiting for the
event
Jump1:
Print
text$
'print the content of the variable
inside the terminal console
Return
|
Try now to change
the content of the textbox and press "Enter" on the keyboard.
Let’s see the
result in the terminal console:
With the concepts
already learned you’ll be able to use the other objects using the
similar logic.
Refer to the pages
below to understand the syntax of each object.
A timer is an "object" that permits the
execution of a particular action at regular intervals.
When the given time expires, the normal
execution of the program is interrupted while control is passed to
the "timer interrupt routine" until after the execution of the
return command.
Then the program continues from the point
where it was interrupted.
Let’s explain with an example :
timer0
1000,
mytimer
wait
mytimer:
wlog "mytimer " +
time$
return
|
Annex WI-Fi Basic
implements 2 timers, Timer0 and Timer1.
The Timer0 has a
higher priority against Timer1.
Many of the actions
are not executed directly by basic commands but can be executed as
asynchronous events.
An "event" is
simply an action that can be executed when something happens.
For example, pin
change interrupts are asynchronous events which can happen at any
time without user control.
In order to manage
the events, a list of commands "ONxxxx" is provided. These commands
define the place where the normal execution of the program will
branch to when the event occurs.
So, when the
"event" happens, the basic interpreter interrupts the normal
execution of the code and "jumps" to the location defined by the
corresponding command "ONxxx". As soon as the code associated with
the "event" is terminated with the command "return", the basic
interpreter continues from the previous interrupted location.
This is a special event that happens every
time aBUTTON$
object is clicked in the HTML pages.
When this happens,
a special variable
HtmlEventButton$ is created containing the name of the
button that was clicked.
This is useful to
determine the button within a group of buttons.
Let’s see an
example:
CLS
HTML
Button$("ON",
buttonEvent) +
" " + Button$("OFF",
buttonEvent)
wait
buttonEvent:
print
"You clicked
on ";
HtmlEventButton$
return
|
This event is triggered when an object present
in the HTML output page changes its value.
It is useful to make actions when something
changes in the HTML Pages.
When this event
happens, a special variable
HtmlEventVar$ is created containing the name of the
variable that changed its value.
This is useful to
determine the object that generated the event.
Let’s see an example :
CLS
text$ = "Change me,
please"
HTML
TEXTBOX$(text$)
OnHtmlChange
Jump1
'will jump to Jump1 when a variable
changes on the web page
Wait
'pause waiting for the
event
Jump1:
Print
text$
'print the content of the variable
inside the terminal console
Return
|
Note that the
special variable
HtmlEventVar$ is only created when the OnHtmlChange
event populates it due to a html object change, therefore it will
cause an error if tested for before an object is changed unless
specifically defined beforehand, eg: HtmlEventVar$ =
“”
This event is triggered when a Websocket
connection request is accepted.
This can be used to automatically fill the
content of the WEB page each time a client connects to the
module.
Let’s see an example :
CLS
OnHtmlReload
Fill_Page
'will jump to Fill_Page when the page
is reloaded
gosub
Fill_Page
'load the page for the first
time
Wait
'pause waiting for the
event
Fill_Page:
'place where the page begins to be
created
CLS
a$ = "Now style me,
please<br>"
a$ = a$ +
"Button1: <button id='but1'
type='button'>ON</button> "
a$ = a$ +
"Button2: <button id='but2'
type='button'>OFF</button>"
HTML
a$
a$ = cssid$("but1",
"background-color:
red;")
a$ = a$ +
cssid$("but2",
"background-color:
green;")
HTML
a$
Return
|
This event is
triggered when a code is received by the infrared receiver.
Refer to chapter
INFRARED
INTERFACE for more details.
This event is
triggered when a message is received on the serial port.
Example:
print
"Ram Available "; ramfree
onserial rec1
wait
rec1:
'print serial.input$
print serial.chr$;
return
|
This event is
triggered when a message is received on the serial port #2.
Example
serial2.mode 9600, 2, 5
' set serial port #2 to 9600 pin 2 TX,
pin 5 RX
print2 "Ram Available "; ramfree
onserial2 rec2
wait
rec2:
print serial2.input$
return
|
This event is
triggered when the TFT screen is touched.
Refer to the
chapter TouchScreen for more details.
This event is
triggered when a UDP message is received.
Example:
udp.begin
5001
'set the UDP commmunication using port
5001
onudp
goudp
'Write several messages to the port
for i
=
0 to 100
udp.write
"192.168.1.44",
5001,
"Hello "
+
str$(i)
next i
wait
goudp:
v$
=
udp.read$
'receive the UDP data
print
v$
return
|
This event is
triggered when a WgetAsync message is received.
This is associated
with the command
WGETASYNC.
The goal of the
WGETASYNC command is to start a html get request without
the module having to wait for the answer.
Because the
response is async, this command specifies the location where the
program should branch to when a message is received.
Example:
ONWGETASYNC
answer_done
WGETASYNC("www.fakeresponse.com/api/?sleep=5",
80)
For
i =
0 to
10000
' a
kind of sleep just to demonstrate that the code continue to
run
Print i
Next
i
Wait
answer_done:
Print
WGETRESULT$
Return
|
This event is
triggered as soon as a web client requests for a web page with the
url composed with http://local_ip/msg?param=value.
This kind of request is typically called an AJAX request as it
permits to exchange in both directions between the client (the web
browser) and the server (the ESP module).
In fact, in the url
request, the client can send parameters in the form of couples of
"param=value" separated by the character "&". For example, if
the client wants to send 2 parameters, it can send the following
request :
http://local_ip/msg?param1=value1¶m2=value2.
As soon as this
message is received by the ESP module, the event OnUrlMessage is
triggered; this means that the program will continue from the
location defined by the command OnUrlMessage.
As soon as the
message is received, the parameters sent by the client can be got
with the function UrlMsgGet$ and a message can be sent back to the
client with the command UrlMsgReturn.
Let’s see an
example :
onUrlMessage
urlAjax
wait
urlAjax:
wlog
"message received " + UrlMsgGet$("a")
+ "
" + UrlMsgGet$("b")
UrlMsgReturn
"Message sent back " + time$
print
UrlMsgGet$("b"),
ramfree
return
|
Now using another
web browser window, let’s type the following url :
http://esp_local_ip/msg?a=10&b=20
As you can see in
the following picture, the message is received by the ESP
module
At the same time,
the client receives the message sent back from the ESP module
If the program is
stopped, the module will answer with the message "STOPPED"
Now, let’s see a more complete example :
cls
' this is the
default value for pwm out
R
= 512
G
= 512
B
= 512
'Setup the
pwm channels
PWM.SETUP
12, 1, R,
10000, 10
PWM.SETUP
15, 1, G,
10000, 10
PWM.SETUP
13, 1, B,
10000, 10
'Set the
default values
PWM.OUT
1,
R
PWM.OUT
2,
G
PWM.OUT
3,
B
' these are
the sliders
a$
= ""
a$
= a$ + |R <input
type="range" id="dimmer_R" oninput="setPWM()" onclick="setPWM()"
min="0" max="1023" value="| & str$(R)
& |"/><br>|
a$
= a$ + |G <input
type="range" id="dimmer_G" oninput="setPWM()" onclick="setPWM()"
min="0" max="1023" value="| & str$(G)
& |"/><br>|
a$
= a$ + |B <input
type="range" id="dimmer_B" oninput="setPWM()" onclick="setPWM()"
min="0" max="1023" value="| & str$(B)
& |"/><br>|
a$
= a$ + |<input
type='text' id="txbox" value='---'>|
html
a$
'this is the
javascript "AJAX" code
fun$
= |function setPWM() {|
fun$
= fun$ & |r=_$("dimmer_R").value;|
fun$
= fun$ & |g=_$("dimmer_G").value;|
fun$
= fun$ & |b=_$("dimmer_B").value;|
fun$
= fun$ & |var xmlHttp =
new XMLHttpRequest();|
fun$
= fun$ & |xmlHttp.open("GET", "msg?r=" + r +"&g=" + g
+"&b=" + b, false);|
fun$
= fun$ & |xmlHttp.send(null);|
fun$
= fun$ & |r =
xmlHttp.responseText;|
fun$
= fun$ & |_$("txbox").value = r;|
fun$
= fun$ & |return
r;}|
' this is
where the javascript code is inserted into the html
jscript
fun$
'this is
where the prog will jump on slider change
onUrlMessage
message
wait
message:
print
UrlMsgGet$()
PWM.OUT
1,
val(UrlMsgGet$("r"))
PWM.OUT
2,
val(UrlMsgGet$("g"))
PWM.OUT
3,
val(UrlMsgGet$("b"))
UrlMsgReturn
UrlMsgGet$()
return
|
Open the input page in another window and run
the program
Using an external RGB led, you’ll be able to
directly control its color.
You’ll see how the exchanges can be fast using
AJAX exchanges. This program uses javascript embedded into the
code. The javascript works with the function XMLHttpRequest.
A good reference for this function is here
AJAX - Send a Request To a Server
This event is
triggered when a ESP-NOW message is received.
Example:
espnow.begin
' init the ESP-NOW
onEspNowMsg message
' set the place where jump in case of message
reception
wait
message:
print "Message
Received!"
return
|
This event is
triggered when a ESP-NOW transmission error occurs.
This happens, in
particular, when the receiver device has not received the
message.
espnow.begin
' init the ESP-NOW
espnow.add_peer "60:01:94:51:D0:7D"
' set the MAC address of the receiver
onEspNowError status
' set the place where jump in case of TX error
espnow.write "TX
message"
' send the message
wait
status:
print "TX
error on ";
espnow.error$
' print the error
return
|
This event is generated when a MQTT message is
received or an MQTT event happens
Example:
....
onmqtt
mqtt_msg
wait
' receive messages from the server
mqtt_msg:
print
"TOPIC : ";
mqtt.topic$
print
"MESSAGE: ";
mqtt.message$
return
|
This event is generated when a “metadata” is
decoded when playing mp3 or streaming a web radio.
At startup, the module will try to
connect to the router using any parameters specified in the page
“Config”.
If no parameters are specified in
the “Config” page, or the connection is unsuccessful, it will
default to AP (Access Point) mode with IP address 192.168.4.1 with
the SSID composed of ESP(+ mac address).
If the connection is successful,
the module will use the IP address defined in the “Config” page or,
if no IP address is specified, the IP will be given automatically
by the Router DHCP server.
After the module has connected to
the router it will try to reconnect automatically if the connection
is lost.
There are several commands /
functions available to manage the WIFI.
The first function is
WIFI.STATUS which permits to get the status of
the connection.
print
WIFI.STATUS ’ print 3 if connected, 6 if
disconnected
The first useful command is
WIFI.CONNECT
SSID$, password$ [,
BSSID$] [, IP$ , MASK$ [, GATEWAY$]]
This command allows you to connect
to any WIFI network (STA mode) overriding the parameters defined
into the’ “Config” page. This function is async so the connection
is done in background, while the program continues to
run.
Is then possible to check the
status of the connection using the function
WIFI.STATUS
Example :
WIFI.CONNECT
"HOMENET", "MyPassword"
print
"connecting"
While
WIFI.STATUS <>
3
Print "."
pause 500
wend
Using the optional
parameter
BSSID$,
will enable the connection to a specific WiFi access
point.
The BSSID represents the MAC
address of the WiFi access point (the router) and it is defined as
6 bytes in hex format separated by colon, i.e.
AA:BB:CC:12:34:56.
For stand alone configuration or
for ESP-NOW applications, there is another command that puts the
module in AP mode.
This command is
WIFI.APMODE
SSID$,
password$ [, channel]
[,
IP$ , MASK$]
The result is immediate and the
status can be checked using the function
WIFI.MODE (see below).
The channel is optional and is 1
by default.
IMPORTANT : the password must be at
least 9 characters
It is eventually possible to
control the output power of the module with the command
WIFI.POWER pow
WIFI.POWER 5
’ set the output power
at 5 dBm.
The module can also be put in WiFi sleep mode.
This mode permits to turn off the WiFi reducing the power
requirements of the module; this is very useful for battery
oriented applications or for applications where the WiFi is not
required.
To put the module in “modem-sleep”, the
command to execute is
WIFI.SLEEP.
The module will stay in that mode until the
execution of the command
WIFI.AWAKE.
After this command, the module will reconnect
automatically to the router (the command
WIFI.CONNECT is not required).
Another function available
is
WIFI.CHANNEL that shows the current Radio
Channel used by the WIFI.
Using the function
WIFI.RSSI is it possible to get the
intensity of the signal received (RSSI)
It is also possible to scan for
the WiFi networks accessible around the module.
This can be done using the
command
WIFI.SCAN and the function
WIFI.NETWORKS(network$).
Example :
WIFI.SCAN
While
WIFI.NETWORKS(A$)
<
0
Wend
Print
a$
The result will be :
Vodaphone, 00:50:56:C0:00:08,
-50, 5
Orange, 00:50:56:C0:32:07, -70,
5
Xxxx,
00:50:56:C0:86:CA,-78, 12
These information represent, in
the order :
SSID, BSSID(mac address),
RSSI(signal intensity), Channel Radio
The function
WIFI.MODE returns the current mode of the WIFI
connection as below:
VALUE
|
MEANING
|
0
|
The WIFI is in sleep
mode
|
1
|
The WIFI is in STATION
mode
|
2
|
The WIFI is in AP mode
|
3
|
The WIFI in AP+STA mode
|
The WIFI in AP+STA mode can
be obtained by configuring the module in AP mode and then using the
command
WIFI.CONNECT in the program.
Using a “fake” SSID / password
(example
WIFI.CONNECT
"A",
"" ) can be used to switch the WIFI
into the AP+STA mode. This can be useful for mixed ESP32 /
ESP8266 ESP-NOW operations.
Another Wifi related command
is
OPTION.MAC
mac$ that
permits to modify the MAC address of the module.
This is very important for the ESP
Now functionality.
Example :
OPTION.MAC
"AA:BB:CC:DD:EE:FF"
In addition, the functions
BAS.SSID$ and
BAS.PASSWORD$ returns respectively the login and
the password used for the STATION wifi connection.
If a program is defined to run automatically
(“Autorun File” in the config page), the WiFi connection process is
slightly different.
If the option “Fast boot” in the config page
is selected, the program will be executed immediately and the WiFi
will be powered ON after a little delay ( 0.1 sec ).
If the command
WIFI.SLEEP is executed during the very beginning of the
program ( for example as the first line of the program) the WiFi
will be simply disabled without using any power.
This enhances the use of the module in low
power applications (i.e. on battery).
The WiFi connection can then be restored later
using the commands
WIFI.CONNECT or
WIFI.APMODE.
If the command
WIFI.SLEEP is not executed at the beginning of the
program, the WiFi connection will be established by default as
described in the previous chapter (WiFI CONNECTIONS).
The function
BAS.RESETREASON can be used at the beginning of the
program to understand the reasons for the restart of the module
enabling it to take the appropriate actions.
In addition, the function
BAS.WAKEUPREASON can be used to determine the cause of
the wakeup from sleep if the module was in deep sleep mode.
In case of any IP or Autorun problem
preventing the module from being accessed, it is possible to
temporarily bypass the IP settings of the module and disable the
Autorun file by connecting the serial TX and RX pins together
(GPIO1 to GPIO3) during the startup phase (power up).
This could happen if, for example, a wrong IP
address has been set.
Doing this action when restarting the module
will put it in AP mode with the IP address at 192.168.4.1, just
like a module that has not been configured.
A message “Recovery Mode” will be printed on
the console, but none of the existing files on the module will be
modified, including the internal configuration parameters.
In this mode it will be possible to gain
access to the module for changing such correct wrong IP parameters
using the configuration page.
When the TX/RX link is removed, the module can
be rebooted to the configured settings at the next restart.
The module can be put into low energy mode to
minimise as much as possible the power requirements.
This mode is called deep sleep and
should reduce the power consumption to a few µA but this is a
function of each ESP32 module as the power requirement
includes the different components installed on the module.
When the module is put into deep sleep all the
module activities are stopped, all the memory content of the module
is lost except for the RTC memory (this is a special memory block
inside the module that holds its content even if the module is
reset, but not when the module is powered OFF).
At the end of the sleep period, the
module restarts and reloads the program defined as autorun from the
beginning (from the first line).
To put the module in deep sleep the following
command is available :
SLEEP
value [, pin, level]
This command puts the ESP32 in deep sleep (low
energy) for 'value' seconds.
At the end of the period, the unit will reboot
and reload the default basic program.
Example
' Sleeps for 600 seconds (10 minutes)
The period can go from 1 second to
several years (1 year = 31,536,000 seconds)
Optionally, it is possible to wake up the
module using an external signal sent on an input pin
In this case the pin and the level must be
specified in addition to the time value.
Example
' Sleeps for 3600 seconds (1 Hour) or until the pin 32 goes to
high
SLEEP
3600, 32, 1
Only RTC IO can be used as a source for
external wake up.
They are pins: 0,2,4,12-15,25-27,32-39.
Level is 1 for wakeup on High and 0 for wakeup
on Low
Optionally, this command can be also used to
wake up the module using the capacitive touch on an input pin.
In this case the command SLEEP maintains the
same syntax but level defines the threshold value for the pin.
Only the following pins can be used for that
purpose (capacitive touch) : 0, 2, 4, 12, 13, 14, 15, 27 32, 33
Level must be > 1 to enable the touch (0
and 1 are reserved for the wake up on Low or Wake up on High).
Example
' Sleeps for 3600 seconds (1 Hour) or until the pin 15 is
touched
SLEEP
3600, 15, 40
' Threshold at 40
The RTC memory will survive after the wake up
permitting to take trace of the actions done before the sleep.
This memory can be set as below :
BAS.RTCMEM$ =
"data to be saved during deep sleep"
And can be read as below :
A$
=
BAS.RTCMEM$
Note : the RTC memory can hold up to 7680
bytes
The ESP module normally synchronises its date
and time from either of two NTP time servers ("pool.ntp.org" and
"time.nist.gov"). Optionally an alternative (eg: intranet) time
server can be defined using the [CONFIG] page.
Using these servers the ESP doesn’t require
any date/time setting (except the configuration of the Time Zone
and DST done using the [CONFIG] page).
The timezone is defined as a string
likeCET-1CEST,M3.5.0,M10.5.0/3
that describes how the local time must be managed in terms of time
shift and DST (summer / winter time).
A complete list of timezone strings can be
found here :
https://github.com/nayarsystems/posix_tz_db/blob/master/zones.csv
An internal timekeeper has been included if no
time server is available, e.g. no available internet access.
This timekeeper starts from 01/01/1970
00:00:00 and counts the seconds since the power on of the
module.
If internet connection becomes available
later, the internal timekeeper will sync its time with the NTP
servers.
The time can be sync with the NTP time server
at any moment using the command
OPTION.NTPSYNC.
This time and date can be manually set using
the command SETTIME.
The Syntax is :
SETTIME year, month, day, hours, minutes,
seconds
Example
Set the date to 02 September 2017 at
13:58:12
SETTIME 17, 9, 2,
13, 58, 12
The time and date can also be
manually synchronised to the computer using the "Time Sync" button
in the File Manager window of the computer utility ‘tool’ if it has
a websocket connection.
WARNING:
In both cases of manual
setting, the time and date will default back to 1970 defaults at
the next module restart, so will require setting
again.
For more information about the
Time Zones and DST, please consult the following page
:
Time Zone and
DST
It is also possible to connect
an RTC (DS1307 or DS3231) to the module.
See the chapter
“RTC
Module”
for more details.
The following functions use the
“Unix Time Stamp” format :
DATEUNIX(date$),
TIMEUNIX(time$),
UNIXDATE$(value [,format]),
UNIXTIME$(value)
The “Unix Time Stamp” is a way
to track time as a running total of seconds.
This count starts at the Unix
Epoch on January 1st, 1970 at UTC.
Therefore, the unix time is
merely the number of seconds between a particular date and the Unix
Epoch.
In synthesys :
-
DATEUNIX("01/01/18")
returns the number
of seconds from 01/01/1970 to the specified date 01/01/2018
(1514764800)
-
TIMEUNIX("12:30:55")
returns the number
of second since midnight (45055)
-
UNIXDATE$("1532773308")
returns
28/07/18
-
UNIXTIME$(1532773308)
returns
10:21:48
Annex32 includes a
FATFS file system hosted on the flash memory chip.
It “emulates” a
disk file system enabling it to save and load files in a
transparent way.
Depending on the
size of the flash chip, the following free space is available :
Flash Chip size
|
Free space available
|
4M
|
1MB
|
[6] 8M
|
5MB
|
16M
|
13MB
|
Annex32 can also
use an SD CARD connected as described in the chapter SD CARD
ADAPTER.
Both the internal
FATFS and the SD CARD utilise the FAT32 file system
This means that
there are no particular limitations in terms of filename length and
directories, compared to the SPIFFS file system limitations hosted
in the ESP8266.
Unlike normal
variables, filenames and folders are case sensitive.
Annex32 supports SD
CARDS up to 16GB.
The internal and the external (SDcard)
space are mutually exclusive and cannot be accessed at the same
time.
By default Annex32 will use the SD, if
available, otherwise it will use the internal flash disk space
(FATFS).
Both the
internal FATFS and external SD CARD share the same command and
functions.
All the file
related functions share the same prefix FILE.
followed by the specific function.
FUNCTIONS / COMMANDS
|
DESCRIPTION
|
FILE.COPY(filename$,
newfile$)
|
Copy the file filename$
into the file newfile$
Returns 1 in case of success or
0 if error
|
|
Delete the file specified by filename$
Returns 1 in case of success or
0 if error
|
|
Returns 1 if filename$
exists, otherwise returns 0
|
|
Rename the file oldname$
to newname$
Returns 1 in case of success or
0 if error
|
|
Returns the size of the file (in bytes) if the
file exist, otherwise returns -1
|
|
Create a directory specified by
dirname$
Returns 1 in case of success or
0 if error
|
|
Remote the directory specified by
dirname$
Returns 1 in case of success or
0 if error
|
|
Will search for files and return the names of
entries found.
path$
represents the directory name.
path$ can
include wildcards characters as ‘*’,
‘.’ and
‘?’
The function will return the first entry
found.
To retrieve subsequent entries use the
function with no arguments. ie,
FILE.DIR$.
The return of an empty string indicates that
there are no more entries to retrieve.
|
FILE.READ$(filename$,
[line_num] | [start, length])
|
Returns the content of the file
filename$.
Specifying line_num,
only the corresponding line is read from the file.
If start
and length
options are specified, the file is read from the start
position for length
characters, otherwise the complete file is read in one go
The line number
starts from 1.
If the line is not
existing (reached the end of file), the function will return
“_EOF_” to indicate the end of the file.
|
|
Append the content of content$
to the file filename$.
If the file does not exist, it will be
created.
The file can be read back using the function
FILE.READ$(filename$)
File size is only limited by available disk
space (internal FFAT or external SD card)
|
FILE.SAVE
filename$,
content$
|
Save the content of content$
to the file filename$.
The file can be read back using the function
FILE.READ$(filename$)
File size is only limited by available disk
space (internal FFAT or external SD card)
|
|
Same functionalities as the previous
command.
Implemented for homogeneity with other
commands
|
|
Convert the file defined ‘source$’ into the
file defined in ‘dest$’.
The source file can be in any format but must
be encoded in base64 format. Useful for wokwi to store any file in
text format
|
|
Convert the file defined ‘source$’ into the
file defined in ‘dest$’.
The source file can be in any format and will
be encoded in base64 format.
|
|
See the chapter I/O buffer for more
details
|
[7] FILE.WRITE_IOBUFF
|
See the chapter I/O buffer for more
details
|
[8] FILE.APPEND_IOBUFF
|
See the chapter I/O buffer for more
details
|
|
See the chapter I/O buffer for more
details
|
Examples:
List all the files
in the directory /html
d$
= FILE.DIR$("/html")
While D$
<> ""
wlog d$
d$
= FILE.DIR$
Wend
|
File operations
file.save
"/test.bas",
"The quick brown fox "
wlog
"exists",
file.exists("/test.bas")
wlog
"size",
file.size("/test.bas")
file.append
"/test.bas",
"jumps over the lazy dog"
wlog
"size",
file.size("/test.bas")
wlog
"copy",
file.copy("/test.bas",
"/AAA.bas")
wlog
"size",
file.size("/AAA.bas")
wlog
"rename",
file.rename("/AAA.bas",
"/BBB.bas")
wlog
"size",
file.size("/BBB.bas")
wlog
"size",
file.size("/AAA.bas")
wlog
"read",
file.read$("/test.bas")
wlog
"delete",
file.delete("/BBB.bas")
|
The command
retrieves a file from a specified URL (url$) and saves it
to the local file path (file_path$). This
can be used both as a standalone command or as a function that
returns a status code, indicating the success or failure of the
download operation.
●
url$: A string specifying the URL of the file to download.
This should be a valid HTTP or HTTPS URL.
●
file_path$: A string specifying the local path where the
downloaded file should be saved.
When used as a function,FILE.DOWNLOAD
returns an integer value that indicates the status of the
download:
●
1: Download completed successfully.
●
-1: Not enough space available to download the file.
●
-2: Failed to open the file for writing.
●
-3: Failed to create an HTTP client.
●
Other HTTP error codes: Various HTTP error codes that may be
returned by the server (e.g., 404 for "Not Found", 500 for
"Internal Server Error").
This command is
also useful for downloading (copying) a file from another Annex RDS
module. By providing the appropriate URL, you can easily transfer
files between modules, which is especially useful for distributing
updates or configurations across multiple devices.
● The
function handles both HTTP and HTTPS URLs, using a secure
client
● The
function checks for available space before attempting the download
and will abort if there is insufficient space.
● All
operations are logged to the serial output for debugging
purposes.
Example 1:
download from the WEB
FILE.DOWNLOAD
"https://updates.cicciocb.com/annex-logo.png",
"/logo.png"
or
Wlog
FILE.DOWNLOAD("http://updates.cicciocb.com/annex_bee_new.png",
"/logo2.png")
Example 1:
download from another Annex RDS Module with IP: 192.168.1.181
FILE.DOWNLOAD
"http://192.168.1.181/program1.bas",
"/program1.bas"
or
Wlog
FILE.DOWNLOAD("http://192.168.1.181/program1.bas",
"/program1.bas")
print file.download
("https://updates.cicciocb.com/annex-logo.png", "/logo.png")
The I/O BUFFER is a functionality that gives
the capability to hold and manage binary data.
In short, the I/O buffer is a block of RAM
memory that can be exchanged as a block or read and written byte
per byte. It overcomes the limitation of strings, which are
unable to include the character ASCII 0 (NUL).
It has a defined length and can be freely
dimensioned and cleared.
It can be used in the code using the
IOBUFF keyword, and Annex exposes 5 I/O buffers numbered
from 0 to 4.
The I/O buffers can have any size within the
limits of the free RAM memory available.
The main goal of this functionality is to
interface with all the functions that require exchanges using
binary data.
In the current implementation it can be used
with :
-
Files
-
Serial Ports
-
SPI
-
I2C
-
UDP
This command
allocates memory for an I/O buffer by defining its size.
●
Parameters:
○
buff_num:
Specifies the buffer ID, ranging from 0 (first buffer) to
4 (last buffer).
○
size:
Specifies the size of the buffer in bytes. The value can range from
0 to the maximum available RAM.
●
Return Value:
○ The
size of the allocated memory or 0 in case of error
●
Behaviour:
●
Allocates the specified amount of memory to the selected
buffer.
● The
buffer retains its size until it is manually destroyed or the
program ends.
Example:
IOBUFF.DIM(0,
1000) 'dimension the I/O buffer 0 with 1000
bytes
Print
IOBUFF.DIM(1,
25) 'dimension the I/O buffer 1 with 25 bytes (prints
25)
|
IOBUFF.DIM(buff_num,size)
= data_list
The
IOBUFF.DIM command can also initialise a buffer with a
sequence of values during its creation.
●
Parameters:
○
buff_num:
Specifies the buffer ID, ranging from 0 (first buffer) to
4 (last buffer).
○
size:
Specifies the size of the buffer in bytes. The value can range from
0 to the maximum available RAM.
○
data_list:
A list of values (e.g., integers, hexadecimal, binary) to store in
the buffer.
●
Return Value:
○ The
size of the allocated memory or 0 in case of error
●
Behaviour:
○
Reserves memory for the buffer and populates it with the specified
values.
Example:
' Fills buffer 0 with 10 values
Print
IOBUFF.DIM(0,
10) = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
' prints 10
' Fills buffer 1 with 5 values
IOBUFF.DIM(1,
5) = &h12,
&hAA, &h50, &O377, &B10101010
|
Releases the memory allocated to a specific buffer.
●
Parameters:
○
buff_num:
Specifies the buffer ID to be destroyed (0–4).
●
Return Value:
○
Always 0
●
Behaviour:
○
Frees the memory allocated for the specified buffer.
○
After destruction, the buffer is no longer accessible until
reallocated.
Example:
IOBUFF.DESTROY(0)
' Destroys buffer 0, releasing its
allocated memory
|
Note: All buffers are automatically destroyed when the
program ends.
Returns the current size (in bytes) of the specified buffer.
●
Parameters:
○
buff_num:
The ID of the buffer to query (0–4).
●
Return Value:
○ The
size of the buffer in bytes.
Example:
Print
IOBUFF.LEN(0)
' Prints the size of buffer
0
|
Reads a single byte from a specified position in a buffer.
●
Parameters:
○
buff_num:
The ID of the buffer to read from (0–4).
○
position:
The byte position to read (0 to buffer length - 1).
●
Return Value:
○ The
value of the byte at the specified position (0–255).
Example:
Print
IOBUFF.READ(0,
4) '
Prints the byte at position 4 from buffer 0
A =
IOBUFF.READ(0, 7)
' Stores the byte at position 7 in
variable A
|
IOBUFF.WRITE(buff_num,position,
value)
Writes a single byte to a specified position in a buffer.
●
Parameters:
○
buff_num:
Specifies the buffer ID to be destroyed (0–4).
○
position:
The byte position to read (0 to buffer length - 1).
○
value:
The byte value to write (0–255).
●
Return Value:
○
Always 0
●
Behaviour:
○
Updates the specified position in the buffer with the given
value.
Example:
IOBUFF.WRITE(0,
5, 123) ' Writes the value 123 at position 5 of buffer
0
|
The I/O buffers communicate with the other
modules using the following syntax:
-
xxxx.READ_IOBUFF(buff_num)
Receive data in the
buffer buff_num
-
xxxx.WRITE_IOBUFF(buff_num,
start, size)
Transmit (send)
data from the buffer buff_num
starting from the position ‘start’
for ‘size’
bytes
-
xxxx.REPLY_IOBUFF(buff_num,
start, size)
Reply to the sender
data from the buffer buff_num
starting from the position ‘start’
for ‘size’
bytes
Where
xxxx can be :
UDP
SERIAL
SERIAL2
FILE
I2C
SPI
Detailed syntax :
UDP.READ_IOBUFF(buff_num)
SERIAL.READ_IOBUFF(buff_num)
SERIAL2.READ_IOBUFF(buff_num)
FILE.READ_IOBUFF(buff_num),
filename$ [, position, nb_of_bytes_to_read]
I2C.READ_IOBUFF(buff_num),
address, register, nb_of_bytes_to_read
SPI.READ_IOBUFF(buff_num),
nb_of_bytes_to_read
UDP.WRITE_IOBUFF(buff_num
[, start [, size]]), IP$,
port
SERIAL.WRITE_IOBUFF(buff_num
[, start [, size]])
SERIAL2.WRITE_IOBUFF(buff_num
[, start [, size]])
FILE.SAVE_IOBUFF(buff_num
[, start [, size]]),
filename$
FILE.WRITE_IOBUFF(buff_num
[, start [, size]]),
filename$
FILE.APPEND_IOBUFF(buff_num
[, start [, size]]),
filename$
I2C.WRITE_IOBUFF(buff_num
[, start [, size]]), address,
register
SPI.WRITE_IOBUFF(buff_num
[, start [, size]])
UDP.REPLY_IOBUFF(buff_num
[, start [, size]])
[,port]
SPI.REPLY_IOBUFF(buff_num
[, start [, size]]), (buff_num_reception)
The IOBUFFER can be used for sending or
receiving data.
When used for receiving data, the syntax is
always.READ_IOBUFF(buff_num).
When receiving data, it is not necessary to
dimension the buffer before as it will be automatically dimensioned
depending on the size of the data received. If the buffer was
already containing some data, these will be flushed and replaced by
the new data.
For example, the following command receives
all the data available from the serial port 2 in the buffer 3 :
SERIAL2.READ_IOBUFF(3)
This command receives the data coming from an
UDP connection in the buffer 1:
UDP.READ_IOBUFF(1)
Additionally some other arguments may be
required.
This command reads 512 bytes from the file
data.bin starting from the file position 123 in the buffer 0:
FILE.READ_IOBUFF(0),
“/data.bin”, 123, 512
This command reads 8 bytes from an I2C device
with address 63 from the register 19 in the buffer 4 :
I2C.READ_IOBUFF(4),
63, 19, 8
This command reads 32 bytes from the SPI bus
in the buffer 2 :
SPI.READ_IOBUFF(2),
32
When used for sending data, the syntax is
always
.WRITE_IOBUFF(buff_num
[, start [, size]])
When sending data, it is possible to send the
entire buffer or only a part of it.
Specifying the optional arguments start and
size it is possible to define the part of the buffer to be sent;
otherwise, if omitted, the entire buffer will be transferred.
For example, the following command sends 10
bytes from the buffer 1 starting from the position 45 to the serial
port :
SERIAL.WRITE_IOBUFF(1,
45, 10)
This command sends the complete buffer 1 to
the serial port 2
SERIAL2.WRITE_IOBUFF(1)
This command sends 8 bytes from the buffer 2
starting from the position 128 to the SPI bus
SPI.WRITE_IOBUFF(2,
128, 8)
Additionally some other arguments may be
required.
This command sends 12 bytes from the buffer 1
starting from the position 64 to the UDP on the address
192.168.1.89 and port 8080 :
UDP.WRITE_IOBUFF(2,
128, 8), “192.168.1.89”,
8080
This command sends the entire buffer 2 on the
same UDP device :
UDP.WRITE_IOBUFF(2),
“192.168.1.89”, 8080
This command writes the buffer 1 to the file
data.bin
FILE.WRITE_IOBUFF(1),
“data.bin”
This command has the same result and is
provided for compatibility with the existing syntax
FILE.SAVE_IOBUFF(1),
“data.bin”
This command appends 36 bytes from the buffer
0 starting from the position 25 to data.bin
FILE.APPEND_IOBUFF(0,
25, 36), “data.bin”
This command sends the buffer 2 to the I2C
device with address 63 and register 19 :
I2C.WRITE_IOBUFF(2),
63, 19
The same operation but sending only 4 bytes
starting from position 0:
I2C.WRITE_IOBUFF(2,
0, 4), 63, 19
The syntax
.REPLY_IOBUFF(buff_num
[, start [, size]])
defines some kind of special operations.
For example, this command sends the buffer 0
back to the UDP message sender:
UDP.REPLY_IOBUFF(0)
This is the equivalent of
UDP.REPLY message$
but with the IOBUFFER
Optionally it is also possible specify part of
the buffer and the destination port (eg: 5001) as below:
UDP.REPLY_IOBUFF(0,
2, 6), 5001
When used with the SPI bus, it transmits and
receives at the same time.
As this operation requires 2 buffers, both
must be specified.
For example, this command sends the buffer 0
and receive into the buffer 2:
SPI.REPLY_IOBUFF(0),
(2)
This command sends 4 bytes from the buffer 0
starting from the position 89 and receive 4 bytes in the buffer
3:
SPI.REPLY_IOBUFF(0,
89, 4), (3)
Several other functions / commands are
available for advanced users.
These enable bit, string and hex
operations
Convert a String
into Buffer Content
●
Parameters:
○
buff_num:
The ID of the buffer (0–4) where the string will be written.
○
var$:
The input string containing the text to be converted, e.g., "This
is a text string".
○
pos:
(Optional) The starting position in the buffer where the string
will be written.
Default: 0 (write from the beginning of the buffer).
●
Return Value:
○ The
number of characters successfully written into the buffer.
○ If
used as a command, the return value is ignored.
●
Behaviour:
○
Converts the input string (var$)
into its binary representation and writes it to the specified
buffer (buff_num).
○ If
pos
is specified, the string starts at the given byte position in the
buffer.
○ If
the buffer does not have enough space, it is automatically resized
to fit the string.
Example:
IOBUFF.FROMSTRING(0,
"Hello") ' Writes "Hello" into buffer 0 starting at position
0.
IOBUFF.FROMSTRING(0,
"World", 10) ' Writes
"World" into buffer 0 starting at position
10.
print
IOBUFF.FROMSTRING(0,
"World") ' Outputs "5"
(the size of the string)
|
Convert Buffer
Content to a String
●
Parameters:
○
buff_num:
The ID of the buffer (0–4) to read data from.
○
start
: (Optional) The starting position in the buffer for reading
data.
Default: 0 (start from the first byte).
○
size:
(Optional) The number of bytes to read from the buffer.
Default: Reads from the starting position to the end of the
buffer.
●
Return Value:
○ The
text string generated from the specified portion of the buffer
content.
●
Behaviour:
○
Converts binary data in the specified buffer (buff_num)
into a string representation.
○ If
start
and size
are not provided, the entire buffer content is converted to a
string.
○ If
the specified range (start
+ size)
exceeds the buffer length, only the available data within the range
is converted.
○
Non-printable or invalid text characters may result in an
incomplete or unexpected string.
●
Note:
○
start
and size
work like MID$ but the 1st byte is 0
Example:
IOBUFF.FROMSTRING(0,
"Hello, World!") ' Write
"Hello, World!" into buffer 0.
text$
= IOBUFF.TOSTRING$(0) ' Convert entire buffer content to a
string.
PRINT text$
' Outputs: "Hello,
World!"
partial$
= IOBUFF.TOSTRING$(0, 7, 5) ' Read 5
bytes starting from position 7.
PRINT partial$
' Outputs:
"World"
|
Convert
Hexadecimal String to Buffer Content
●
Parameters:
○
buff_num:
The ID of the buffer (0–4) to store the converted data.
○
var$:
The hexadecimal string to convert.
Must contain only valid hexadecimal characters (0–9
and A–F/a–f) with an even
length.
Example:
"aabbcc1235".
○
pos:
(Optional) The starting position in the buffer where the converted
data will be stored.
Default: 0 (start writing at the beginning of the buffer).
●
Return Value:
○ The
number of bytes successfully converted and written to the
buffer.
○ If
used as a command, this return value is ignored.
●
Behaviour:
○
Converts the specified hexadecimal string (var$)
into its binary representation and writes it into the buffer
(buff_num).
○ If
pos
is specified, the conversion starts from the given position in the
buffer.
○ If
the string contains invalid characters an error is raised.
○ If
the buffer does not have enough space, it is automatically
resized.
Example:
bytes_written
= IOBUFF.FROMHEX(0, "aabbcc1235")
PRINT bytes_written
' Outputs: 5 (bytes converted and
stored).
PRINT
IOBUFF.TOHEX$(0)
' Outputs:
"AABBCC1235"
IOBUFF.FROMHEX(0,
"ff", 10)
' Write single byte (FF) at position
10.
PRINT
IOBUFF.READ(0,
10)
' Outputs: 255 (decimal value of
FF).
' Advanced example
IOBUFF.FROMHEX(1,
"01020304050607080910")
IOBUFF.FROMHEX(1,
MID$("abcdef123456", 3, 4), 5) '
Convert "cdef" and write at position 5.
PRINT
IOBUFF.TOHEX$(1)
' Outputs:
"0102030405CDEF080910"
|
Convert Buffer
Content to Hexadecimal String
IOBUFF.TOHEX$(buff_num, [, start [,
size]])
●
Parameters:
○
buff_num:
The ID of the buffer (0–4) containing the data to convert.
○
start:
(Optional) The starting position in the buffer for the
conversion.
Default: 0 (start from the beginning of the buffer).
○
size:
(Optional) The number of bytes to convert from the starting
position.
Default: Converts all bytes from start to the end of the
buffer.
●
Return Value:
○
A hexadecimal string representing the converted binary data
from the buffer.
○
Each byte in
the buffer is converted to a two-character hexadecimal value (e.g.,
255 → "FF").
●
Behaviour:
○
Reads the specified range of bytes from the buffer (buff_num) and
converts them into a continuous hexadecimal string.
○ If
start
and size
are omitted, the entire buffer is converted.
○ The
conversion does not modify the content of the buffer.
●
Note:
○
start
and size
work like MID$ but the 1st byte is 0
Example:
IOBUFF.DIM(0,
10)
' Allocate buffer 0 with 10
bytes.
IOBUFF.WRITE(0,
0, &hFF)
' Write byte 255 (hex FF) at position
0.
IOBUFF.WRITE(0,
1, &hAA)
' Write byte 170 (hex AA) at position
1.
PRINT
IOBUFF.TOHEX$(0)
' Outputs:
"FFAA0000000000000000"
PRINT
IOBUFF.TOHEX$(0, 0,
2)
' Outputs: "FFAA" (first two
bytes).
PRINT
IOBUFF.TOHEX$(0, 1,
1)
' Outputs: "AA" (second byte
only).
' Advanced example
IOBUFF.DIM(1,
20)
' Allocate buffer 1 with 20
bytes.
IOBUFF.WRITE(1,
5, &h12)
' Write byte 18 (hex 12) at position
5.
IOBUFF.WRITE(1,
6, &h34)
' Write byte 52 (hex 34) at position
6.
hex_str$
= IOBUFF.TOHEX$(1, 5, 2) ' Convert bytes at position 5–6 to
hex.
PRINT hex_str$
'
Outputs: "1234"
|
Encode Buffer
Content to Base64
Encodes the
content of the specified buffer into a Base64-encoded
string.
●
Parameters:
○
buff_num:
The ID of the buffer (0–4) containing the data to encode.
●
Return Value:
○ The
size of the Base64-encoded string (in bytes).
○ If
used as a command, this return value is ignored.
●
Behaviour:
○
Converts the binary data in the buffer into a Base64 string.
○ The
original data in the buffer is replaced by the Base64 string
○
Automatically resizes the buffer to fit the decoded data.
Example:
' Encodes buffer 0 into Base64 and returns the size
Base64Size
= IOBUFF.TOBASE64(0)
Print Base64Size
' Displays the size of the Base64
string
|
Decode Base64
String into Buffer Content
Decodes a Base64
string and writes the resulting binary data into the specified
buffer.
●
Parameters:
○
buff_num:
The ID of the buffer (0–4) containing the data to decode.
○
Base64String$:
The Base64-encoded string to decode.
●
Return Value:
○ The
size of the decoded buffer (in bytes).
○ If
used as a command, this return value is ignored.
●
Behaviour:
○
Decodes the Base64 string into binary data.
○ The
original data in the buffer is replaced by the decoded data.
○
Automatically resizes the buffer to fit the decoded data.
Example:
' Decodes buffer 0 from Base64 format and returns the
size
DecodedSize
= IOBUFF.FROMBASE64(0)
Print DecodedSize
' Displays the size of the Decoded
buffers
|
Encrypts the data
in the buffer using the AES-128 algorithm with PKCS7
padding
●
Parameters:
○
buff_num:
ID of the buffer (0–4).
○
key$:
A 16-character string representing the encryption key (128
bits).
●
Return Value:
○ The
size of the encrypted buffer (in bytes).
○ If
used as a command, this return value is ignored.
●
Behaviour:
○
Encrypts the content of the specified buffer in place using
the AES-128 algorithm.
○ The
original data in the buffer is replaced by its encrypted form.
○ The
key must be exactly 16 characters long.
○ The
encrypted buffer can only be decrypted using the same key.
○ The
buffer content is padded according to the PKCS7 method to ensure
alignment with AES-128 block size (16 bytes).
Decrypts data in
the buffer using the AES-128 algorithm
●
Parameters:
○
buff_num:
ID of the buffer (0–4).
○
key$:
The 16-character encryption key used during encryption.
●
Return Value:
○ The
size of the decrypted buffer (in bytes).
○ If
used as a command, this return value is ignored.
●
Behaviour:
○
Decrypts the content of the specified buffer in place using
the AES-128 algorithm.
○ The
original encrypted data in the buffer is replaced by its decrypted
form.
○ The
key must match the one used for encryption.
○ The
buffer is unpadded to its original content according to the PKCS7
method.
Example:
key$
= "my_Personal_key1"
' Sets the crypting
key
IObuff.FromString(0,
"Hello, World!") ' Converts a
string into IO Buffer
print
IObuff.Encrypt(0,
key$)
' Encrypts using a 16 characters
key
wlog
IObuff.ToHex$(0)
' Shows the result in Hex
format
wlog
IObuff.Decrypt(0,
key$) ' Decrypts using the same key
wlog
IObuff.ToString$(0) '
shows the decrypted string (same as the
original)
|
Calculates a
Cyclic Redundancy Check (CRC) value for a given input
buffer.
IOBUFF.CRC(buff_num, nb_bits,
polynom, initial_value, ref_in, ref_out, xor_out)
●
Parameters:
○
buff_num:
ID of the buffer (0–4) containing the data for which the CRC needs
to be calculated.
○
nb_bits:
Bit order for the CRC calculation. It can be set from 8 to 32 (i.e.
16 for a 16-bit CRC).
○
polynom:
CRC polynomial used in the calculation .
○
initial_value:
Initial CRC value. This value is used to initialise the CRC
calculation.
○
ref_in:
Input reflection flag (1 for true, 0 for false). If set to 1, the
input data is processed in reverse bit order.
○
ref_out:
Output reflection flag (1 for true, 0 for false). If set to 1, the
CRC output is reflected (i.e., processed in reverse bit order).
○
xor_out:
Final XOR value. This value is applied to the final CRC value
before returning it.
●
Return Value:
○ The
calculated CRC value, or 0 if the input buffer is empty.
●
Behaviour:
○ This
function computes the CRC value for the data in the specified I/O
buffer. It supports customizable CRC parameters to accommodate
different CRC algorithms. You can define the polynomial, initial
value, and final XOR value, and also specify whether to reflect the
input data and/or output CRC.
○
Nb_bits
specifies the bit size of the CRC (e.g., 16-bit, 32-bit).
○
polynom
defines the polynomial used for the calculation (e.g.,
0x4c11db7 for CRC-32).
○
initial_value
is the initial CRC value, commonly 0xffffffff for
CRC-32.
○
ref_in
and ref_out
allow for reflection of input and output bits.
○
xor_out
applies an XOR operation to the final CRC value before
returning.
●
Note:
○
Ensure that the I/O buffer contains the data you want to calculate
the CRC for before calling this function. If the buffer is empty,
the function returns 0.
CRC Demo
Code
This demo code demonstrates how to calculate various CRC (Cyclic
Redundancy Check) values for the string
"123456789". It uses a variety of CRC algorithms, from
CRC-8 to CRC-32, with different settings for each. The results are
compared with expected CRC values, which can be verified using
online tools like crc-calculator.
'CRC demo code
'references to https://crccalc.com/
a$
= "123456789"
wlog
IObuff.fromstring(0,
a$)
wlog
"Algo CRC ", "Expected",
"Result"
wlog
"CRC-8/AUTOSAR", hex$(0xDF),
hex$(IObuff.CRC(0, 8, 0x2F, 0xFF, 0, 0, 0xFF))
wlog
"CRC-8/BLUETOOTH", hex$(0x26),
hex$(IObuff.CRC(0, 8, 0xA7, 0x00, 1, 1, 0x00))
wlog
"CRC-8/CDMA2000", hex$(0xDA),
hex$(IObuff.CRC(0, 8, 0x9B, 0xFF, 0, 0, 0x00))
wlog
"CRC-8/DARC", hex$(0x15),
hex$(IObuff.CRC(0, 8, 0x39, 0x00, 1, 1, 0x00))
wlog
"CRC-8/DVB-S2", hex$(0xBC),
hex$(IObuff.CRC(0, 8, 0xD5, 0x00, 0, 0, 0x00))
wlog
"CRC-8/GSM-A", hex$(0x37),
hex$(IObuff.CRC(0, 8, 0x1D, 0x00, 0, 0, 0x00))
wlog
"CRC-8/GSM-B", hex$(0x94),
hex$(IObuff.CRC(0, 8, 0x49, 0x00, 0, 0, 0xFF))
wlog
"CRC-8/HITAG", hex$(0xB4),
hex$(IObuff.CRC(0, 8, 0x1D, 0xFF, 0, 0, 0x00))
wlog
"CRC-8/I-432-1", hex$(0xA1),
hex$(IObuff.CRC(0, 8, 0x07, 0x00, 0, 0, 0x55))
wlog
"CRC-8/I-CODE", hex$(0x7E),
hex$(IObuff.CRC(0, 8, 0x1D, 0xFD, 0, 0, 0x00))
wlog
"CRC-8/LTE", hex$(0xEA),
hex$(IObuff.CRC(0, 8, 0x9B, 0x00, 0, 0, 0x00))
wlog
"CRC-8/MAXIM-DOW", hex$(0xA1),
hex$(IObuff.CRC(0, 8, 0x31, 0x00, 1, 1, 0x00))
wlog
"CRC-8/MIFARE-MAD", hex$(0x99),
hex$(IObuff.CRC(0, 8, 0x1D, 0xC7, 0, 0, 0x00))
wlog
"CRC-8/NRSC-5", hex$(0xF7),
hex$(IObuff.CRC(0, 8, 0x31, 0xFF, 0, 0, 0x00))
wlog
"CRC-8/OPENSAFETY", hex$(0x3E),
hex$(IObuff.CRC(0, 8, 0x2F, 0x00, 0, 0, 0x00))
wlog
"CRC-8/ROHC", hex$(0xD0),
hex$(IObuff.CRC(0, 8, 0x07, 0xFF, 1, 1, 0x00))
wlog
"CRC-8/SAE-J1850", hex$(0x4B),
hex$(IObuff.CRC(0, 8, 0x1D, 0xFF, 0, 0, 0xFF))
wlog
"CRC-8/SMBUS", hex$(0xF4),
hex$(IObuff.CRC(0, 8, 0x07, 0x00, 0, 0, 0x00))
wlog
"CRC-8/TECH-3250", hex$(0x97),
hex$(IObuff.CRC(0, 8, 0x1D, 0xFF, 1, 1, 0x00))
wlog
"CRC-8/WCDMA", hex$(0x25),
hex$(IObuff.CRC(0, 8, 0x9B, 0x00, 1, 1, 0x00))
wlog
"CRC-16/ARC", hex$(0xBB3D),
hex$(IObuff.CRC(0, 16, 0x8005, 0x0000, 1, 1,
0x0000))
wlog
"CRC-16/CDMA2000", hex$(0x4C06),
hex$(IObuff.CRC(0, 16, 0xC867, 0xFFFF, 0, 0,
0x0000))
wlog
"CRC-16/CMS", hex$(0xAEE7),
hex$(IObuff.CRC(0, 16, 0x8005, 0xFFFF, 0, 0,
0x0000))
wlog
"CRC-16/DDS-110", hex$(0x9ECF),
hex$(IObuff.CRC(0, 16, 0x8005, 0x800D, 0, 0,
0x0000))
wlog
"CRC-16/DECT-R", hex$(0x007E),
hex$(IObuff.CRC(0, 16, 0x0589, 0x0000, 0, 0,
0x0001))
wlog
"CRC-16/DECT-X", hex$(0x007F),
hex$(IObuff.CRC(0, 16, 0x0589, 0x0000, 0, 0,
0x0000))
wlog
"CRC-16/DNP", hex$(0xEA82),
hex$(IObuff.CRC(0, 16, 0x3D65, 0x0000, 1, 1,
0xFFFF))
wlog
"CRC-16/EN-13757", hex$(0xC2B7),
hex$(IObuff.CRC(0, 16, 0x3D65, 0x0000, 0, 0,
0xFFFF))
wlog
"CRC-16/GENIBUS", hex$(0xD64E),
hex$(IObuff.CRC(0, 16, 0x1021, 0xFFFF, 0, 0,
0xFFFF))
wlog
"CRC-16/GSM", hex$(0xCE3C),
hex$(IObuff.CRC(0, 16, 0x1021, 0x0000, 0, 0,
0xFFFF))
wlog
"CRC-16/IBM-3740", hex$(0x29B1),
hex$(IObuff.CRC(0, 16, 0x1021, 0xFFFF, 0, 0,
0x0000))
wlog
"CRC-16/IBM-SDLC", hex$(0x906E),
hex$(IObuff.CRC(0, 16, 0x1021, 0xFFFF, 1, 1,
0xFFFF))
wlog
"CRC-16/ISO-IEC-14443-3-A", hex$(0xBF05),
hex$(IObuff.CRC(0, 16, 0x1021, 0xC6C6, 1, 1,
0x0000))
wlog
"CRC-16/KERMIT", hex$(0x2189),
hex$(IObuff.CRC(0, 16, 0x1021, 0x0000, 1, 1,
0x0000))
wlog
"CRC-16/LJ1200", hex$(0xBDF4),
hex$(IObuff.CRC(0, 16, 0x6F63, 0x0000, 0, 0,
0x0000))
wlog
"CRC-16/M17", hex$(0x772B),
hex$(IObuff.CRC(0, 16, 0x5935, 0xFFFF, 0, 0,
0x0000))
wlog
"CRC-16/MAXIM-DOW", hex$(0x44C2),
hex$(IObuff.CRC(0, 16, 0x8005, 0x0000, 1, 1,
0xFFFF))
wlog
"CRC-16/MCRF4XX", hex$(0x6F91),
hex$(IObuff.CRC(0, 16, 0x1021, 0xFFFF, 1, 1,
0x0000))
wlog
"CRC-16/MODBUS", hex$(0x4B37),
hex$(IObuff.CRC(0, 16, 0x8005, 0xFFFF, 1, 1,
0x0000))
wlog
"CRC-16/NRSC-5", hex$(0xA066),
hex$(IObuff.CRC(0, 16, 0x080B, 0xFFFF, 1, 1,
0x0000))
wlog
"CRC-16/OPENSAFETY-A", hex$(0x5D38),
hex$(IObuff.CRC(0, 16, 0x5935, 0x0000, 0, 0,
0x0000))
wlog
"CRC-16/OPENSAFETY-B", hex$(0x20FE),
hex$(IObuff.CRC(0, 16, 0x755B, 0x0000, 0, 0,
0x0000))
wlog
"CRC-16/PROFIBUS", hex$(0xA819),
hex$(IObuff.CRC(0, 16, 0x1DCF, 0xFFFF, 0, 0,
0xFFFF))
wlog
"CRC-16/RIELLO", hex$(0x63D0),
hex$(IObuff.CRC(0, 16, 0x1021, 0xB2AA, 1, 1,
0x0000))
wlog
"CRC-16/SPI-FUJITSU", hex$(0xE5CC),
hex$(IObuff.CRC(0, 16, 0x1021, 0x1D0F, 0, 0,
0x0000))
wlog
"CRC-16/T10-DIF", hex$(0xD0DB),
hex$(IObuff.CRC(0, 16, 0x8BB7, 0x0000, 0, 0,
0x0000))
wlog
"CRC-16/TELEDISK", hex$(0x0FB3),
hex$(IObuff.CRC(0, 16, 0xA097, 0x0000, 0, 0,
0x0000))
wlog
"CRC-16/TMS37157", hex$(0x26B1),
hex$(IObuff.CRC(0, 16, 0x1021, 0x89EC, 1, 1,
0x0000))
wlog
"CRC-16/UMTS", hex$(0xFEE8),
hex$(IObuff.CRC(0, 16, 0x8005, 0x0000, 0, 0,
0x0000))
wlog
"CRC-16/USB", hex$(0xB4C8),
hex$(IObuff.CRC(0, 16, 0x8005, 0xFFFF, 1, 1,
0xFFFF))
wlog
"CRC-16/XMODEM", hex$(0x31C3),
hex$(IObuff.CRC(0, 16, 0x1021, 0x0000, 0, 0,
0x0000))
wlog
"CRC-32/AIXM", hex$(0x3010BF7F), hex$(IObuff.CRC(0, 32, 0x814141AB, 0x00000000, 0, 0,
0x00000000))
wlog
"CRC-32/AUTOSAR", hex$(0x1697D06A), hex$(IObuff.CRC(0, 32, 0xF4ACFB13, 0xFFFFFFFF, 1, 1,
0xFFFFFFFF))
wlog
"CRC-32/BASE91-D", hex$(0x87315576), hex$(IObuff.CRC(0, 32, 0xA833982B, 0xFFFFFFFF, 1, 1,
0xFFFFFFFF))
wlog
"CRC-32/BZIP2", hex$(0xFC891918), hex$(IObuff.CRC(0, 32, 0x04C11DB7, 0xFFFFFFFF, 0, 0,
0xFFFFFFFF))
wlog
"CRC-32/CD-ROM-EDC", hex$(0x6EC2EDC4), hex$(IObuff.CRC(0, 32, 0x8001801B, 0x00000000, 1, 1,
0x00000000))
wlog
"CRC-32/CKSUM", hex$(0x765E7680), hex$(IObuff.CRC(0, 32, 0x04C11DB7, 0x00000000, 0, 0,
0xFFFFFFFF))
wlog
"CRC-32/ISCSI", hex$(0xE3069283), hex$(IObuff.CRC(0, 32, 0x1EDC6F41, 0xFFFFFFFF, 1, 1,
0xFFFFFFFF))
wlog
"CRC-32/ISO-HDLC", hex$(0xCBF43926), hex$(IObuff.CRC(0, 32, 0x04C11DB7, 0xFFFFFFFF, 1, 1,
0xFFFFFFFF))
wlog
"CRC-32/JAMCRC", hex$(0x340BC6D9), hex$(IObuff.CRC(0, 32, 0x04C11DB7, 0xFFFFFFFF, 1, 1,
0x00000000))
wlog
"CRC-32/MEF", hex$(0xD2C22F51), hex$(IObuff.CRC(0, 32, 0x741B8CD7, 0xFFFFFFFF, 1, 1,
0x00000000))
wlog
"CRC-32/MPEG-2", hex$(0x0376E6E7), hex$(IObuff.CRC(0, 32, 0x04C11DB7, 0xFFFFFFFF, 0, 0,
0x00000000))
wlog
"CRC-32/XFER", hex$(0xBD0BE338), hex$(IObuff.CRC(0, 32, 0x000000AF, 0x00000000, 0, 0,
0x00000000))
|
These bit operations provide low-level control
over the buffer's contents, enabling manipulation of individual
bits in each byte.
Get the Value of a
Specific Bit in a Byte
IObuff.bit(buff_num,
position, bit)
●
Parameters:
○
buff_num:
The ID of the buffer (0–4).
○
position:
The byte position in the buffer to examine.
○
bit:
The bit position within the byte (0–7).
■ 0 is
the least significant bit (rightmost bit).
■ 7 is
the most significant bit (leftmost bit).
●
Return Value:
○ The
value of the specified bit within the byte.
■
Returns 0 if the bit is clear (0).
■
Returns 1 if the bit is set (1).
●
Behaviour:
○
Extracts the bit value from the specified byte in the buffer.
○ Does
not modify the buffer content.
Example:
IOBUFF.DIM(0,
2)
' Allocate buffer 0 with 2
bytes.
IOBUFF.WRITE(0,
0, &hF0)
' Write byte 240 (hex F0) at position
0.
PRINT
IOBUFF.BIT(0, 0,
7)
' Outputs: 1 (bit 7 of 0th byte is
set).
PRINT
IOBUFF.BIT(0, 0,
3)
' Outputs: 0 (bit 3 of 0th byte is
clear).
|
Set a Specific Bit
in a Byte
●
Parameters:
○
buff_num:
The ID of the buffer (0–4).
○
position:
The byte position in the buffer where the bit will be set.
○
bit:
The bit position (0–7) to be set to 1.
■ 0 is
the least significant bit (rightmost bit).
■ 7 is
the most significant bit (leftmost bit).
●
Return Value:
○ The
value of the bit after setting (should always return 1).
○ The
return value is ignored if used as a command.
●
Behaviour:
○ Sets
the specified bit in the specified byte of the buffer to 1.
○ Does
not affect other bits in the byte.
○ The
function returns 1 but this is typically ignored when used as a
command.
Example:
IOBUFF.DIM(0,
1)
' Allocate buffer 0 with 1
byte.
IOBUFF.WRITE(0,
0, &h01)
' Write byte 1 (hex 01) at position
0.
PRINT
IOBUFF.SETBIT(0, 0,
7)
' Set bit 7 in byte 0. Returns:
1.
PRINT
IOBUFF.BIT(0, 0,
7)
' Outputs: 1 (bit 7 is now
set).
|
Clear a Specific
Bit in a Byte
●
Parameters:
○
buff_num:
The ID of the buffer (0–4).
○
position:
The byte position in the buffer where the bit will be cleared.
○
bit:
The bit position (0–7) to be cleared to 0.
■ 0 is
the least significant bit (rightmost bit).
■ 7 is
the most significant bit (leftmost bit).
●
Return Value:
○ The
value of the bit after clearing (should always return 0).
○ The
return value is ignored if used as a command.
●
Behaviour:
○
Clears the specified bit in the specified byte of the buffer,
setting it to 0.
○ Does
not affect other bits in the byte.
○ The
function returns 0 but this is typically ignored when used as a
command.
Example:
IOBUFF.DIM(0,
1)
' Allocate buffer 0 with 1
byte.
IOBUFF.WRITE(0,
0, &hFF)
' Write byte 255 (hex FF) at position
0.
PRINT
IOBUFF.CLEARBIT(0, 0,
7) ' Clear bit 7 in byte 0. Returns: 0
(ignored).
PRINT
IOBUFF.BIT(0, 0,
7)
' Outputs: 0 (bit 7 is now
cleared).
|
Toggle a Specific
Bit in a Byte
●
Parameters:
○
buff_num:
The ID of the buffer (0–4).
○
position:
The byte position in the buffer where the bit will be toggled.
○
bit:
The bit position (0–7) to toggle
■ 0 is
the least significant bit (rightmost bit).
■ 7 is
the most significant bit (leftmost bit).
●
Return Value:
○ The
new value of the toggled bit (0 or 1).
○ The
return value is ignored if used as a command.
●
Behaviour:
○
Toggles the specified bit in the specified byte of the buffer:
■ If
the bit is 0, it becomes 1.
■ If
the bit is 1, it becomes 0.
○ Does
not affect other bits in the byte.
○ The
function returns the new value of the bit but this is typically
ignored when used as a command.
Example:
IOBUFF.DIM(0,
1)
' Allocate buffer 0 with 1
byte.
IOBUFF.WRITE(0,
0, &h0F)
' Write byte 15 (hex 0F) at position
0.
PRINT
IOBUFF.TOGGLEBIT(0, 0,
3) ' Toggle bit 3 in byte 0. Returns:
0.
PRINT
IOBUFF.BIT(0, 0,
3)
' Outputs: 0 (bit 3 is now
toggled).
|
Copy Data from One Buffer to
Another
IObuff.copy(dest_buff_num
[,pos]) , (source_buff_num, [,
start [, size]])
●
Parameters:
○
dest_buff_num:
The ID of the destination buffer (0–4) where the data will be
copied to.
○
pos:
(optional) The position within the destination buffer where the
copy will begin.
Defaults to 0 if not specified.
○
source_buff_num:
The ID of the source buffer (0–4) from which the data will be
copied.
○
start:
(optional) The starting byte in the source buffer from where
copying will begin.
Defaults to 0 if not specified.
○
size:
(optional) The number of bytes to copy from the source
buffer.
If omitted, it will copy from the start position to the end of the
source buffer.
●
Return Value:
○ The
number of bytes successfully copied to the destination buffer.
○ If
used as a command, the return value is ignored.
●
Behaviour:
○
Copies data from a source buffer to a destination buffer.
○ If
start and size are specified, only the selected portion of the
source buffer will be copied.
○ If
pos is specified, it determines where in the destination buffer the
data will be copied to.
○ The
content of the destination buffer is replaced or modified by the
copied data, depending on the pos value.
○ The
copy operation automatically resizes the destination buffer if the
size exceeds its capacity.
Example:
IOBUFF.DIM(1,
10)
' Allocate 10 bytes for buffer 1
(source).
IOBUFF.WRITE(1,
0, &h01) ' Write byte 1 at position 0 in buffer
1.
IOBUFF.WRITE(1,
1, &h02) ' Write byte 2 at position 1 in buffer
1.
IOBUFF.COPY(0,
0), (1, 0, 2) ' Copy 2
bytes from buffer 1 (starting from position 0) to buffer 0
(starting at position 0).
PRINT
IOBUFF.TOHEX$(0)
' Outputs: "0102" (2 bytes copied to
buffer 0).
|
UDP - use the remote controller APP for IOS
devices (iphone and Ipad)
' I/O buffers example using the RCWController
' available in the IOS app store.
' It uses by default the port 10000
' The APP sends a block of 10 bytes that
' will be printed in the console on the same line
udp.begin 10000
' define the place where jump on message reception
onudp received
wait
received:
' read the incoming data in the buffer 0
udp.read_iobuff(0)
size
= iobuff.len(0)
print
"received "; size; "
bytes"
for z
= 0 to 9
' read and print 1 byte at the time on
the same line
print iobuff.read(0, z),
next z
Print
' print an empty line
return
|
File read and transfer to the serial port
by blocks
' I/O BUFFERS example using files
' read a file in blocks of 512 characters
' and send them to the serial port (print)
fileName$
= "/data8.txt"
block_size
= 512 '
size of the block to be read
file_size
= file.size(fileName$)
print
"File size "; file_size
print file_size
for z
= 0 to file_size - 1 step
block_size
file.read_iobuff(0), fileName$, z, block_size
' send the block on the serial port
(print)
serial.write_iobuff(0)
next
|
Serial port data logger
' I/O BUFFERS example to create a serial data logger
' receive bytes from the serial port and
' write them into the file /mylog.txt
' all the characters will be recorded
' including the ASCII 0 (NUL)
filename$
= "/mylog.txt"
' define the place where jump on message reception
onserial received
wait
received:
' waits for 10 millisec giving time to receive all the
data
pause 10
' read the incoming data in the buffer 0
serial.read_iobuff(0)
size
= iobuff.len(0)
print
"received "; size; "
bytes"
' appends the received data to the file
file.append_iobuff(0),
filename$
return
|
This diagram
shows pin mapping for the popular ESP32 DEV Board
module.
(*) pins GPIO6 to
GPIO11 are not available.
Annex 32, as it
supports by default the M5stack wiring, assumes the following pins
already allocated/dedicated
PIN
|
FUNCTION
|
DESCRIPTION
|
32
|
PWM
BL TFT
|
Backlight TFT display
|
33
|
RST
TFT
|
RST
pin TFT
|
27
|
D/C
TFT
|
D/C
pin TFT
|
14
|
CS
TFT
|
CS
pin TFT
|
23
|
SPI
MOSI
|
SPI
MOSI pin (shared with SD and TFT)
|
19
|
SPI
MISO
|
SPI
MISO pin (shared with SD and TFT)
|
18
|
SPI
SCK
|
SPI
CLOCK pin (shared with SD and TFT)
|
4
|
CS
SDCARD
|
CS
pin SDCARD
|
0
|
CS
TFT TOUCH
|
CS
pin Touchscreen (from the TFT)
|
|
|
|
3
|
RX0
|
Serial Port RX pin
|
1
|
TX0
|
Serial Port TX pin
|
|
|
|
25
|
SPEAKER
|
Speaker or mono audio output
|
21
|
SDA
I2C
|
I2C
SDA pin
|
22
|
SCL
I2C
|
I2C
SCL pin
|
|
|
|
2
|
I2S
DATA
|
Audio
DAC I2S DATA pin
|
5
|
I2S
BCLK
|
Audio
DAC I2S BCLK pin
|
26
|
I2S
LRCK
|
Audio
DAC I2S LRCK pin
|
16
|
PSRAM
|
Optional PSRAM
|
17
|
PSRAM
|
Optional PSRAM
|
Pin numbers
correspond directly to the ESP32 GPIO pin numbering.
The function of the
pin (input / output) must be defined before using the function
PIN.MODE as below :
To define the pin 5
as input :
PIN.MODE 15,
INPUT
To define the pin 4
as input with a pullup:
PIN.MODE 4,
INPUT, PULLUP
To define the pin 4
as input with a pulldown:
PIN.MODE 4,
INPUT, PULLDOWN
To define the pin 2
as output
PIN.MODE 2,
OUTPUT
To define the pin 2
as output open collector
PIN.MODE 2,
OUTPUT, 1
Pins may also serve
other functions, like Serial, I2C, SPI.
These functions are
normally activated by the corresponding library.
The value from a
pîn can be read as shown below :
A
= PIN(5)‘ read from GPIO5 pin
The pin value can
be set as below
PIN(2)=
0
‘
set 0 on the GPIO2
pin
The pin value (0 or
1) can also be easily toggled by subtracting it from 1 (because
1-0=1 and 1-1=0), eg:
PIN(2)=
1 -
PIN(2)‘
toggles the value of GPIO2
pin
This part is applicable only
to the “classic” ESP32 as the other members of the family have
different H/W characteristics and
Although pin numbers can be from 0 to 39, gpio pins
6 to 11 should not be used because they are connected to
flash memory chips on most modules. Trying to use these pins as IOs
will likely cause the program to crash.
Pins 34 to 39 are
INPUT only and cannot be configured as
PULLUP or
PULLDOWN.
Pins 0 to 33 can be
INPUT,
OUTPUT,
INPUT, PULLUP or
INPUT, PULLDOWN.
Note:
If the module is equipped with PSRAM, the gpio pins
16 and 17 are reserved and must not be used.
The command
PIN.STRENGTH can be used to define the drive capability
of the output pins from a scale from 0 to 3.
For example, the
following command set the pin 15 with a drive capability of 2.
The ESP32 provides four drive strength levels for its GPIO
pins:
●
0: Weakest drive strength, approximately 5 mA.
●
1: Low drive strength, approximately 10 mA.
●
2: Medium drive strength, approximately 20 mA.
●
3: Maximum drive strength, approximately 40 mA.
Annex
supports two commands for serially shifting data:
-
PIN.SHIFTOUT for sending data
-
PIN.SHIFTIN for receiving data.
Both commands
allow control over bit order, bit count, and timing delays.
These commands are
in particular useful to control external shift registers or simple
SPI bus devices.
The
PIN.SHIFTOUT command is used to send data out serially
through a specified data pin. It shifts out data bits one at a
time, synchronised with a clock signal. The command allows you to
specify the order in which bits are shifted (least significant bit
first or most significant bit first), the number of bits to shift,
and the timing delay between each bit. This command drives the data
pin high or low according to the current bit in the data, and
toggles the clock pin to indicate when each bit should be read by
the receiving device.
Syntax:
PIN.SHIFTOUT
pin_data,
pin_clk, data [, bit_order] [, nb_bits] [,
delay_us]
Parameters:
●
pin_data:
○
Description: GPIO pin number used for the data line.
●
pin_clk:
○
Description: GPIO pin number used for the clock line that
synchronises the data transfer.
●
data
:
○
Description: Data to be shifted out.
●
Bit_order
(optional):
○
Description: Specifies the bit order for shifting data.
Possible values:
■
0
(default) : LSBFIRST Least Significant Bit first.
■
1
: MSBFIRST Most Significant Bit first.
●
Nb_bits
(optional):
○
Description: Number of bits to shift out from the data.
Default is 8 bits.
●
Delay_us
(optional):
○
Description: Delay in microseconds between each bit shift.
Default is 1 microsecond.
Details:
● This
command uses critical section management to ensure atomic
operations during the data shift process. However, because it
relies on software delays, the timing may not be very precise,
particularly for delays shorter than 10 microseconds
●
Bit Order: The bit order determines whether the least
significant bit (LSBFIRST) or the most significant bit (MSBFIRST)
is shifted out first.
●
Number of Bits: Specifies how many bits from the data value
will be shifted out. If not specified, the default is 8 bits.
●
Delay: Introduces a delay between the setting of the data
pin and toggling of the clock pin to control the timing of the data
shift.
Example:
PIN.SHIFTOUT 13, 14,
0xFF ' Shift out 8 bits
from data 0xFF
PIN.SHIFTOUT 13, 14,
0xFF, 1' Shift out 8 bits from data
0xFF with MSBFIRST
PIN.SHIFTOUT 13, 14,
0xFFFF, 1, 16, 2 ' Shift out 16
bits from data 0xFFFF with MSBFIRST, 2 µs
delay
|
The
PIN.SHIFTIN function is used to receive data serially
through a specified data pin. It shifts in data bits one at a time,
using a clock signal to determine when to sample the data pin.
Similar to
PIN.SHIFTOUT, it allows you to specify the bit order,
the number of bits to shift, and the timing delay between each bit.
This function reads the state of the data pin in sync with
the clock signal, capturing each bit as it arrives and storing it
in a variable.
Syntax:
PIN.SHIFTIN(
pin_data,
pin_clk [, bit_order] [, nb_bits] [, delay_us] )
Parameters:
●
pin_data:
○
Description: GPIO pin number used for the data line.
●
pin_clk
:
○
Description: GPIO pin number used for the clock line that
synchronises the data reading.
●
Bit_order
(optional):
○
Description: Specifies the bit order for shifting data.
Possible values:
■
0
(default) : LSBFIRST Least Significant Bit first.
■
1
: MSBFIRST Most Significant Bit first.
●
Nb_bits
(optional):
○
Description: Number of bits to read from the data line.
Default is 8 bits.
●
Delay_us
(optional):
○
Description: Delay in microseconds between each bit read.
Default is 1 microsecond.
Details:
● This
command uses critical section management to ensure atomic
operations during the data shift process. However, because it
relies on software delays, the timing may not be very precise,
particularly for delays shorter than 10 microseconds
●
Bit Order: Determines whether the least significant bit
(LSBFIRST) or the most significant bit (MSBFIRST) is read
first.
●
Number of Bits: Specifies how many bits will be read from
the data line. If not specified, the default is 8 bits.
●
Delay: Introduces a delay between each bit read, allowing
for control over timing and synchronisation.
Example:
A
= PIN.SHIFTIN(21, 22)
' Shift in 8 bits from data pin 21 with
clock pin 22
B
= PIN.SHIFTIN(13, 14, 1) ' Shift in 8
bits from data pin 13 with clock pin 14, reading
MSBFIRST
C
= PIN.SHIFTIN(13, 14, 1, 16, 2) ' Shift
in 16 bits from data pin 13 with clock pin 14, reading MSBFIRST, 2
µs delay
|
The
INTERRUPT command permits to trigger an event when the
signal on an input pin changes.
The interrupt is
triggered BOTH when the signal goes from LOW to HIGH and HIGH to
LOW.
Therefore a
momentary pulse actually generates 2 interrupts which need testing
for Hi or Lo as appropriate.
Example:
pin.mode 12,
input ' set pin 12 as input
interrupt 12, change_input
' set interrupt on pin 12
wait
change_input:
if pin(12)
= 0 then return ' if the pin is low, returns back
print "The pin changed to HIGH"
Return
|
It is possible to
add an optional parameter, mode,
that specify if the interrupt must be generated on the rising edge,
the falling edge or on change:
Syntax:
INTERRUPT pin_no,
{OFF | label} [, mode]
Parameters:
- pin_no: The input
pin number for which the interrupt is being defined. It must be an
integer value ranging from 0 to the maximum pin number supported by
the specific variant of the ESP32 (-s2, -c3, -s3).
- label: The branch
label to which the program will jump when the designated input pin
signal changes. It must be a valid label in the program's
context.
- OFF: Use this
keyword to remove the interrupt associated with the specified input
pin.
- mode (optional):
An integer parameter or keyword specifying the trigger condition
for the interrupt. It can take one of the following values:
- 1, RISING:
Rising edge trigger
- 2,
FALLING: Falling edge trigger
- 3, CHANGE:
Any change in signal trigger (default if 'mode' parameter is
omitted)
Examples:
-
To set up an interrupt that jumps to the 'PIN5_CHANGE' label when a
rising edge is detected on pin 5:
INTERRUPT 5,
PIN5_CHANGE, RISING
-
To remove the interrupt associated with pin 5:
INTERRUPT 5,
OFF
-
To set up an interrupt that jumps to the 'PIN13_TRANSITION' label
when any change is detected on pin 13:
INTERRUPT 13,
PIN13_TRANSITION , CHANGE
-
To set up an interrupt without specifying the trigger mode
(defaulting to any change in signal) that jumps to the
'PIN7_UPDATE' label when pin 7 signal changes:
INTERRUPT 7,
PIN7_UPDATE
Note:
-
Interrupts can provide a way to respond to external events
asynchronously.
-
The optional 'mode' parameter allows you to customize the trigger
condition for the interrupt to match your specific application
requirements.
The
input pin (pin_no) must be previously configured as an input before
setting up the interrupt.
Ensure
that the specified 'pin_no' and 'label' are valid within the scope
of your program.
The
maximum pin number supported by the ESP32 variant should be
considered based on the specific model (-s2, -c3, -s3).
Annex32 has 8 ADC
pins with 12 bits resolution which are available to users.
The function
ADC(pin)
can be used to read voltage on the pins defined in the table
below.
GPIO Pins Available as
Analog Input
|
32
|
33
|
34
|
35
|
36
|
37
|
38
|
39
|
To read the voltage applied at the pin, the
function ADC can be used as below :
print
ADC(39)' read voltage
from the pin 39
The voltage range is
0 ... 3.3V and the corresponding range returned by the function is
0 … 4095.
NOTE: When using the
function
ADC,the pin is automatically configured as an Analog
Input
Annex32
supports an additional ESP32 feature, the capacitive
touch.
With this
feature, it is possible to activate inputs with your fingers with
just one wire attached to the pin.
The
function
PIN.TOUCH(pin)
can be used to read the touch
value on the pins defined in the table below.
GPIO Pins Available as Touch
Input
|
0
|
2
|
4
|
12
|
13
|
14
|
15
|
27
|
32
|
33
|
The
function
PIN.TOUCH(pin)
returns a value that drops as soon
as the pin is touched.
Normal values
are around 70 when not touched and lower than 20 when
touched.
'Pin Touch
example
'Place a
wire on pin 13 and look how the value changes when touching
it
while
1
print pin.touch(13)
pause 100
wend
end
|
Annex32 has 2 DAC output pins with 8
bits resolution which are available to users.
This function is available only on the
pin GPIO25 and GPIO26
The function
PIN.DAC pin,
value can be used to set the output voltage on the
pin.
The output voltage is approximately 0V @
value=0 and 3.3V @ value=255
'DAC output
example
PIN.DAC 25,
128 'Set the pin
25 at ~1.65V
PIN.DAC 26,
64 'Set the pin
26 at ~0.82V
|
NOTE: When using the command
PIN.DAC,the pin is automatically configured as an
Analog Output
The ESP32 contains several H/W interfaces that
can be controlled by Annex32 WI-Fi using specific commands and
functions.
This functionality permits to control the
output duty cycle of any pin, acting like an analog output.
There are 16 channels available where each
channel can be connected to any output pin.
To use it, the function must first be
configured using the command
PWM.SETUP and then the value can be set using the
command
PWM.OUT.
The frequency and the
resolution can be defined individually for each channel.
The resolution can be from
1 to 15 bits.
The maximal frequency is
80000000 / 2^resolution
This table resumes the
maximal frequency available in function of the resolutions and the
associated range:
RESOLUTION (BITS)
|
MAX FREQUENCY
|
VALUE RANGE
|
1
|
40000000
|
0 ... 1
|
2
|
20000000
|
0 ... 3
|
3
|
10000000
|
0 ... 7
|
4
|
5000000
|
0 .. 15
|
5
|
2500000
|
0 .. 31
|
6
|
1250000
|
0 … 63
|
7
|
625000
|
0 … 127
|
8
|
312500
|
0 … 255
|
9
|
156250
|
0 … 511
|
10
|
78125
|
0 … 1023
|
11
|
39063
|
0 … 2047
|
12
|
19531
|
0 … 4095
|
13
|
9766
|
0 … 8191
|
14
|
4883
|
0 … 16383
|
15
|
2441
|
0 … 32767
|
All the output pins can be
used for the PWM (the pins from GPIO0 to GPIO33).
As there are 16 channels,
up to 16 individual output pins can be used.
If using the M5Stack, the
channels 0 and 7 are already reserved and attached to the pins 25
and 32.
In this case the channels
0 and 7 must be avoided.
To setup an output pin as
a PWM output the following command must be used :
PWM.SETUP
pin, channel,
default_value, [,frequency] [,resolution]
For example, to define a
PWM output at 5KHz with 12 bits of resolution on the pin GPIO5 the
command is :
PWM.SETUP 5, 1,
2048, 5000, 12 ‘ pin 5, channel 1, output value at 2048
(50%), 5KHz, 12 bits
As the resolution is set
at 12 bits, the range will be from 0 to 4095 (hence 2048 is
50%).
To define a PWM output at
10KHz with 8 bits on the pin GPIO22, the command is :
PWM.SETUP 22, 2,
128 ‘ pin 22, channel 2, value 128 ( 50%) , freq
10 KHz (default), resolution 8 bits (default)
As soon as the command
PWM.SETUP is done, the PWM output can simply be changed with the
command :
For example, the
command
PWM.OUT 1,
1000
Set the channel 1
(associated with the pin 5 in the previous command) at 1000.
And the command
PWM.OUT 2, 10
Set the channel 2 (associated with the pin 22
in the previous command) at 10
To disconnect the pin from the PWM output the
command is :
PWM.SETUP pin,
OFF.
For example the command
PWM.SETUP 5,
OFF
Disconnect the pin 5 fro the PWM
NOTE for the
M5stack:
The channel 0 is
dedicated to the internal speaker (pin 25)
The channel 7 is
dedicated to the TFT backlight (pin 32)
This functionality exposes the ability to
control RC (hobby) servo motors.
There are no special commands dedicated as the
servo can simply be used by setting a PWM pin with a 50Hz
frequency.
For example, the following command :
PWM.SETUP 17, 1,
150, 50, 12
Defines the pin 17 with the pwm channel 1 with
a default value of 150 (frequency at 50 Hz and resolution at 12
bits).
The output can then be set with the
command
PWM.OUT 1,
307‘ channel 1 set at 90°
A typical servo motor expects to be updated
every 20 ms with a pulse between 1 ms and 2 ms, or in other words,
between a 5 and 10% duty cycle on a 50 Hz waveform. With a 1.5 ms
pulse, the servo motor will be at the natural 90 degree position.
With a 1 ms pulse, the servo will be at the 0 degree position, and
with a 2 ms pulse, the servo will be at 180 degrees. You can obtain
the full range of motion by updating the servo with any value in
between.
Using a 12 bits resolution (max value = 4095
for 20 msec pulse (1/50 Hz)), the theoretical values should be
:
0° -> 1 msec -> 1/20 * 4096 =
205
90° -> 1.5 msec -> 1.5/20 * 4096 =
307
180° -> 2 msec -> 2/20 * 4096 =
409
Generating Tones
This section introduces the functionality of
generating tones using the
PWM.TONE command.
This command provides the means to create
tones using the PWM.
Syntax
The
PWM.TONE command follows a concise syntax:
PWM.TONE channel,
frequency [, duration_ms]
-
channel: Selects a specific PWM channel for tone output.
-
frequency: Specifies the frequency of the generated tone in Hertz
(Hz).
-
duration_ms: (Optional) Defines the duration of the tone in
milliseconds (ms). If omitted, the tone will play indefinitely.
Practical Examples
Example 1:
Single Tone
To generate a continuous tone at 1000 Hz on
channel 1, use:
PWM.TONE 1,
1000
This command establishes a steady 1000 Hz tone
on channel 1.
Example 2:
Timed Tone
For a tone lasting 200 ms at 2000 Hz on
channel 2, apply:
PWM.TONE 2, 2000,
200
Channel 2 will produce a tone at 2000 Hz for a
duration of 200 milliseconds.
Example 3:
Stopping a Tone
To halt an ongoing tone on channel 1, use the
following command
PWM.TONE 1,
0 command
Prior to using PWM.TONE, ensure proper channel
setup using the PWM.SETUP command, for example using
PWM.SETUP 5, 1,
0. (pin 5, channel1, default output at 0)
Be mindful of the channel's frequency range
and resolution limits.
I²S (Inter-IC Sound), is an electrical serial
bus interface standard used for connecting digital audio devices
together. It is used to communicate PCM audio data between
integrated circuits in an electronic device.
The I²S bus separates clock and serial data
signals, resulting in a lower jitter than is typical of
communications systems that recover the clock from the data
stream.
Despite the name similarity, I²S is
unrelated to the bidirectional I²C (I2C) bus.
The bus consists of three lines:
Bit clock line
-
Typically called "bit clock (BCLK)". PIN GPIO5
Word clock line
-
Typically called "left-right clock (LRCLK)" or “Word Select
(WSEL)”. PIN GPIO26
Data line
-
Typically called "serial data (SD)". Can also be called (SDIN,
SDOUT or DATA). PIN GPIO2
The typical use of the I2S is to connect an
external DAC to provide a High Quality stereo sound output.
Using the PLAY.xxx commands, it will be
possible to play MP3 and WAV files directly from the disk.
Any generic I2S DAC can be used.
Annex32 has been successfully tested with the
PC5102A and the UDA1334A
UDA1334A I2S DAC
PCM5102A I2S DAC
NOTE:
This module requires the following setting
(solder joints)
Component side:
Next to the sck connection
Back side:
1 set to L
2 set to L
3 set to H
4 set to L
It is now also possible to use the CODEC
ES8388 using the command
OPTION.ES8388
The M5stack contains an internal speaker
connected, via an audio amplifier, to the pin GPIO25.
This permits the generation of audio signals
using the internal 8 bits DAC.
Using the PLAY.xxx commands, it will be
possible to play MP3 and WAV files directly from the disk.
It is possible to connect an earphone directly
on the output between the pin GPIO25 and the ground but the best is
to connect a little audio amplifier.
NOTE: it is recommended to put a capacitor
( ~100nF) between the GPIO25 and the audio amplifier in order to
remove the DC component from the audio signal.
The I²C bus allows the module to connect to
I²C devices.
I²C uses only two bidirectional open-drain
lines, Serial Data Line (SDA) and Serial Clock Line (SCL), pulled
up with resistors (typically 4.7K to 10K).
The I²C has a 7 bit address space permitting,
theoretically, to connect up to 126 I/O devices.
The maximal number of nodes is limited by the
address space and also by the total bus capacitance of 400 pF,
which restricts practical communication distances to a few meters.
The relatively high impedance and low noise immunity requires a
common ground potential, which again restricts practical use to
communication within the same PC board or small system of
boards.
The current implementation is master mode @
100Khz by default.
The SDA and SCL pins can be freely defined
using the command
I2C.SETUP sda_pin,
scl_pin.
For example, to define pins
21(SDA) and 22(SCL) the command is :
I2C.SETUP 21,
22
It is important to provide correct pullup
resistors on these lines; values between 4.7K to 10K should be
appropriate.
The commands available are :
I2C.BEGIN,
I2C.END, I2C.REQFROM, I2C.SETUP, I2C.WRITE
The functions available are :
I2C.LEN,
I2C.READ, I2C.END
There are also other advanced
functions / commands to simplify exchanges with the i2c
bus.
The advanced commands available
are :
I2C.READREGARRAY,
I2C.WRITEREGBYTE,I2C.WRITEREGARRAY
The advanced functions available are :
I2C.READREGBYTE[9] [10]
The I2C bus can also
be used with the IO Buffers ( look at the dedicated chapter)
As all the devices can have a "not well"
determined address, please find here a little i2c scanner program
which returns the address of all the devices found connected to the
bus
'I2C Address
Scanner
'print in the
console the address of the devices found
I2C.SETUP
21, 22
' set I2C port on pins 21 and
22
for
i
= 0 to 120
i2c.begin i
if i2c.end = 0
then
print "found "; i , hex$(i)
pause 10
end if
next
i
end
|
This is an example of connection of a module
with PCF8574 bought on Ebay at less than 2€
This drawing shows
how this module must be connected to the ESP32.
It provides 8
digital inputs or outputs.
This is an example of code that "drives" this
module:
I2C.SETUP 21,
22 ' set I2C
port on pins 21 and 22
device_address = 32 'set to
module i2c address
'Write from 0
to 255 on the module
'Each pin
will blink at different frequency
For
i
= 0 to 255
PCF8574_write
i
Next
i
'Read all the
inputs
'The result
is printed into the serial console
' put all the
inputs at pullup state
PCF8574_write
255
r
= 0
For
i
= 0 to 1000
PCF8574_read r
Print r
Next
i
End
sub
PCF8574_write(x)
i2c.begin
device_address
i2c.write x
i2c.end
end
sub
sub
PCF8574_read(x)
i2c.reqfrom device_address,
1
x
= i2c.read
i2c.end
end
sub
|
This is another example of connection of a
module with ADS1115 bought on Ebay at less than 2€.
This is a 16 Bit ADC 4 channel Module with
Programmable Gain Amplifier.
Because the module already contains two 10K
I2C pullups, no external resistors are required
As this device is quite simple to interface,
it can be directly driven using a “driver” written in basic.
' ADS1115
Driver for Annex
' datasheet
http://www.ti.com/lit/ds/symlink/ads1115.pdf
' ADS1115
Registers
ADS1115_ADDRESS
= &h48
ADS1115_CONV_REG
= 0 : ADS1115_CONF_REG = 1
ADS1115_HI_T_REG
= 2 : ADS1115_LO_T_REG = 3
i2c.setup
21, 22
' set I2C bus
' Set the
ADS1115 with :
'
AINp = AIN0 and AINn = AIN1
'
FSR = ±4.096 V
'
16 SPS
ADS1115_setup 0, 1,
1
' scale in
volt
scale = 4.096 /
32768
v = 0
for
i
= 0 to 100000
ADS1115_read v
' read from the
module
print v *
scale
next
i
end
'---------------------------------------------------------
' INPUT
MULTIPLEX :
' AINp is
the input positive
' AINn is
the input negative
'0 : AINp =
AIN0 and AINn = AIN1
'1 : AINp =
AIN0 and AINn = AIN3
'2 : AINp =
AIN1 and AINn = AIN3
'3 : AINp =
AIN2 and AINn = AIN3
'4 : AINp =
AIN0 and AINn = GND
'5 : AINp =
AIN1 and AINn = GND
'6 : AINp =
AIN2 and AINn = GND
'7 : AINp =
AIN3 and AINn = GND
'GAIN
'0 : FSR =
±6.144 V
'1 : FSR =
±4.096 V
'2 : FSR =
±2.048 V
'3 : FSR =
±1.024 V
'4 : FSR =
±0.512 V
'5 : FSR =
±0.256 V
'6 : FSR =
±0.256 V
'7 : FSR =
±0.256 V
'DATA
RATE
'0 : 8
SPS
'1 : 16
SPS
'2 : 32
SPS
'3 : 64
SPS
'4 : 128
SPS
'5 : 250
SPS
'6 : 475
SPS
'7 : 860
SPS
sub
ADS1115_setup(inp_mux, gain, rate)
local conf
conf = (inp_mux
<< 12) or
(gain << 9)
or (rate << 5)
or 3 ' +
disable comp
'use the IO Buffer 0 for
writing
iobuff.dim(0,2)
= (conf and
&hff00) >> 8
, conf and &hff
i2c.write_iobuff(0),
ADS1115_ADDRESS, ADS1115_CONF_REG
end
sub
sub
ADS1115_read(ret)
'use the IO Buffer 0 for
reading
i2c.read_iobuff(0),
ADS1115_ADDRESS, ADS1115_CONV_REG, 2
if iobuff.len(0)
= 0 then
print "No
communication"
ret
= 0
else
ret
= iobuff.read(0, 0)
<< 8 + iobuff.read(0, 1)
end
if
if ret >
32768 then ret = ret -
65536
end
sub
|
This is another example for connecting an I2C
module, an MCP20S17 bought on Ebay at less than 2€.
This module provides 16 GPIO pins that can be
used as digital inputs or outputs.
Because the module already contains two 10K
I2C pullups, no external resistors are required
As this device is quite simple to interface,
it can be directly driven using a “driver” written in basic.
' MCP23017
Driver for Annex
' datasheet
http://ww1.microchip.com/downloads/en/DeviceDoc/20001952C.pdf
I2C.SETUP
21, 22
' set I2C port on pins 21 and
22
device_address
= 32 'set to module i2c address
'MCP23017
internal registers
IODIRA
= 0 : IODIRB
= 1 : IPOLA = 2 : IPOLB = 3
GPINTENA = 4 : GPINTENB = 5 : DEFVALA =
6 : DEFVALB = 7
INTCONA = 8 : INTCONB = 9 : IOCONA = 10 : IOCONB = 11
GPPUA
= 12 : GPPUB
= 13 : INTFA
= 14 : INTFB
= 15
INTCAPA = 16 : INTCAPB =
17 : GPIOA = 18 :
GPIOB =
19
OLATA
= 20 : OLATB
= 21
i2C.WriteRegByte
device_address, IOCONA,
&h08 ' init MCP23S17 with bit HAEN
i2C.WriteRegByte
device_address, IODIRA,
&hFF ' all PORT A pins as input
i2C.WriteRegByte
device_address,
GPPUA, &hff ' set PORT A pullup on all
pins
i2C.WriteRegByte
device_address, IODIRB,
&h00 ' all PORT B pins as output
r = 0
for
z
= 0 to 255
I2C.WriteRegByte device_address, GPIOB, z
' pulse all GPIOB
pins
r = i2C.ReadRegByte(device_address, GPIOA) ' read
all GPIOA pins
print r
pause 100
next
z
|
The SPI bus allows
the module to connect to SPI devices.
The Serial
Peripheral Interface bus (SPI) is a synchronous serial
communication interface used for short distance communication
between devices.
SPI devices
communicate in full duplex mode using a master-slave architecture
where the ESP32 is the master. The ESP32 generates the frame for
reading and writing.
Multiple slave
devices are supported through selection with individual chip select
(CS) lines.
The SPI bus utilise four
logic signals:
SIGNAL
|
DESCRIPTION
|
I/O
PIN
|
SCLK
|
Serial
Clock (output from the ESP32)
|
GPIO18
|
MISO
|
Master
Input Slave Output (data input to the ESP32)
|
GPIO19
|
MOSI
|
Master
Output Slave Input (data output from the ESP32)
|
GPIO23
|
CS
|
Chip
Select (often active low, output from the ESP32)
|
Any
output pin, controlled automatically
|
Because these
pins are allocated by default, they may not not be available, by
default, to be used as generic GPIO pins.
For that the
command
SPI.STOP enable to recover the control on these I/O
pins
CS pin
As many devices can
be connected in parallel, sharing the same SCLK, MISO and MOSI
signals, each device is controlled individually using an individual
CS signal.
As Annex32
implements multitasking, in order to guarantee that the CS signal
is generated in phase with the data to be transferred, the CS pin
is managed automatically.
The command
SPI.CSPIN pin [,
polarity] permits the pin associated with the device to
be controlled. Additionally, it permits to define the
polarity as 0 = active low (default) and 1 = active high.
SPI
Mode: Polarity and Clock Phase
The SPI
interface defines no protocol for data exchange, limiting overhead
and allowing for high speed data streaming. Clock polarity (CPOL)
and clock phase (CPHA) can be specified as ‘0’ or ‘1’ to form four
unique modes to provide flexibility in communication between master
and slave as shown below :
If CPOL
and CPHA are both ‘0’ (defined as Mode 0) data is sampled at the
leading rising edge of the clock. Mode 0 is by far the most
common mode for SPI bus slave communication.
If CPOL
is ‘1’ and CPHA is ‘0’ (Mode 2), data is sampled at the leading
falling edge of the clock. Likewise, CPOL = ‘0’ and CPHA = ‘1’
(Mode 1) results in data sampled on the trailing falling edge and
CPOL = ‘1’ with CPHA = ‘1’ (Mode 3) results in data sampled on the
trailing rising edge.
The
table below summarizes the available modes.
Mode
|
CPOL
|
CPHA
|
0
|
0
|
0
|
1
|
0
|
1
|
2
|
1
|
0
|
3
|
1
|
1
|
The data can also
be sent MSB first or LSB first.
This is defined as
bit order and is MSB first by default
Even if the chip is
able to achieve 80Mhz, the maximum realistic SPI speed is
40Mhz.
The commands available are :
SPI.SETUP speed
[,data_mode [, bit_order]]
SPI.CSPIN pin [,
polarity]
The functions available are :
ret =
SPI.BYTE(byte)
a$ =
SPI.STRING$(data$,
len)
a$ =
SPI.HEX$(datahex$,
len)
As said
previously, because the ESP32 uses multitasking, it is
impossible to warrant the exclusive use of the SPI bus during the
execution of the script (it could be used by the SD card or the
TFT, for example).
For this reason, the
CS pin is managed internally by Annex directly by the SPI
functions.
This is defined with
the command
SPI.CSPIN pin [,
polarity]
The optional
parameter polarity
defines if the CS signal must be active low (0 = default) or active
high (1).
This command will set
the pin automatically as output.
The SPI bus can also
be used with the IO Buffers ( look at the dedicated chapter)
Look at the examples
below for more details:
This is an example of connection of a module
with 74HC595 bought on Ebay at less than 2€
This drawing shows
how this module must be connected to the ESP8266.
It provides 8
digital outputs.
This is an example
of code that "drives" this module:
'Write from 0
to 255 on the module
'Each pin
will blink at different frequency
spi.setup
100000
' set the SPI port at
100KHz
SPI.CSPIN 15,
1 ' defines the pin 15 as CS active
high
for
i
= 0 to 255
r
= spi.byte(i)
next
i
end
|
This is another example for connecting an SPI
module, an MCP23S17 bought on Ebay at less than 2€.
This module provides 16 GPIO pins that can be
used as digital inputs or outputs.
As this device is quite simple to interface,
it can be directly driven using a “driver” written in basic.
This is an example using the SPI pins and the
GPIO15 as CS signal
' MCP23S17 Driver for Annex
' datasheet
http://ww1.microchip.com/downloads/en/DeviceDoc/20001952C.pdf
spi.setup 1000000
'MCP23S17 SPI address
MCP23S17_ADDR
= &h40 '
assumes A2, A1, A0 to GND
'MCP23S17 internal registers
IODIRA
= 0 : IODIRB
= 1 : IPOLA = 2 : IPOLB = 3
GPINTENA
= 4 : GPINTENB = 5 : DEFVALA =
6 : DEFVALB = 7
INTCONA
= 8 : INTCONB
= 9 : IOCONA = 10 : IOCONB = 11
GPPUA
= 12 : GPPUB
= 13 : INTFA
= 14 : INTFB
= 15
INTCAPA
= 16 : INTCAPB = 17 : GPIOA = 18 : GPIOB = 19
OLATA
= 20 : OLATB
= 21
MCP23S17_WRITE
IOCONA, &h08 ' init MCP23S17 with bit HAEN
MCP23S17_WRITE
IODIRA, &h00 ' all PORT A pins as output
MCP23S17_WRITE
IODIRB, &hff ' all PORT B pins as input
MCP23S17_WRITE
GPPUB , &hff ' all PORT B pins as pullup
v
= 0
for i
= 0 to 255
for z
= 0 to 255
MCP23S17_WRITE GPIOA, z ' pulse all
GPIOA pins
MCP23S17_READ GPIOB, v '
read all GPIOB pins
print v
next z
next i
End
' function for read / write the MCP23S17
sub MCP23S17_WRITE(register,
value)
SPI.CSPIN
15
a
= SPI.byte(MCP23S17_ADDR)
a
= SPI.byte(register)
a
= SPI.byte(value)
end
sub
sub
MCP23S17_READ(register, value)
local a
SPI.CSPIN 15
a = SPI.byte(MCP23S17_ADDR or 1)
a = SPI.byte(register)
value = SPI.byte(0)
end
sub
|
A Controller Area Network (CAN bus) is a
robust vehicle bus
standard designed to allow microcontrollers
and devices to communicate with each other's applications without a
host computer.
It is a message-based
protocol, designed originally for multiplex
electrical wiring within automobiles to save on copper, but can
also be used in many other contexts.
The Annex32 implements the support for
standard CAN 2.0A (11-bit identifier) and CAN 2.0B (29-bit
identifier).
To interface with an external CAN BUS, the
ESP32 requires the use of a CAN transceiver like the
TJA1050, the MCP2551 or the SN65HVD230.
For example this module is based on the chip
TJA1050 and can be bought for around 1€ on the internet.
Annex32 supports the transmission and
reception of CAN BUS frames.
The bus can be initialised in NORMAL mode, NO
ACK mode and LISTEN ONLY mode
The following BUS speeds are supported 25, 50,
100, 125, 250, 500, 800, 1000 (Kbits / sec).
To use the CAN BUS, it must be initialised
before using the function
CAN.SETUP :
ret
= CAN.SETUP(speed, pin_tx, pin_rx, [can_mode [,
filter_code, filter_mask]])
where :
speed
is the bus speed in Kbit/sec and can be 25, 50, 100, 125, 250, 800,
1000
pin_tx
is the pin of the ESP32 used for the TX signal (connected to the
transceiver)
pin_rx
is the pin of the ESP32 used for the RX signal (connected to the
transceiver)
can_mode
can be 0 (NORMAL), 1 (NO ACK) or 2 (LISTEN ONLY). Optional,
defaults to 0 (NORMAL)
filter_code
is the reception filter code. Optional, defaults to &h00000000
(32 bits)
filter_mask
is the reception filter mask. Optional, defaults to &hFFFFFFFF
(32 bits)
The function returns 0 if OK or another value
in case of error
can_mode
represents how the ESP32 interfaces with the BUS
can_mode
|
DESCRIPTION
|
NORMAL
|
Normal operating mode where CAN controller can
send/receive/acknowledge messages
|
NO
ACK
|
Transmission does not require acknowledgment.
Use this mode for self testing
|
LISTEN ONLY
|
The CAN controller will not influence the bus
(No transmissions or acknowledgments) but can receive messages
|
filter_code
and filter_mask can be used to filter messages of a
particular ID.
[11]
Example:
ret
= CAN.SETUP(500, 4, 5, 1) 'Set the bus
at 500Kb/sec in NO ACK mode using the pins 4 and
5
Alternatively, the CAN BUS can be initialised
using the function
CAN.INIT; this function has the same functionality such
as the
CAN.SETUP but gives more control on the BUS timing
(for advanced users) :
ret
= CAN.INIT(pin_tx, pin_rx, can_mode, brp, tset_1,
tseg_2, sjw, triple_sampling, [filter_code,
filter_mask])
where :
pin_tx
is the pin of the ESP32 used for the TX signal (connected to the
transceiver)
pin_rx
is the pin of the ESP32 used for the RX signal (connected to the
transceiver)
can_mode
can be 0 (NORMAL), 1 (NO ACK) or 2 (LISTEN ONLY)
brp
is the Baudrate prescaler (i.e., APB clock divider) can be any even
number from 2 to 128
tset_1
is the Timing segment 1 (Number of time quanta, between 1 to
16)
tset_2
is the Timing segment 2 (Number of time quanta, 1 to 8)
sjw
is the Synchronization Jump Width (Max time quanta jump for
synchronize from 1 to 4)
triple_samp
can be 1 to enable the triple sampling when the CAN controller
samples a bit
filter_code
is the reception filter code. Optional, defaults to &h00000000
(32 bits)
filter_mask
is the reception filter mask. Optional, defaults to &hFFFFFFFF
(32 bits)
The function returns 0 if OK or another value
in case of error
[12]
Example:
PRINT
CAN.INIT(4,
5, 2, 8, 15, 4, 3, 0)
'Set the bus at 500Kb/sec in LISTEN
ONLY mode using the pins 4 and 5
The function
CAN.STOP permits to stop the driver disconnecting it
from the BUS :
ret
= CAN.STOP
The function returns 0 if OK or another value
in case of error
The function
CAN.WRITE permits to write a message on the BUS; the
message can be composed from 0 to 8 bytes.
ret
= CAN.WRITE( id, can_flags [,b0 [,b1 [,b2 [,b3 [,b4
[,b5 [,b6 [,b7 ]]]]]]]])
where :
id
is the ID of the message to be sent; must be 11 bits or 29 bits for
extended messages
can_flags
is used to indicate the type of
message transmitted/received.
b0 ...
b7 message
bytes. Any combination from 0 to 8 bytes can be specified
The function returns 0 if OK or 1 of
message not sent correctly
can_flags
represents the type of message transmitted/received.
can_flags
|
DESCRIPTION
|
0
|
No message flags (Standard Frame Format)
|
1
|
Extended Frame Format (29bit ID)
|
2
|
Message is a Remote Transmit Request
|
4
|
Transmit as a Single Shot Transmission
|
8
|
Transmit as a Self Reception Request
|
16
|
Message's Data length code is larger
than 8. This will break compliance with CAN2.0B
|
Example:
PRINT
CAN.WRITE(
&h12345678,
1, 10, 20, 30) 'Send an extended message with ID &h12345678
composed of 3 bytes (10, 20, 30)
The message can also be sent using the
IOBUFFERS with the function
CAN.WRITE_IOBUFF :
ret
= CAN.WRITE_IOBUFF(bufnum)
The function returns 0 if OK or 1 of
message not sent correctly
The iobuffer must be set before and must
contains from 5 to 13 bytes structured as below :
IOBUFFER
BYTE
|
DESCRIPTION
|
0
|
Message ID Byte 0 (Most significant byte)
|
1
|
Message ID Byte 1
|
2
|
Message ID Byte 2
|
3
|
Message ID Byte 3 (Least significant byte)
|
4
|
Can_flags defined as the previous table
|
5 to
12
|
Message bytes ( can span from 5 to 12 for
message bytes 0 to 8)
|
Another event,
ONCANBUS , has been included to determine when a CAN
message ha