Compare commits

...

120 Commits

Author SHA1 Message Date
b103423a53 0.3.20 2016-08-11 12:11:04 -07:00
a82a44e587 Bump pxt-core to 0.3.23 2016-08-11 12:11:02 -07:00
e6f612283f remove dead page 2016-08-11 11:41:59 -07:00
fcd60876ab Removing streaming menu dialog 2016-08-11 11:41:07 -07:00
5daa9a0bb6 broken links 2016-08-11 10:44:17 -07:00
4fb3926073 fix snippets 2016-08-11 10:40:48 -07:00
73932f4619 0.3.19 2016-08-10 23:27:46 -07:00
c99138b02e adding SPI support 2016-08-10 23:26:58 -07:00
64d584681a docs tweaks 2016-08-10 16:09:57 -07:00
9788dd49cc fix testsnippet crash 2016-08-10 14:06:26 -07:00
9d15c4e270 fixing docs issues 2016-08-10 13:46:11 -07:00
fe7b06d763 0.3.18 2016-08-10 13:12:26 -07:00
0e0275e496 doc fixes 2016-08-10 13:10:40 -07:00
ffd4d96539 properly escape values in json payload 2016-08-10 09:28:22 -07:00
a6b4c9645a Merge pull request #199 from Microsoft/ignore-snippets
-ignore snippet notation
2016-08-10 08:29:05 -07:00
a9141d027f Add package info for server side check 2016-08-10 13:44:10 +01:00
807e581c3d Addition of ignore notation
Some snippets are designed to show syntax errors or refer to earlier variables. In this case the automated checker needs to avoid compiling them
2016-08-10 13:43:48 +01:00
41a4dfeb68 Documentation snippet fixes 2016-08-10 10:51:55 +01:00
4430391e87 0.3.17 2016-08-09 22:16:31 -07:00
81667f4df5 Bump pxt-core to 0.3.22 2016-08-09 22:16:28 -07:00
835048132c adjustments to electron app 2016-08-09 22:08:46 -07:00
00217305c2 0.3.16 2016-08-09 12:38:30 -07:00
85e8a70f76 Bump pxt-core to 0.3.21 2016-08-09 12:38:28 -07:00
bbdf27de5a adding pxt-neopixel to pre-populated package list 2016-08-09 11:02:23 -07:00
3e63d4083e update title 2016-08-09 10:27:39 -07:00
d1b8e3c752 added electron host 2016-08-09 09:55:37 -07:00
1164feb754 More snippet types 2016-08-09 16:55:43 +01:00
9ebd9d4f04 Add more snippet types for better detection 2016-08-09 16:52:24 +01:00
9fd2a3a3e6 Remove trailing whitespace 2016-08-09 16:39:50 +01:00
7f40889103 Add package info to mic docs (for testing) 2016-08-09 16:35:45 +01:00
ee37b4a959 Add package info to radio docs (for testing) 2016-08-09 16:28:08 +01:00
99d05ec91b Merge branch 'master' of https://github.com/thomasdenney/pxt-microbit 2016-08-09 16:11:27 +01:00
412e5bd034 Fix doc comment 2016-08-09 16:10:53 +01:00
141420d337 Correct Bluetooth doc comment 2016-08-09 16:05:25 +01:00
084f83ba1b Merge branch 'master' of https://github.com/thomasdenney/pxt-microbit 2016-08-09 15:13:35 +01:00
8601eff170 fixed snippets 2016-08-08 20:44:43 -07:00
5da4d74a2a adding messenger project 2016-08-08 18:12:34 -07:00
4215574a7c 0.3.15 2016-08-08 16:58:02 -07:00
da9d986a3e Bump pxt-core to 0.3.19 2016-08-08 16:58:00 -07:00
7481b9c24c call receiveNumber in onDataReceived to flush queue if needed (startup race)
fixed simulator issue when event onDataReceived gets raised
2016-08-08 16:54:43 -07:00
de5def8dde adding led.toggle as a block 2016-08-08 16:53:55 -07:00
dd011b977a wired up onPinReleased to simulator 2016-08-08 15:27:13 -07:00
20d0dd91ad added input.onPinRelease. Fix for #294 2016-08-08 15:23:18 -07:00
825c6d57e7 testing fr jsdoc transtions 2016-08-08 13:47:45 -07:00
b3edb81d3c adding URL for SEO 2016-08-08 13:08:15 -07:00
78089da134 0.3.14 2016-08-05 08:37:58 -07:00
3aef765d35 Bump pxt-core to 0.3.18 2016-08-05 08:37:56 -07:00
f4727f12c9 0.3.13 2016-08-04 10:10:03 -07:00
a36cb65aa5 Bump pxt-core to 0.3.17 2016-08-04 10:09:56 -07:00
3b16e59ee1 Merge branch 'master' of https://github.com/Microsoft/pxt-microbit 2016-08-04 10:09:42 -07:00
f2c43c74ac support for start/length in buffer methods 2016-08-04 08:42:47 -07:00
1c4c93dc60 0.3.12 2016-08-03 17:19:26 -07:00
d73847bfba Bump pxt-core to 0.3.15 2016-08-03 17:19:19 -07:00
4e46682489 keep older value longer 2016-08-02 15:35:33 -07:00
ab7aa00747 0.3.11 2016-08-02 13:25:13 -07:00
2bebb6056d Bump pxt-core to 0.3.14 2016-08-02 13:25:11 -07:00
22046c417c adding uservoice info 2016-08-02 13:18:07 -07:00
dc8afa6d45 0.3.10 2016-08-02 11:06:34 -07:00
22e2ab5ad9 Bump pxt-core to 0.3.13 2016-08-02 11:06:31 -07:00
f365726a8e fixed regfression in showleds
see 65594842fc
2016-08-02 11:04:49 -07:00
e329b3bd2e prepend all radio blocks with "radio" 2016-08-01 16:02:06 -07:00
d7b709e97b added screenshots 2016-08-01 16:01:45 -07:00
9714ec46e9 support page 2016-08-01 14:24:25 -07:00
20ef54f565 fixed win10 app 2016-08-01 14:23:40 -07:00
554df0bce9 0.3.9 2016-07-29 14:22:51 -07:00
6c89dddef6 Bump pxt-core to 0.3.12 2016-07-29 14:22:48 -07:00
23f91895f7 restore advanced section in reference 2016-07-29 14:19:21 -07:00
3f83cda087 mark serial messages as simulated 2016-07-29 13:42:21 -07:00
7e79635413 0.3.8 2016-07-29 10:49:38 -07:00
56e1cf91ac Bump pxt-core to 0.3.11 2016-07-29 10:49:36 -07:00
f9f96f33f0 0.3.7 2016-07-29 11:37:58 +01:00
0b33073be1 Bump pxt-core to 0.3.10 2016-07-29 11:37:57 +01:00
65594842fc Fix issue with multi digit numbers not scrolling all the way off screen as is the case on the physical pxt. 2016-07-28 15:54:10 -07:00
c6ed665f84 Fix for issue 176: basic.showNumber timing in the simulator
- updated basic.cpp::showNumber to use printChar instead of print.
2016-07-28 15:04:56 -07:00
79462deb24 Merge pull request #190 from Microsoft/microsoftsam/issue179
Fix for issue 179: Watch Challenges goes to Rock Paper Scissors instead of the challenges code
2016-07-28 14:21:18 -07:00
5c05f3e241 Fix for issue 179: Watch Challenges goes to Rock Paper Scissors instead of the challenges code 2016-07-28 13:13:33 -07:00
4f7dd75fbe Finished animation API 2016-07-28 12:16:18 -07:00
338e507b51 temporary fix for reference 2016-07-28 12:03:03 -07:00
601231a5dc 0.3.6 2016-07-28 11:54:23 -07:00
f0850336e5 Bump pxt-core to 0.3.9 2016-07-28 11:54:18 -07:00
a6b2187ec5 Edited advanced page 2016-07-28 10:56:37 -07:00
28ae4f4230 better board name detection 2016-07-28 10:22:05 -07:00
09933b6a8d advanced section 2016-07-28 09:15:31 -07:00
45bb6e7cb3 0.3.5 2016-07-28 12:47:58 +01:00
33c234a87e Bump pxt-core to 0.3.8 2016-07-28 12:47:57 +01:00
e9aa343d67 0.3.4 2016-07-28 11:51:44 +01:00
d83039430c Bump pxt-core to 0.3.7 2016-07-28 11:51:43 +01:00
5b2e877aef Merge branch 'master' of github.com:Microsoft/pxt-microbit 2016-07-28 11:49:04 +01:00
c5b28f5b8e Document testing 2016-07-28 11:47:45 +01:00
e765021bf9 Compile lang-tests to binary 2016-07-28 11:38:35 +01:00
dbcd9e535c Get generic part of lang-test from pxt-core package 2016-07-28 11:35:17 +01:00
cff88d67ad Update README.md 2016-07-27 13:48:57 -07:00
3f241e8bc9 Merge pull request #180 from Microsoft/snippetfixes
Fixes to documentation snippets
2016-07-27 13:30:39 -07:00
69c3d2d249 Update README.md 2016-07-27 13:28:57 -07:00
bc04d30595 some updates to setup instructions 2016-07-27 13:15:30 -07:00
63a26835b1 Format code 2016-07-27 19:32:58 +01:00
79113115e0 docs update 2016-07-27 10:57:18 -07:00
573ed7f6f2 updated localization strings in bundled packages 2016-07-27 08:42:58 -07:00
61da1032d6 0.3.3 2016-07-27 07:26:24 -07:00
36d455c693 Bump pxt-core to 0.3.5 2016-07-27 07:26:20 -07:00
42c766b6d7 updated shim definition 2016-07-26 16:17:54 -07:00
6f00384891 Merge branch 'master' of https://github.com/Microsoft/pxt-microbit 2016-07-26 13:52:01 -07:00
8440f7c763 adding "pin is pressed" block 2016-07-26 13:51:41 -07:00
8a8e864f99 fix reference section 2016-07-26 14:18:44 -04:00
7a3402b782 add FAQ for language 2016-07-26 14:10:41 -04:00
5e9a5b29f4 fix formatting problem 2016-07-26 14:10:41 -04:00
aff9d1ee60 clean up docs 2016-07-26 09:03:42 -07:00
8add7e8efb updated radio strings / docs page 2016-07-26 08:47:45 -07:00
e7dfd0531b 0.3.2 2016-07-26 13:12:48 +01:00
d2b1f70ce2 Bump pxt-core to 0.3.2 2016-07-26 13:12:48 +01:00
28b28d0b52 Change array declaration for first snippet in headbands 2016-07-25 11:11:51 +01:00
0ee2b285c0 Deleted list of bad snippets 2016-07-25 11:10:01 +01:00
d5cb085264 Rename function call in number documentation 2016-07-25 11:01:10 +01:00
c055a5d329 Syntax fixes to LED plotting docs 2016-07-25 11:00:34 +01:00
8fe8b78f4c Syntax fixes for hero lesson 2016-07-25 10:39:02 +01:00
f627f125c0 Syntax fixes for headbands lesson 2016-07-25 10:35:15 +01:00
7d3254477a Fix case of math in documentation snippet 2016-07-25 10:22:15 +01:00
3149ed4c1d Line numbers 2016-07-25 10:15:35 +01:00
baeafcdebe List of all snippets with errors 2016-07-25 09:39:34 +01:00
e942fb5733 Minor linting changes 2016-07-18 10:12:00 +01:00
127 changed files with 1479 additions and 1777 deletions

4
.gitignore vendored
View File

@ -7,11 +7,15 @@ typings
tmp
temp
projects/**
clients/win10/app/AppPackages
clients/win10/app/BundlePackages
clients/win10/app/BundleArtifacts
clients/win10/app/bin
clients/win10/app/bld
clients/win10/*.opendb
clients/**/bin/**
clients/**/obj/**
clients/electron/projects
*.user
*.sw?

View File

@ -4,6 +4,9 @@ node_js:
script:
- "node node_modules/pxt-core/built/pxt.js travis"
- "(cd libs/lang-test0; node ../../node_modules/pxt-core/built/pxt.js run)"
- "(cd libs/lang-test1; node ../../node_modules/pxt-core/built/pxt.js run)"
- "(cd libs/lang-test0; node ../../node_modules/pxt-core/built/pxt.js test)"
- "(cd libs/lang-test1; node ../../node_modules/pxt-core/built/pxt.js test)"
- "node node_modules/pxt-core/built/pxt.js testdir tests"
- "node node_modules/pxt-core/built/pxt.js uploaddoc"
- "(cd libs/hello; node ../../node_modules/pxt-core/built/pxt.js testconv https://az851932.vo.msecnd.net/files/td-converter-tests-v0.json)"

View File

@ -9,12 +9,19 @@ PXT ([Microsoft Programming Experience Toolkit](https://github.com/Microsoft/pxt
## Local server
The local server allows to run the editor and the documentation from your computer.
### Setup
The following commands are a 1-time setup after synching the repo on your machine.
* clone this repo to your computer
* install the PXT command line
* if not yet installed, install [Node.js 4.4.5 or higher](https://nodejs.org/en/download/)
* [clone this repo](https://help.github.com/articles/cloning-a-repository/) to your computer and go in the project folder
```
git clone https://github.com/microsoft/pxt-microbit
cd pxt-microbit
```
* install the PXT command line (add ``sudo`` for Mac/Linux shells).
```
npm install -g pxt
```
@ -37,7 +44,9 @@ If you need modify the `.cpp` files, turn on yotta compilation with the ``-yt``
pxt serve -yt
```
To make sure you're running the latest tools, run (add ``sudo`` for Mac/Linux shells)
## Updates
To update your PXT version and make sure you're running the latest tools, run (add ``sudo`` for Mac/Linux shells)
```
pxt update
```
@ -54,6 +63,23 @@ that wraps ``codethemicrobit.com`` and provides additional features.
* Install Visual Studio 2015 Update 2 or higher. Make sure the Windows 10 templates are installed.
* open the ``win10/app.sln`` solution and launch the ``codethemicrobit`` project.
## Testing
The build automatically runs the following:
* make sure the built-in packages compile
* `pxt run` in `libs/lang-test*` - this will run the test in command line runner;
there is a number of asserts in both of these
* `pxt testdir` in `tests` - this makes sure all the files compile and generates .hex files
* run the TD->TS converter on a number of test scripts from `microbit.co.uk` and make sure the results compile
To test something on the device:
* do a `pxt deploy` in `libs/lang-test*` - they should show `1` or `2` on the screen (and not unhappy face)
* run `pxt testdir` in `tests` and deploy some of the hex files from `tests/built`
The `lang-test0` source comes from the `pxt-core` package. It's also tested with `pxt run` there.
## Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.

67
clients/electron/main.js Normal file
View File

@ -0,0 +1,67 @@
const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
// pxt toolchain
const pxt = require('pxt-core')
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
function createWindow() {
console.log('starting app...')
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800, height: 600,
webPreferences: {
nodeIntegration: false,
}
})
ts.pxt.Util.debug = true;
pxt.mainCli("C:/gh/pxt-microbit/clients/electron/node_modules/pxt-microbit", ["serve", "-just"]);
// no menu
mainWindow.setMenu(null);
// and load the index.html of the app.
mainWindow.loadURL(`http://localhost:3232/#local_token=08ba9b8f-6ccb-4202-296d-28fac7a553d9`)
// Open the DevTools.
mainWindow.webContents.openDevTools()
// Emitted when the window is closed.
mainWindow.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

View File

@ -0,0 +1,19 @@
{
"name": "codethemicrobit",
"version": "0.1.0",
"description": "A Blocks / JavaScript editor for the micro:bit",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"author": "Microsoft",
"license": "MIT",
"devDependencies": {
"electron-prebuilt": "^1.2.0"
},
"dependencies": {
"typescript": "1.8.7",
"pxt-core": "*",
"pxt-microbit": "*"
}
}

View File

@ -20,22 +20,18 @@
<ProjectConfiguration Include="Release|AnyCPU">
<Configuration>Release</Configuration>
<Platform>AnyCPU</Platform>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM">
<Configuration>Release</Configuration>
<Platform>ARM</Platform>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x86">
<Configuration>Release</Configuration>
<Platform>x86</Platform>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

View File

@ -28,11 +28,12 @@ export function deployCoreAsync(res: ts.pxt.CompileResult) {
function getBitDrivesAsync(): Promise<string[]> {
if (process.platform == "win32") {
let rx = new RegExp("^([A-Z]:).* " + pxt.appTarget.compile.deployDrives)
return execAsync("wmic PATH Win32_LogicalDisk get DeviceID, VolumeName, FileSystem")
.then(buf => {
let res: string[] = []
buf.toString("utf8").split(/\n/).forEach(ln => {
let m = /^([A-Z]:).* MICROBIT/.exec(ln)
let m = rx.exec(ln)
if (m) {
res.push(m[1] + "/")
}
@ -41,8 +42,9 @@ function getBitDrivesAsync(): Promise<string[]> {
})
}
else if (process.platform == "darwin") {
let rx = new RegExp(pxt.appTarget.compile.deployDrives)
return readDirAsync("/Volumes")
.then(lst => lst.filter(s => /MICROBIT/.test(s)).map(s => "/Volumes/" + s + "/"))
.then(lst => lst.filter(s => rx.test(s)).map(s => "/Volumes/" + s + "/"))
} else {
return Promise.resolve([])
}

View File

@ -5,4 +5,8 @@ for (let i = 0;i<5;++i) {}
if (true){}
let x = 0;
Math.random(5);
```
```
## See Also
[logic](/blocks/logic), [loops](/blocks/loops), [math](/blocks/math), [variables](/blocks/variables)

View File

@ -86,7 +86,7 @@ if (led.point(1,1) && led.point(2,2)) {
When you compare two Numbers, you get a Boolean value, such as the comparison `x < 5` in the code below:
```blocks
let x = math.random(5)
let x = Math.random(5)
if(x < 5) {
basic.showString("low");
} else {

View File

@ -46,7 +46,7 @@ basic.showNumber(counter);
To change the contents of a variable use the assignment operator. The following code sets `counter` to 1 and then increments `counter` by 10:
```blocks
```blocks
let counter = 1;
counter = counter + 10;
basic.showNumber(counter);

View File

@ -48,41 +48,45 @@ The micro:bits *scheduler* provides the capability to concurrently execute di
The first job of the scheduler is to allow multiple *subprograms* to be queued up for later execution . For our purposes, a subprogram is just a statement or sequence of statements in the context of a larger program. Consider the Touch Develop program below for counting button presses.
```
export function countButtonPresses() {
input.onButtonPressed(Button.A, () => {
count = count + 1
})
basic.forever(() => {
basic.showNumber(count, 150)
})
count = 0
}
```
The program above contains three statements that execute in order from top to bottom. The first statement
```
```blocks
let count = 0
input.onButtonPressed(Button.A, () => {
count = count + 1
count++;
})
```
informs the scheduler that on each and every event of the A button being pressed, a subprogram (called the event handler) should be queued for execution. The event handler is demarcated by the do/end keywords; it increments the global variable `count` by one. The second statement
```
basic.forever(() => {
basic.showNumber(count, 150)
})
```
queues a `forever` loop for later execution by the scheduler; the body of this loop (between the do/end keywords) displays the current value of global variable `count` on the LED screen. The third statement
The program above contains three statements that execute in order from top to bottom.
The first statement initializes the global variable `count` to zero.
```
count = 0
```blocks
let count = 0
```
initializes the global variable `count` to zero. The function ends after the execution of these three statements, but this is not the end of program execution! Thats because the function queued the `forever` loop for execution by the scheduler.
The second statement informs the scheduler that on each and every event of the A button being pressed, a subprogram (called the event handler) should be queued for execution. The event handler is demarcated by the do/end keywords; it increments the global variable `count` by one.
```blocks
let count = 0
// ...
input.onButtonPressed(Button.A, () => {
count++;
})
```
The third statement queues a `forever` loop for later execution by the scheduler; the body of this loop (between the do/end keywords) displays the current value of global variable `count` on the LED screen. The third statement
```blocks
let count = 0
// ...
basic.forever(() => {
basic.showNumber(count, 150)
})
```
The function ends after the execution of these three statements, but this is not the end of program execution! Thats because the function queued the `forever` loop for execution by the scheduler.
The second job of the scheduler is to periodically interrupt execution to read (poll) the various inputs to the micro:bit (the buttons, pins, etc.) and fire off events (such as “button A pressed”). Recall that the firing of an event causes the event handler subprogram associated with that event to be queued for later execution. The scheduler uses a timer built into the micro:bit hardware to interrupt execution every 6 milliseconds and poll the inputs, which is more than fast enough to catch the quickest press of a button.
@ -96,9 +100,18 @@ If you hadnt guessed already, a footballer represents subprogram and dribblin
We will call this “passing control of execution” rather than “passing the ball”. However, in the world of the micro:bit, the concurrently executing subprograms are not aware of each other, so they dont actually pass control directly to one another. Rather they pass control of execution back to the scheduler and the scheduler determines the subprogram to pass control to next. The programmer inserts a call to the `pause` function to indicate a point in the subprogram where control of execution passes to the scheduler. Also, when a subprogram ends execution, control passes to the scheduler.
Lets take a look at the implementation of the `forever` statement to see an example of cooperative scheduling:
Lets take a look at the implementation of the `basic.forever` function to see an example of cooperative scheduling:
![](/static/mb/device/reactive-2.png)
```typescript
function forever(body: () => void) {
control.inBackground(() => {
while(true) {
body()
basic.pause(20)
}
})
}
```
The `forever` loop actually is a function that takes a subprogram (an *Action* in Touch Develop) as a parameter. The function uses the `control -> in background` function of the micro:bit runtime to queue a `while true` loop for execution by the scheduler. The while loop has two statements. The first statement runs the subprogram represented by the `body` parameter. The second statement passes control to the scheduler (requesting to “sleep” for 20 milliseconds).
@ -128,15 +141,15 @@ Through this example, we have seen that the micro:bit scheduler enables you to c
As a result, you can easily add a new capability to the micro:bit by just adding a new subprogram. For example, if you want to add a reset feature to the counter program, all you need to do is add a new event handler for a press of button B that sets the global variable "count" to zero, as shown below:
```
```typescript
export function countButtonPressesWithReset() {
let count = 0
input.onButtonPressed(Button.A, () => {
count = count + 1
})
basic.forever(() => {
basic.showNumber(count, 150)
})
count = 0
input.onButtonPressed(Button.B, () => {
count = 0
})

View File

@ -27,5 +27,15 @@ Visit the cards below to starting programming JavaScript and TypeScript with the
},{
"name": "Classes",
"url": "/js/classes"
}]
},{
"name": "FAQ",
"url": "/js/faq"
}
]
```
### See Also
[calling](/js/call), [sequencing](/js/sequence), [variables](/js/variables), [operators](/js/operators), [statements](/js/statements), [functions](/js/functions),
[types](/js/types), [classes](/js/classes), [FAQ](/js/faq)

View File

@ -49,7 +49,7 @@ basic.clearScreen()
It's a syntax error to have a left parenthesis without the "closing" right parenthesis:
```typescript
```
basic.clearScreen(
```

View File

@ -43,7 +43,7 @@ Of course, one of the most fundamental patterns in class-based programming is be
Let's take a look at an example:
```ts
```ts-ignore
class Animal {
name: string;
constructor(theName: string) { this.name = theName; }
@ -105,7 +105,7 @@ In TypeScript, each member is `public` by default.
You may still mark a member `public` explicitly.
We could have written the `Animal` class from the previous section in the following way:
```ts
```ts-ignore
class Animal {
public name: string;
public constructor(theName: string) { this.name = theName; }
@ -119,7 +119,7 @@ class Animal {
When a member is marked `private`, it cannot be accessed from outside of its containing class. For example:
```ts
```ts-ignore
class Animal {
private name: string;
constructor(theName: string) { this.name = theName; }
@ -138,7 +138,7 @@ The same applies to `protected` members.
Let's look at an example to better see how this plays out in practice:
```ts
```ts-ignore
class Animal {
private name: string;
constructor(theName: string) { this.name = theName; }
@ -174,7 +174,7 @@ Even though `Employee` also has a `private` member called `name`, it's not the o
The `protected` modifier acts much like the `private` modifier with the exception that members
declared `protected` can also be accessed by instances of deriving classes. For example,
```ts
```ts-ignore
class Person {
protected name: string;
constructor(name: string) { this.name = name; }
@ -204,7 +204,7 @@ we can still use it from within an instance method of `Employee` because `Employ
A constructor may also be marked `protected`.
This means that the class cannot be instantiated outside of its containing class, but can be extended. For example,
```ts
```ts-ignore
class Person {
protected name: string;
protected constructor(theName: string) { this.name = theName; }
@ -233,7 +233,7 @@ let john = new Person("John"); // Error: The 'Person' constructor is protected
You can make properties readonly by using the `readonly` keyword.
Readonly properties must be initialized at their declaration or in the constructor.
```ts
```ts-ignore
class Octopus {
readonly name: string;
readonly numberOfLegs: number = 8;
@ -252,7 +252,7 @@ This turns out to be a very common practice.
*Parameter properties* let you create and initialize a member in one place.
Here's a further revision of the previous `Octopus` class using a parameter property:
```ts
```ts-ignore
class Octopus {
readonly numberOfLegs: number = 8;
constructor(readonly name: string) {

58
docs/js/faq.md Normal file
View File

@ -0,0 +1,58 @@
# Frequently asked questions
# What is the language supported for the micro:bit?
For the micro:bit, we support a "static" subset of TypeScript (itself a superset of JavaScript):
## Supported language features
* variables with `let`, `const`, and `var`
* functions with lexical scoping and recursion
* top-level code in the file; hello world really is `console.log("Hello world")`
* `if ... else if ... else` statements
* `while` and `do ... while` loops
* `for(;;)` loops (see below about `for ... in/of`)
* `break/continue`; also with labeled loops
* `switch` statement (on numbers only)
* `debugger` statement for breakpoints
* conditional operator `? :`; lazy boolean operators
* namespaces (a form of modules)
* all arithmetic operators (including bitwise operators); note that in microcontroller targets
all arithmetic is performed on integers, also when simulating in the browser
* strings (with a few common methods)
* [string templates](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) (`` `x is ${x}` ``)
* arrow functions `() => ...`
* classes with fields, methods and constructors; `new` keyword
* array literals `[1, 2, 3]`
* enums
## Unsupported language features
We generally stay away from the more dynamic parts of JavaScript.
Things you may miss and we may implement:
* exceptions (`throw`, `try ... catch`, `try ... finally`)
* `for ... of` statements
* object literals `{ foo: 1, bar: "two" }`
* method-like properties (get/set accessors)
* class inheritance
For JS-only targets we may implement the following:
* regular expressions
* classes implementing interfaces
Things that we are not very likely to implement:
* file-based modules (`import * from ...`, `module.exports` etc); we do support namespaces
* spread operator
* `yield` expression and ``function*``
* `await` expression and `async function`
* `typeof` expression
* tagged templates ``tag `text ${expression} more text` ``; regular templates are supported
* binding with arrays or objects: `let [a, b] = ...; let { x, y } = ...`
* `with` statement
* `eval`
* `delete` statement
* `for ... in` statements
* JSX (HTML as part of JavaScript)

View File

@ -45,7 +45,7 @@ TypeScript can figure the return type out by looking at the return statements, s
In TypeScript, the number of arguments given to a function has to match the number of parameters the function expects.
```ts
```ts-ignore
function buildName(firstName: string, lastName: string) {
return firstName + " " + lastName;
}
@ -60,7 +60,7 @@ When they do, their value is `undefined`.
We can get this functionality in TypeScript by adding a `?` to the end of parameters we want to be optional.
For example, let's say we want the last name parameter from above to be optional:
```ts
```ts-ignore
function buildName(firstName: string, lastName?: string) {
if (lastName)
return firstName + " " + lastName;
@ -80,7 +80,7 @@ In TypeScript, we can also set a value that a parameter will be assigned if the
These are called default-initialized parameters.
Let's take the previous example and default the last name to `"Smith"`.
```ts
```ts-ignore
function buildName(firstName: string, lastName = "Smith") {
return firstName + " " + lastName;
}
@ -115,7 +115,7 @@ Unlike plain optional parameters, default-initialized parameters don't *need* to
If a default-initialized parameter comes before a required parameter, users need to explicitly pass `undefined` to get the default initialized value.
For example, we could write our last example with only a default initializer on `firstName`:
```ts
```ts-ignore
function buildName(firstName = "Will", lastName: string) {
return firstName + " " + lastName;
}
@ -134,7 +134,7 @@ In JavaScript, you can work with the arguments directly using the `arguments` va
In TypeScript, you can gather these arguments together into a variable:
```ts
```ts-ignore
function buildName(firstName: string, ...restOfName: string[]) {
return firstName + " " + restOfName.join(" ");
}
@ -148,7 +148,7 @@ The compiler will build an array of the arguments passed in with the name given
The ellipsis is also used in the type of the function with rest parameters:
```ts
```ts-ignore
function buildName(firstName: string, ...restOfName: string[]) {
return firstName + " " + restOfName.join(" ");
}

View File

@ -35,7 +35,7 @@ basic.showNumber(1);
basic.showNumber(2);
```
## The empty statement
### The empty statement
In JavaScript, there is the concept of an *empty statement*, which is whitespace followed by
a semicolon in the context where a statement is expected.

View File

@ -44,7 +44,7 @@ Another property of block-scoped variables is that they can't be read or written
While these variables are "present" throughout their scope, all points up until their declaration are part of their *temporal dead zone*.
This is just a sophisticated way of saying you can't access them before the `let` statement, and luckily TypeScript will let you know that.
```typescript
```typescript-ignore
a++; // illegal to use 'a' before it's declared;
let a;
```

View File

@ -62,7 +62,7 @@ export function newAction() {
Now let's implement `PRESS PIN 0` in the main. Create a condition of `input->on pin pressed("P0")` that will add one to the score and calls the method `new action`.
```
```blocks
// **. . .**
input.onButtonPressed(Button.B, () => {
basic.showNumber(game.score(), 150) // ***

View File

@ -86,3 +86,7 @@ Have fun reviewing your simulation and analyze the acceleration by chart the Exc
* The first person and second person take turns tilting the micro:bit in the "x" direction while the other player charts the data on the micro:bit!
* Review and analyze the actual micro:bit device acceleration data on Excel
* Display acceleration with y or z using plot bar graph by changing acceleration from "x" to "y" or "z"
```package
microbit-radio
```

View File

@ -34,8 +34,7 @@ Let's code the third part of Happy Birthday!
To do this, you need to add blocks after the last line of the `play` blocks. We want to continue to adding musical chords with the `play` block. Then insert the appropriate chord blocks `G`, `E`, `C`, `B`, `A` to complete the third part of the song. Modify your code so that your code looks like this.
``` blocks
```blocks
music.playTone(music.noteFrequency(Note.C), music.beat(BeatFraction.Quater));
music.playTone(music.noteFrequency(Note.C), music.beat(BeatFraction.Quater));
music.playTone(music.noteFrequency(Note.D), music.beat(BeatFraction.Quater));
@ -57,8 +56,7 @@ music.playTone(music.noteFrequency(Note.F), music.beat(BeatFraction.Quater));
music.playTone(music.noteFrequency(Note.E), music.beat(BeatFraction.Quater));
music.playTone(music.noteFrequency(Note.D), music.beat(BeatFraction.Quater));
basic.pause(100);
```
```
* click *run * to see if the code works as expected.

View File

@ -5,7 +5,7 @@
Your beginning code should look like this:
```blocks
let coll = (<string[]>[])
let coll: string[] = []
coll.push("puppy")
coll.push("clock")
coll.push("night")
@ -27,7 +27,7 @@ game.startCountdown(30000)
Let's add more words for the player to act out! But first, we need to increase the time in one round to give the player more time get through all the words. Let's change the `game->start countdown` statement.
```blocks
let coll = (<string[]>[])
let coll: string[] = []
coll.push("puppy")
coll.push("clock")
coll.push("night")
@ -52,7 +52,8 @@ game.startCountdown(60000)
Now let's add 5 more words to our list of charade words. Right above the the line `word:=coll->at(index)` add 5 lines that say `coll->add("")`. In this example, we will add the words **bicycle, telephone, sun, car, and ant** but you can add whatever words you like.
```blocks
let coll.push("puppy")
let coll: string[] = []
coll.push("puppy")
coll.push("clock")
coll.push("night")
coll.push("cat")

View File

@ -19,7 +19,7 @@ A 'collection' is a group of variables of the same type stored together. A 'coll
## 2. Consider the following lines of code.
```blocks
let coll = (<string[]>[])
let coll: string[] = []
coll.push("puppy")
coll.push("clock")
```
@ -35,7 +35,7 @@ basic.showString(coll[0], 150)
## 3. Consider the following lines of code.
```blocks
let coll = (<string[]>[])
let coll: string[] = []
coll.push("puppy")
coll.push("clock")
coll.push("cat")
@ -52,7 +52,7 @@ basic.showString(coll[2], 150)
## 4. Consider the following line of code.
```blocks
let coll = (<string[]>[])
let coll: string[] = []
```
Write the five (5) lines of code that will add the following five words to `data->coll`: puppy, clock, night, cat, cow.
@ -60,7 +60,8 @@ Write the five (5) lines of code that will add the following five words to `data
<br/>
```blocks
let coll.push("puppy")
let coll: string[] = []
coll.push("puppy")
coll.push("clock")
coll.push("night")
coll.push("cat")
@ -72,6 +73,7 @@ coll.push("cow")
<br/>
```blocks
let coll: string[] = []
let index = Math.random(coll.length)
let word = coll[index]
```

View File

@ -39,7 +39,7 @@ coll.push("cat")
## 4. Write the five (5) lines of code that will add the following five words to `data->coll`: puppy, clock, night, cat, cow.
```
```ts
let coll = (<string[]>[])
```

View File

@ -211,7 +211,7 @@ Let's setup the logic for the food and the ghost to be in different quadrants. F
let hero = game.createSprite(2, 2);
let food = game.createSprite(4, 4);
let ghost = game.createSprite(0, 0);
let ghost.change(LedSpriteProperty.Blink, 100);
ghost.change(LedSpriteProperty.Blink, 100);
food = led.brightness() == 8;
while (true) {
basic.pause(400);
@ -265,7 +265,7 @@ while (true) {
}
}
0.set(LedSpriteProperty.X, 4);
ghost.set(LedSpriteProperty.X, 4);
```

View File

@ -42,3 +42,7 @@ radio.onDataReceived(() => { })
* learn how to conditionally run code depending on whether a condition is true or not
* learn how to run code when an input button is pressed
* learn how to pause your code for the specified number of milliseconds
```package
microbit-radio
```

View File

@ -162,3 +162,7 @@ radio.onDataReceived(() => {
Connect the first micro:bit to your computer using your USB cable and run the pogo script on it.
Connect the second micro:bit to your computer using your USB cable and run the pogo script on it.
The first person and second person take turns jumping in the “y” direction while the other player uses the micro:bit to track the results on the micro:bit!
```package
microbit-radio
```

View File

@ -33,3 +33,7 @@ radio.receiveNumber();
* learn how to return the sum of the two numbers
* learn how to get acceleration value in milli-gravitys
* learn how to read the connector value as analog as a value comprised between 0 and 1023
```package
microbit-radio
```

View File

@ -195,4 +195,6 @@ Let's select Style 10 as an example.
* The first person and second person take shaking or moving the micor:bit in any direction while the other player charts the data on the micro:bit!
* Review and analyze the actual micro:bit device acceleration data on Excel
```package
microbit-radio
```

View File

@ -2,8 +2,13 @@
The editor is open source on GitHub under the MIT license. Contributions are welcome, please check our GitHub repos.
### Repos
### Source Code
* [microsoft/pxt-microbit](https://github.com/Microsoft/pxt-microbit), PXT target for BBC micro:bit, also includes the documentation.
* [microbit/pxt](https://github.com/Microsoft/pxt), programming experience toolkit (PXT)
* [microsoft/pxt-microbit-core](https://github.com/Microsoft/pxt-microbit-core), Yotta module used to build the BBC micro:bit runtime
## C++ Runtime
The [C++ micro:bit runtime](http://lancaster-university.github.io/microbit-docs/), created at [Lancaster University](http://www.lancaster.ac.uk/), provides access to the hardware functions of the micro:bit,
as well as a set of helper functions (such as displaying a number/image/string on the LED screen).

View File

@ -47,5 +47,6 @@ Here are some cool projects that you can build with your micro:bit!
}]
```
### See Also
[Flashing Heart](/projects/flashing-heart), [Smiley Buttons](/projects/smiley-buttons), [Love Meter](/projects/love-meter), [Rock Paper Scissors](/projects/rock-paper-scissors), [Compass](/projects/compass), [Hack your headphones](/projects/hack-your-headphones), [Banana keyboard](/projects/banana-keyboard), [Telegraph](/projects/telegraph), [Radio](/projects/radio), [Watch](/projects/the-watch)

View File

@ -0,0 +1,65 @@
# messenger
![](/static/mb/projects/a9-radio.png)
Use the radio to create an app that sends "YO" messages.
## Step 1
Use [on button pressed](/reference/input/on-button-pressed) to send the number "0" over radio.
```blocks
input.onButtonPressed(Button.A, () => {
radio.sendNumber(0);
});
```
## Step 2
Use [radio on data received](/reference/radio/on-data-received) display "YO" when the number ``0`` is received
by radio.
```blocks
let message = 0;
radio.onDataReceived(() => {
message = radio.receiveNumber();
if (message == 0) {
basic.showString("YO")
}
})
```
Compile the program and **upload the same .hex file to 2 devices!**
## Step 3
Use [on button pressed](/reference/input/on-button-pressed) to send the number "1" over radio.
```blocks
input.onButtonPressed(Button.B, () => {
radio.sendNumber(1);
});
```
## Step 4
Add blocks in [radio on data received](/reference/radio/on-data-received) to display "BYE" when the number ``1`` is received
by radio.
```blocks
let message = 0;
radio.onDataReceived(() => {
message = radio.receiveNumber();
if (message == 0) {
basic.showString("YO")
}
if (message == 1) {
basic.showString("BYE")
}
})
```
```package
microbit-radio
```

View File

@ -89,4 +89,8 @@ Have fun reviewing your simulation and analyze the acceleration by chart the Exc
### ~button /projects/the-watch
NEXT: The Watch
### ~
### ~
```package
microbit-radio
```

View File

@ -1,12 +1,12 @@
# telegraph activity
Build a telgraph.
Build a telegraph.
# micro:bit telegraph
Have you ever tried to communicate through a telegraph? Let's try coding a "Telegraph" on two BBC micro:bits !
Complete the following [guided tutorial](/projects/telegraph), your hack should look like this:
Complete the following [tutorial](/projects/telegraph), your hack should look like this:
![](/static/mb/lessons/telegraph-0.png)

View File

@ -148,12 +148,6 @@ Trim any leftover fabric, threads or tape.
Your watch is ready!
### ~avatar avatar
Excellent, you're ready to continue with the [challenges](/projects/rock-paper-scissors)!
### ~
### Acknowledgements
Artistic design by Melinda Hoeneisen.

View File

@ -22,15 +22,19 @@ control.inBackground(() => {
});
```
## Advanced
```namespaces
devices.tellCameraTo(MesCameraEvent.TakePhoto);
bluetooth.onBluetoothConnected(() => {});
```
```package
microbit-radio
microbit-devices
microbit-bluetooth
```
```
### See Also
[basic](/reference/basic), [input](/reference/input), [music](/reference/music), [led](/reference/led), [Math (blocks)](/blocks/math), [String](/reference/types/string), [game](/reference/game), [images](/reference/images), [pins](/reference/pins), [serial](/reference/serial), [control](/reference/control), [radio](/reference/radio), [devices](/reference/devices), [bluetooth](/reference/bluetooth)

View File

@ -3,3 +3,7 @@
```cards
String.fromCharCode(0);
```
### See Also
[fromCharCode](/reference//math/string-from-char-code)

View File

@ -32,3 +32,7 @@ basic.showAnimation(`
. . . . .
`);
```
### See Also
[showNumber](/reference/basic/show-number), [showLeds](/reference/basic/show-leds), [showString](/reference/basic/show-string), [clearScreen](/reference/basic/clear-screen), [forever](/reference/basic/forever), [pause](/reference/basic/pause), [plotLeds](/reference/basic/plot-leds), [showAnimation](/reference/basic/show-animation)

View File

@ -23,7 +23,7 @@ In this animation, each row is 15 spaces wide because
there are three frames in the animation, and each frame is
five spaces wide, just like the screen on the BBC micro:bit.
```
```blocks
basic.showAnimation(`
. . # . . . # # # . . # # # .
. # # . . . . . # . . . . # .
@ -47,7 +47,7 @@ In this animation, each row is 30 spaces wide because
there are six frames in the animation, and each frame is
five spaces wide, just like the screen.
```
```blocks
basic.showAnimation(`
. . . . . # . . . . . . . . . . . . . # . . . . . # . . . .
. . # . . . . . . . . . # . . . . . . . . . # . . . . . . .

View File

@ -21,4 +21,8 @@ bluetooth.onBluetoothDisconnected(() => {
```package
microbit-bluetooth
```
```
### See Also
[startAccelerometerService](/reference/bluetooth/start-accelerometer-service), [startButtonService](/reference/bluetooth/start-button-service), [startIOPinService](/reference/bluetooth/start-io-pin-service), [startLEDService](/reference/bluetooth/start-led-service), [startMagnetometerService](/reference/bluetooth/start-magnetometer-service), [startTemperatureService](/reference/bluetooth/start-temperature-service), [uartRead](/reference/bluetooth/uart-read), [uartWrite](/reference/bluetooth/uart-write), [onBluetoothConnected](/reference/bluetooth/on-bluetooth-connected), [onBluetoothDisconnected](/reference/bluetooth/on-bluetooth-disconnected)

View File

@ -8,3 +8,7 @@ control.inBackground(() => {
});
control.reset();
```
### See Also
[inBackground](/reference/control/in-background), [reset](/reference/control/reset)

View File

@ -17,3 +17,11 @@ devices.onSignalStrengthChanged(() => {
});
```
```package
microbit-devices
```
### See Also
[tellCameraTo](/reference/devices/tell-camera-to), [tellRemoteControlTo](/reference/devices/tell-remote-control-to), [raiseAlertTo](/reference/devices/raise-alert-to), [onNotified](/reference/devices/on-notified), [onGamepadButton](/reference/devices/on-gamepad-button), [signalStrength](/reference/devices/signal-strength), [onSignalStrengthChanged](/reference/devices/on-signal-strength-changed)

View File

@ -0,0 +1,38 @@
# On Signal Strength Changed
Register code to run when the signal strength of the paired device changes.
### ~hint
The functions in the ``devices`` namespace allow the BBC micro:bit to communicate with a separate (remote) device,
such as a smartphone, over Bluetooth (Smart).
The set of supported events will depend on the remote device and the BBC micro:bit apps available for the remote device.
### ~
```sig
devices.onNotified(MesDeviceInfo.IncomingCall, () => {})
```
### Parameters
* ``body``: code to run when the signal strength changes.
### Examples
Display the signal strength on screen:
```blocks
devices.onNotified(MesDeviceInfo.IncomingCall, () => {
basic.showString("RING RING")
})
```
### See Also
[tell remote control to](/reference/devices/tell-remote-control-to), [raise alert to](/reference/devices/raise-alert-to), [signal strength](/reference/devices/signal-strength)
```package
microbit-devices
```

View File

@ -23,7 +23,7 @@ devices.onSignalStrengthChanged(() => {})
Display the signal strength on screen:
```
```blocks
devices.onSignalStrengthChanged(() => {
basic.showNumber(devices.signalStrength(), 150)
})

View File

@ -1,47 +0,0 @@
# tell microphone to
The tell microphone to function.
Access the audio recording capabilities of the device using the ``tell microphone to`` function.
The functions in the antenna namespace allow the BBC micro:bit to communicate with a separate (remote) device, such as a smartphone, over Bluetooth (Smart). The set of supported events will depend on the remote device and the BBC micro:bit apps available for the remote device.
### Block Editor
![](/static/mb/tell-microphone-to-0.png)
### JavaScript
```
export function tellMicrophoneTo(event: string)
```
### Parameters
* event - an event identifier
### Event values
* play
* stop
* pause
* forward
* rewind
* volume up
* volume down
* previous track
* next track
### Examples
To tell the connected device to start recording audio
```
devices.tellMicrophoneTo("start capture")
```
To tell the connected device to stop recording audio
```
devices.tellMicrophoneTo("stop capture")
```

View File

@ -9,3 +9,7 @@ game.startCountdown(10000);
game.gameOver();
game.setScore(0);
```
### See Also
[addScore](/reference/game/change-score-by), [score](/reference/game/score), [startCountdown](/reference/game/start-countdown), [gameOver](/reference/game/game-over), [setScore](/reference/game/set-score)

View File

@ -6,7 +6,7 @@ Turn off all the pixels in an [Image](/reference/images/image).
### JavaScript
```
```sig
export function clear(img: micro_bit.Image)
```
@ -18,7 +18,7 @@ export function clear(img: micro_bit.Image)
The following example turns off the pixels of `img` when the A input button is pressed:
```
```blocks
let img = images.createImage(`
. . . . .
. # # # .

View File

@ -1,148 +0,0 @@
# Game Library
The game library supports simple single-player time-based games. The player has a **sprite**, number of **lives** and a **score**. The game has a sprite, number of **levels** and a **countdown clock**. The general goal of a game will be to move the sprite and achieve a top score before time runs out or the number of lives goes to zero.
The code below shows a simple game where the user gets to press the button ``A`` as much times as possible in 10 seconds.
```blocks
input.onButtonPressed(Button.A, () => {
game.addScore(1)
})
game.startCountdown(10000)
```
### [Create sprite](/reference/game/create-sprite)
Create sprite with x, y coordinates and returns a LED Sprite. Create a new LED sprite.
![](/static/mb/create-sprite-0.png)
```
export function createSprite(x: number, y: number) : micro_bitSprites.LedSprite
```
### [Move](/reference/game/move)
Sprite move by a certain number
![](/static/mb/game-library/move-0.png)
```
export function move(_this: micro_bitSprites.LedSprite, leds: number)
```
### [Turn](/reference/game/turn)
Rotates a sprite to the right by a certain number of degrees
![](/static/mb/game-library/turn-0.png)
```
export function turnRight(_this: micro_bitSprites.LedSprite, degrees: number)
```
Rotates a sprite to the left by a certain number of degrees
```
export function turnLeft(_this: micro_bitSprites.LedSprite, degrees: number)
```
### [Change](/reference/game/change)
Sprite will change the x position by this number
![](/static/mb/change-0.png)
```
export function changeXBy(_this: micro_bitSprites.LedSprite, x: number)
```
Sprite will change the y position by this number
```
export function changeYBy(_this: micro_bitSprites.LedSprite, y: number)
```
### [Set](/reference/game/set)
Sprite will change the x position by this number
```
export function setX(_this: micro_bitSprites.LedSprite, x: number)
```
Sprite will change the y position by this number
![](/static/mb/change-0.png)
```
export function changeYBy(_this: micro_bitSprites.LedSprite, y: number)
```
### [If on edge, bounce](/reference/game/if-on-edge-bounce)
Sprite - If the sprite is on the edge, the sprite will bounce
![](/static/mb/game-library/if-on-edge-bounce-0.png)
```
export function ifOnEdgeBounce(_this: micro_bitSprites.LedSprite)
```
### [Change score by](/reference/game/change-score-by)
When a player achieves a goal, you can increase the game score
* add score points to the current score
![](/static/mb/game-library/pic1.png)
```
export function addScore(points: number)
```
### [Score](/reference/game/score)
* set the current score to a particular value.
```
export function setScore(value: number)
```
* get the current score value
![](/static/mb/game-library/pic2.png)
```
export function score() : number
```
### [Countdown](/reference/game/start-countdown)
If your game has a time limit, you can start a countdown in which case `game->current time` returns the remaining time.
* start a countdown with the maximum duration of the game in milliseconds.
![](/static/mb/game-library/pic3.png)
```
export function startCountdown(ms: number)
```
### [Game over](/reference/game/game-over)
If the `life` reaches zero or the time expires (see countdown), the game enters the **game over** mode. When the game is over, `game->is running` returns false
* check if the game still running.
```
let running = game.isRunning()
```
You can also end the game by calling the `game -> game over` function:
![](/static/mb/game-library/pic0.png)
```
game.gameOver()
```

View File

@ -2,12 +2,12 @@
Reports the x position of a sprite on the LED screen
```
```sig
export function x(_this: micro_bitSprites.LedSprite) : number
```
Reports the y position of a sprite on the LED screen
```
```sig
export function y(_this: micro_bitSprites.LedSprite) : number
```

View File

@ -4,24 +4,24 @@ Reports the x or y position, the current direction of a sprite, or the brightne
Reports the x position of a sprite on the LED screen
```
```sig
export function x(_this: micro_bitSprites.LedSprite) : number
```
Reports the y position of a sprite on the LED screen
```
```sig
export function y(_this: micro_bitSprites.LedSprite) : number
```
Reports the brightness of a sprite on the LED screen
```
```sig
export function brightness(_this: micro_bitSprites.LedSprite) : number
```
Reports the current direction of a sprite on the LED screen
```
```sig
export function direction(_this: micro_bitSprites.LedSprite) : number
```

View File

@ -0,0 +1,30 @@
# Set Score
Sets the current score.
```sig
game.setScore(1)
```
### Parameters
* a [number](/reference/types/number) that represents the new score.
### Examples
This program is a simple game.
Press button ``A`` as much as possible to increase the score.
Press ``B`` to display the score and reset the score.
```blocks
input.onButtonPressed(Button.B, () => {
basic.showNumber(game.score())
game.setScore(0)
})
input.onButtonPressed(Button.A, () => {
game.addScore(1)
})
```
### See Also
[score](/reference/game/score), [start countdown](/reference/game/start-countdown)

View File

@ -18,3 +18,7 @@ images.createBigImage(`
. . . . .
`);
```
### See Also
[createImage](/reference/images/create-image), [createBigImage](/reference/images/create-big-image)

View File

@ -6,7 +6,7 @@ Get the state of a pixel in an [Image](/reference/images/image).
### JavaScript
```
```sig
export function pixel(_this: micro_bit.Image, x: number, y: number) : boolean
```
@ -29,7 +29,7 @@ This example gets the state of pixel `0, 0` in the `img` variable:
### ~hide
```
```blocks
let img = images.createImage(`
. . # . . . . . . .
. # . # . . . # . .
@ -41,7 +41,7 @@ let img = images.createImage(`
### ~
```
```typescript-ignore
let state = img.pixel(0, 0)
```

View File

@ -6,7 +6,7 @@ Display an [Image](/reference/images/image) on the BBC micro:bit's [LED screen](
### JavaScript
```
```sig
export function plotFrame(_this: micro_bit.Image, index: number)
```
@ -20,7 +20,7 @@ The `plot frame` function takes the index of the frame (if there are two frames,
### Example
```
```blocks
let img = images.createImage(`
# . . . # # . . . #
. # . # . . # # # .

View File

@ -6,7 +6,7 @@ Display an [Image](/reference/images/image) on the BBC micro:bit's [LED screen](
### JavaScript
```
```sig
export function plotImage(_this: micro_bit.Image, xOffset: number)
```
@ -20,7 +20,7 @@ The `show image` function has a built in delay of 400ms after display of the ima
### Example
```
```blocks
let img = images.createImage(`
# . . . # # . . . #
. # . # . . # # # .

View File

@ -6,7 +6,7 @@ Set the on/off state of pixel in an [Image](/reference/images/image).
### JavaScript
```
```sig
export function setPixel(_this: micro_bit.Image, x: number, y: number, value: boolean)
```
@ -24,7 +24,7 @@ To figure out the ``x``, ``y`` coordinates, see [LED screen](/device/screen).
The following example creates an image and stores it in the `img` variable. The `set pixel` function sets the centre pixel off, before `img` is shown using `show image`.
```
```blocks
let img = images.createImage(`
. . # . .
. # . # .

View File

@ -6,7 +6,7 @@ Display an [Image](/reference/images/image) on the BBC micro:bit's [LED screen](
### JavaScript
```
```sig
export function showFrame(img: micro_bit.Image, frame: number)
```
@ -16,11 +16,11 @@ export function showFrame(img: micro_bit.Image, frame: number)
### Difference from `plot frame`
The `show frame` function is the same as [plot frame](/reference/image/plot-frame), but contains a built-in delay after the LED screen has been updated (whereas `plot frame` has no built-in delay)
The `show frame` function is the same as [plot frame](/reference/images/plot-frame), but contains a built-in delay after the LED screen has been updated (whereas `plot frame` has no built-in delay)
### Example
```
```blocks
let img = images.createImage(`
# . . . # # . . . #
. # . # . . # # # .

View File

@ -20,7 +20,7 @@ The following example gets the width of `img` and stores it in the `w` variable:
### ~hide
```
```blocks
let img = images.createImage(`
. . # . . . . . . .
. # . # . . . # . .
@ -32,7 +32,7 @@ let img = images.createImage(`
### ~
```
```typescript-ignore
let w = img.width()
```
@ -40,7 +40,7 @@ let w = img.width()
The following example uses the `width` function with a [for](/blocks/loops/for) loop to show each image frame on the screen:
```
```typescript
let img2 = images.createImage(`
. . # . . . # # # # . # # # .
. # # . . . . . . # . . . # .

View File

@ -14,6 +14,7 @@ input.onPinPressed(TouchPin.P0, () => {
});
input.buttonIsPressed(Button.A);
input.compassHeading();
input.pinIsPressed(TouchPin.P0);
input.temperature();
input.acceleration(Dimension.X);
input.lightLevel();
@ -21,7 +22,6 @@ input.rotation(Rotation.Pitch);
input.magneticForce(Dimension.X);
input.runningTime();
input.setAccelerometerRange(AcceleratorRange.OneG);
input.pinIsPressed(TouchPin.P0);
input.calibrate();
input.onLogoDown(() => {
@ -39,3 +39,7 @@ input.onShake(() => {
});
```
### See Also
[onButtonPressed](/reference/input/on-button-pressed), [onGesture](/reference/input/on-gesture), [onPinPressed](/reference/input/on-pin-pressed), [buttonIsPressed](/reference/input/button-is-pressed), [compassHeading](/reference/input/compass-heading), [pinIsPressed](/reference/input/pin-is-pressed), [temperature](/reference/input/temperature), [acceleration](/reference/input/acceleration), [lightLevel](/reference/input/light-level), [rotation](/reference/input/rotation), [magneticForce](/reference/input/magnetic-force), [runningTime](/reference/input/running-time), [setAccelerometerRange](/reference/input/set-accelerometer-range), [calibrate](/reference/input/calibrate), [onLogoDown](/reference/input/on-logo-down), [onLogoUp](/reference/input/on-logo-up), [onScreenDown](/reference/input/on-screen-down), [onScreenUp](/reference/input/on-screen-up), [onShake](/reference/input/on-shake)

View File

@ -0,0 +1,48 @@
# On Pin Released
Start an [event handler](/reference/event-handler) (part of the
program that will run when something happens, like when a button is
pressed). This handler works when you release pin `0`, `1`, or `2`
together with `GND`. When you are using this function in a web
browser, click and release the pins on the screen instead of the ones on the BBC
micro:bit.
If you hold the `GND` pin with one hand and touch pin `0`, `1`, or `2`
with the other, a very small (safe) amount of electricity will flow
through your body and back into the micro:bit. This is called
**completing a circuit**. It's like you're a big wire!
```sig
input.onPinReleased(TouchPin.P0, () => {
})
```
## ~hint
This function works best when the BBC micro:bit is using batteries for power,
instead of the USB cable.
## ~
## Parameters
* ``name`` means the pin that is being released, either `P0`, `P1`, or `P2`
### Example: pin pressed counter
This program counts how many times you release the `P0` pin.
Every time you release the pin, the program shows the number of times on the screen.
```blocks
let count = 0
basic.showNumber(count, 100)
input.onPinReleased(TouchPin.P0, () => {
count = count + 1
basic.showNumber(count, 100)
})
```
### See also
[BBC micro:bit pins](/device/pins), [pin is pressed](/reference/input/pin-is-pressed), [analog read pin](/reference/pins/analog-read-pin), [analog write pin](/reference/pins/analog-write-pin), [digital read pin](/reference/pins/digital-read-pin), [digital write pin](/reference/pins/digital-write-pin)

View File

@ -18,3 +18,7 @@ led.toggle(0, 0);
led.toggleAll();
led.setDisplayMode(DisplayMode.BackAndWhite);
```
### See Also
[plot](/reference/led/plot), [unplot](/reference/led/unplot), [point](/reference/led/point), [brightness](/reference/led/brightness), [setBrightness](/reference/led/set-brightness), [stopAnimation](/reference/led/stop-animation), [plotBarGraph](/reference/led/plot-bar-graph), [fadeIn](/reference/led/fade-in), [fadeOut](/reference/led/fade-out), [plotAll](/reference/led/plot-all), [screenshot](/reference/led/screenshot), [toggle](/reference/led/toggle), [toggleAll](/reference/led/toggle-all), [setDisplayMode](/reference/led/set-display-mode)

View File

@ -3,11 +3,11 @@
Display an [Image](/reference/images/image) on the BBC micro:bit's [LED screen](/device/screen). NOTE: `basic -> plot image` has been replaced by `basic -> show leds`.
```sig
basic.plotLeds(`
basic.showLeds(`
. . . . .
. # . # .
. . # . .
# ; . . #
# . . . #
. # # # .
`)
```
@ -16,14 +16,14 @@ basic.plotLeds(`
* leds - a series of LED on/off states that form an image (see steps below)
### Example: simley
### Example: smiley
```blocks
basic.plotLeds(`
basic.showLeds(`
. . . . .
. # . # .
. . # . .
# ; . . #
# . . . #
. # # # .
`)
```

View File

@ -9,14 +9,24 @@ led.stopAnimation()
### Example
This program...
This program sets up the ``stop animation`` part of the program,
and then shows a string that you can stop with button ``B``.
```blocks
basic.showString("STOP ME! STOP ME! PLEASE, WON'T SOMEBODY STOP ME?");
input.onButtonPressed(Button.B, () => {
led.stopAnimation();
});
'```
basic.showString("STOP ME! STOP ME! PLEASE, WON'T SOMEBODY STOP ME?");
```
### ~hint
It's important to set up ``stop animation`` before showing the
animation, so the ``stop animation`` part of the program will be ready
to go.
### ~
### See Also
[show animation](/reference/basic/show-animation)

View File

@ -12,3 +12,7 @@ music.tempo();
music.changeTempoBy(20);
music.setTempo(120);
```
### See Also
[playTone](/reference/music/play-tone), [ringTone](/reference/music/ring-tone), [rest](/reference/music/rest), [noteFrequency](/reference/music/note-frequency), [beat](/reference/music/beat), [tempo](/reference/music/tempo), [changeTempoBy](/reference/music/change-tempo), [setTempo](/reference/music/set-tempo)

View File

@ -17,7 +17,12 @@ pins.servoWritePin(AnalogPin.P0, 180);
pins.servoSetPulse(AnalogPin.P0, 1500);
pins.i2cReadNumber(0, NumberFormat.Int8LE);
pins.i2cWriteNumber(0, 0, NumberFormat.Int8LE);
pins.spiWrite(0);
pins.setPull(DigitalPin.P0, PinPullMode.PullDown);
pins.analogPitch(0, 0);
pins.analogSetPitchPin(AnalogPin.P0);
```
### See Also
[digitalReadPin](/reference/pins/digital-read-pin), [digitalWritePin](/reference/pins/digital-write-pin), [analogReadPin](/reference/pins/analog-read-pin), [analogWritePin](/reference/pins/analog-write-pin), [analogSetPeriod](/reference/pins/analog-set-period), [map](/reference/pins/map), [onPulsed](/reference/pins/on-pulsed), [pulseDuration](/reference/pins/pulse-duration), [servoWritePin](/reference/pins/servo-write-pin), [servoSetPulse](/reference/pins/servo-set-pulse), [i2cReadNumber](/reference/pins/i2c-read-number), [i2cWriteNumber](/reference/pins/i2c-write-number), [setPull](/reference/pins/set-pull), [analogPitch](/reference/pins/analog-pitch), [analogSetPitchPin](/reference/pins/analog-set-pitch), [spiWrite](/reference/pins/spi-write)

View File

@ -13,7 +13,7 @@ pins.analogPitch(440, 300)
### Example
```
```blocks
pins.analogSetPitchPin("P0")
let frequency1 = 440
let duration = 1000

View File

@ -12,7 +12,7 @@ pins.analogSetPitchPin(AnalogPin.P0)
### Example
```
```blocks
pins.analogSetPitchPin(AnalogPin.P0)
let frequency = 440
let duration = 1000

View File

@ -29,7 +29,7 @@ pins.servoWritePin(AnalogPin.P0, 90)
```blocks
basic.forever(() => {
let millig = input.acceleration(Dimensions.X)
let millig = input.acceleration(Dimension.X)
// map accelerometer readings to angle
let angle = pins.map(millig, -1023, 1023, 0, 180)
pins.servoWritePin(AnalogPin.P0, angle)

View File

@ -0,0 +1,19 @@
# SPI Write
Write to the SPI Slave and return the response.
```sig
pins.spiWrite(0);
```
### Parameters
* ``value``: value Data to be sent to the SPI slave
### Returns
* a [number](/reference/types/number) Response from the SPI slave
### See also
[SPI](https://developer.mbed.org/handbook/SPI)

View File

@ -14,7 +14,15 @@ radio.receivedNumberAt(0);
radio.receiveString();
radio.receivedSignalStrength();
radio.setGroup(0);
radio.setTransmitPower(0);
radio.setTransmitPower(7);
radio.setTransmitSerialNumber(false);
radio.writeValueToSerial();
radio.setTransmitSerialNumber(true);
```
```package
microbit-radio
```
### See Also
[sendNumber](/reference/radio/send-number), [sendValue](/reference/radio/send-value), [sendString](/reference/radio/send-string), [onDataReceived](/reference/radio/on-data-received), [receiveNumber](/reference/radio/receive-number), [receivedNumberAt](/reference/radio/received-number-at), [receiveString](/reference/radio/receive-string), [receivedSignalStrength](/reference/radio/received-signal-strength), [setGroup](/reference/radio/set-group), [setTransmitPower](/reference/radio/set-transmit-power), [setTransmitSerialNumber](/reference/radio/set-transmit-serial-number), [writeValueToSerial](/reference/radio/write-value-to-serial)

View File

@ -33,3 +33,6 @@ radio.onDataReceived(() => {
[receive number](/reference/radio/receive-number),
[send number](/reference/radio/send-number), [set group](/reference/radio/set-group)
```package
microbit-radio
```

View File

@ -64,3 +64,6 @@ basic.forever(() => {
[send number](/reference/radio/send-number), [on data received](/reference/radio/on-data-received)
```package
microbit-radio
```

View File

@ -89,3 +89,7 @@ radio.onDataReceived(() => {
### See also
[send string](/reference/radio/send-string), [on data received](/reference/radio/on-data-received)
```package
microbit-radio
```

View File

@ -38,3 +38,7 @@ basic.forever(() => {
### See also
[receive number](/reference/radio/receive-number), [send number](/reference/radio/send-number), [on data received](/reference/radio/on-data-received)
```package
microbit-radio
```

View File

@ -43,3 +43,7 @@ basic.forever(() => {
### See also
[receive number](/reference/radio/receive-number), [on data received](/reference/radio/on-data-received)
```package
microbit-radio
```

View File

@ -40,3 +40,7 @@ A radio that can both transmit and receive is called a _transceiver_.
### See also
[receive string](/reference/radio/receive-string), [on data received](/reference/radio/on-data-received)
```package
microbit-radio
```

View File

@ -44,3 +44,6 @@ radio.onDataReceived(() => {
[receive number](/reference/radio/receive-number), [on data received](/reference/radio/on-data-received)
```package
microbit-radio
```

View File

@ -34,3 +34,6 @@ radio.setGroup(128)
[receive number](/reference/radio/receive-number), [send number](/reference/radio/send-number), [on data received](/reference/radio/on-data-received)
```package
microbit-radio
```

View File

@ -38,3 +38,7 @@ radio.setTransmitPower(7)
### See also
[receive number](/reference/radio/receive-number), [send number](/reference/radio/send-number), [on data received](/reference/radio/on-data-received)
```package
microbit-radio
```

View File

@ -0,0 +1,31 @@
# Set Transmit Serial Number
Make the ``radio`` packet embed the board serial number with each packet of data.
```sig
radio.setTransmitSerialNumber(true);
```
### Parameters
* ``transmit`` is a [boolean](/reference/types/boolean) that represents whether the serial number needs to be transmitted.
### Simulator
This function only works on the micro:bit, not in browsers.
### Example
This program makes the ``radio`` send the serial number in each packet.
```blocks
radio.setTransmitSerialNumber(true);
```
### See also
[receive number](/reference/radio/receive-number), [send number](/reference/radio/send-number), [on data received](/reference/radio/on-data-received)
```package
microbit-radio
```

View File

@ -1,18 +1,26 @@
# Write Value To Serial
Writes the full data received data via ``radio`` to serial in JSON format.
**Note** - This method only works for [send number](/reference/radio/send-number) and [send value](/reference/radio/send-value). It does not work for [send string](/reference/radio/send-string) (although a string can be sent with [send value](/reference/radio/send-value)).
Writes the data received by ``radio`` to serial in JSON format.
```sig
radio.writeValueToSerial();
```
## Data received format
The format for received data printed to serial is as follows
- [send number](/reference/radio/send-number) - ```{v:ValueSent,t:MicrobitTimeAlive,s:Unused}```
- [send value](/reference/radio/send-number) - ```{v:Value,t:MicrobitTimeAlive,s:Unused,n:"Name"}```
- [send string](/reference/radio/send-string) - ```{}``` (currently unavailable)
### ~hint
This method only works for [send number](/reference/radio/send-number)
and [send value](/reference/radio/send-value). It does not work for
[send string](/reference/radio/send-string), although you can send a
string as part of [send value](/reference/radio/send-value).
### ~
### Data received format
The format for received data printed to serial is as follows:
- [send number](/reference/radio/send-number): ```{v:ValueSent,t:MicrobitTimeAlive,s:Unused}```
- [send value](/reference/radio/send-value): ```{v:ValueSent,t:MicrobitTimeAlive,s:Unused,n:"Name"}```
### Simulator
@ -20,7 +28,9 @@ This function only works on the micro:bit, not in browsers.
### Examples
When ```radio``` data is received (after pressing A button on 2nd micro:bit), output temperature data to serial.
When ```radio``` data is received (after pressing the ``A`` button on
the second micro:bit), this program sends temperature data to
serial.
```blocks
input.onButtonPressed(Button.A, () => {
@ -30,9 +40,18 @@ radio.onDataReceived(() => {
radio.writeValueToSerial();
});
```
Example output to serial when A button pressed:
```{v:27,t:323,s:0}```
Sample output to serial when ``A`` button pressed:
```Text
{v:27,t:323,s:0}
```
### See also
[send number](/reference/radio/send-number), [send value](/reference/radio/send-number), [on data received](/reference/radio/on-data-received)
[send number](/reference/radio/send-number),
[send value](/reference/radio/send-value),
[on data received](/reference/radio/on-data-received)
```package
microbit-radio
```

View File

@ -5,8 +5,12 @@ Reading and writing data over a serial connection.
```cards
serial.writeLine("");
serial.writeNumber(0);
serial.writeValue(x, 0);
serial.writeValue("x", 0);
serial.writeString("");
serial.readLine();
serial.redirect(SerialPin.P0, SerialPin.P0, BaudRate.BaudRate115200);
```
### See Also
[writeLine](/reference/serial/write-line), [writeNumber](/reference/serial/write-number), [writeValue](/reference/serial/write-value), [writeString](/reference/serial/write-string), [readLine](/reference/serial/read-line), [redirect](/reference/serial/redirect-to)

View File

@ -46,8 +46,6 @@ for
forever
game-library
game-over
if

View File

@ -0,0 +1,16 @@
# Boolean
true or false.
A Boolean has one of two possible values: `true`; `false`. Boolean (logical) operators (*and*, *or*, *not*) take Boolean inputs and yields a Boolean value. Comparison operators on other types ([numbers](/reference/types/number), [strings](/reference/types/string) yields a Boolean value.
The following blocks represent the true and false Boolean values, which can be plugged in anywhere a Boolean value is expected:
```blocks
true;
false;
```
### See Also
[boolean (blocks)](/blocks/logic/boolean.md)

View File

@ -61,7 +61,7 @@ The [math library](/blocks/math) includes math related functions.
For example, the `absolute` function returns the returns the absolute value of input parameter `x`:
```blocks
let abs = math.absolute(-42);
let abs = Math.abs(-42);
basic.showNumber(abs);
```

3
docs/support.md Normal file
View File

@ -0,0 +1,3 @@
# Support
Please use the [GitHub issue tracker](https://github.com/microsoft/pxt-microbit) to report bugs.

View File

@ -1,9 +0,0 @@
# You completed the survey!
```sim
basic.forever(() => { basic.showString("THANK YOU") })
```
Thank you for participating in this survey.
Please [contact us](mailto:microbitpilots@microsoft.com) with any information you think we might find useful.

View File

@ -1,12 +0,0 @@
# Windows 10 App
## Features
The Windows 10 App provides all the existing features of [codethemicrobit](https://codethemicrobit.com) plus the following ones:
* **auto-upload**: the compiled .hex file is automatically deployed to all connected BBC micro:bits
* **serial piping**: all serial data sent by connected BBC micro:bit is automatically imported and analyzed in the editor.
## Installing the app
Coming to the store soon!

View File

@ -1,774 +0,0 @@
//
// Note that this is supposed to run from command line.
// Do not use anything besides basic.pause, control.inBackground, console.log
//
//% shim=pxtrt::panic
function panic(code2: number): void { }
function msg(s: string): void {
//console.log(s)
//basic.pause(50);
}
function assert(cond: boolean, msg_: string) {
if (!cond) {
console.log("ASSERT: " + msg_);
panic(45);
}
}
//
// start tests
//
var glb1: number;
var s2: string;
var x: number;
var action: Action;
var tot: string;
var lazyAcc: number;
var sum: number;
var xyz = 12;
console.log("Starting...")
//lib.print_17(3);
basic.showNumber(0);
//assert(lib3.getX() == 17 * 3, "");
testNums();
testStrings();
testNumCollection();
testStringCollection();
testStringOps();
testReccoll();
inBg();
testAction(1);
testAction(7);
testIter();
testActionSave();
testLazyOps();
testRefLocals();
testByRefParams();
testFunDecl();
testDefaultArgs();
testMemoryFree();
testMemoryFreeHOF();
postPreFix()
eqOp()
testEnums()
testBuffer()
// test some top-level code
let xsum = 0;
for (let i = 0; i < 11; ++i) {
xsum = xsum + i;
}
assert(xsum == 55, "mainfor")
control.inBackground(() => {
xsum = xsum + 10;
})
basic.pause(20)
assert(xsum == 65, "mainforBg")
assert(xyz == 12, "init")
function incrXyz() {
xyz++;
return 0;
}
var unusedInit = incrXyz();
assert(xyz == 13, "init2")
testClass()
basic.showNumber(1)
console.log("ALL TESTS OK")
function defaultArgs(x: number, y = 3, z = 7) {
return x + y + z;
}
function testDefaultArgs() {
msg("testDefaultArgs");
assert(defaultArgs(1) == 11, "defl0")
assert(defaultArgs(1, 4) == 12, "defl1")
assert(defaultArgs(1, 4, 8) == 13, "defl2")
assert(optargs(1) == 1, "opt0");
assert(optargs(1, 2) == 3, "opt1");
assert(optargs(1, 2, 3) == 3, "opt2");
assert(optstring(3) == 6, "os0")
assert(optstring(3, "7") == 10, "os1")
assert(optstring2(3) == 6, "os0")
assert(optstring2(3, "7") == 10, "os1")
}
function optargs(x: number, y ?: number, z ?: number) {
return x + y;
}
function optstring(x: number, s ?: string) {
if (s != null) {
return parseInt(s) + x;
}
return x * 2;
}
function optstring2(x: number, s: string = null) {
if (s != null) {
return parseInt(s) + x;
}
return x * 2;
}
function testNums(): void {
let x = 40 + 2;
assert(x == 42, "add");
x = 40 / 2;
assert(x == 20, "div");
let r = fib(15);
msg("FIB" + r);
assert(r == 987, "fib");
let x3 = doStuff(x, 2);
assert(x3 == 10, "call order");
glb1 = 5;
incrBy_2();
assert(glb1 == 7, "glb1");
incrBy_2();
assert(glb1 == 9, "glb2");
assert(Math.abs(-42) == 42, "abs");
assert(Math.abs(42) == 42, "abs");
assert(Math.sign(42) == 1, "abs");
testIf();
assert((3 & 6) == 2, "&")
assert((3 | 6) == 7, "|")
assert((3 ^ 6) == 5, "^")
assert((-10 >> 2) == -3, ">>")
assert((-10 >>> 20) == 4095, ">>>")
assert((-10 << 2) == -40, "<<")
assert((10 << 2) == 40, "<<+")
assert((10 >> 2) == 2, ">>+")
assert((10 >>> 2) == 2, ">>>+")
assert(1000000 * 1000000 == -727379968, "*")
assert(100000001 * 100000001 == 2074919425, "*2")
assert(105 % 100 == 5, "perc")
}
function fib(p: number): number {
if (p <= 2) {
return p;
}
let p2 = p - 1;
return fib(p2) + fib(p - 2);
}
function doStuff(x: number, x2: number): number {
let x3 = x / x2;
return x3;
}
function testIf(): void {
let b = false;
if (!b) {
glb1 = 7;
} else {
assert(false, "b0");
}
assert(glb1 == 7, "glb3");
if (b) {
assert(false, "b1");
} else {
glb1 = 8;
}
assert(glb1 == 8, "glb3");
}
function incrBy_2(): void {
glb1 = glb1 + 2;
}
function testStrings(): void {
assert((42).toString() == "42", "42");
let s = "live";
assert(s == "live", "hello eq");
s = s + "4OK";
s2 = s;
assert(s.charCodeAt(4) == 52, "hello eq2");
assert(s.charAt(4) == "4", "hello eq2X");
assert(s[4] == "4", "hello eq2X");
assert(s.length == 7, "len7");
s = "";
for (let i = 0; i < 10; i++) {
s = s + i;
}
assert(s == "0123456789", "for");
let x = 10;
s = "";
while (x >= 0) {
s = s + x;
x = x - 1;
}
assert(s == "109876543210", "while");
msg(s);
msg(s2);
s2 = "";
// don't leak ref
x = 21
s = "foo"
s = `a${ x * 2 }X${ s }X${ s }Z`
assert(s == "a42XfooXfoo" + "Z", "`")
assert("X" + true == "Xt" + "rue", "boolStr")
}
function testNumCollection(): void {
let collXYZ: number[] =[];
assert(collXYZ.length == 0, "");
collXYZ.push(42);
assert(collXYZ.length == 1, "");
collXYZ.push(22);
assert(collXYZ[1] == 22, "");
collXYZ.splice(0, 1);
assert(collXYZ[0] == 22, "");
collXYZ.removeElement(22);
assert(collXYZ.length == 0, "");
for (let i = 0; i < 100; i++) {
collXYZ.push(i);
}
assert(collXYZ.length == 100, "");
collXYZ =[1, 2, 3];
assert(collXYZ.length == 3, "cons");
assert(collXYZ[0] == 1, "cons0");
assert(collXYZ[1] == 2, "cons1");
assert(collXYZ[2] == 3, "cons2");
}
function testStringCollection(): void {
let coll = (< string[] >[]);
coll.push("foobar");
coll.push((12).toString());
coll.push(coll[0] + "xx");
assert(coll.indexOf("12") == 1, "idx");
coll =[
"a" + "b",
coll[2],
]
assert(coll[0] == "ab", "")
assert(coll[1] == "foob" + "arxx", "")
assert(coll.length == 2, "")
}
function testStringOps(): void {
assert("foo".concat("bar") == "foobar", "concat");
assert("xAb".charCodeAt(1) == 65, "code at");
assert("B".charCodeAt(0) == 66, "tcc");
assert(parseInt("-123") == -123, "tonum");
assert("fo"[1] == "o", "at");
assert("fo".length == 2, "count");
assert("fo".charCodeAt(17) == 0, "ct oor");
}
class Testrec {
str: string;
num: number;
bool: boolean;
str2: string;
}
function recordId(x: Testrec) {
lazyAcc++
return x
}
function postPreFix() {
msg("postPref")
let x = new Testrec()
lazyAcc = 0
recordId(x).num = 12
assert(x.num == 12 && lazyAcc == 1, "X0")
let y = recordId(x).num++
assert(x.num == 13 && lazyAcc == 2, "X1")
assert(y == 12, "X2")
y = ++recordId(x).num
assert(y == 14 && x.num == 14 && lazyAcc == 3, "X2")
recordId(x).num >>= 1
assert(x.num == 7, "X3")
assert(lazyAcc == 4, "X4")
}
function eqOp() {
msg("eqOp")
let x = 12
assert((x += 10) == 22, "Y0")
assert(x == 22, "Y1")
x /= 2
assert(x == 11, "Y2")
let s = ("fo" + 1)
let t = ("ba" + 2)
s += t
assert(s == "fo1b" + "a2", "fb")
}
function testRec0(): Testrec {
let testrec = new Testrec();
testrec.str2 = "Hello" + " world";
testrec.str = testrec.str2;
testrec.num = 42;
assert(testrec.str == "Hello world", "recstr");
assert(testrec.num == 42, "recnum");
msg(testrec.str2);
let testrec2 = < Testrec > null;
assert(testrec2 == null, "isinv");
assert(testrec == testrec, "eq");
assert(testrec != null, "non inv");
return testrec;
}
function testReccoll(): void {
let coll: Testrec[] =[];
let item = testRec0();
msg("in reccoll");
coll.push(item);
}
function inBg() {
let k = 7
let q = 14
let rec = new Testrec();
glb1 = 0
control.inBackground(() => {
glb1 = glb1 + 10 + (q - k)
rec.str = "foo"
})
control.inBackground(() => {
glb1 = glb1 + 1
})
basic.pause(50)
assert(glb1 == 18, "inbg0")
assert(rec.str == "foo", "inbg1")
}
function runTwice(fn: Action): void {
msg("r2 start");
fn();
fn();
msg("r2 stop");
}
function iter(max: number, fn: (v: number) => void) {
for (var i = 0; i < max; ++i) {
fn(i);
}
}
function testIter() {
x = 0
iter(10, v => {
x = x + (v + 1)
})
assert(x == 55, "55")
}
function testAction(p: number): void {
let s = "hello" + "1";
let coll =[] as number[];
let p2 = p * 2;
x = 42;
runTwice(() => {
x = x + p + p2;
coll.push(x);
msg(s + x);
});
assert(x == 42 + p * 6, "run2");
assert(coll.length == 2, "run2");
}
function add7() {
sum = sum + 7;
}
function testFunDecl() {
msg("testFunDecl");
let x = 12;
sum = 0;
function addX() {
sum = sum + x;
}
function add10() {
sum = sum + 10;
}
runTwice(addX)
assert(sum == 24, "cap")
msg("testAdd10");
runTwice(add10);
msg("end-testAdd10");
assert(sum == 44, "nocap");
runTwice(add7);
assert(sum == 44 + 14, "glb")
addX();
add10();
assert(sum == 44 + 14 + x + 10, "direct");
}
function saveAction(fn: Action): void {
action = fn;
}
function saveGlobalAction(): void {
let s = "foo" + "42";
tot = "";
saveAction(() => {
tot = tot + s;
});
}
function testActionSave(): void {
saveGlobalAction();
runTwice(action);
msg(tot);
assert(tot == "foo42foo42", "");
tot = "";
action = null;
}
function testLazyOps(): void {
lazyAcc = 0;
if (incrLazyAcc(10, false) && incrLazyAcc(1, true)) {
assert(false, "");
} else {
assert(lazyAcc == 10, "lazy1");
}
assert(lazyAcc == 10, "lazy2");
if (incrLazyAcc(100, true) && incrLazyAcc(1, false)) {
assert(false, "");
} else {
assert(lazyAcc == 111, "lazy4");
}
lazyAcc = 0;
if (incrLazyAcc(100, true) && incrLazyAcc(8, true)) {
assert(lazyAcc == 108, "lazy5");
} else {
assert(false, "");
}
lazyAcc = 0;
if (incrLazyAcc(10, true) || incrLazyAcc(1, true)) {
assert(lazyAcc == 10, "lazy1b");
} else {
assert(false, "");
}
assert(lazyAcc == 10, "lazy2xx");
if (incrLazyAcc(100, false) || incrLazyAcc(1, false)) {
assert(false, "");
} else {
assert(lazyAcc == 111, "lazy4x");
}
lazyAcc = 0;
if (incrLazyAcc(100, false) || incrLazyAcc(8, true)) {
assert(lazyAcc == 108, "lazy5");
} else {
assert(false, "");
}
lazyAcc = 0;
if (incrLazyAcc(10, true) && incrLazyAcc(1, true) && incrLazyAcc(100, false)) {
assert(false, "");
} else {
assert(lazyAcc == 111, "lazy10");
}
lazyAcc = 0;
if (incrLazyAcc(10, true) && incrLazyAcc(1, true) || incrLazyAcc(100, false)) {
assert(lazyAcc == 11, "lazy101");
} else {
assert(false, "");
}
lazyAcc = 0;
assert((true ? incrLazyNum(1, 42): incrLazyNum(10, 36)) == 42, "?:")
assert(lazyAcc == 1, "?:0");
assert((false ? incrLazyNum(1, 42): incrLazyNum(10, 36)) == 36, "?:1")
assert(lazyAcc == 11, "?:2");
}
function incrLazyAcc(delta: number, res: boolean): boolean {
lazyAcc = lazyAcc + delta;
return res;
}
function incrLazyNum(delta: number, res: number) {
lazyAcc = lazyAcc + delta;
return res;
}
function testRefLocals(): void {
msg("start test ref locals");
let s = "";
// For 4 or more it runs out of memory
for (let i = 0; i < 3; i++) {
msg(i + "");
let copy = i;
control.inBackground(() => {
basic.pause(10 * i);
copy = copy + 10;
});
control.inBackground(() => {
basic.pause(20 * i);
s = s + copy;
});
}
basic.pause(200);
assert(s == "101112", "reflocals");
}
function byRefParam_0(p: number): void {
control.inBackground(() => {
basic.pause(1);
sum = sum + p;
});
p = p + 1;
}
function byRefParam_2(pxx: number): void {
pxx = pxx + 1;
control.inBackground(() => {
basic.pause(1);
sum = sum + pxx;
});
}
function testByRefParams(): void {
msg("testByRefParams");
refparamWrite("a" + "b");
refparamWrite2(new Testrec());
refparamWrite3(new Testrec());
sum = 0;
let x = 1;
control.inBackground(() => {
basic.pause(1);
sum = sum + x;
});
x = 2;
byRefParam_0(4);
byRefParam_2(10);
basic.pause(30);
assert(sum == 18, "by ref");
}
function refparamWrite(s: string): void {
s = s + "c";
assert(s == "abc", "abc");
}
function refparamWrite2(testrec: Testrec): void {
testrec = new Testrec();
assert(testrec.bool == false, "");
}
function refparamWrite3(testrecX: Testrec): void {
control.inBackground(() => {
basic.pause(1);
assert(testrecX.str == "foo", "ff");
testrecX.str = testrecX.str + "x";
});
testrecX = new Testrec();
testrecX.str = "foo";
basic.pause(30);
assert(testrecX.str == "foox", "ff2");
}
function testMemoryFree(): void {
msg("testMemoryFree");
for (let i = 0; i < 1000; i++) {
allocImage();
}
}
function runOnce(fn: Action): void {
fn();
}
function createObj() {
return new Testrec();
}
function testMemoryFreeHOF(): void {
msg("testMemoryFreeHOF");
for (let i = 0; i < 1000; i++) {
runOnce(() => {
let tmp = createObj();
});
}
}
function allocImage(): void {
let tmp = createObj();
}
class Foo {
pin: number;
buf: number[];
constructor(k: number, l: number) {
this.pin = k - l
}
setPin(p: number) {
this.pin = p
}
getPin() {
return this.pin
}
init() {
this.buf =[1, 2]
}
}
function testClass() {
let f = new Foo(272, 100);
assert(f.getPin() == 172, "ctor")
f.setPin(42)
assert(f.getPin() == 42, "getpin")
}
enum En {
A,
B,
C,
D = 4200,
E,
}
enum En2 {
D0 = En.D,
D1,
D2 = 1,
}
function testEnums() {
msg("enums")
let k = En.C as number
assert(k == 2, "e0")
k = En.D as number
assert(k == 4200, "e1")
k = En.E as number
assert(k == 4201, "e43")
k = En2.D0 as number
assert(k == 4200, "eX0")
k = En2.D1 as number
assert(k == 4201, "eX1")
msg("enums0")
assert(switchA(En.A) == 7, "s1")
assert(switchA(En.B) == 7, "s2")
assert(switchA(En.C) == 12, "s3")
assert(switchA(En.D) == 13, "s4")
assert(switchA(En.E) == 12, "s5")
assert(switchA(-3 as En) == 12, "s6")
msg("enums1")
assert(switchB(En.A) == 7, "x1")
assert(switchB(En.B) == 7, "x2")
assert(switchB(En.C) == 17, "x3")
assert(switchB(En.D) == 13, "x4")
assert(switchB(En.E) == 14, "x5")
}
function switchA(e: En) {
let r = 12;
switch (e) {
case En.A:
case En.B: return 7;
case En.D: r = 13; break;
}
return r
}
function switchB(e: En) {
let r = 33;
switch (e) {
case En.A:
case En.B: return 7;
case En.D: r = 13; break;
case En.E: r = 14; break;
default: return 17;
}
return r;
}
function bufferIs(b: Buffer, a: number[]) {
assert(b.length == a.length, "bis-len")
for (let i = 0; i < a.length; ++i) {
if (a[i] != b[i]) {
assert(false, `bufferIs: buf[${ i }]:${ b[i] } != ${ a[i] }`)
}
}
}
function testBuffer() {
let b = pins.createBuffer(3);
assert(b[0] == 0, "buf0");
assert(b[1] == 0, "buf0");
assert(b[2] == 0, "buf0");
assert(b[-100000] == 0, "bufM");
assert(b[100000] == 0, "bufM");
b[0] = 42;
bufferIs(b,[42, 0, 0]);
b[2] = 41;
bufferIs(b,[42, 0, 41]);
b.rotate(1)
bufferIs(b,[0, 41, 42]);
b.rotate(-2)
bufferIs(b,[41, 42, 0]);
b.shift(1)
bufferIs(b,[42, 0, 0]);
b.rotate(9)
bufferIs(b,[42, 0, 0]);
b.rotate(-9)
bufferIs(b,[42, 0, 0]);
b.fill(4);
bufferIs(b,[4, 4, 4]);
b.fill(12, 1, 1);
bufferIs(b,[4, 12, 4]);
b.fill(13, 1, -1);
bufferIs(b,[4, 13, 13]);
b.fill(100, -1, -1);
bufferIs(b,[4, 13, 13]);
b.shift(-1)
bufferIs(b,[0, 4, 13]);
}

View File

@ -6,6 +6,7 @@
"lang-test0.ts"
],
"public": true,
"additionalFilePath": "../../node_modules/pxt-core/libs/lang-test0",
"dependencies": {
"microbit": "file:../microbit"
}

View File

@ -0,0 +1,77 @@
//
// Note that this is supposed to run from command line.
// Do not use anything besides basic.pause, control.inBackground, console.log
//
//% shim=pxtrt::panic
function panic(code2: number): void { }
function msg(s: string): void {
//console.log(s)
//basic.pause(50);
}
function assert(cond: boolean, msg_: string) {
if (!cond) {
console.log("ASSERT: " + msg_);
panic(45);
}
}
console.log("Starting...")
basic.showNumber(0);
testBuffer()
basic.showNumber(2);
console.log("ALL TESTS OK")
function bufferIs(b: Buffer, a: number[]) {
assert(b.length == a.length, "bis-len")
for (let i = 0; i < a.length; ++i) {
if (a[i] != b[i]) {
assert(false, `bufferIs: buf[${i}]:${b[i]} != ${a[i]}`)
}
}
}
function testBuffer() {
let b = pins.createBuffer(3);
assert(b[0] == 0, "buf0");
assert(b[1] == 0, "buf0");
assert(b[2] == 0, "buf0");
assert(b[-100000] == 0, "bufM");
assert(b[100000] == 0, "bufM");
b[0] = 42;
bufferIs(b, [42, 0, 0]);
b[2] = 41;
bufferIs(b, [42, 0, 41]);
b.rotate(1)
bufferIs(b, [0, 41, 42]);
b.rotate(-2)
bufferIs(b, [41, 42, 0]);
b.shift(1)
bufferIs(b, [42, 0, 0]);
b.rotate(9)
bufferIs(b, [42, 0, 0]);
b.rotate(-9)
bufferIs(b, [42, 0, 0]);
b.fill(4);
bufferIs(b, [4, 4, 4]);
b.fill(12, 1, 1);
bufferIs(b, [4, 12, 4]);
b.fill(13, 1, -1);
bufferIs(b, [4, 13, 13]);
b.fill(100, -1, -1);
bufferIs(b, [4, 13, 13]);
b.shift(-1)
bufferIs(b, [0, 4, 13]);
}

12
libs/lang-test1/pxt.json Normal file
View File

@ -0,0 +1,12 @@
{
"name": "lang-test1",
"description": "Test for the TypeScript -> HEX compiler; microbit specific parts",
"installedVersion": "file:.",
"files": [
"lang-test1.ts"
],
"public": true,
"dependencies": {
"microbit": "file:../microbit"
}
}

View File

@ -0,0 +1,15 @@
{
"bluetooth": "Support for additional Bluetooth services.",
"bluetooth.onBluetoothConnected": "Register code to run when the micro:bit is connected to over Bluetooth",
"bluetooth.onBluetoothConnected|param|body": "Code to run when a Bluetooth connection is established",
"bluetooth.onBluetoothDisconnected": "Register code to run when a bluetooth connection to the micro:bit is lost",
"bluetooth.onBluetoothDisconnected|param|body": "Code to run when a Bluetooth connection is lost",
"bluetooth.startAccelerometerService": "Starts the Bluetooth accelerometer service",
"bluetooth.startButtonService": "Starts the Bluetooth button service",
"bluetooth.startIOPinService": "Starts the Bluetooth IO pin service.",
"bluetooth.startLEDService": "Starts the Bluetooth LED service",
"bluetooth.startMagnetometerService": "Starts the Bluetooth magnetometer service",
"bluetooth.startTemperatureService": "Starts the Bluetooth temperature service",
"bluetooth.uartRead": "Reads from the Bluetooth UART service buffer, returning its contents when the specified delimiter character is encountered.",
"bluetooth.uartWrite": "Writes to the Bluetooth UART service buffer. From there the data is transmitted over Bluetooth to a connected device."
}

View File

@ -0,0 +1,13 @@
{
"bluetooth.onBluetoothConnected|block": "on bluetooth connected",
"bluetooth.onBluetoothDisconnected|block": "on bluetooth disconnected",
"bluetooth.startAccelerometerService|block": "bluetooth accelerometer service",
"bluetooth.startButtonService|block": "bluetooth button service",
"bluetooth.startIOPinService|block": "bluetooth io pin service",
"bluetooth.startLEDService|block": "bluetooth led service",
"bluetooth.startMagnetometerService|block": "bluetooth magnetometer service",
"bluetooth.startTemperatureService|block": "bluetooth temperature service",
"bluetooth.uartRead|block": "bluetooth uart read %del=bluetooth_uart_delimiter_conv",
"bluetooth.uartWrite|block": "bluetooth uart write %data",
"bluetooth|block": "bluetooth"
}

View File

@ -84,8 +84,8 @@ namespace bluetooth {
/**
* Starts the Bluetooth UART service
*/
// help=bluetooth/start-uart-service
// blockId=bluetooth_start_uart_service block="bluetooth uart service" blockGap=8
//% help=bluetooth/start-uart-service
//% blockId=bluetooth_start_uart_service block="bluetooth uart service" blockGap=8
void startUartService() {
if (uart) return;
// 61 octet buffer size is 3 x (MTU - 3) + 1

View File

@ -49,6 +49,13 @@ declare namespace bluetooth {
//% blockId=bluetooth_start_button_service block="bluetooth button service" blockGap=8 shim=bluetooth::startButtonService
function startButtonService(): void;
/**
* Starts the Bluetooth UART service
*/
//% help=bluetooth/start-uart-service
//% blockId=bluetooth_start_uart_service block="bluetooth uart service" blockGap=8 shim=bluetooth::startUartService
function startUartService(): void;
/**
* Writes to the Bluetooth UART service buffer. From there the data is transmitted over Bluetooth to a connected device.
*/

View File

@ -0,0 +1,18 @@
{
"devices": "Control a phone with the BBC micro:bit via Bluetooth.",
"devices.onGamepadButton": "Register code to run when the micro:bit receives a command from the paired gamepad.",
"devices.onGamepadButton|param|body": "code to run when button is pressed",
"devices.onGamepadButton|param|name": "button name",
"devices.onNotified": "Registers code to run when the device notifies about a particular event.",
"devices.onNotified|param|body": "code handler when event is triggered",
"devices.onNotified|param|event": "event description",
"devices.onSignalStrengthChanged": "Registers code to run when the device notifies about a change of signal strength.",
"devices.onSignalStrengthChanged|param|body": "Code run when the signal strength changes.",
"devices.raiseAlertTo": "Sends an ``alert`` command to the parent device.",
"devices.raiseAlertTo|param|event": "event description",
"devices.signalStrength": "Returns the last signal strength reported by the paired device.",
"devices.tellCameraTo": "Sends a ``camera`` command to the parent device.",
"devices.tellCameraTo|param|event": "event description",
"devices.tellRemoteControlTo": "Sends a ``remote control`` command to the parent device.",
"devices.tellRemoteControlTo|param|event": "event description"
}

Some files were not shown because too many files have changed in this diff Show More