A simple server built into the stand-alone MicroBlocks IDE allows browsers, Snap! and other clients to interact with MicroBlocks via HTTP. (This feature is not supported by the Chrome OS and Chrome browser versions of MicroBlocks.)
For an example of using the HTTP server to connect MicroBlocks to BeetleBlocks (a 3D world build on Snap!), see the microPlane project.
Start by selecting "show advanced blocks" in the MicroBlocks (gear icon) menu, then select "start HTTP server":
A dialog box appears to tell you that the server is running:
Open a browser and navigate enter the URL http://127.0.0.1/6473 to view the HTTP server home page:
The home page summarizes how a browser or a client such as Snap! can interact with a MicroBlocks project. The capabilities are simple yet powerful. The client can get and set global variables, send broadcasts to the MicroBlocks project, or get a list of the most recent broadcasts sent by the project.
In conjunction with a simple MicroBlocks script, the getVar request can be used to read sensor values. Create a variable named "light", then write a script that sets that variable to the sensor value:
You can use a browser to view that variable:
Setting a variable can be used to remotely control a MicroBlocks project. Create a variable named "face" and write a script to display different faces based on the value of that variable:
Setting the face variable in the browser changes the face displayed on the micro:bit:
Another way to control a MicroBlocks project from a browser is to send broadcasts. These scripts use that technique to control the micro:bit display:
Now you can broadcast "frown" from the browser:
A client can also monitor the broadcasts sent by MicroBlocks scripts. The getBroadcasts request returns a list of all the messages broadcast by MicroBlocks scripts since the last getBroadcasts request. For example, after running this script:
The broadcasts are:
The HTTP server allows Snap! projects to interact with MicroBlocks. For example, you might use the micro:bit's tilt sensor to control a Snap! sprite. Or you might a create buttons in Snap! to control the micro:bit display, motors, or other hardware devices.
Start by opening the extensions version of Snap!:
Note: You can't use the normal Snap! link because that is a secure (HTTPS) page and the browser does not allow HTTP requests from a secure page.
In MicroBlocks, create a variable named "tilt" and a script to set its value to the "tilt x" sensor:
In Snap!, use the URL block to create a script that uses the "tilt" variable to control the x position of the sprite: