LEARN.PARALLAX.COM
Published on LEARN.PARALLAX.COM (https://learn.parallax.com)
Home > Parallax WX Wi-Fi Module for the BS2

Parallax WX Wi-Fi Module for the BS2

The Parallax WX ESP8266 Wi-Fi module opens up a whole new world of interactive Internet and web features to your microcontroller and robotics projects.  The breadboard-friendly, 5 and 3.3 V compatible SIP package (32420S) works well with the BASIC Stamp 2 microcontroller.

What it’s about

The following tutorial will introduce you the Parallax WX Wi-Fi Module, and get it ready to work with your BASIC Stamp 2 microcontroller.  Then you will create web interfaces for interacting with simple BASIC Stamp controlled pushbutton, LED, and servo circuits. New to HTML and/or Javascript? No problem. We’ll take you through fundamentals so that you can learn to create and optimize your own custom webpages.  Use the navigation below when you’re ready to get started.

Hardware needed

  • WX ESP8266 Wi-Fi Module, SIP (#32420S)
  • Board of Education with BASIC Stamp 2, or
  • BASIC Stamp HomeWork Board
  • a pushbutton
  • LEDs
  • 220 ohm resistors
  • Parallax standard servo
  • Jumper wires

Before you start

This guide assumes you’ve already got some BASIC Stamp + circuit building experience along with PBASIC programming.  If not, here are some nice getting started tutorials and a full reference on PBASIC.

  • Getting started with the BASIC Stamp and robotics
    • Boe-Bot Robot Kit (Kit)
    • Robotics with the Boe-Bot (Free book PDF)
  • Getting started with the BASIC Stamp and circuits
    • BASIC Stamp Activity Kit (Kit)
    • What’s a Microcontroller (Free book PDF)
  • Reference
    • BASIC Stamp Manual (Printed book)
    • BASIC Stamp Manual (Free book PDF)
    • PBASIC Language Reference (online)

After you finish

Once you have gone through this tutorial, you will be ready to integrate Wi-Fi capability into your BASIC Stamp projects to join the Internet of Things.  If you have a Boe-Bot Robot, you can interface it with your smart phone.

 

Parallax WX Wi-Fi Module for the BS2

The Parallax WX ESP8266 Wi-Fi module opens up a whole new world of interactive Internet and web features to your microcontroller and robotics projects.  The breadboard-friendly, 5 and 3.3 V compatible SIP package (32420S) works well with the BASIC Stamp 2 microcontroller.

What it’s about

The following tutorial will introduce you the Parallax WX Wi-Fi Module, and get it ready to work with your BASIC Stamp 2 microcontroller.  Then you will create web interfaces for interacting with simple BASIC Stamp controlled pushbutton, LED, and servo circuits. New to HTML and/or Javascript? No problem. We’ll take you through fundamentals so that you can learn to create and optimize your own custom webpages.  Use the navigation below when you’re ready to get started.

Hardware needed

  • WX ESP8266 Wi-Fi Module, SIP (#32420S)
  • Board of Education with BASIC Stamp 2, or
  • BASIC Stamp HomeWork Board
  • a pushbutton
  • LEDs
  • 220 ohm resistors
  • Parallax standard servo
  • Jumper wires

Before you start

This guide assumes you’ve already got some BASIC Stamp + circuit building experience along with PBASIC programming.  If not, here are some nice getting started tutorials and a full reference on PBASIC.

  • Getting started with the BASIC Stamp and robotics
    • Boe-Bot Robot Kit (Kit)
    • Robotics with the Boe-Bot (Free book PDF)
  • Getting started with the BASIC Stamp and circuits
    • BASIC Stamp Activity Kit (Kit)
    • What’s a Microcontroller (Free book PDF)
  • Reference
    • BASIC Stamp Manual (Printed book)
    • BASIC Stamp Manual (Free book PDF)
    • PBASIC Language Reference (online)

After you finish

Once you have gone through this tutorial, you will be ready to integrate Wi-Fi capability into your BASIC Stamp projects to join the Internet of Things.  If you have a Boe-Bot Robot, you can interface it with your smart phone.

 

Connecting WX Wi-Fi to BS2

STOP: Complete each check mark in order below! Do not connect the module until you reach the appropriate step, or you may damage your Wi-Fi Module.

With the Board of Education, you can connect the WX Wi-Fi module to the AppMod Header (marked X1) or to the breadboard. 

 

Board of Education AppMod X1 Header Instructions

  • Remove all circuits from the Board of Education breadboard, AppMod header, and servo headers that are connected to even-numbered I/O pins.
  • Set PWR switch to 1.
  • Run this program.
' {$STAMP BS2}
' {$PBASIC 2.5}

END
  • Set PWR switch to 0.
  • Socket the module in the BOE AppMod header’s left column of sockets using the diagrams below as a guide.
  • Verify that:
    • The module’s silkscreen side (no parts) is facing left, toward the BS2;
    • The module’s pins are in BOE AppMod header’s left column of sockets, closer to the even numbers;
    • The AppMod header’s right column with the odd numbered labels SHOULD BE EMPTY.

  • Build the pushbutton switch on the breadboard with one terminal connected to P14 and the other connected to Vss.

 

Board of Education Breadboard Instructions

It is possible to build the same circuit on the Board of Education breadboard. However, this leaves much less room for other breadboard circuits, so you may need to create your own alternative parts placements in later activities.

  • Remove all circuits from the breadboard.
  • Connect power to your board.
  • Run this program.
' {$STAMP BS2}
' {$PBASIC 2.5}

END
  • Disconnect power.
  • Build the Wi-Fi module and pushbutton circuits on the breadboard, as shown below.

  • Verify that:
    • The module’s silkscreen side (no parts) is facing left, toward the BS2
    • The module’s pins are in the I/O pin sockets given in the diagram, and not in pins 12-15 (on the Board of Education it would be easy to connect something to those same I/O pins via the servo headers on accident).

Join the Module’s Wi-Fi Network

Now we need our computer to join our module’s network:

  • Set PWR switch to 1.
  • Press/release the P14 pushbutton rapidly 4 times (within two seconds).
  • Find and join the module’s network, it’ll begin with either ESP_ or WX_ followed by a unique six-digit number.

Update the Module Firmware

  • Once you are connected to your module’s network, use your web browser to go to http://192.168.4.1/

  • Click Firmware, and then click Choose File.

  • Navigate to the folder you created in the Download the Latest Firmware Examples step.
  • Select 32420-Parallax-ESP-vnnn.ota (where nnn is the version number) and click Open.

  • Click the Update button.

The page should display “Updating…” for a few seconds, then “Updating done. Rebooting…” When it returns to the original “Please select an .ota file to load…”, it means the update was successfully completed.

Configure Module Communication

Click the Settings button, and make the following adjustments:

  • Set Communications Baud Rate to 4800
  • Set Communications Stop Bits to 2 Stop Bits
  • Click Save
  • Click Save to Flash

Load and View a Test Page

Now it’s time to load a test webpage into your module. Locate the HTML files you downloaded with the firmware in the beginning of this tutorial series, and then follow the steps below:

  • Click the Files button.
  • Click Choose File.

  • Navigate to the PBASIC subfolder.
  • Find and select val-from-micro.html, then click the Open button.
  • Verify that the page displays “File loaded.” below the Progress bar.
  • Open a new tab in your browser and go to http://192.168.4.1/files/val-from-micro.html
  • You should see the following page come up:

Next, we’ll load some test code into your BS2 that will allow you to interact with this webpage. Do not close it.

Test the BS2 to Webpage Connection

First let’s load the test program into your BS2.

  • Navigate to the PBASIC folder.  
    • If you are using the BASIC Stamp Editor, open Val from Micro Host.bs2.
    • If you are using Parallax IDE, open Val from Micro Host.bs2 with a text editor, then copy and paste into the Parallax IDE.
  • Connect power to your board and a programming cable from your board to the computer.
  • Set the board PWR switch to either 1 or 2.
  • Load the program into the BASIC Stamp 2 (BASIC Stamp Editor Run button, or Parallax IDE Download button).

Now we’ll check the connection between your BS2 and the webpage we had you open in the previous page. Make sure you have the page open and visible.

The BASIC Stamp counts upwards at about 4x per second.  Every time you click the web page’s Enter button, the BASIC Stamp should send an updated (and higher) value.

  • Try clicking the web page’s Enter button, wait a few seconds, then click it again.  

In addition to an updated number in the web page, your BASIC Stamp programming software’s Debug Terminal should display that it sent a number each time you click the button:

Join Another Wi-Fi Network

You might have noticed that your computer cannot access the internet while it is part of the Wi-Fi module’s network. So, it’s better to have your computer and the Wi-Fi module both join another network that is able to access the Internet. After you do this, you’ll still be able to do all the same activities with the Wi-Fi module.  The only difference will be instead of 192.168.4.1, you will have to use the IP address that the Wi-Fi network assigns your Wi-Fi module.

  • Click the Networks button.

  • If the Wi-Fi module’s Mode is not already set to STA+AP, select it from the mode drop-down menu now.

You may need to wait for a minute or two for the module to check for and display available networks.

The Wi-Fi module has 3 modes: AP, STA, and STA+AP.  AP stands for access point, and that’s when the Wi-Fi module provides its own access point. In this mode, you can make your computer or phone join the Wi-Fi module’s network and access its web pages. STA is short for station mode, and that’s when the Wi-Fi module has joined another access point and is a station on its Wi-Fi network.  The other access point will assign the Wi-Fi module an IP address.  From that point forward, you’ll use the IP address the module was assigned to access its web pages (instead of 192.168.4.1).  STA+AP mode allows it to function as both an access point and a station.  This mode should only be used for a brief period of time to search access points and join one.  

Stay Secure! Once you have made the Wi-Fi module join another access point, you should switch to station mode (STA) immediately after you have noted the station IP address the Wi-Fi module was assigned by the network.  This way, you can minimize the likelihood that hackers will try to use the module as a bridge into another network.There may be many networks available; scrolling up and down on the page will help you locate the network you want to join. 

  • Select your network.
  • Enter the password (…and hopefully your network will have a more secure password than “MyPassword”!).
  • Click Connect!

After the Wi-Fi module joins another network, it will show you the IP address the network assigned it. Make sure to record the IP address the Wi-Fi access point assigns your Wi-Fi Module. From here on out, you can use that in place of 192.168.4.1.

  • Record the IP address that was assigned to your Wi-Fi module.
  • Connect your computer to the same Wi-Fi network you just had the ESP module join.

IMPORTANT: After the Wi-Fi Module has joined a network, you should note the Station IP Address, and then immediately switch to STA mode. 

  • Click the Networks button to return to that page.
  • Set the Wi-Fi mode to STA.

After the Wi-Fi module is in station mode, its Wi-Fi access point will no longer be available.  So, make sure to connect your computer to the same Wi-Fi network you just connected the Wi-Fi module to. Then, make sure to always use the IP address the Wi-Fi module was assigned.

  • Set your computer to the same network you just had the Wi-Fi module join.

  • In your web browser, replace 192.168.4.1 with the IP address that the Wi-Fi acces point assigned your module.  (In the example above, it’s 192.168.43.64 in this example, but yours may be different. It might even start with values like 10.10. 
  • Did the configuration page come up? Great! You can continue from here using that IP address instead of the 192.168.4.1 shown in these examples.

Get Started With HTML

This primer introduces just enough HTML to help get you started with creating web pages that can interact with your BASIC Stamp + Wi-Fi Module. To help keep the focus on the code, we’ll only include the parts you’ll need to make the web page communicate with a microcontroller, and leave out any additional features. 

The recommended software for these exercises includes the Google Chrome web browser and the text editor provided by your operating system: Windows Notepad, Mac TextEdit, Ubuntu (Linux) gedit.  If you have a Chromebook, find the Caret app in the Chrome Web Store and add to Chrome.

Here is HTML code that displays text in a web page. 

  • Open your text editor program.
  • Click the File menu and select New.
  • Enter the three lines of HTML code below.
<html>
Hello, this is a web page.
</html>
  • Click the File menu and select Save as…
  • Setting the file type will vary with your editor.  In Windows notepad, set the File type to All files (*.*) or All Files.  Other OS text editors typically offer an HTML file type.
  • Set the File name to 01-first-web-page.html.
  • Click Save.

Now that your HTML file has been saved, let’s view it in Chrome.    

  • Open your Chrome browser, press the CTRL + O keys (that’s O as in Open), browse to your file and double-click it.  Note: In Mac, it’s Command + O.
  • Verify that the text message you typed between <html> and </html> is displayed.

 

Try This

  • Click the text editor’s file menu, and select Save As…
  • This time, name your file 02-heading-and-paragraph.html.
  • Open it with your Chrome browser (CTRL+O again).
<html>
  <h1>Page Heading</h1>
  <p>Paragraph text.</p>
</html>

 

How it Works

This is an opening html tag <html>.  This is a closing html tag </html>.  The content between those two tags can be in hypertext markup language, which is abbreviated html.  In html, the <pre><h1>…</h1></pre> opening and closing tags make the browser display text between them as a level 1 heading.  For paragraph text, you can use <p>…</p>.

You can do lots of great things with HTML, and here are some tutorials that start simple and cover the topics you’ll need to make your pages awesome:  

  • w3schools.com HTML(5) Tutorial
  • Tutorialspoint.com HTML5 Tutorial

Get Started With Javascript

Like the HTML primer, this one introduces just enough JavaScript to help get you started and familiarize you with another component of webpage design for your module.  The w3schools.com site will have lots more examples for you to try.

Html also has features for creating interface elements like buttons and checkboxes.  Here is an example that creates a button with the <button>…</button> tags.  The button doesn’t actually do anything yet.  For that, we’ll need Javascript.

  • Use your text editor to enter and save this as 03-button-no-action.html.
  • Open it with your Chrome browser and verify that the button displays, but doesn’t seem to do anything when you click it.
<html>

  <p>This button doesn’t do anything yet.</p>
  <p>The next program will make it do something.</p>
  <button>Button</button>

</html>

 

Try This

Javascript is code you can embed in an HTML document to make it do things automatically. Here is an example that makes an alert box pop up when you click the button.

Some browsers will give you an option to prevent a site from displaying popup alert windows. For the purpose of these lessons, you need to allow your browser to show popup alerts – at least temporarily.

  • Click the text editor file menu, and select Save As…
  • This time, name your file 04-button-with-javascript.html.
  • Open it with your Chrome browser (CTRL+O again).
<html>
  <p>Click button to see alert popup message.</p>
  <button onclick = "showAlert()">Alert Popup</button>
 
  <script>
    function showAlert()
    {
      alert(’This is an alert!’);
    }
  </script>
</html>

 

How it Works

A JavaScript function named showAlert was added between <script>…</script> tags.  The code in this function is contained by curly braces { }.  Inside this function, there’s one JavaScript method call – alert(‘This is an alert!’); 

Changing <button> to <button onclick = “showAlert()”> adds an onclick event to the button tag to make it call the showAlert function when the button is clicked.    

You can do even more great things with a combination of JavaScript and HTML.  So, here are some JavaScript tutorials that also start simple and cover the topics you’ll need to make your pages and IoT applications awesome:  

  • w3schools.com JavaScript Tutorial
  • Tutorialspoint.com JavaScript Tutorial

 

Relay Information with JavaScript

One common task for Internet of Things (IoT) applications is for a page to send information to a “thing” on the internet.  Whether it’s a web-controlled robot, a remote-controlled alarm system, or whatever else you can imagine, the principle is pretty much the same: the JavaScript code has to be able to accept an input, and send information to the Internet thing about the input it received.

Before sending info to the BASIC Stamp through the Wi-Fi module, let’s start with using JavaScript to change text in a web page.

  • Use your text editor to enter and save this as 05-button-changes-text.html.
  • Open it with your Chrome browser and verify that the text below the button changes after you click it.
<html>
  <button onclick = "changeText()">Change Text</button>
  <p id = "myText">Click button to change this text.</p>
 
  <script>
    function changeText()
    {
       document.getElementById("myText").innerHTML =
       "Hey, look, the text changed!!!";
    }
  </script>
</html>

 

How it Works

In this example, the paragraph <p> tag was expanded to <p id = “myText”>.  With this identifier, the JavaScript can modify this paragraph element using document.getElementById(“myText”).innerHTML = “Hey, look, the text changed!!!”;  
In JavaScript, document is an example of an object.  Objects have methods, which are actions that can be performed on their data, like getElementById(“myText”), which finds the element with  the myText ID.  Objects also have properties, and innerHTML is an example of one of the document object’s properties.  By setting that innerHTML equal to “Hey, look, the text has changed!!!”, it replaces the existing innerHTML – Click button to change this text.”

 

Try This

We’ve given HTML button and paragraph elements IDs so that JavaScript can access and modify them.  In this example, JavaScript uses a text input’s ID to get information, adds some text to it, and then displays that text in the web page.

  • Click your text editor’s file menu, and select Save As…
  • This time, name your file 06-text-enter-display.html.
  • Open it with your Chrome browser.
  • Type some text into the text input.
  • Click the Enter button and verify that it displays “You typed: “ followed by the message you typed.
<html>
  <p>Type something, then click Enter: </p>
  <input type = "text" id = "textField">
  <button onclick = "changeText()">Enter</button>
  <p id = "myText">Waiting...</p>
 
  <script>
    function changeText()
    {
       var x = document.getElementById("textField").value;

       document.getElementById("myText").innerHTML =
       "You typed: " + x;
    }
  </script>
</html>

 

How it Works

This creates the text input and gives it an ID <input type = “text” id = “textField”>.  The button and paragraph also have IDs: <button onclick = “changeText()”>Enter</button> and <p id = “myText”>Waiting…</p>. 

Inside the changeText function, var x = document.getElementById(“textField”).value declares a variable named x that receives the value contained in the text input.  Next, document.getElementById(“myText”).innerHTML = “You typed: ” + x; adds “You typed: “ to whatever you typed in the text input and puts it in the paragraph with the myText ID. 

This application of client server communication through JavaScript is called AJAX, and there’s some great tutorials on it too:   

  • w3schools.com AJAX Tutorial
  • Tutorialspoint.com AJAX Tutorial

Send Web Page Event Info to the BS2

Now that you can use a program to modify and display information to a page, you can also modify and send information to the BASIC Stamp. 

  • Go to your Wi-Fi module’s Files page http://192.168.4.1/update-ffs.html.
  • Remember, if you followed the instructions in the Join Another Wi-Fi Network section, you’ll have to replace 192.168.4.1 with the Wi-Fi module’s station IP address.
  • Use the Choose file button to upload text-page-to-micro.html  to your Wi-Fi module.

This is going to be similar to what you did in the Load a Test Page into the Module section.

  • In your web browser, open 192.168.4.1/files/text-page-to-micro.html.
  • Again, if your Wi-Fi module has joined another network, use the IP address you noted instead of 192.168.4.1.
  • Use your BASIC Stamp programming software to open Text Page to Micro Host.bs2.
  • Connect your BOE + BS2 to power and your computer, and set PWR to 2.
  • Run Text Page to Micro Host.bs2.
  • Verify that the Starting… and Listener setup succeeded messages are shown.
  • Type some characters (5 or fewer) into the web page’s text input and then click the Enter button.
  • Verify that the BASIC Stamp Debug Terminal displays textStr = followed by the characters you typed.

 

Try This

Want to use the Enter key as a shortcut to clicking Send? Change this line:

<input type = “text” id = “textField” maxlength = “5”>

…to:

<input type = “text” id = “textField” maxlength = “5” onchange = “changeText()”>

 

How it Works – The JavaScript

One way that a web page can transmit information like button clicks and text to a server is through an HTTP POST request.  An example of this you might be familiar with is if you type into a search field, and ?search=WhatYouTyped appears after the .html in the web address.  In some pages do not show that in response to a search because they’ll send the text invisibly through a part of the HTTP POST called the post body, which is what this example does.

Most of the html and JavaScript works the same way that it did in the section you just finished (06-text-enter-display from the Relay Information with JavaScript section).  One of the parts that changed is that now, if you type “Hi!” and click the button, the changeText function:

  • Creates a variable named name that stores the string “txt”.
  • Creates another variable named val that stores the value you typed “Hi!” for our example.
  • Creates a third variable named msg that combines name, “=” and val.  In this example, the string it builds is “txt=Hi!”.

This is a name-value pair that the BASIC Stamp program is expecting in an HTTP POST request that contains the path “/fptm”.  So, the line with httpPost(“/fptm”, msg); passes “/fptm” and the msg variable, which is currently storing “txt=Hi!”.  The httpPost function receives that path and parameter, and sends them to the Parallax Wi-Fi module web server as a post request.

The text highlighting in this code example is provided by Notepad++, available from notepad++.org.  

 

How it Works – The PBASIC

There are three important pieces of this JavaScript you’ll need for your BS2:

  1. This is an HTTP POST request.
  2. The path component is “/fptm”
  3. The string sent is going to contain “txt=” + msg, where message is the characters you typed.

1) Inside your BASIC Stamp Code, you’ll need to set #DEFINE POSTS = 1, which adds the variables and subroutines your program will need to support post requests.

2) The Listen_Setup subroutine will need the address of a string command (CMD) that tells the Wi-Fi module to LISTEN for HTTP requests with the path /fptm, which is short for from page to microcontroller.  A carriage return is required to complete a serial command to the Wi-Fi module.

3) The Wi-Fi module can filter out the “txt=” part of the POST request so that your BASIC Stamp just receives “hello”, “bye” and other things you typed.

Path can be /fptm* to allow for different types of information delivered on different paths.  Since the string comparisons for this take more code and memory, we’ll examine it more closely later.Your PBASIC code will need to store a listener ID, and 6 characters for a string of up to 5.  The PAUSE 1000 prevents certain operating systems from thinking a serial plug and play device is trying to connect.  GOSUB Break sends a Break condition to the Wi-Fi Module to tell it to communicate serially with a microcontroller. 

The Listen_Setup subroutine takes care of sending the ListenToPg DATA to the Wi-Fi module.  Just set eeAddr to ListenToPg, then call the Listen_Setup subroutine.  It will place a value in a variable named id.  Copy this value to msgId for use at various places in the program.  Up to 4 ID values are available, from 1 to 4.  If id stores 0, it means that something went wrong, so the program doesn’t continue.

If Listen_Setup contained a valid id, the program continues to the main loop, which repeatedly calls the Poll_Events subroutine and conditionally executes other code depending on the values of op, id, and handle.  Since only POSTS are supported in this program, Poll_Events can only return “P” for POST, “N” for nothing, or “E” for ERROR.  If op is equal to “P”, it’s a POST request, and if the id variable is equal to the msgId variable (from GOSUB Listen_Setup), then, the program knows it came though on the /fptm path, and it’s time to start processing it.   

For a full list of possible responses, see the “Serial Protocol” section of the Parallax Wi-Fi Module API document. 

To process the post request, set eeAddr to MsgKey (that’s “txt”), and then call GOSUB Post_Request_Start.  Next, use a SERIN command to capture the HTTP POST request’s value that corresponds to the “txt” key.  Examples of value would be “hello”, “bye”, andy anything else (up to 5 characters) that you type into the page’s field and then click the Enter button.  SERIN FromDo, Baud, 250, Timeout, [Wait($FE, “=”), WAIT(“,”), STR textStr6CR] waits for up to .25 seconds for a reply that starts with 0xFE’,’.  Then, it waits for a comma, and loads up to the next six characters received into textStr, but terminates early if a CR is received.

Below the loop, you will find a collection of constants, variables, and subroutines that allow your code to focus on the basics, like sending a break, setting up a listener, and polling for and processing events.

 

Inside Communication with the Wi-Fi Module

The information below shows the the transmitter (BS2 or WX) along with a brief description of the message, the actual base-16 hexadecimal values, and the constant names in the PBASIC program. To find out more about each of the serial values and what they mean, check the Parallax Wi-Fi Module Serial API.

Message: BS2: Break condition
Hex: [0][0][0][0][0]
Constants: [0][0][0][0][0]

Message: BS2: Listen for /fptm path ; WX: Success, listener ID 1
Hex: [fe][e7][f7]/fptm[0d] ; [fe]=S,1[0d]
Constants: [CMD][LISTEN][HTTP]/fptm[CR] ; [CMD]=S,1[CR]

Message: BS2: Poll listener IDs ; WX: No requests
Hex: [fe][ec][0d] ; [fe]=N,0,0[0d]
Constants: [CMD][POLL][CR] ; [CMD]=N,0,0[CR]

Message: BS2: Poll listener IDs ; WX: POST request handle 5, ID 1
Hex: [fe][ec][0d] ; [fe]=P,5,1[0d] ; [fe][e6]5,txt[0d]
Constants: [CMD][POLL][CR] ; [CMD]=P,5,1[CR] ; [CMD][ARG]5,txt[CR]

Message: BS2: Ask for txt in name ; WX: Success, txt=Hi!
Hex: [fe]=S,Hi![0d] ; [fe][e5]5,200,2[0d]OK ; [fe]=S,0[0d]
Constants: [CMD]=S,Hi![CR] ; [CMD][REPLY]5,200,2[CR]OK ; [CMD]=S,0[CR]

Message: BS2: Handle 5 200 OK (success)* ; WX: Success reply processed
Hex: [fe][ec][0d] ; [fe]=S,5,0[0d]
Constants: [CMD][POLL][CR] ; [CMD]=S,5,0[CR]

Message: BS2: Poll listener IDs ; WX: Success, handle 5 confirmed
Hex: [fe][ec][0d] ; [fe]=N,0,0[0d]
Constants: [CMD][POLL][CR] ; [CMD]=N,0,0[CR]

Message: BS2: Poll listener IDs ; WX: No requests
Hex: N/A
Constants: N/A

* Reply to handle 5 with the value 200 (success) and 2 characters of text “OK” which can be displayed in the web page’s developer console.

Web Page Controlled LED Lights

An HTML page that can send “hello” or “bye” to the Propeller can just as easily control circuits.  For example, with the LEDs connected to P26 and P27 as shown, the web page can send io=pin26state1 to make an LED connected to P26 turn on.  The other three possible combinations are: io=pin27state1, io=pin26state0, io=pin27state0.

Instead of a text field, this example gets its user input from textboxes.  Click the checkbox once, and a checkmark appears and the light turns on.  Click it again, and the checkbox disappears and the light turns off.  With each click of a checkbox, the message the page sends the Propeller (like io=pin26,state1) gets displayed in the page too.

Keep in mind: If you followed the instructions in the Join Another Wi-Fi Network section, you’ll have to replace 192.168.4.1 with the Wi-Fi module’s station IP address.

  • Go to your Wi-Fi module’s Files page at http://192.168.4.1/update-ffs.html.
  • Use the Choose File button to upload page-controls-light.html to your Wi-Fi module and then click Upload.
  • In your web browser, open 192.168.4.1/files/page-controls-light.html.
  • Use SimpleIDE to open Page Controls Light Host.side.
  • Connect your Activity Board to power and your computer, and set PWR to 1.
  • Click SimpleIDE’s Run with Terminal button.
  • Verify that SimpleIDE Terminal displays ledId = 1 (any value greater than zero will be fine).
  • Try clicking each checkbox to set a checkmark, and verify that the corresponding P26/P27 LED on the Activity Board emits light.
  • Try clicking each checkbox again and verify that each LED stops emitting light.

 

How it Works – the Web Page

The HTML and JavaScript is very similar to the previous example.  Aside from some variable and function name changes, the main differences are in how the checkboxes are handled. 

When a given checkbox is clicked, the onclick event calls the ledVals function, passing the button’s id -either 26 or 27.  The paragraph with the ledval ID will hold a copy of the text that gets sent to the Propeller through the Wi-Fi module.

The C program running in the Propeller will have a listener filtering for HTTP POSTs with a path named “/leds”.  It also has code that expects a message like “io=pin26state1” to turn the P26 LED on, “io=pin26state0” to turn it off, and so on.  So the ledVals function has to assemble a string with the io=pin#state# information, and pass that and the “/leds” path to the httpPost function.

When you click one of the checkboxes, the browser detects the onclick event and calls ledVals function, passing the html’s checkbox id (either 26 or 27) to the ledVals pinId parameter.  Then, var state = document.getElementById(pinId).checked copies the state of that checkbox (true or false) into a variable named state.  Next, var nameVal = “io=pin” + pinId “ “state” + Number(state) uses all that information to put together the “io=pin#state#”.  After printing the nameVal string to the ledval paragraph with document.getElementById…, the httpPost(“/leds”, nameVal) function call passes the “/leds” path and the nameVal variable to the httpPost function.  Remember, the nameVal variable is the one that contains a string that’s something like “io=pin26state1”.  

The checked property is Boolean, that’s true or false. Number(led) converts it to a 1 or 0.  The JavaScript responds to the fact that strings are being added together by automatically converting to “1” or “0” before appending the string.Here’s the httpPost function.  It transmits the “/leds” path and the param string, which will contain a string like “io=pin26state1” to the Parallax Wi-Fi module that’s hosting the web page, and the module in turn relays that information to the Propeller.  

The string “io=pin26state1” is considered a post parameter that consists of a name-value pair.  The name is “io” and the value is “pin26state1”.

 

How it Works – the Propeller C Code

The fourth line is where this program starts to differ from the previous example.  Instead of just declaring postFromPageId, this program instead declares a variable named ledId, along with variables named pin and state.  The main function starts off the same, calling wifi_start.  In the previous program, the second line in the main function was postFromPageId = wifi_listen(HTTP, “/fptm”).  That’s because the previous page’s JavaScript sent its POST requests with the “/fptm” path.  The JavaScript in this example sends its POST requests to a different path: “/leds”.  So, this program uses ledId = wifi_listen(HTTP, “/leds”) to:

  • Set up a listener that monitors for HTTP requests with a path of “/leds”
  • Store the listener ID in a variable named ledId

After that, it uses simpletools library set_direction function calls to set P26 and P27 to outputs (since the main loop will need to turn those lights on/off). 

#include "simpletools.h"
#include "wifi.h"

int event, id, handle;
int ledId, pin, state;

int main()
{
  wifi_start(31, 30, 115200, WX_ALL_COM);
  ledId = wifi_listen(HTTP, "/leds");
  print("ledId = %d\n", ledId);
 
  set_direction(26, 1);
  set_direction(27, 1);

  while(1)
  {
    wifi_poll(&event, &id, &handle);
    print("event = %c, id = %d, handle = %d\r", event, id, handle);
    if(event == 'P')
    {
      if(id == ledId)
      {
        print("Incoming POST request\r");
        wifi_scan(POST, handle, "io%d%d", &pin, &state);
        print("pin=%d, state=%d\n", pin, state);
        set_output(pin, state);
      }        
    }
    pause(500);
  }    
}

Every time through the while(1) loop, wifi_poll(&event, &id, &handle) checks if any listeners reported events.  If there are no events, the event variable will store ‘N’, and handle & id will both store 0.  When a POST request from the browser comes through with a path of “/leds”,  wifi_poll will set event to ‘P’, id to whatever value ledId stored during the initialization, and handle to a value the program will use to retrieve the post body.  When event stores ‘P’ and id matches ledId, the program prints the incoming POST request message, then calls wifi_scan. 

Instead of the previous example’s wifi_scan(POST, handle, “txt%s”, &s), this program uses wifi_scan(POST, handle, “io%d%d, &pin &state).  The io tells the Wi-Fi module to reply with the value part of a POST that contain something like io=pin26state1.  In this example, the Wi-Fi module sends “pin26state1”.  The %d%d places the first two text strings that represent integer values (like 26 and 1) into the two variable parameters in the list that follows the format string: &pin and &state.  This happens in about the same way that the scan statement from Print and Scan Function Review captured that string when you typed it into the SimpleIDE terminal.  

With the pin and state variables containing meaningful values, print(“pin = %d, state = %d\r”, pin, state) displays those values in the terminal.  Then, set_output(pin, state) from the simpletools library uses those values to turn P26 or P27 on or off.  The pause(500) before repeating the while(1) loop mainly prevents sending data to the SimpleIDE Terminal faster than a human could follow along. 

Motor Control with Sliders

With just a few small tweaks to the JavaScript and Propeller C code, that light control with checkboxes app can be transformed into slider control of servo position. 

Keep in mind: If you followed the instructions in the Join Another Wi-Fi Network section, you’ll have to replace 192.168.4.1 with your IP address.

  • Go to the Standard Servo, and follow its instructions for connecting and testing a standard servo.
  • Go to your Wi-Fi module’s Files page at http://192.168.4.1/update-ffs.html.
  • Use the Choose file button to upload page-controls-servo.html to your Wi-Fi module.
  • In your web browser, open 192.168.4.1/files/page-controls-servo.html.
  • Use SimpleIDE to open Page Controls Servo Host.bs2.
  • Run Page Controls Servo Host.bs2.
  • Verify that the SimpleIDE Terminal displays servoId = 1.
  • Try dragging and releasing the slider control on the web page to various positions, and verify that the servo turns to and holds the corresponding angle. 

 

How it Works – The JavaScript

This is the HTML that displays the slider and the angle.  When the slider is adjusted, the onchage=”servoPosition(id)” passes the id of the slider to the servoPosition function’s sliderID parameter.  

  <H2>Servo</H2>

  Position: 150
    <input type="range" id="position"
    min="30" max="150" value="90"
    onchange="servoPosition(id)">
  30

The servoAngle variable gets the slider’s value with document.getElementById(sliderId).value.  The slider actually counts from 30 to 150, so servoAngle = (150 – servoAngle) + 30 calculates what the angle we really want is.  For example, when the slider is ⅓ of the way from left to right, the range type returns 70, but we really want that to be 110. With servoAngle = (150 – servoAngle) + 30 we get 110 = 150 – 70 + 30.  After that, nameVal = “angle=” + servoAngle creates the name value pair parameter to send to the httpPost function.  For example, with the slider set to ⅓ of the way from left to right, it might send “angle=110”.  The Propeller C program has a listener set up to monitor HTTP POST requests with the “/servo” path, so the httpPost call is httpPost(“/servo”, nameVal).

  function servoPosition(sliderId)
  {
    var servoAngle = document.getElementById(sliderId).value;
    servoAngle = (150 - servoAngle) + 30;
    var nameVal = "angle=" + servoAngle;
    document.getElementById("servoval").innerHTML = nameVal;
    httpPost("/servo", nameVal);
  }

 

How it Works – The Propeller C

As with the text message and LED light control examples, the information about where the web page wants to position the servo will come through as HTTP POST requests.  The main changes are:

  • #include servo.h added for controlling the servo
  • The variable for holding the listener ID has been changed to servoId
  • The listener is set up with a different path –”/servo”.
#include "simpletools.h"
#include "servo.h"
#include "wifi.h"

int event, id, handle;
int servoId, angle;

int main()
{
  wifi_start(31, 30, 115200, WX_ALL_COM);
  servoId = wifi_listen(HTTP, "/servo");
  print("ledId = %d\n", servoId);

The main loop checks if there are any POST requests coming from with the “/servo” path.  When one comes through, event should store ‘P’, id should match servoId, and handle will have a reference .  When  these conditions are met, handle will contain the identifier wifi_scan needs to retrieve the POST body’s value.

  while(1)
  {
    wifi_poll(&event, &id, &handle);
    print("event = %c, id = %d, handle = %d\r", event, id, handle);
    
    if(event == 'P')
    {
      if(id == servoId)
      {
        print("Incoming POST request\r");
        wifi_scan(POST, handle, "angle%d\r", &angle);
        print("servoAngle: %d\n", angle);
        servo_angle(16, angle * 10);
      }        
    }
    pause(500);
  }    
}

The name in the name/value pair is “angle”, so if the angle is 45 degrees, we expect the POST body to contain “angle=45”.  With that info, we can make the format string in our wifi_scan function be “angle%d”.  Adding “angle” makes the Wi-Fi module only transmit the characters that represent the value, like the characters ‘4’ and ‘5’ in the case of 45 degrees.  The %d in the format string makes the wifi_scan function put the value “45” corresponds to in the angle variable.  So, our wifi_scan function should look like this: wifi_scan(POST, handle, “angle%d”, &angle). 

The value wifi_scan stores in the angle variable is terms of degrees, but the servo_angle function needs 10ths of degrees.  So, instead of servo_angle(16, 45), we’d need servo_angle(450).  That’s why there’s a * 10 in servo_angle(16, angle * 10).  It multiplies degrees in the angle variable by 10 to give it to servo_angle in terms of 10ths of degrees.

Page Requests Info from BS2

Up to this point, your page has been sending information to the microcontroller host with HTTP POST requests.  There’s also a way for the page to ask the microcontroller for information with HTTP GET requests.  Here is an example where each time you click the Update button, the page asks for, gets, and displays a new value from the BASIC Stamp 2.

Reminder: If you followed the instructions in the Join Another Wi-Fi Network section, you’ll have to replace 192.168.4.1 with your IP address.

  • Go to your Wi-Fi module’s Files page at http://192.168.4.1/update-ffs.html.
  • Use the Choose file button to upload val-from-micro.html to your Wi-Fi module.
  • In your web browser, open 192.168.4.1/files/val-from-micro.html.
  • Use your BASIC Stamp programming software to open Val from Micro Host.bs2.
  • Connect your BOE + BS2 to power and your computer, and set PWR to 2.
  • Run Val from Micro Host.bs2.
  • Click the web page’s update button and check the number by value.
  • Wait a few seconds and click Update again.  

Since the BASIC Stamp program counts upwards at several times per second, the number should be higher each time you click the button.

 

Try This – Automatic

Don’t want to have to click the button to see the value updated?  The page can do it automatically.  Here’s an example that updates every 3 seconds.

  • Add this line line to the script: var myTimer = setInterval(getFromMcu, 3000).
  • Upload the modified page to the Wi-Fi module
  • Refresh 192.168.4.1/files/val-from-micro.html in your browser.

Note: it’s probably not a good idea to try to see how fast you can make this go, because it can end up making the application unresponsive.  We have websockets (introduced soon) to establish a communication line that’s much more streamlined than HTTP requests.

 

How it Works

The HTML has a button with an onclick event to call a function in the JavaScript called getFromMCU.  The JavaScript updates the paragraph with the value ID as soon as it gets the reply from the microcontroller.

Using this JavaScript is pretty easy.  In getFromMcu, you give it the path, “/tpfm” in this case, which is an abbreviation of “to page from microcontroller.  The reply from the BASIC Stamp will appear inside the response parameter of useMcuReply(response) when it’s ready.  The “when it’s ready” part depends on network traffic and also how long the BS2 takes to get around to answering.  For more info on how this code works, there’s an Advanced Topic after an explanation of the BASIC Stamp 2 code.

Since the page we have here isn’t making any HTTP POST requests, #define POSTS has been set to 0.  Conversely, since the page is making HTTP GET requests, #define GETS has been set to 1 to add the GET subroutines to the application.  Aside from that, setting up a listener for GET requests is the the same process as setting it up for POST requests.  The only difference is that there’s no key string accompanying GET requests.

Inside the main loop, the code is adds 1 to a variable named val ever ¼ second and then checking for a “G” in the op variable after a call to Poll_Events.  If the op variable does contain a “G”, it means the Wi-Fi module has received an HTTP GET request from one if its listener IDs.  Just like there’s a Post_Request_Start and Post_Request_Ack for handling POST requests, there’s also a Get_Request_Start and Get_Request_Ack for handling GET requests.  The difference is that instead of POSTing information to the server (our BASIC Stamp 2), this page is GETting information.  Before calling Get_Request_Start it’s important to set charCount to the number of characters the reply to the GET request will contain.  Then, between Get_Request_Start and Get_Request_Ack, SEROUT ToDi, Baud, [DEC5 val].  Note that the because charCount was 5, the SEROUT sends DEC5 val.

 

Advanced Topic: What’s Really Happening in That JavaScript?

The true inside req.open(“GET, path, true) means that the request will get processed asynchronously.  Asynchronously means that the the httpGet function won’t wait till everything is ready because other things and scripts in a given web page might need attention in the meantime.  So, the main thread actually executes everything inside the httpGet function right away and returns.  However, after the httpGet function is done, req.onreadystatechange contains a function that gets run each time the readyState property advances through its five states.

According to AJAX – The onreadystatechange Event, the readyState property advances through five states: (0) request not yet initialized, (1) server connection established, (2) request received, (3) processing request, (4) request finished and response ready.  There’s also a status property that’s 200 for “OK” or 404 for “page not found”. 

The important thing to keep in mind is that each time the readyState changes, the function inside onreadystatechange automatically executes, checking if readyState has reached 4 and status is 200.  When both of those are true, the response is ready.

When the response IS finally ready, the callback parameter contains useMcuReply.  That’s the function the httpGet(“/tpfm”, useMcuReply) passed when it called httpGet, with the understanding that it would “call back” that usMcuReply function at some later time (when readyState is 4 and status is 200).  At that point, callback(req.responseText) becomes useMcuReply(req.responseText). 

If the BASIC Stamp replied with “42”, that’s what req.responseText will contain, and also what gets passed to the useMcuReply function’s response parameter.  Inside useMcuReply, there’s JavaScript that would display “Value: 42” in the paragraph with the value label.

Display Pushbutton States

Now that we have a way for the page to make the browser ask the Propeller questions, let’s make the page ask for sensor states.  In this example, the page makes the browser ask the Propeller about pushbutton states every 3 seconds and updates the states of radio buttons and text displaying the button states.  

  • Build the pushbutton circuit shown here.
  • Go to  and follow the instructions for testing the circuit, and come back here when you’re done.

Reminder: If you followed the instructions in the Join Another Wi-Fi Network section, you’ll have to replace 192.168.4.1 with your IP address.

  • Go to your Wi-Fi module’s Files page at http://192.168.4.1/update-ffs.html.
  • Use the Choose file button to upload page-displays-buttons.html to your Wi-Fi module.
  • In your web browser, open 192.168.4.1/files/page-displays buttons.html.
  • Open Page Displays Buttons Host.side with SimpleIDE.
  • Click the web page’s refresh button.
  • Verify that it displays Value: 00 while no buttons are pressed (for at least 2 seconds).
  • Press and hold the P3 pushbutton on your Activity Board and wait for more than 2 seconds.
  • Verify that the page displays Value: 01 and the P3 radio button has a solid dot inside it.
  • Repeat this test for P4, and then for P3 and P4 at the same time.

 

Try This – Reduce the Sample Interval

To really speed things up, we’ll use WebSockets, but that’s in a later activity.  For the time being, we can speed it up a little without risking data loss due to unpredictable times it takes for HTTP requests to complete.    

  • Open page-displays-buttons.html with a text editor.
  • Change the 2000 to 1500 in this line : var myTimer = setInterval(getFromMcu, 2000).
  • Save the modified file and re-upload it to the Wi-Fi module.
  • Refresh 192.168.4.1/files/page-displays-buttons.html in your browser.

Note: it’s probably not a good idea to try to see how fast you can make this go, because it can end up making the application unresponsive.  We have WebSockets (introduced soon) to establish a communication line that’s much more streamlined than HTTP requests.

 

How it Works – HTML & JavaScript

The HTML part of the page is just a couple of radio buttons.  You might have seen radio buttons from online quizzes and questionnaires.  You normally click them to select your answer or reply.  In this example, the JavaScript updates their selected/not selected states according to whether the BASIC Stamp sends a 1 (pressed) or 0 (not pressed) for a given pushbutton.  As with other elements, the radio buttons have IDs so that the JavaScript can act on one when a given button is pressed on the Propeller Activity Board.

  <body>

    <H2>Pushbutton States</H2>

    <p>P4: <input type="radio" id="P4"></p>
    <p>P3: <input type="radio" id="P3"></p>

    <p id="value">Waiting...</p>

    <script>

The var myTimer = setInterval(getFromMcu, 2000) is one way to tell a web page to repeatedly call a function.  There’s a lot more to this than meets the eye, but for now, just remember that this line causes the browser to automatically call the getFromMCU function every 2 seconds (2000 ms).  

      var myTimer = setInterval(getFromMcu, 2000);

The getFromMcu function, which now gets called every 2 seconds, calls the httpGet function.  Remember from the How it Works section in Page Requests Info from Propeller that the Propeller’s C program has code that detects when a GET request comes through with a path of “/tpfm” (to page from microcontroller).  Remember also that the GET request will take an unknown amount of time and is designed to take care of that in the background while the main thread moves on, and that its second argument is the function to call when it’s done.    

      function getFromMcu()
      {
        httpGet("/btns", useMcuReply);
      }

This is the httpGet function, which sends the GET request and then eventually reaches a readyState of 4 and calls the callback function, which in your program is useMcuReply.  For more info on how this works, revisit the Page Requests Info from Propeller activity’s Advanced Topic section. 

      function httpGet(path, callback)
      {
        var req = new XMLHttpRequest();
        req.open("GET", path, true);
        req.onreadystatechange = function()
        {
          if (req.readyState == 4)
            if(req.status == 200)
              callback(req.responseText);
            else
              callback("Waiting...");
        }
        req.send(null);
      }

The useMcuReply function is the one that gets called when the httpGet request is done and is really the only function that has changed since Page Requests Info from Propeller.  The response parameter is going to contain a reply from the Propeller, which is running Page Displays Buttons Host.c.  That program replies with a string that contains the characters representing two binary digits.  The four different strings that might come across are “11”, “10”, “01”, and “00”.  The left digit is 1 if the P4 pushbutton is pressed, or 0 if it’s not.  Likewise, the right digit is 1 if the P3 pushbutton is pressed, and 0 if it’s not.  Keep in mind that’s what response contains.  

      function useMcuReply(response)
      {
        var val = document.getElementById("value");
        val.innerHTML = "Value: " + response;

        if(response.charAt(1) == "1")
          P3.checked = true;
        else
          P3.checked = false;
        if(response.charAt(0) == "1")
          P4.checked = true;
        else
          P4.checked = false;
      }

The first thing useMcuReply does is change the HTML paragraph with the value ID to something like Value = 01.  (That would be if the P3 button is pressed and held down.)  The two lines that do that are var val = document.getElementById(“value”); and val.innerHTML = “Value: “ + response.  Assuming the response contained “01” that would cause Value = 01 to be displayed.

Next, a couple of if…else statements set the states of the radio buttons.  In the case of “01”, the response.charAt(0) gets the leftmost 0th character from the string.  Since it’s a “0”, the code sets the radio button with the P4 ID to false (unchecked or un-selected).  The second if condition is true since charAt(1), which is the second character in the string, really is “1”.  So it sets the checked property in the radio button object with the P3 ID to true, causing it to appear to be checked or selected.

 

How it Works – The Propeller C Code

The setup in Page Displays Buttons Host.c is very similar to Val from Micro Host.c from the Page Requests Info from Propeller tutorial.  When an HTTP GET request comes through requesting the resource from the “/btns” path, the wifi_poll function stores a value in the id variable that matches getsId.  When those two conditions are true, the buttonP4 and buttonP3 variables get values from input function calls that return 1 if a button is pressed or 0 if it is not.  Then, wifi_print(GET, handle, “%d%d\r”, buttonP4, buttonP3) sends a string with the characters that represent the two binary states followed by a carriage return.  The first %d the will be “1” if buttonP4 is 1, or “0” if buttonP4 is 0.  The second %d will also be a “1” if buttonP3 is 1, or a “0” if buttonP3 is 0.  The result again is “11\r”, “10\r”, “01\r”, or “00\r”.  The Propeller transmits that to the Wi-Fi module, which relays it to the browser executing the JavaScript.  

#include "simpletools.h"
#include "wifi.h"

int event, id, handle;
int buttonId;
int buttonP3, buttonP4;

int main()
{
  wifi_start(31, 30, 115200, WX_ALL_COM);

  buttonId = wifi_listen(HTTP, "/btns");
  print("getFromPageId = %d\n", buttonId);

  while(1)
  {
    wifi_poll(&event, &id, &handle);
    print("event = %c, id = %d, handle = %d\r", event, id, handle);
    if(event == 'G')
    {
      if(id == buttonId)
      {
        buttonP4 = input(4);
        buttonP3 = input(3);
        wifi_print(GET, handle, "%d%d\r", buttonP4, buttonP3);
        print("Incoming GET request, sending %d%d\r", buttonP3, buttonP4);
      }        
    }
    pause(500);
  }    
}

DISCUSSION FORUMS | PARALLAX INC. STORE

About | Terms of Use | Feedback: learn@parallax.com | Copyright©Parallax Inc. 2024


Source URL:https://learn.parallax.com/courses/parallax-wx-wi-fi-module-for-the-bs2/
Links