The BBC micro:bit is a maker board that was given to all 11 year old students in the UK. It was designed for beginners and to be used in schools: friendly shape and design, connector rings for croc-clips, drag and drop web-based editors and online lessons.
The micro:bit is actually a great hardware combo (nRF51, 25 LEDs, sensors, edge connector) that experienced makers can leverage too. There are lots of choices to program the micro:bit, from C++ through the Lancaster runtime to Node.js and BLE. In this project, we will use the PXT command line to edit and deploy programs in JavaScript on the micro:bit.
In order to handle the restrictions of the M0, we decided to avoid running an interpreter on the device -- and instead compile a subset of JavaScript to ARM Thumb assembly code in the browser. Michał Moskal has a great write up on the history and details of this approach.
In a nutshell, PXT compiles the JavaScript to ARM Thumb assembly, then links it against a pre-compiled .hex file of mbed + micro:bit runtime (the .hex file is compiled on-demand in the cloud; after first compilation of a given runtime version, there is no more cloud interaction). The compilation toolchain is all in JavaScript and can run from a browser or node.js.
Give me a command line!Install the PXT command line from npm.
> npm install -g pxt
The PXT command line contains commands to initialize projects, compile and deploy them. It also support streaming of serial data when using the local server.
Creating a new projectCreate a folder and setup the microbit
target for it.
> mkdir microbit
> cd microbit
> pxt target microbit
Under your microbit folder, create a new folder for blink and run the pxt init
command to initialize the project.
> mkdir blink
> cd blink
> pxt init
The init
command generated all the files needed for your project. In future, you can create other projects, parallel to blink
.
Edit main.ts
in your favorite IDE to match this code, which blinks a smiley and a empty screen in a loop.
basic.forever(() => {
basic.showLeds(`
. . . . .
. # . # .
. . . . .
# . . . #
. # # # .
`)
basic.showLeds(`
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
`)
})
To compile and deploy, simply run pxt
with no argumnets. PXT will compile and link your code into an .hex file and deploy it to all connected micro:bits.
> pxt
Using PXT/microbit from C:\gh\temp\node_modules\pxt-microbit.
running 'pxt deploy' (run 'pxt help' for usage)
Package built; hexsize=564492
Better with @codeIf you are using Visual Studio Code, you can use the Build shortcut (Ctrl+Shift+B or Cmd+Shift+B) to deploy and you'll enjoy excellent IDE support for JavaScript.
That's it! We've learned how to use the PXT compiler from the command line. In future projects, we'll cover how to package your JavaScript projects and surface them in the https://pxt.microbit.org editor.
Comments