Place to put your Basic demos and examples

Moderator: Mmiscool

User avatar
By Electroguard
#46940 ESP_Basic Driving Lessons - Chapter 1.

This isn't intended to teach Basic, it's to help newcomers have a quick leg-up and get them quickly dabbling with ESP_Basic for themselves. Don't take the offered help as official or gospel, nor shoot me for my doubtless many mistakes... it is merely personal hindsight and opinion being offered to anyone who might appreciate it. At the time of writing the latest version is Alpha 21.

At A Glance
Chapter 1: (this) Explains how ESP_Basic differs from what you may already know. It walks you through the installation of ESP_Basic, then prepares you for the driving seat.
Chapter 2: Gives you your first ESP_Basic driving lessons, and points out several tips and gotchas. It also provides you with a Time Machine and starts you on a journey several days into the future.
Chapter 3: Completes your journey into the future, having transformed you into a competent ESP_Basic debugger in minutes rather than the many days (or weeks) it would otherwise take.
Chapter 4: Warns you about the Mad House.
Chapter 5: Takes you racing with hardware.
Chapters 6, 7, 8, 9: Reserved for future use - one will be a udp networking tutorial


Chalk and Cheese
If you are coming from Arduino and C++, well good on you - but it won't do you much good here... better to forget all pre-conceptions and approach ESP_Basic as a complete beginner, because they couldn't be more different from each other.
I would liken the Arduino and C++ ways of doing things to being in the armed forces - strict rules, rigidly enforced discipline, assault courses, survival of the fittest, hard graft, pain, blood sweat and tears, not for the faint-hearted.
In comparison, ESP_Basic is like play school - quickly dive straight in and be left alone to have as much boisterous fun as you want, without any lengthy training, or any punishment for getting things wrong. If you think that's fanciful, then let's do a quick real comparison:
Arduino and C++ requires you to use hundreds of Mb just for the IDE alone, never mind all the libraries and additional tools you'll eventually collect. Once you've got that running, you need to compile your sketch, which will refuse to compile with just 1 tiny character missing or out of place. For a first-time newcomer, just to get a sketch working can take several hours (if not days) of strictly regimented tasks, and then trying to learn from experimental changes can be a very long and wearisome task of failing re-compiles.
ESP_Basic on the other hand lets you start dabbling with a script in less than 5 minutes, and then trying out any experimental script changes takes just seconds. If you doubt that, or think it exageration, I suggest you time how long it takes for yourself!

INSTALLATION
This is the process in a nutshell for a complete techno-virgin...
Download the ESP_Basic 'Flashing' utility from here:
http://www.esp8266basic.com/download.html
It's just one small exe that can be saved and run from wherever you like (even the desktop if you wish).
Double-click the downloaded file to run it.
No folder structure is needed or created, it simply pops up a window for you to enter your particular ESP's flash size (just select 512K if you're not sure about yours), the com port you will be using to connect to your ESP, and a couple of big un-missable buttons.
Boot your ESP into flash mode (power-on or reset with gpio00 button or jumper on), click the flashers big Re-flash button, then wait a few seconds for the blue led to stop flashing... then the ESP will automatically reboot up as your ESP_Basic wifi AP (access point) for you to connect up to in your browser by entering its default IP address of 192.168.4.1
Job done! And it couldn't have been any easier or quicker.

LIGHTWEIGHT
First thing to realise is that the browser is all you need for using ESP_Basic on your ESP.
If you are awake, and not in awe, then you truly are a techno-virgin! - because that should be quite an astonishing sentence to assimilate for anyone who is used to the arduino IDE and compilers and toolchains and libraries etc.
To ensure you are fully awake - having flashed with ESP_Basic once, you no longer need to flash with the UART again unless you wish to upgrade or re-install ESP_Basic - because any and all ESP_Basic programming is now done remotely via wifi and the web browser.
Let me spell that out in case you missed the significance - Lighting-fast Over The Air programming straight out of the box as standard, and without needing to lose half of your ESP flash memory for the privilige!
If you are now paying full attention, then assimilate this - ESP_Basic is capable of running scripts up to 5,000 (FIVE THOUSAND) lines long, and yet ALREADY INCLUDES built-in functionality for web pages, Infra-Red, I2C and SPI peripheral buses, UDP networking, twin serial ports (ie: soft serial), LCD screen drivers, NEO-pixels, etc, etc, and more is being added all the time!

So, it's a case of Basic by name, but certainly not by nature.

To put things into balanced perspective, pre-compiled code allows arduino C++ to do things faster, and the use of libraries allows it to do some things that ESP_Basic cannot (yet) do, but any single ESP_Basic device is capable of collectively doing many more things without running out of resources, and it can do it all much simpler than the equivalent C++ code... which typically requires at least double the lines of code to achieve the same result.

To put it another way... C++ is more for dedicated purists who want faster compiled code operation, whereas ESP_Basic interpreter is more for impatient hobbyists who want faster and easier results.
Last edited by Electroguard on Fri May 06, 2016 1:43 am, edited 2 times in total.
User avatar
By Electroguard
#46941 ESP_Basic Driving Lessons - Chapter 2.

FIRST LESSONS
So assuming you may be an impatient hobbyist who would like some quick and easy results, let's dive straight in...

TIP - unlike the Arduino IDE, you can right-click code with your mouse and do a Copy or Paste, but you may find these bog-standard keyboard shortcuts come in handy: CTRL A to Select All text - CTRL C to Copy selected text to clipboard - CTRL V to Paste text from clipboard - CTRL Z to Undo changes.

If you haven't yet installed ESP_Basic, do so now as per the installation instructions above.
After the ESP reboots, connect to the new ESP access_point which should now be available in your wifi connections, then after the connection is established, type 192.168.4.1 in your browser address bar to connect to it.
Notice the options available at the top, [ VARS ] [ EDIT ] [ RUN ] [ SETTINGS ] [ FILE MANAGER ]

IMPORTANT LESSON 1 - Beware... Edit is misleading - it does not edit the script in your browser Edit window, it downloads the last saved script from the ESP and splats it over whatever was previously in the browser Edit window. You have been warned.

Click [Edit] ... this would load the last 'Saved' Basic script from the ESP (you can't do THAT with an Arduino and C++), but because nothing has yet been Saved you should just have an empty Edit window.

Type GOLD-DUST into the edit window. Now click VARS or SETTINGS or FILE MANAGER, then click EDIT, and see that your pile of gold dust has vanished.

IMPORTANT TIP - when faced with disasterous loss, FREEZE and DO NOTHING, until you can calmly think about what you are going to do next.

Assuming your browser has history enabled, your gold dust should still be sitting safely in the browser history... you just need to click your browser Back button until you get back to it.
When you can see it, stay calm, and carefully do a Select-all (CTRL A) and Copy (CTRL C) to get it temporarily safe in the clipboard (taking care not to do a CTRL V Paste instead of CTRL C Copy else you'll overwrite the script with the previous contents of the clipboard!).

So REMEMBER - in desperate times, your browser Back button can we a good friend!

You then have the opportunity to save it to a text file on computer for safe-keeping.

IMPORTANT LESSON 2 - Beware... Save is misleading - it does not save the script to computer, it uploads it to the ESP. If you subsequently over-write the ESP script by doing a Save or reformat or reflash without saving the script to file on the computer first, then you will lose it. You have been warned.

TIP - Create a new computer text file in notepad and copy and paste your script to that.

TIP - Don't keep pasting to the same file, because eventually you will cock up and overwrite your file with something you didn't intend to. Do a Save As, and append a 'version' letter or number to the filename, so you will accumulate a file version history of progress that you can go back through if required. It's better to periodically delete things you no longer need, rather than rue the loss of something irreplaceable.

TIME MACHINE
The following is an interrupt driven 'blinky' led timer example.
But it is also a time machine capable of transporting a complete beginner hours or even days into the future!
Click SELECT ALL in the top left CODE: bar of the example below to highlight the text.
Notice the last line which says 'end'.

Code: Select allend
let led_pin = 1                      ' Assign onboard blue gpio01 to led
let led_state = 1                    ' Create a variable for remembering on/off condition of led
timer 1000 [toggle_led]              ' Set timed interrupt to periodically toggle led
'let main = "Yes"
wait
end

[toggle_led]
'let branch = "Yes"
if led_state == 1 then led_state == 0  else led_state == 1  ' toggles led_state
po led_pin led_state
wait
end


Copy the highlighted example text whichever way you prefer (keyboard CTRL C shortcut, or mouse right-click then Copy).
Paste the code into the browser Edit window (CTRL V, or right-click then Paste )
Now scroll to the bottom and notice what the last line of the Edit window now shows!

'end' is a valid ESP_Basic instruction, but 'end - blah blah blah' is not, so the added garbage could cause the last line to produce an error rather than carry out the intended last command.

TIP - always check and clean up the last line of your code after pasting anything from the ESP8266 forum or else it could produce an error - it is a forum quirk, and nothing to do with ESP_Basic.

Having scrolled down to the bottom of the text to clean up the last line by deleting everything after the 'end' instruction, you will see that the top line options [VARS ] [ EDIT ] [ RUN ] [ SETTINGS ] [ FILE MANAGER ] have all disappeared. You could scroll back to the top of text to get them back, but that's not quite so easy if your script is hundreds of lines long, so...

TIP - move the cursor up to the buttons area above the script, then do a Scroll_Up to make the options re-appear.

If you look at the first line of the example script it says 'end', this is deliberate in order to teach a couple of lessons. The 'end' instruction tells the Basic parser to terminate it's parsing for instructions because it has reached the 'end' of your program... even if that isn't actually at the physical end of the script.

Click Run. The program terminates with the 'done...' message without actually doing anything.
Click browser Back button to return to the Edit page, then delete the first 'end' line.
Now click Run. The program still terminates without doing anything.

IMPORTANT LESSON 3 - nothing actually happens in your browser, it is only a 'remote controller' to your ESP device, which can only run whatever script you actually Save to it... in this case nothing, because you haven't yet done a Save to the ESP. To prove that point, we will load the contents of the ESP back into the Edit window.

IMPORTANT LESSON 4 - you are about to accidentally on purpose lose your script you've been editing - it won't hurt now, but it probably will in the future... so always better to be safe than sorry by doing a Ctrl A (Select All) and Ctrl C (Copy to Clipboard) before doing anything else after editing your script - then if things go wrong, at least you will still have your script saved to the windows clipboard. You have been warned.

Click Edit to reload your last Saved script, but pay attention to the fact that your latest script edits would be over-written by the old last-saved ESP contents... which is probably not what you would normally be wanting.

That might have been a disaster, but you were prudent, so just need to Ctrl V (Paste) your lost script back into the Edit window from the clipboard. Now do a Save, and ok the confirmation.

So REMEMBER - any script you are looking at in your browser Edit window is still ONLY in your browser UNTIL you click Save to upload it to the ESP ... and not even then, unless the save returns with a confirmed ok.

Lounge Lizard
That's most of the theory out of the way and soon we'll actually hit the road, but first there's a strange beast you will encounter which needs explaining...

If you come from arduino and C++ background you will already be aware of the DELAY command - ESP_Basic also has DELAY, but also an additional WAIT command... which isn't what it sounds like.

To understand what it does, you need to be aware of the brilliant browser functionality that is already built-in to ESP_Basic as standard, and which offers it some outstanding capabilities.
Writing to the browser from the ESP is as simple as HTML "Hello World <BR>", or BUTTON "Press Me" [branch_ to_jump_to]. That is a lot of power condensed into a single instruction, and there are several other web components available such as TEXTBOX and SLIDER and DROPDOWN and IMAGEBUTTON and others.

What all these web components have in common is that they are all generated by the script on the ESP, but only actually get sent out and written to the browser screen when the program reaches the next WAIT instruction.
So WAIT is not a delay, it is the 'trigger' instruction which sends all the requested and accumulated browser components out to the browser screen.

So a way of looking at it is... you are the browser, ordering all your browser goodies from the online ESP store, then having to WAIT for their collective delivery on the same van.

Many other powerful interrupt-driven features are first declared then WAIT to be repeatedly activated... including TIMER {string or var for wait time in milliseconds}, {branch label}. The important point to note is that the specified branch must end with a wait instruction.
Ok, now let's go for a test drive.
Last edited by Electroguard on Fri May 06, 2016 6:04 am, edited 3 times in total.
User avatar
By Electroguard
#46942 ESP_Basic Driving Lessons - Chapter 3.

TIME MACHINE
Make sure you have copied and pasted the example code into the Edit page, then deleted the first 'end' line, then Saved the script.
Click [VARS], taking note that the list of variables is empty, and none of the gpio pins displayed down the right-hand side have been used.
Browser Back to the Edit page.
Click Run. Note the Syntax Error; Label or argument missing.

Which means we have a problem to debug.
Browser Back to the Edit page again.

TIP - you have 2 innocuous but very useful debugging tools at your desposal... the 'end' instruction, and the apostrophe (') to comment out a line. If your program errors with a bug, and you don't know where that bug is in order to correct it, then you need to start hunting it down until you can pin it down. You can do that by inserting 'end' towards the beginning of your script to cause the program to end before it reaches the bug, then keep progressively 'walking' the 'end' instruction deeper into the script, until eventually the error returns because you have gone past the bug line.
You can prove which is the bug line even if the bug is not apparent for the moment, simply by putting an apostrophe at the beginning of the line to comment it out, and then checking that the error msg has stopped.

TIP - if your script does stuff under the covers without any visible cues to look for, you might want to add your own test variables to various branches etc to prove whether the script is actually reaching those parts or not.
This will be clearer if you remove the apostrophe from the beginning of the 2 test lines which I've already added to the script... 'let main = "Yes", and 'let branch = "Yes".
Notice that the test variables are not mentioned anywhere else, so if they ever attain the value of "Yes" it proves the program MUST have reached that point.

Click [VARS] and take note of what it is showing you at the moment with the bug present.

REMEMBER IMPORTANT LESSON 1 - because if you click Edit now to return to your script YOU WILL NOT RETURN TO IT, but will instead download the last saved ESP contents which will splatter over your edited script and lose all your edits - but you did already automatically do a Ctrl A and Ctrl C after doing your edits to save them to clipboard, didn't you?...

So browser Back to the edit page and click Save, then acknowledge the save - I'm not now going to keep repeating that after every Save, but just REMEMBER that if Save DOESN'T come back with an acknowledgement then it DID NOT ACTUALLY ACCOMPLISH THE SAVE!).

Now let's explain the script properly to remove any doubts...
line 1 declares a pin variable for using gpio01 led
line 2 declares an initial state for the led
line 3 configures timer to wait for 1 sec (1000 millis) then generate an interrupt which will cause the program to jump to the [toggle_led] branch.
line 4 now declares our 'main' test variable.
line 5 is where the the program will 'wait' until it is interrupted by the timer.
line 6 end is unnecessary and will never be reached, it is just for proof that the program is still 'wait'ing at the line above for an interrupt.

When timer duration is exceeded it generates an interrupt which causes the program to jump to the [toggle_led] branch label. The next line of the branch declares our 'branch' test variable.

The following IF line just toggles the leds state from whatever it was to the opposite. And the next line actually writes the new toggled state to the led pin. Then it 'waits' for further interrupts. The final 'end' line is again unnecessary and just added to prove the point that the program will indefinitely be 'waiting' for new interrupt events at the line above.

Ok, now that you know what is expected and what to be looking for, click Run, note the same error msg, then browser Back, then click Vars again.

You can see in the left-hand Variable Dump that the first 2 lines were actioned ok and created their 2 variables, and you can see there's no mention of the test variables 'main' or 'branch', so you know the bug must be somewhere after the first 2 lines but before either of the two test variable lines, which pretty much pins it down to the TIMER line doesn't it.

So here's the Language Reference syntax description for TIMER {string or var for wait time in milliseconds}, {branch label}... and notice that innocuous little comma hiding between milliseconds} and {branch. Add that pesky annoyance after the appropriate last zero of your timer line in the script, Save it, then Run it again.

Oh bother...(or words to that effect)... now what?

Browser Back to Edit, click Vars, and see what they are telling you.

The program is obviously now reaching both the 'main' and 'branch' test variables, but led_state which was previously initialised ok to '1' is now showing 'error'.

So we need to browser Back to Edit and examine the line that changes the led_state variable...
if led_state == 1 then led_state == 0 else led_state == 1 ' toggles led_state

Ok, let me save you some time again... two equals (==) is only used for comparisons, only 1 equals is used to set a value, so you need to remove one of the equals before the zero.
You will also need to similarly remove one of the equals before the following 1, but don't do that just yet, just remove the = from before 0, then Save and Run.

Ouch, that's a bit nasty isn't it - sure, you already know what's causing the problem in this instance, but if you didn't you wouldn't have a clue, and although the cause is exactly the same as the problem you've just corrected, the symptoms (or lack of) are completely different.

Browser Back, click Vars, and have the comfort of knowing that your test vars can allow you to pinpoint even where invisible bugs are lurking.

So browser Back to edit, remove the unwanted '=', Save and Run, and now you can see the TIME MACHINE blinking merrily away as it should ... and you can also now consider yourself to be a fairly competent debugger no matter what might get thrown at you in the future.
Last edited by Electroguard on Thu May 05, 2016 4:29 pm, edited 2 times in total.
User avatar
By Electroguard
#46943 ESP_Basic Driving Lessons - Chapter 4.

ALOOF
The TIME MACHINE still has another surprise for you yet though...

Once you have the blue led blinking, Browser Back to the edit screen, click Vars, and notice that the right-hand Pin Stats show that pin 1 has been 'PO'd, proving that your specified io pin is being addressed as required. This is very handy when you need to check various inputs and outputs are as expected.

If you were alert you may have noticed that the TIME MACHINE is still blinking merrily away!

* EDIT *
I don't know if the Lolin NodeMcu V3 even existed at the time of writing the original article, but I've been asked to mention that "On the LoLin NodeMcu V3 Dev Board THE BLUE LED IS ON PIN 2".

Similarly I've been asked to mention that "After running the program for a while go into debug and you can watch the led_status change. Press Stop to stop the program", but I should point out that the Driving Lessons were written during the V2 era before the debug facility was even introduced.



IMPORTANT LESSON 5 - Your ESP has a mind of it's own!

You and your browser are just ESP passengers for as long as it cares to tolerate you... it will continue doing its own thing even after disconnection of your wifi or browser connection!
So don't annoy it with your errors, or it will BITE YOU... you have been warned!

Currently, the only effective way of stopping the ESP from running your basic program is by pressing Save, but it is moody and head-strong and prone to simply ignoring such commands and turning it's royal back on you - so remember this when trying to do a Save which it ignores, and just remember who is the boss... cos it aint you.

I show patient submissiveness by hovering the mouse cursor over the 'Files List' button to the left of the 'Save' button, which can show me when the moody dictator is receptive to outsiders again by the fact that the button becomes noticably active once more... then it should be safe to try to do another timid Save.

If it does not come back to you with a Saved OK acknowledgement, then I'm afraid there's nothing you're gonna do to bully it... so you just need to be patient and keep trying Save again after you've noticed it becoming receptive again. Simple fact of the matter is that it is moody and not going be rushed into doing anything it doesn't feel like doing.

HEAD CASE
It's quite important to remember that variables and branch names are case-sensitive, so if you type the same var name from memory further down in your script and it's not spelt exactly the same as original... then you actually have 2 entirely different un-related variables, which at a quick glance you'd think were the same.

So REMEMBER - Name, name and NAME are all entirely different variable names, and a potential cause of problems. The same goes for branch names.

TIP - if you don't have a mind as sharp as a razor I suggest it's not worth the risk of introducing problems by using vars or branch names that use mixed case letters... if you keep them all in upper or lower case you'll make life a lot easier for yourself.

READ BETWEEN THE LINES
But if you do slip up, VARS is where you can spot that sort of problem, and also look for variables whose contents are not what you should be expecting. You can also check that you are actually addressing the correct gpio pins, and that they have the expected 'states'.

TIP - VARS shows what variables the script encountered when it was run - so just bear in mind that any variables declared in parts of the script that didn't actually get 'excercised' when you ran it are not going to show up because the parser had not even reached them yet!

With a little thought, the deceptively simple Vars page can offer a surprising amount of useful feedback - missing vars, extra vars, unexpected var contents... they can all tell a good story if you're really listening.


I've barely scratched the surface in these chapters, and don't know that much more about ESP_Basic myself yet anyway, but this should be enough info to get you up and running quickly, and able to start trying out the various examples you'll find around the forum and then start experimenting for yourself. You're bound to come across all sorts of problems, but most will already have been explained on the forum if you take the time to look.

A lot of useful info can be found in forlottos very comprehensive and helpful guide here...
http://www.esp8266.com/viewtopic.php?f=40&t=6732
... and many questions can often be answered with a little bit of experimental trial 'n' error.
Don't be afraid to ask if you really are stuck, because someone will try to help if they can. Please just bear in mind though that the only 2 real experts are a couple of very dedicated clever guys who are tirelessly working hard to improve ESP_Basic for everybody, so you can do your bit to help them by not unnecessarily calling mummy just to wipe your nose cos you can't be bothered to go get a hanky. ESP_Basic is actually one of the easier languages to learn even though it does pack a surprisingly powerful punch, so it won't be long before you're surprising yourself by what you can do!

Other chapters might be added in due course, perhaps by other people as well as myself, and maybe even by you... ESP_Basic is still so new that it only takes a focused interest in some aspect to turn you into the resident expert in that area.
Last edited by Electroguard on Sat Jan 28, 2017 8:43 am, edited 3 times in total.