Your Pages‎ > ‎

Code Snippets

Add any useful or frequently used code snippets below...


Simple LED Toggle

CODE: Simple LED Toggle

pin(ledpin) = 1 - pin(ledpin)   'assuming ledpin has been previously assigned to a gpio pin




Display Background Image - Electroguard 1/4/18

CODE: Display Background Image

a$ = a$ + |<style>body {background-image: url("/img/wood.jpg");}</style>| 'Tiles the image

A$ = A$ + |<style>body {background: url("/img/c42.jpg") no-repeat center fixed; background-size: cover;}</style>| 'Stretches image to fit


(where /img/ is the spiffs folder containing the image files)



Colour Picker - Electroguard  2/4/18

CODE: Colour Picker

cls

col$ = "#ff0000"   'sets the default colour

a$ =  |<input type="color" data-var='col$' onchange='cmdChange(event)' value="#ff0000">|

html a$

timer0 1000, readcolor

wait


readcolor:

wlog col$    'shows selected colour in web console

print col$    'shows selected colour in serial console

return



Centered Div - Electroguard  2/4/18

a$ = "<div id='clock' data-var='mybranch' onclick='cmdButton(this)' style='display: table; margin-right: auto; margin-left: auto;;'>" + time$ + "</div>"



Embedding Fonts using @FontFace Rule  - Electroguard  2/4/18

<style>@font-face {font-family: myfont; src: url('/path/filename.ext');}</style>


Substitute 'myfont' for your own preferred name if you wish.
Substitute '/path/' for the 'root-relative' path to your font(s). eg: '/font/'
Substitute 'filename.ext' for the saved font filename and its extension (eg:ttf)
Or preferably use a pre-defined variable in place of the literal 'filename.ext'
 ---------------------------------------


Radio Buttons - Cicciocb 14/06/18

CODE: Radio Buttons

cls

a$ = ""

a$ = a$ + |<input type="radio" data-var="a$" name="gender" onchange="cmdChange(event)" value="1"> Choice 1<br>|

a$ = a$ + |<input type="radio" data-var="a$" name="gender" onchange="cmdChange(event)" value="2"> Choice 2<br>|

a$ = a$ + |<input type="radio" data-var="a$" name="gender" onchange="cmdChange(event)" value="3"> Choice 3<br>|

html a$





Refresh using Javascript- Cicciocb 06/07/18

CODE: Refresh using Javascript (actual value 500 msec)

jscall "if (typeof rfr != 'undefined') clearInterval(rfr);rfr=setInterval(function(){ getVariables(); }, 500);"




File History Check - Electroguard 18/08/18

CODE: File History Check Snippet

' File History Check Snippet v1.2, by Electroguard - warns if the currently loaded file was not the previously loaded file
' Creates a history file called "filehistory" which contains a 'most recent first' list of previously used files on the device
' It is optional if the history list gets displayed or not, and the file can simply be deleted using File Manager when too long
' Until Annex includes such a feature, simply add this snippet to the top of all scripts which you use on all your modules
' Useful for reminding to update the Config autorun filename after editing and saving different versions of an autorunning file
' Also useful as a reminder of what file you were last using on different devices when switching between modules
filename$ = BAS.FILENAME$: historyfile$ = "/filehistory": history$ = ""
if FILE.EXISTS(historyfile$) > 0 then
 history$ = FILE.READ$(historyfile$)
 if word$(history$,1,chr$(10)) <> filename$ then
  wlog  "Attention: this file " + filename$ + " was not the last loaded file shown in the history list"
  wlog history$   'comment out to prevent history list from showing
  print "Attention: this file " + filename$ + " was not the last loaded file shown in the history list"
  print history$  'comment out to prevent history list from showing
 endif
endif
if word$(history$,1,chr$(10)) <> filename$ then
 history$ = filename$ + chr$(10) + history$ 
 FILE.SAVE historyfile$, history$ 
endif
'------- End of File History Check Snippet -------

When a device no longer has the last used browser Editor page available it can be difficult to remember what was the last stage of development of the last project under development on all the different ESP modules laying around... so when switching between different modules it is very easy to lose track of recent progress and end up repeating much of it again.

Another gotcha is saving different progress versions of a script that is being autorun - and after much failed debugging and headscratching you realise you forget to update the autorun filename in the Config page to the latest version you have been editing... so you have not actually been autorunning the latest file you have been editing.

This File History Check snippet prevents such problems, by offering a file history of all files used on a device, and warning if the loaded file is different to the last used file.
If I had taken the time to do it a while ago I could have saved myself a lot of wasted time - I just need to remember to add it to the top of all scripts I use from now on.

The actual file history contents of "/filehistory" can be viewed, or the file deleted, from the File Manager page.

 
Autorun filename Updater - Electroguard 24/09/18

I'm not a natural programmer with a mind as sharp as a blade, so most of my 'development' is a matter of 'trial n error' wrestling things into the general direction I want to go.
Often, experimental changes on subsequent parts of the script introduce unnoticed problems into previously working sections, and the bigger the script gets, the bigger the mess.
So to minimise such potential disasters, and provide an obvious breadcrumb trail of the various stages of development, I've got into the habit of periodically incrementing the last letter or number of the filename... so for example changing "myfile.bas" to "myfile2.bas" to "myfile25b.bas" etc. Sure it can accumulate a lot of old junk, but it is easy enough to archive  everything off into a "myfile.zip" and delete most of the the old files periodically, and it means I always have the different stages of development to fall back on if ever needed.

However, incrementing filenames can sometimes be its own source of problems - cos no point developing a script which cannot restart by itself in the event of returning power outages etc - so any scripts I create invariably need to Autorun. 
But whenever I save a different incremental filename to an autorun file, I need to remember to also update the config.ini "Autorun=filename" entry with the appropriate new filename... else it will be the old file which autoruns, misleading me into thinking my last edits on the new filename did not have the expected result.
This has happened enough times that I was motivated to do something about it, and the resulting snippet can now be added to the top of any scripts I work on.
When the script is run, the snippet compares the scripts filename with the config.ini "Autorun=" filename entry. If they are the same, or Autorun is blank (therefore autorun is turned off) it does nothing, but if the script name differs from the autorun filename then the config.ini Autorun= entry is updated to match the script name. 
Simply Run the script at least once after Saving as a new filename for that new filename to be able to autorun.

'Autorun filename updater snippet to follow incremented file saves
filename$ = BAS.FILENAME$: config$ = file.read$("/config.ini"): autorun$ = word.getparam$(config$, "Autorun",":")
if autorun$ <> "" and autorun$ <> filename$ then
 wlog "Original Autorun file=" + autorun$:  wlog "This filename=" + filename$
 word.setparam config$, "Autorun", filename$, ":": file.save "/config.ini", config$
 wlog "New Autorun file=" + word.getparam$(config$, "Autorun",":")
endif
'------ end of autorun updater snippet -------

Can be even simpler if you don't want the 2 wlog lines to notify of any autorun updates...

filename$ = BAS.FILENAME$: config$ = file.read$("/config.ini"): autorun$ = word.getparam$(config$, "Autorun",":")
if autorun$ <> "" and autorun$ <> filename$ then word.setparam config$, "Autorun", filename$, ":": file.save "/config.ini", config$


Define constants from an external file - cicciocb 12/03/19
CODE: constants_in_file.bas

'this is a snippet on how define constants into an external file and import into Annex
'
'fill a text file with several lines as below
' constant1 = 123
' contrant2 = 555
' .......

'running this snippet, will create these constants into the basic

'constants filename
k_filename$ = "/constants.txt"

z = 1
a$ = file.read$(k_filename$, z)
while (a$ <> "_EOF_")
  command a$
  z = z + 1
  a$ = file.read$(k_filename$, z)
wend


Add Tooltips to Annex components using 'title' attribute - cicciocb 21/01/20
CODE: tooltip-easy.bas

cls
b$="ciao"

t$ = textbox$(b$)
html replace$(t$, "<input ", "<input title='this is a textbox'")
 
t$ = button$("Press Me", gohere)
html replace$(t$, "<button ", "<button title='this is a button'")

gohere:


Non-volatile 'Track n Trace' - Electroguard  23/12/2020
Requires Annex 1.42.5C
Add this snippet to find out the last thing your bricked script did before it hung or rebooted.
If you just wish to monitor memory usage, then you don't need to add the breadcrumb trail to the top of your subroutine branches... but you'll probably wish you had eventually.
Make sure you remember to click the "Stop log" checkbox in the Editors screen, else when you Run the script your important info may disappear before you get a chance to see it (particularly frustrating if you forgot to previously clear the log).

Add this snippet to the top of the script to show the previously saved info at startup...
wlog "Last saved info: " + bas.rtcmem$ + chr$(10)       'requires relevant info to have been previously saved (see below)
spy = 1    '0=disable, 1=keep saving last info, eg: breadcrumb$ plus Ramfree plus time$ + date$ to non-volatile mem, which can be read at next startup in case of unexpected hanging or reboot.

Add something somewhere to save important info anywhere of interest and whenever appropriate
The first is a shortened example snippet from my repeating timer0 1000, Heartbeat subroutine...
HEARTBEAT:
if spy = 1 then bas.rtcmem$ = "Breadcrumb$=" + breadcrumb$ + " Ramfree=" + str$(ramfree) + " at " + time$ + " on " + date$
breadcrumb$ = "heartbeat":  if breadcrumbs >= 4 then wlog " .. " + breadcrumb$   'add something similar to all subroutines
'blah blah
return

This next is from my Restart (reboot) subroutine...
RESTART:
msg$ = " Controlled reboot at " + time$ + " on " + date$
breadcrumb$ = "RESTART": if breadcrumbs >= 2 then wlog " .. " + breadcrumb$ + " msg$=" + msg$
bas.rtcmem$ = msg$
pause 1000
reboot
return

The numeric variable breadcrumbs sets the reporting level for the breadcrumb trail, eg: breadcrumbs=3 would show the jump to RESTART: but not all the repeating jumps to HEARTBEAT: 
The numeric variable spy=0 allows turning off the repeating writes to the non-volatile mem from heartbeat without needing to rip out the code.
(I still prefer to record scheduled and controlled shutdowns).
 ---------------------------------------