增加擴充模組
mBlock v2.2.0 provides a new feature of extension management. Users are able to add or remove extensions from now on.
I’ll show you how to add an extension in the following steps(Download Demo.zip126 (3.3 KB) to see demo extension). The feature of demo extension: (1) Output HIGH and LOW level from digital pin on Arduino board (2) LED blink
Files in demo extension Unzip the demo.zip file, you’ll get following files:
js file: called JavaScript codes for online communication(Scratch online programming) src file: .h and .cpp files for Arduino compiling(Arduino offline programming) s2e file: description file of this extension
Defining extension Open demo.s2e, you’ll get following codes:
{ "extensionName": "Demo", "sort":0, "javascriptURL":"js/demo.js", // define the path of JavaScript file "firmware":"1.0", // firmware version "extensionPort":0, // network port of extension, 0 for serial port "blockSpecs": [ // module defining array ["h","Demo Program","runArduino"], [ "w", // "h" for event module, "w" for write module, "r" for read module "digitalWrite( %n , %d.digital )", // module display name, %n is number type, %d.digital is menu value with menu name "digital" "digitalWrite", // called javascript function "13", // default value of the first parameter "HIGH", // default value of the second parameter { // define Arduino programming "setup":"pinMode({0},OUTPUT); \n", // codes inserted into void setup{} "inc":"", // included header file, such as #include"def":"", // define variables, such as double _num = 0; "work":"digitalWrite({0},{1});\n", // output implementing codes "loop":"" // codes inserted into loop{} } ], [ "w", "blink", "blink", { "setup":"", "inc":"#include \"demo.h\"", "def":"DemoClass demo; \n", "work":"demo.blink(); \n", "loop":"" } ] ], "menus": { "digital":["HIGH","LOW"] // menu }, "values":{ // corresponding values for "HIGH" and "LOW" "HIGH":1, "LOW":0 }, "translators":{ "zh_tw":{ // Chinese version "Demo Program":"示範程式", "HIGH":"高電位", "LOW":"低電位", "digitalWrite( %n , %d.digital )":"數位接脧輸出( %n ,%d.digital )", "blink":"閃爍" } } }
3.Writing JavaScript codes Define corresponding functions.
ext.digitalWrite = function(pin,level) { // digitalWrite function runPackage(30,pin,typeof level=="number"?level:levels[level]); }; var _level = 0; ext.blink = function(){ // blink function _level = 1 - _level; runPackage(30,13,_level); };
- Writing source codes for Arduino programming (1) Create demo.h and demo.cpp files in src folder. (2) Define blink function in demo.cpp file.
#include "demo.h" DemoClass::DemoClass(){ pinMode(13,OUTPUT); level = 0; } void DemoClass::blink(){ level= 1- level; digitalWrite(13,level); }
- Zip the files Zip the files and add them to mBlock with extension management. It should look like this:
Let’s run a test. Create a program with drag-and-drop in mBlock and output its Arduino codes.