In MakeCode, all blocks are defined from a Static TypeScript function or property using some annotations in the comment. MakeCode takes care of handling the conversion to Google Blockly and back.

Your First Block!

Let's start with a simple statement block that blinks an LED. Place this code in main.ts of your Extension.

/**
* Cool LED functionalities
*/
namespace ledTricks {
    /**
    * Blinks the LED once.
    */
    //% block
    export function blink() {
        pins.LED.digitalWrite(true)
        pause(500)
        pins.LED.digitalWrite(false)
        pause(500)
    }
}

If you switch tab to your test project, you will see a LED TRICKS category in the toolbox with a single blink block. Let's break it down line by line:

/**
* Cool LED functionalities
*/
namespace ledTricks {

The name of namespacem, ledTricks is used to organize your blocks, just like it organizes your JavaScript functions.

    /**
    * Blinks the LED once.
    */
    //% block
    export function blink() {

The //% block comment tells MakeCode to "mount" a block for this function. MakeCode will infer the shape of the block by looking at the inputs and return value of the function. In this case, this function does not have any input or output.

The descriptive comment is also mined by MakeCode and injected in the tooltip of the block.

That's it! You've just created a new block!!!

More on blocks

There is actually a ton of options and knobs to beautify the blocks shown in MakeCode editors. The best place to learn about them is the MakeCode Playground.

The complete docs on this topic is available at https://makecode.com/defining-blocks .

This guide was first published on Mar 15, 2019. It was last updated on Mar 15, 2019.

This page (Custom Blocks) was last updated on Oct 15, 2021.

Text editor powered by tinymce.