merged changes

This commit is contained in:
Peli de Halleux 2016-03-30 16:42:44 -07:00
commit 5899647865
72 changed files with 847 additions and 507 deletions

View File

@ -57,12 +57,11 @@ Overview of lessons for the BBC micro:bit.
* [Hack your Headphones](/microbit/lessons/hack-your-headphones), create music on the BBC micro:bit by hacking your headphones * [Hack your Headphones](/microbit/lessons/hack-your-headphones), create music on the BBC micro:bit by hacking your headphones
* [Banana Keyboard](/microbit/lessons/banana-keyboard), create music with fruits * [Banana Keyboard](/microbit/lessons/banana-keyboard), create music with fruits
* [Telegraph](/microbit/lessons/telegraph), play the telegraph game between two BBC micro:bits * [Telegraph](/microbit/lessons/telegraph), play the telegraph game between two BBC micro:bits
* [Ornament Chain](/microbit/lessons/ornament-chain), play the ornament chain game between two BBC micro:bits
## Advanced ## Advanced
* [Hero](/microbit/lessons/hero), reconstruct the classic arcade game pac man with the BBC micro:bit * [Hero](/microbit/lessons/hero), reconstruct the classic arcade game pac man with the BBC micro:bit
* [Catch the Egg](/microbit/lessons/catch-the-egg-game), reconstruct the classic game of Catch the Egg with the BBC micro:bit
### ~ ### ~
### @section full ### @section full

View File

@ -10,14 +10,9 @@ Variables
## Quick Links ## Quick Links
* [tutorial](/microbit/lessons/catch-the-egg-game/tutorial) * [activity](/microbit/lessons/catch-the-egg-game/activity)
* [quiz](/microbit/lessons/catch-the-egg-game/quiz) * [quiz](/microbit/lessons/catch-the-egg-game/quiz)
* [quiz answers](/microbit/lessons/catch-the-egg-game/quiz-answers) * [quiz answers](/microbit/lessons/catch-the-egg-game/quiz-answers)
* [challenges](/microbit/lessons/catch-the-egg-game/challenges)
## Class
Year 7
## Prior learning/place of lesson in scheme of work ## Prior learning/place of lesson in scheme of work
@ -40,7 +35,7 @@ Learn how to create a catch the egg game game with **plot**, `led->plot` , **unp
## Objectives ## Objectives
* learn how to create a global variable as a place where you can store data so that you can use it later in your code, accessible across functions and in nested code blocks * learn how to create a variable as a place where you can store data so that you can use it later in your code, accessible across functions and in nested code blocks
* learn how to repeat code in the background forever * learn how to repeat code in the background forever
* learn how to turn off a LED light on the LED screen * learn how to turn off a LED light on the LED screen
* learn how to turn on a LED light on the LED screen * learn how to turn on a LED light on the LED screen
@ -52,40 +47,3 @@ Learn how to create a catch the egg game game with **plot**, `led->plot` , **unp
* learn how to return the modulus * learn how to return the modulus
* learn how to show a number of the BBC micro:bit screen * learn how to show a number of the BBC micro:bit screen
* learn how to pause your code for the specified number of milliseconds * learn how to pause your code for the specified number of milliseconds
## Progression Pathways / Computational Thinking Framework
#### Algorithms
* Designs solutions (algorithms) that use repetition and two-way selection, ie if, then and else.(AL)
* Uses logical reasoning to predict outputs, showing an awareness of inputs (AL)
* Recognises that different solutions exist for the same problem (AL) (AB) Understands that iteration is the repetition of a process such as a loop (AL)
* Represents solutions using a structured notation (AL) (AB)
#### Programming & Development
* Creates programs that implement algorithms to achieve given goals (AL)
* Declares and assigns variables(AB)
* Understands the difference between, and appropriately uses if and if, then and else statements(AL)
* Uses a variable and relational operators within a loop to govern termination (AL) (GE)
* Has practical experience of a high-level textual language, including using standard libraries when programming(AB) (AL)
* Uses a range of operators and expressions e.g. Boolean, and applies them in the context of program control. (AL)
* Selects the appropriate data types(AL) (AB
Computational Thinking Concept: AB = Abstraction; DE = Decomposition; AL = Algorithmic Thinking; EV = Evaluation; GE = Generalisation
## Activity
* time: 20 min.
* [tutorial](/microbit/lessons/catch-the-egg-game/tutorial)
* [quiz](/microbit/lessons/catch-the-egg-game/quiz)
## Extended Activity
* time: 20 min.
* [challenges](/microbit/lessons/catch-the-egg-game/challenges)
## Homework
* Extended Activity: [challenges](/microbit/lessons/catch-the-egg-game/challenges)

View File

@ -4,13 +4,9 @@ Coding challenges for catch the egg game.
## Before we get started ## Before we get started
Complete the following guided tutorial: Your starting code should look like this:
* [tutorial](/microbit/lessons/catch-the-egg-game/tutorial) ```blocks
At the end of the tutorial, click `keep editing`. Your code should look like this:
```
let basketX = 2 let basketX = 2
let eggX = 2 let eggX = 2
let eggY = 0 let eggY = 0
@ -20,7 +16,7 @@ basic.forever(() => {
eggY = eggY + 1 eggY = eggY + 1
led.plot(eggX, eggY) led.plot(eggX, eggY)
basic.pause(300) basic.pause(300)
let accX = input.acceleration("x") let accX = input.acceleration(Dimension.X)
basketX = 2 + Math.min(2, Math.max(-2, accX / 200)) basketX = 2 + Math.min(2, Math.max(-2, accX / 200))
led.plot(basketX, 4) led.plot(basketX, 4)
if (eggY > 4) { if (eggY > 4) {
@ -35,21 +31,13 @@ basic.forever(() => {
### Challenge 1 ### Challenge 1
Let's start by adding the **game** library.
### ~
### ~avatar avatar improvised
### Challenge 2
Let's use an **IF** statement to detect if the egg and the basket are lined up. Let's use an **IF** statement to detect if the egg and the basket are lined up.
Now that we know when an egg is caught, we can keep track of the score! We need to use the `add score` function built into the game library to add `1` point for every egg that is caught. However, let's not forget to `remove life` if an egg falls off the display before it's caught! Now that we know when an egg is caught, we can keep track of the score! We need to use the `add score` function built into the game library to add `1` point for every egg that is caught. However, let's not forget to `remove life` if an egg falls off the display before it's caught!
### ~ ### ~
``` ```blocks
let basketX1 = 2 let basketX1 = 2
let eggX1 = 2 let eggX1 = 2
let eggY1 = 0 let eggY1 = 0
@ -59,8 +47,8 @@ basic.forever(() => {
eggY1 = eggY1 + 1 eggY1 = eggY1 + 1
led.plot(eggX1, eggY1) led.plot(eggX1, eggY1)
basic.pause(300) basic.pause(300)
let accX1 = input.acceleration("x") let accX = input.acceleration(Dimension.X)
basketX1 = 2 + Math.min(2, Math.max(-2, accX1 / 200)) basketX1 = 2 + Math.min(2, Math.max(-2, accX / 200))
led.plot(basketX1, 4) led.plot(basketX1, 4)
if (eggY1 > 4) { if (eggY1 > 4) {
eggY1 = -1 eggY1 = -1
@ -81,13 +69,13 @@ basic.forever(() => {
### ~avatar avatar encourage ### ~avatar avatar encourage
### Challenge 3 ### Challenge 2
Catching eggs gets easier with practice so let's make the eggs fall faster every 5 catches. We can do this by tracking how long the egg pauses in each position while falling with a global variable called **falling pause**. Let's create this variable and set it to `300` initially. Don't forget to also create a condition that will be true every 5 catches. Catching eggs gets easier with practice so let's make the eggs fall faster every 5 catches. We can do this by tracking how long the egg pauses in each position while falling with a global variable called **falling pause**. Let's create this variable and set it to `300` initially. Don't forget to also create a condition that will be true every 5 catches.
### ~ ### ~
``` ```blocks
let basketX2 = 2 let basketX2 = 2
let eggX2 = 2 let eggX2 = 2
let eggY2 = 0 let eggY2 = 0
@ -98,7 +86,7 @@ basic.forever(() => {
eggY2 = eggY2 + 1 eggY2 = eggY2 + 1
led.plot(eggX2, eggY2) led.plot(eggX2, eggY2)
basic.pause(300) basic.pause(300)
let accX2 = input.acceleration("x") let accX2 = input.acceleration(Dimension.X)
basketX2 = 2 + Math.min(2, Math.max(-2, accX2 / 200)) basketX2 = 2 + Math.min(2, Math.max(-2, accX2 / 200))
led.plot(basketX2, 4) led.plot(basketX2, 4)
if (eggY2 > 4) { if (eggY2 > 4) {
@ -108,7 +96,7 @@ basic.forever(() => {
if (eggY2 == 4) { if (eggY2 == 4) {
if (basketX2 == eggX2) { if (basketX2 == eggX2) {
game.addScore(1) game.addScore(1)
if (math.mod(game.score(), 5) == 0) { if (game.score() %5 == 0) {
} }
} else { } else {
game.removeLife(1) game.removeLife(1)
@ -120,13 +108,13 @@ basic.forever(() => {
### ~avatar avatar surprised ### ~avatar avatar surprised
### Challenge 4 ### Challenge 3
### @video td/videos/catch-the-egg-game-4 ### @video td/videos/catch-the-egg-game-4
Let's make the egg fall faster by decreasing the amount of time it pauses in each position by decreasing **falling pause** by `25` every 5 catches. Now, instead of pausing for 300 milliseconds we can pause for the value of **falling pause**. Let's make the egg fall faster by decreasing the amount of time it pauses in each position by decreasing **falling pause** by `25` every 5 catches. Now, instead of pausing for 300 milliseconds we can pause for the value of **falling pause**.
``` ```blocks
let basketX3 = 2 let basketX3 = 2
let eggX3 = 2 let eggX3 = 2
let eggY3 = 0 let eggY3 = 0
@ -137,7 +125,7 @@ basic.forever(() => {
eggY3 = eggY3 + 1 eggY3 = eggY3 + 1
led.plot(eggX3, eggY3) led.plot(eggX3, eggY3)
basic.pause(300) basic.pause(300)
let accX3 = input.acceleration("x") let accX3 = input.acceleration(Dimension.X)
basketX3 = 2 + Math.min(2, Math.max(-2, accX3 / 200)) basketX3 = 2 + Math.min(2, Math.max(-2, accX3 / 200))
led.plot(basketX3, 4) led.plot(basketX3, 4)
if (eggY3 > 4) { if (eggY3 > 4) {
@ -147,7 +135,7 @@ basic.forever(() => {
if (eggY3 == 4) { if (eggY3 == 4) {
if (basketX3 == eggX3) { if (basketX3 == eggX3) {
game.addScore(1) game.addScore(1)
if (math.mod(game.score(), 5) == 0) { if (game.score()% 5 == 0) {
fallingPause1 = fallingPause1 - 25 // *** fallingPause1 = fallingPause1 - 25 // ***
} }
} else { } else {
@ -156,6 +144,7 @@ basic.forever(() => {
} }
basic.pause(fallingPause1) // *** basic.pause(fallingPause1) // ***
}) })
``` ```
Fantastic! Your game is now ready to show off. Fantastic! Your game is now ready to show off.

View File

@ -22,7 +22,10 @@ Answer the questions while completing the tutorial. Pay attention to the dialogu
<br/> <br/>
``` ```blocks
let basketX = 2
let eggX = 2
let eggY = 0
led.plot(eggX, eggY) led.plot(eggX, eggY)
led.plot(basketX, 4) led.plot(basketX, 4)
``` ```
@ -31,28 +34,22 @@ led.plot(basketX, 4)
<br/> <br/>
``` ```blocks
let basketX = 2
let eggX = 2
let eggY = 0
led.unplot(eggX, eggY) led.unplot(eggX, eggY)
eggY = eggY + 1 eggY = eggY + 1
led.plot(eggX, eggY) led.plot(eggX, eggY)
``` ```
## 4. Write the code that calculates 'basket x' given the variable 'acc x'. ## 4. . Write the code that resets the egg after it has fallen past the bottom of the BBC micro:bit.
<br/> <br/>
``` ```blocks
let accX = input.acceleration("x") let eggX = 2
basketX = 2 + Math.min(2, Math.max(-2, accX / 200)) let eggY = 0
```
Note: the first line of code in this answer is optional.
## 5. Write the code that resets the egg after it has fallen past the bottom of the BBC micro:bit.
<br/>
```
if (eggY > 4) { if (eggY > 4) {
eggY = -1 eggY = -1
eggX = Math.random(5) eggX = Math.random(5)

View File

@ -6,11 +6,11 @@ Programming a game of catch the egg using the accelerometer.
## Directions ## Directions
Use this activity document to guide your work in the [catch the egg tutorial](/microbit/lessons/catch-the-egg-game/tutorial) Use this activity document to guide your work in the [catch the egg challenges](/microbit/lessons/catch-the-egg-game/activity)
Answer the questions while completing the tutorial. Pay attention to the dialogues! Answer the questions while completing the tutorial. Pay attention to the dialogues!
## 1. Write the data type for the global variables 'basket' and 'egg'. ## 1. Write the data type for the variables 'basket' and 'egg'.
<br/> <br/>
@ -24,11 +24,7 @@ Answer the questions while completing the tutorial. Pay attention to the dialogu
<br/> <br/>
## 4. Write the code that calculates 'basket x' given the variable 'acc x'. ## 4. Write the code that resets the egg after it has fallen past the bottom of the BBC micro:bit.
<br/>
## 5. Write the code that resets the egg after it has fallen past the bottom of the BBC micro:bit.
<br/> <br/>

View File

@ -11,9 +11,7 @@ Music
* [activity](/microbit/lessons/classic-beatbox/activity) * [activity](/microbit/lessons/classic-beatbox/activity)
* [challenges](/microbit/lessons/classic-beatbox/challenges) * [challenges](/microbit/lessons/classic-beatbox/challenges)
## Class
Year 7
## Prior learning/place of lesson in scheme of work ## Prior learning/place of lesson in scheme of work
@ -23,40 +21,3 @@ Learn how to make a beatbox music player using pins P1 and P2. We will be learni
* learn how to code music on the BBC micro:bit * learn how to code music on the BBC micro:bit
## Progression Pathways / Computational Thinking Framework
#### Algorithms
* Uses diagrams to express solutions.(AB)
* Represents solutions using a structured notation (AL) (AB)
#### Programming & Development
* Creates programs that implement algorithms to achieve given goals (AL)
* Selects the appropriate data types(AL) (AB
#### Communication Networks
* Demonstrates responsible use of technologies and online services, and knows a range of ways to report concerns Understands how search engines rank search results (AL)
#### Information Technology
* Collects, organizes, and presents data and information in digital content (AB)
* Makes appropriate improvements to solutions based on feedback received, and can comment on the success of the solution (EV)
Computational Thinking Concept: AB = Abstraction; DE = Decomposition; AL = Algorithmic Thinking; EV = Evaluation; GE = Generalisation
## Activity
* time: 20 min.
* [activity](/microbit/lessons/classic-beatbox/activity)
## Extended Activity
* time: 20 min.
* [challenges](/microbit/lessons/classic-beatbox/challenges)
## Homework
* Extended Activity: [challenges](/microbit/lessons/classic-beatbox/challenges)

View File

@ -12,7 +12,8 @@ If (Conditionals)
* [activity](/microbit/lessons/compass/activity) * [activity](/microbit/lessons/compass/activity)
* [challenges](/microbit/lessons/compass/challenges) * [challenges](/microbit/lessons/compass/challenges)
* [quiz](/microbit/lessons/compass/quiz)
* [quiz answers](/microbit/lessons/compass/quiz-answers)
## Prior learning/place of lesson in scheme of work ## Prior learning/place of lesson in scheme of work

View File

@ -41,7 +41,7 @@ If `degrees` is less than 135, the micro:bit is mostly pointing East. Display `E
```blocks ```blocks
let degrees = null; let degrees = 0;
basic.forever(() => { basic.forever(() => {
degrees = input.compassHeading(); degrees = input.compassHeading();
if (degrees < 45) { if (degrees < 45) {
@ -57,7 +57,7 @@ If `degrees` is less than 225, the micro:bit is mostly pointing South. Display `
```blocks ```blocks
let degrees = null; let degrees = 0;
basic.forever(() => { basic.forever(() => {
degrees = input.compassHeading(); degrees = input.compassHeading();
if (degrees < 45) { if (degrees < 45) {
@ -76,7 +76,7 @@ basic.forever(() => {
If none of these conditions returned true, then the micro:bit must be pointing West. Display `W` on the micro:bit. If none of these conditions returned true, then the micro:bit must be pointing West. Display `W` on the micro:bit.
```blocks ```blocks
let degrees = null; let degrees = 0;
basic.forever(() => { basic.forever(() => {
degrees = input.compassHeading(); degrees = input.compassHeading();
if (degrees < 45) { if (degrees < 45) {

View File

@ -7,7 +7,7 @@ Display the direction that the micro:bit is facing using the compass
Complete the following [guided tutorial](/microbit/lessons/compass/activity), your code should look like this: Complete the following [guided tutorial](/microbit/lessons/compass/activity), your code should look like this:
```blocks ```blocks
let degrees = null; let degrees = 0;
basic.forever(() => { basic.forever(() => {
degrees = input.compassHeading(); degrees = input.compassHeading();
if (degrees < 45) { if (degrees < 45) {
@ -30,7 +30,7 @@ basic.forever(() => {
Instead of displaying `N` when the BBC micro:bit is pointing North, display a star to indicate the north star. Instead of displaying `N` when the BBC micro:bit is pointing North, display a star to indicate the north star.
```blocks ```blocks
let degrees = null; let degrees = 0;
basic.forever(() => { basic.forever(() => {
degrees = input.compassHeading(); degrees = input.compassHeading();
if (degrees < 45) { if (degrees < 45) {
@ -61,7 +61,7 @@ basic.forever(() => {
Instead of displaying just `N`, `W`, `S`, or `E`, display the full word. Instead of displaying just `N`, `W`, `S`, or `E`, display the full word.
```blocks ```blocks
let degrees = null; let degrees = 0;
basic.forever(() => { basic.forever(() => {
degrees = input.compassHeading(); degrees = input.compassHeading();
if (degrees < 45) { if (degrees < 45) {

View File

@ -26,6 +26,7 @@ let degrees = input.compassHeading()
```blocks ```blocks
let degrees = input.compassHeading()
if (degrees < 45) { if (degrees < 45) {
basic.showString("N", 150) basic.showString("N", 150)
} }
@ -35,6 +36,7 @@ if (degrees < 45) {
```blocks ```blocks
let degrees = input.compassHeading()
if (degrees < 135) { if (degrees < 135) {
basic.showString("E", 150) basic.showString("E", 150)
} }
@ -44,6 +46,7 @@ if (degrees < 135) {
```blocks ```blocks
let degrees = input.compassHeading()
if (degrees < 225) { if (degrees < 225) {
basic.showString("S", 150) basic.showString("S", 150)
} }

View File

@ -12,6 +12,8 @@ Variables
* [activity](/microbit/lessons/counter/activity) * [activity](/microbit/lessons/counter/activity)
* [challenges](/microbit/lessons/counter/challenges) * [challenges](/microbit/lessons/counter/challenges)
* [quiz](/microbit/lessons/counter/quiz)
* [quiz answers](/microbit/lessons/counter/quiz-answers)
## Prior learning/place of lesson in scheme of work ## Prior learning/place of lesson in scheme of work

View File

@ -27,10 +27,10 @@ let count = 0
## 3. Draw which LEDs are ON after running this code and pressing button "A" once. Explain you chose to draw that number ## 3. Draw which LEDs are ON after running this code and pressing button "A" once. Explain you chose to draw that number
```blocks ```blocks
let count_ = 0 let counts = 0
input.onButtonPressed(Button.A, () => { input.onButtonPressed(Button.A, () => {
count_ = count_ + 1 counts = counts + 1
basic.showNumber(count_, 100) basic.showNumber(counts, 150)
}) })
``` ```
@ -41,10 +41,10 @@ input.onButtonPressed(Button.A, () => {
## 4. Draw which LEDs are ON after running this code and pressing button "A" three times. Explain you chose to draw that number ## 4. Draw which LEDs are ON after running this code and pressing button "A" three times. Explain you chose to draw that number
```blocks ```blocks
count_ = 0 let counting= 0
input.onButtonPressed(Button.A, () => { input.onButtonPressed(Button.A, () => {
count_ = count_ + 1 counting = counting + 1
basic.showNumber(count_, 100) basic.showNumber(counting, 100)
}) })
``` ```

View File

@ -12,7 +12,8 @@ If (Conditionals)
* [activity](/microbit/lessons/die-roll/activity) * [activity](/microbit/lessons/die-roll/activity)
* [challenges](/microbit/lessons/die-roll/challenges) * [challenges](/microbit/lessons/die-roll/challenges)
* [quiz](/microbit/lessons/die-roll/quiz)
* [quiz answers](/microbit/lessons/die-roll/quiz-answers)
## Prior learning/place of lesson in scheme of work ## Prior learning/place of lesson in scheme of work

View File

@ -6,7 +6,7 @@ Create a die when the BBC micro:bit is shaken
## Directions ## Directions
Use this activity document to guide your work in the [die roll tutorial](/microbit/lessons/die-roll/tutorial). Use this activity document to guide your work in the [die roll tutorial](/microbit/lessons/die-roll/activity).
Answer the questions while completing the tutorial. Pay attention to the dialogues! Answer the questions while completing the tutorial. Pay attention to the dialogues!

View File

@ -12,6 +12,8 @@ While Loop
* [activity](/microbit/lessons/digi-yoyo/activity) * [activity](/microbit/lessons/digi-yoyo/activity)
* [challenges](/microbit/lessons/digi-yoyo/challenges) * [challenges](/microbit/lessons/digi-yoyo/challenges)
* [quiz](/microbit/lessons/digi-yoyo/quiz)
* [quiz answers](/microbit/lessons/digi-yoyo/quiz-answers)
## Prior learning/place of lesson in scheme of work ## Prior learning/place of lesson in scheme of work
@ -20,20 +22,12 @@ Learn how to creating a **while loop**, `while condition do` to repeat code whil
## Documentation ## Documentation
```docs ```docs
let x = 0 let x = 0
basic.showNumber(0) basic.showNumber(0)
while (true) { while (true) {
basic.pause(20) basic.pause(20)
} }
``` ```
## Objectives ## Objectives

View File

@ -18,7 +18,6 @@ let count = 0
Add a while loop that will loop over and over until the variable `count` equals 10. Add a while loop that will loop over and over until the variable `count` equals 10.
![](/static/mb/blocks/lessons/digi-yoyo-1.jpg)
```blocks ```blocks
let count = 0 let count = 0

View File

@ -69,5 +69,7 @@ Now, we need `count` to decrease by one after the micro:bit has displayed the va
We can do this by adding this line: We can do this by adding this line:
```blocks ```blocks
let count = count + (count - 1); let count = 0;
count = count + (count - 1);
``` ```

View File

@ -16,7 +16,7 @@ A loop that repeats code while a condition is true.
<br/> <br/>
``` ```blocks
let count = 0 let count = 0
``` ```
@ -26,7 +26,8 @@ let count = 0
<br/> <br/>
``` ```blocks
let count = 0
while (count < 5) { while (count < 5) {
count = count + 1 count = count + 1
} }

View File

@ -6,7 +6,7 @@ Create a counter with a while loop
## Directions ## Directions
Use this activity document to guide your work in the [digi yoyo tutorial](/microbit/lessons/digi-yoyo/tutorial) Use this activity document to guide your work in the [digi yoyo tutorial](/microbit/lessons/digi-yoyo/activity)
Answer the questions while completing the tutorial. Pay attention to the dialogues! Answer the questions while completing the tutorial. Pay attention to the dialogues!

View File

@ -10,10 +10,8 @@ Acceleration
* [activity](/microbit/lessons/glowing-pendulum/activity) * [activity](/microbit/lessons/glowing-pendulum/activity)
* [challenges](/microbit/lessons/glowing-pendulum/challenges) * [challenges](/microbit/lessons/glowing-pendulum/challenges)
* [quiz](/microbit/lessons/glowing-pendulum/quiz)
## Class * [quiz answers](/microbit/lessons/glowing-pendulum/quiz-answers)
Year 7
## Prior learning/place of lesson in scheme of work ## Prior learning/place of lesson in scheme of work

View File

@ -29,16 +29,19 @@ let acceleration = input.acceleration("y")
<br/> <br/>
```blocks ```blocks
let acceleration = math.abs(acceleration) let acceleration = input.acceleration(Dimension.X)
let accelerationAbsolute = Math.abs(acceleration)
``` ```
## 4. Write the code that uses the acceleration value from question #3 to set the brightness on the BBC micro:bit. ## 4. Write the code to use the acceleration value from question 3 to set the brightness on the BBC micro:bit.
<br/> <br/>
```blocks ```blocks
let acceleration = acceleration / 4 let accelerationX = input.acceleration(Dimension.X)
led.setBrightness(acceleration) let accelerationAbsolute = Math.abs(accelerationX)
let accelerationDivided = accelerationX / 4
led.setBrightness(accelerationX)
``` ```
## 5. Write the code that tuns all the LEDs on (as the image displays below) ## 5. Write the code that tuns all the LEDs on (as the image displays below)

View File

@ -6,7 +6,7 @@ construct a pendulum that glows using acceleration #LED #number #math #accelerat
## Directions ## Directions
Use this activity document to guide your work in the [glowing pendulum tutorial](/microbit/lessons/glowing-pendulum/tutorial) Use this activity document to guide your work in the [glowing pendulum tutorial](/microbit/lessons/glowing-pendulum/activity)
Answer the questions while completing the tutorial. Pay attention to the dialogues! Answer the questions while completing the tutorial. Pay attention to the dialogues!
@ -22,7 +22,7 @@ Answer the questions while completing the tutorial. Pay attention to the dialogu
<br/> <br/>
## 4. Write the code that uses the acceleration value from question #3 to set the brightness on the BBC micro:bit. ## 4. Write the code to include acceleration value question 3 to set the brightness on the BBC micro:bit.
<br/> <br/>

View File

@ -12,6 +12,8 @@ Math - Pick Random
* [activity](/microbit/lessons/guess-the-number/activity) * [activity](/microbit/lessons/guess-the-number/activity)
* [challenges](/microbit/lessons/guess-the-number/challenges) * [challenges](/microbit/lessons/guess-the-number/challenges)
* [quiz](/microbit/lessons/guess-the-number/quiz)
* [quiz answers](/microbit/lessons/guess-the-number/quiz-answers)
## Prior learning/place of lesson in scheme of work ## Prior learning/place of lesson in scheme of work

View File

@ -31,7 +31,7 @@ let randomNumber = Math.random(10)
If the rectangle below represents the BBC micro:bit, shade the areas that will be displayed. Explain why that particular area is shaded. If the rectangle below represents the BBC micro:bit, shade the areas that will be displayed. Explain why that particular area is shaded.
```blocks ```blocks
randomNumber = Math.random(10) let randomNumber = Math.random(10)
``` ```

View File

@ -6,7 +6,7 @@ Learn how to generate a random number on the micro:bit. #math #random #docs
## Directions ## Directions
Use this activity document to guide your work in the [guess the number tutorial](/microbit/lessons/guess-the-number/tutorial). Use this activity document to guide your work in the [guess the number tutorial](/microbit/lessons/guess-the-number/activity).
Answer the questions while completing the tutorial. Pay attention to the dialogues! Answer the questions while completing the tutorial. Pay attention to the dialogues!

View File

@ -10,10 +10,6 @@ Hack your headphone
* [activity](/microbit/lessons/hack-your-headphones/activity) * [activity](/microbit/lessons/hack-your-headphones/activity)
## Class
Year 7
## Prior learning/place of lesson in scheme of work ## Prior learning/place of lesson in scheme of work
Learn how to convert your BBC micro:bit into a music player using pins P0 and GND, headphones (or speakers), as well as crocodile clips (or spring clips). Learn how to convert your BBC micro:bit into a music player using pins P0 and GND, headphones (or speakers), as well as crocodile clips (or spring clips).

View File

@ -12,6 +12,9 @@ For Loop
* [activity](/microbit/lessons/looper/activity) * [activity](/microbit/lessons/looper/activity)
* [challenges](/microbit/lessons/looper/challenges) * [challenges](/microbit/lessons/looper/challenges)
* [quiz](/microbit/lessons/looper/quiz)
* [quiz answers](/microbit/lessons/looper/quiz-answers)
## Class ## Class

View File

@ -6,7 +6,7 @@ Learn how to create a series of numbers with a for loop. #LED #screen #plot #doc
## Directions ## Directions
Use this activity document to guide your work in the [looper tutorial](/microbit/lessons/looper/tutorial) Use this activity document to guide your work in the [looper tutorial](/microbit/lessons/looper/activity)
Answer the questions while completing the tutorial. Pay attention to the dialogues! Answer the questions while completing the tutorial. Pay attention to the dialogues!

View File

@ -10,6 +10,8 @@ If (Conditionals)
* [activity](/microbit/lessons/magic-8/activity) * [activity](/microbit/lessons/magic-8/activity)
* [challenges](/microbit/lessons/magic-8/challenges) * [challenges](/microbit/lessons/magic-8/challenges)
* [quiz](/microbit/lessons/magic-8/quiz)
* [quiz answers](/microbit/lessons/magic-8/quiz-answers)
## Prior learning/place of lesson in scheme of work ## Prior learning/place of lesson in scheme of work
@ -28,7 +30,6 @@ input.onGesture(Gesture.Shake, () => {
basic.showNumber(7) basic.showNumber(7)
basic.clearScreen() basic.clearScreen()
basic.showString("Hello!") basic.showString("Hello!")
``` ```
## Objectives ## Objectives

View File

@ -25,12 +25,13 @@ let x = Math.random(3)
## 3. Write the 'if statement' to check if ``x`` is equal to 2. Inside the 'if statement', display the string "Yes". ## 3. Write the 'if statement' to check if ``x`` is equal to 2. Inside the 'if statement', display the string "Yes".
```blocks ```blocks
let x = Math.random(3)
if (x == 2) { if (x == 2) {
basic.showString("Yes", 150) basic.showString("Yes", 150)
} }
``` ```
## 3. Write the 'if statement' to check if ``x`` is equal to 1. Inside the 'if statement', display the string "No." ## 4. Write the 'if statement' to check if ``x`` is equal to 1. Inside the 'if statement', display the string "No."
```blocks ```blocks
let x = Math.random(3) let x = Math.random(3)

View File

@ -6,7 +6,7 @@ create a magic 8 ball on the BBC micro:bit #math #random #docs
## Directions ## Directions
Use this activity document to guide your work in the [magic 8 tutorial](/microbit/lessons/magic-8/tutorial). Use this activity document to guide your work in the [magic 8 tutorial](/microbit/lessons/magic-8/activity).
Answer the questions while completing the tutorial. Pay attention to the dialogues! Answer the questions while completing the tutorial. Pay attention to the dialogues!
@ -22,7 +22,7 @@ Answer the questions while completing the tutorial. Pay attention to the dialogu
<br /> <br />
## 3. Write the 'if statement' to check if ``x`` is equal to 1. Inside the 'if statement', display the string "No." ## 4. Write the 'if statement' to check if ``x`` is equal to 1. Inside the 'if statement', display the string "No."
<br /> <br />

View File

@ -12,6 +12,8 @@ On Logo Up
* [activity](/microbit/lessons/magic-logo/activity) * [activity](/microbit/lessons/magic-logo/activity)
* [challenges](/microbit/lessons/magic-logo/challenges) * [challenges](/microbit/lessons/magic-logo/challenges)
* [quiz](/microbit/lessons/magic-logo/challenges)
* [quiz answers](/microbit/lessons/magic-logo/challenges)
## Prior learning/place of lesson in scheme of work ## Prior learning/place of lesson in scheme of work

View File

@ -22,7 +22,7 @@ When the micro:bit goes logo up, the code nested under the `on logo up` function
```blocks ```blocks
input.onLogoUp(() => { input.onLogoUp(() => {
basic.showAnimation(` basic.showLeds(`
. . # . . . . # . .
. # # # . . # # # .
# # # # # # # # # #
@ -31,6 +31,7 @@ input.onLogoUp(() => {
`) `)
}) })
``` ```
Run your code and try to turn around the micro:bit to see the **logo up** event in action! Run your code and try to turn around the micro:bit to see the **logo up** event in action!

View File

@ -8,7 +8,7 @@ Complete the [magic logo](/microbit/lessons/magic-logo/activity) activity and yo
```blocks ```blocks
input.onLogoUp(() => { input.onLogoUp(() => {
basic.showAnimation(` basic.showLeds(`
. . # . . . . # . .
. # # # . . # # # .
# # # # # # # # # #
@ -28,7 +28,7 @@ How about when the logo is down? We should display an arrow pointing downward!
```blocks ```blocks
input.onLogoUp(() => { input.onLogoUp(() => {
basic.showAnimation(` basic.showLeds(`
. . # . . . . # . .
. # # # . . # # # .
# # # # # # # # # #
@ -37,7 +37,7 @@ input.onLogoUp(() => {
`) `)
}) })
input.onLogoDown(() => { input.onLogoDown(() => {
basic.showAnimation(` basic.showLeds(`
. . # . . . . # . .
. . # . . . . # . .
# # # # # # # # # #

View File

@ -44,7 +44,7 @@ input.onLogoUp(() => {
```blocks ```blocks
input.onLogoDown(() => { input.onLogoDown(() => {
basic.plotImage(` basic.showLeds(`
. . # . . . . # . .
. . # . . . . # . .
# # # # # # # # # #

View File

@ -12,6 +12,8 @@ Set Brightness
* [activity](/microbit/lessons/night-light/activity) * [activity](/microbit/lessons/night-light/activity)
* [challenges](/microbit/lessons/night-light/challenges) * [challenges](/microbit/lessons/night-light/challenges)
* [quiz](/microbit/lessons/night-light/quiz)
* [quiz answers](/microbit/lessons/night-light/quiz-answers)
## Prior learning/place of lesson in scheme of work ## Prior learning/place of lesson in scheme of work

View File

@ -16,9 +16,15 @@ If the rectangle above represents the BBC micro:bit, write the code to set all t
<br /> <br />
``` ```blocks
led.setBrightness(255) led.setBrightness(255)
led.plotAll() basic.showLeds(`
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
`)
``` ```
## 3. Consider the following image ## 3. Consider the following image
@ -29,9 +35,15 @@ If the rectangle above represents the BBC micro:bit, write the code to set the s
<br/> <br/>
``` ```blocks
led.setBrightness(128) led.setBrightness(128)
led.plotAll() basic.showLeds(`
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
`)
``` ```
## 4. Consider the following image ## 4. Consider the following image
@ -40,7 +52,7 @@ led.plotAll()
If the rectangle above represents the BBC micro:bit, write the code to turn off all the LEDs. If the rectangle above represents the BBC micro:bit, write the code to turn off all the LEDs.
``` ```blocks
led.setBrightness(0) led.setBrightness(0)
``` ```

View File

@ -6,7 +6,7 @@ change the brightness of the BBC micro:bit #LED #image #brightness #fade #docs
## Directions ## Directions
Use this activity document to guide your work in the [night light tutorial](/microbit/lessons/night-light/tutorial) Use this activity document to guide your work in the [night light tutorial](/microbit/lessons/night-light/activity)
Answer the questions while completing the tutorial. Pay attention to the dialogues! Answer the questions while completing the tutorial. Pay attention to the dialogues!

View File

@ -4,16 +4,12 @@ display beautiful images on the BBC micro:bit #var #pause #docs
## Topic ## Topic
Telegraph Network devices
## Quick Links ## Quick Links
* [activity](/microbit/lessons/ornament-chain/activity) * [activity](/microbit/lessons/ornament-chain/activity)
## Class
Year 7
## Prior learning/place of lesson in scheme of work ## Prior learning/place of lesson in scheme of work
Learn how to convert your BBC micro:bit into a telegraph using a second BBC micro:bit as well as pin P1, P2, 3V, GND, and crocodile clips (or spring clips). The connect BBC micro:bit uses pins P1, P2, 3V, GND. Learn how to convert your BBC micro:bit into a telegraph using a second BBC micro:bit as well as pin P1, P2, 3V, GND, and crocodile clips (or spring clips). The connect BBC micro:bit uses pins P1, P2, 3V, GND.

View File

@ -6,7 +6,7 @@ shift an image horizontally across the display with offset #offset #screen #var
## Directions ## Directions
Use this activity document to guide your work in the [rock paper scissors tutorial](/microbit/lessons/rock-paper-scissors/tutorial). Use this activity document to guide your work in the [rock paper scissors tutorial](/microbit/lessons/rock-paper-scissors/activity).
Answer the questions while completing the tutorial. Pay attention to the dialogues! Answer the questions while completing the tutorial. Pay attention to the dialogues!

View File

@ -10,10 +10,8 @@ While Loop
* [activity](/microbit/lessons/rotation-animation/activity) * [activity](/microbit/lessons/rotation-animation/activity)
* [challenges](/microbit/lessons/rotation-animation/challenges) * [challenges](/microbit/lessons/rotation-animation/challenges)
* [quiz](/microbit/lessons/rotation-animation/quiz)
## Class * [quiz answers](/microbit/lessons/rotation-animation/quiz-answers)
Year 7
## Prior learning/place of lesson in scheme of work ## Prior learning/place of lesson in scheme of work
@ -38,17 +36,14 @@ while (true) {
basic.pause(20) basic.pause(20)
} }
``` ```
## Objectives ## Objectives
* learn how to create a global variable for a place where you can store data, accessible across functions, and in nested code blocks * learn how to create a variable for a place where you can store data, accessible across functions, and in nested code blocks
* learn how to set or change the value of a global variable * learn how to set or change the value of a variable
* learn how to repeat code while a condition is true * learn how to repeat code while a condition is true
* learn how to declare a global boolean variable to determine which code will execute next * learn how to declare a boolean variable to determine which code will execute next
* learn how to run code when an input button is pressed * learn how to run code when an input button is pressed
* learn how to show a series of image frames on the LED screen * learn how to show a series of image frames on the LED screen
* learn how to pause your code for the specified number of milliseconds * learn how to pause your code for the specified number of milliseconds

View File

@ -54,9 +54,6 @@ Now let's add to this by creating a condition for on button pressed `A` before t
```blocks ```blocks
let rotating = true; let rotating = true;
input.onButtonPressed(Button.A, () => {
serial.writeLine("hello")
})
while (rotating) { while (rotating) {
serial.writeLine("loop") serial.writeLine("loop")
basic.showLeds(` basic.showLeds(`
@ -88,8 +85,9 @@ while (rotating) {
. . . . . . . . . .
`) `)
} }
input.onButtonPressed(Button.A, () => {
serial.writeLine("hello")
})
``` ```
@ -101,10 +99,6 @@ Now that we have the on button pressed condition, let's make the animation stop
```blocks ```blocks
let rotating = true; let rotating = true;
input.onButtonPressed(Button.A, () => {
serial.writeLine("hello")
rotating = false
})
while (rotating) { while (rotating) {
serial.writeLine("loop") serial.writeLine("loop")
basic.showLeds(` basic.showLeds(`
@ -136,7 +130,10 @@ while (rotating) {
. . . . . . . . . .
`) `)
} }
input.onButtonPressed(Button.A, () => {
serial.writeLine("hello")
rotating = false
})
``` ```

View File

@ -4,44 +4,82 @@ Learn how to create a rotating image with a while loop. #image #loop #while #do
This is the answer key for the [rotation animation quiz](/microbit/lessons/rotation-animation/quiz). This is the answer key for the [rotation animation quiz](/microbit/lessons/rotation-animation/quiz).
## 1. What is a "global variable"? ## 1. What is a " variable"?
Answers may vary. A global variable is a place where you can store data so that you can use it later in your code. Answers may vary. A variable is a place where you can store data so that you can use it later in your code.
## 2. Consider the following directions ## 2. Write the code to create a ** variable** called `foo` that stores a boolean and initialize it to **false**.
Write the code to create a **global variable** called `foo` that stores a boolean and initialize it to **false**.
```
rotating = true ```blocks
let rotating = true;
``` ```
## 3. Consider the following code ## 3. Explain what this line of code does.
``` ```blocks
let rotating = true;
while (rotating) { while (rotating) {
basic.showLeds(`
. . . . .
. . . . .
. . # . .
. . . . .
. . . . .
`)
basic.showLeds(`
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
`)
} }
``` ```
Explain what this line of code does.
<br/> <br/>
It is a **while** loop that will be executed only if the **global variable** called `rotating` is **true**. It is a **while** loop that will be executed only if the ** variable** called `rotating` is **true**.
## 4. Consider the following code ## 4. If the rectangle below represents the BBC micro:bit, shade the areas that will be displayed. Explain why that particular area is shaded.
``` ```blocks
basic.showAnimation(` basic.showLeds(`
# . . . . . . # . . . . . . # . . . . . . . # . .
. # . . . . . # . . . . . # . . . . . . . . # . .
. . # . . . . # . . . . # . . # # # # # . . # . .
. . . # . . . # . . . # . . . . . . . . . . # . .
. . . . # . . # . . # . . . . . . . . . . . # . .
`, 400) `)
basic.showLeds(`
. . . . .
. . . . .
# # # # #
. . . . .
. . . . .
`)
basic.showLeds(`
. . . . #
. . . # .
. . # . .
. # . . .
# . . . .
`)
basic.showLeds(`
. . . . #
. . . # .
. . # . .
. # . . .
# . . . .
`)
``` ```
If the rectangle below represents the BBC micro:bit, shade the areas that will be displayed. Explain why that particular area is shaded.
![](/static/mb/lessons/rotation-animation-0.png) ![](/static/mb/lessons/rotation-animation-0.png)

View File

@ -6,37 +6,75 @@ Learn how to create a rotating image with a while loop. #image #loop #while #do
## Directions ## Directions
Use this activity document to guide your work in the [rotation animation tutorial](/microbit/lessons/rotation-animation/tutorial). Use this activity document to guide your work in the [rotation animation tutorial](/microbit/lessons/rotation-animation/activity).
Answer the questions while completing the tutorial. Pay attention to the dialogues! Answer the questions while completing the tutorial. Pay attention to the dialogues!
## 1. What is a "global variable"? ## 1. What is a " variable"?
<br /> <br />
## 2. Write the code to create a global variable called foo that stores a boolean and initialize it to false. ## 2. Write the code to create a variable called foo that stores a boolean and initialize it to false.
<br/> <br/>
## 3. Explain why you use a while loop with a global variable ## 3. Explain why you use a while loop with a variable
``` ```blocks
let rotating = true;
while (rotating) { while (rotating) {
basic.showLeds(`
. . . . .
. . . . .
. . # . .
. . . . .
. . . . .
`)
basic.showLeds(`
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
`)
} }
``` ```
<br/> <br/>
## 4. Draw the areas on the micro:bits to illustrate the code below. Explain why you chose to draw in those areas. ## 4. Draw the areas on the micro:bits to illustrate the code below. Explain why you chose to draw in those areas.
``` ```blocks
basic.showAnimation(` basic.showLeds(`
# . . . . . . # . . . . . . # . . . . . . . # . .
. # . . . . . # . . . . . # . . . . . . . . # . .
. . # . . . . # . . . . # . . # # # # # . . # . .
. . . # . . . # . . . # . . . . . . . . . . # . .
. . . . # . . # . . # . . . . . . . . . . . # . .
`, 400) `)
basic.showLeds(`
. . . . .
. . . . .
# # # # #
. . . . .
. . . . .
`)
basic.showLeds(`
. . . . #
. . . # .
. . # . .
. # . . .
# . . . .
`)
basic.showLeds(`
. . . . #
. . . # .
. . # . .
. # . . .
# . . . .
`)
``` ```
![](/static/mb/lessons/looper-2.png) ![](/static/mb/lessons/looper-2.png)

View File

@ -13,14 +13,14 @@ Welcome! This tutorial will help you make a smiley face blink. Let's get started
Create an animation with an image displaying a smiley face and the next image with no LEDs lit up. This will make it look like the smiley face is blinking as the display switches between images. Create an animation with an image displaying a smiley face and the next image with no LEDs lit up. This will make it look like the smiley face is blinking as the display switches between images.
```blocks ```blocks
basic.showAnimation(` basic.showLeds(`
. # . # . . # . # .
. # . # . . # . # .
. . . . . . . . . .
# . . . # # . . . #
. # # # . . # # # .
`) `)
basic.showAnimation(` basic.showLeds(`
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .

View File

@ -8,14 +8,14 @@ Complete the [smiley activity](/microbit/lessons/smiley/activity) and your code
```blocks ```blocks
basic.showAnimation(` basic.showLeds(`
. # . # . . # . # .
. # . # . . # . # .
. . . . . . . . . .
# . . . # # . . . #
. # # # . . # # # .
`) `)
basic.showAnimation(` basic.showLeds(`
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
@ -33,14 +33,14 @@ Let's make add code that will run when button A is pressed!
```blocks ```blocks
basic.showAnimation(` basic.showLeds(`
. # . # . . # . # .
. # . # . . # . # .
. . . . . . . . . .
# . . . # # . . . #
. # # # . . # # # .
`) `)
basic.showAnimation(` basic.showLeds(`
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
@ -59,14 +59,14 @@ input.onButtonPressed(Button.A, () => {
Now, we want to show a frowny face when this button is pressed. Let's show the LEDs. Now, we want to show a frowny face when this button is pressed. Let's show the LEDs.
```blocks ```blocks
basic.showAnimation(` basic.showLeds(`
. # . # . . # . # .
. # . # . . # . # .
. . . . . . . . . .
# . . . # # . . . #
. # # # . . # # # .
`) `)
basic.showAnimation(` basic.showLeds(`
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
@ -74,7 +74,7 @@ basic.showAnimation(`
. . . . . . . . . .
`) `)
input.onButtonPressed(Button.A, () => { input.onButtonPressed(Button.A, () => {
basic.showAnimation(` basic.showLeds(`
. # . # . . # . # .
. # . # . . # . # .
. . . . . . . . . .

View File

@ -51,7 +51,7 @@ basic.forever(() => {
. . # . . . . # . .
`) `)
}) })
```blocks ```
Run your code in the simulator or download it to your BBC micro:bit to see what happens! Run your code in the simulator or download it to your BBC micro:bit to see what happens!

View File

@ -6,25 +6,59 @@ Coding challenges for snowflake fall.
Complete the [snowflake fall](/microbit/lessons/snowflake-fall/activity) activity and your code will look like this: Complete the [snowflake fall](/microbit/lessons/snowflake-fall/activity) activity and your code will look like this:
![](/static/mb/blocks/lessons/snowflake-fall-1.jpg) ```blocks
basic.forever(() => {
basic.showLeds(`
. . . . .
. . # . .
. # # # .
. . # . .
. . . . .
`)
basic.showLeds(`
. . # . .
. # . # .
# . . . #
. # . # .
. . # . .
`)
})
```
### Challenge 1 ### Challenge 1
### @video td/videos/snowflake-fall-1 ### @video td/videos/snowflake-fall-1
Let's begin creating our falling effect by adding another snowflake with `show LEDs` that displays a different snowflake pattern after the first one. We need 2 frames in the new animation that display both the first and the second snowflake images.
![](/static/mb/blocks/lessons/snowflake-fall-2.jpg)
* Run your program to see the cool animation.
### Challenge 2
### @video td/videos/snowflake-fall-2
To finalize our snowflake fall, let's add a different snowflake pattern. To finalize our snowflake fall, let's add a different snowflake pattern.
![](/static/mb/blocks/lessons/snowflake-fall-3.jpg) ```blocks
basic.forever(() => {
basic.showLeds(`
. . . . .
. . # . .
. # # # .
. . # . .
. . . . .
`)
basic.showLeds(`
. . # . .
. # . # .
# . . . #
. # . # .
. . # . .
`)
basic.showLeds(`
. # . # .
# # # # #
. # . # .
# # # # #
. # . # .
`)
})
```
* Run your program and see if it works. * Run your program and see if it works.

View File

@ -28,7 +28,24 @@ basic.forever(() => {
![](/static/mb/lessons/snowflake-fall-0.png) ![](/static/mb/lessons/snowflake-fall-0.png)
![](/static/mb/blocks/lessons/snowflake-fall-5.png) ```blocks
basic.forever(() => {
basic.showLeds(`
. . . . .
. . # . .
. # # # .
. . # . .
. . . . .
`);
basic.showLeds(`
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
`)
});
```
## 4. Write the code for a forever loop and show LEDS for these images! ## 4. Write the code for a forever loop and show LEDS for these images!
@ -36,5 +53,21 @@ basic.forever(() => {
![](/static/mb/lessons/snowflake-fall-2.png) ![](/static/mb/lessons/snowflake-fall-2.png)
![](/static/mb/blocks/lessons/snowflake-fall-6.png) ```blocks
basic.forever(() => {
basic.showLeds(`
. . . . .
. . # . .
. # # # .
. . # . .
. . . . .
`);
basic.showLeds(`
# # # # #
# # . # #
# . # . #
# # . # #
# # # # #
`)
});
```

View File

@ -12,6 +12,8 @@ If (Conditionals)
* [activity](/microbit/lessons/spinner/activity) * [activity](/microbit/lessons/spinner/activity)
* [challenges](/microbit/lessons/spinner/challenges) * [challenges](/microbit/lessons/spinner/challenges)
* [quiz](/microbit/lessons/spinner/quiz)
* [quiz answers](/microbit/lessons/spinner/quiz-answers)
## Prior learning/place of lesson in scheme of work ## Prior learning/place of lesson in scheme of work

View File

@ -12,19 +12,95 @@ Welcome! This guided tutorial will teach how to program a script that randomly p
Let's begin by adding an `on shake` condition to know when the micro:bit is shaken. Let's begin by adding an `on shake` condition to know when the micro:bit is shaken.
![](/static/mb/blocks/lessons/spinner-0.jpg) ```blocks
input.onGesture(Gesture.Shake, () => {
})
```
Now let's randomly generate a number from 0 to 3 so that we can randomly display an arrow in a given direction. Now let's randomly generate a number from 0 to 3 so that we can randomly display an arrow in a given direction.
![](/static/mb/blocks/lessons/spinner-1.jpg) ```blocks
input.onGesture(Gesture.Shake, () => {
let randomArrow = Math.random(4)
if (randomArrow = 3) {
basic.showLeds(`
. . # . .
. # # # .
# # # # #
. . # . .
. . # . .
`)
}
})
```
Now let's handle each of the cases by displaying the appropriate arrow. (Let's display an up arrow if `random arrow` is 0. Now let's handle each of the cases by displaying the appropriate arrow. (Let's display an up arrow if `random arrow` is 0.
![](/static/mb/blocks/lessons/spinner-2.jpg) ```blocks
input.onGesture(Gesture.Shake, () => {
let randomArrow = Math.random(4)
if (randomArrow = 3) {
basic.showLeds(`
. . # . .
. # # # .
# # # # #
. . # . .
. . # . .
`)
}
if (randomArrow = 2) {
basic.showLeds(`
. . # . .
. . # . .
# # # # #
. # # # .
. . # . .
`)
}
})
```
Now let's handle the rest of the cases for `random arrow`. Now let's handle the rest of the cases for `random arrow`.
![](/static/mb/blocks/lessons/spinner-3.jpg)
```blocks
input.onGesture(Gesture.Shake, () => {
let randomArrow = Math.random(4)
if (randomArrow = 3) {
basic.showLeds(`
. . # . .
. # # # .
# # # # #
. . # . .
. . # . .
`)
}
if (randomArrow = 2) {
basic.showLeds(`
. . # . .
. . # . .
# # # # #
. # # # .
. . # . .
`)
}
if (randomArrow = 1) {
basic.showLeds(`
. . # . .
. # # . .
# # # # #
. # # . .
. . # . .
`)
}
})
```
### ~avatar avatar ### ~avatar avatar

View File

@ -6,21 +6,164 @@ Create an arrow that randomly points to a player.
Complete the following [guided tutorial](/microbit/lessons/spinner/activity), your code should look like this: Complete the following [guided tutorial](/microbit/lessons/spinner/activity), your code should look like this:
![](/static/mb/blocks/lessons/spinner-3.jpg) ```blocks
input.onGesture(Gesture.Shake, () => {
let randomArrow = Math.random(4)
if (randomArrow = 3) {
basic.showLeds(`
. . # . .
. # # # .
# # # # #
. . # . .
. . # . .
`)
}
if (randomArrow = 2) {
basic.showLeds(`
. . # . .
. . # . .
# # # # #
. # # # .
. . # . .
`)
}
if (randomArrow = 1) {
basic.showLeds(`
. . # . .
. # # . .
# # # # #
. # # . .
. . # . .
`)
}
})
```
### Challenge 1 ### Challenge 1
Modify the random number generator so that it can include new arrows we will create in the next challenge. Modify the random number generator so that it can include new arrows we will create in the next challenge.
![](/static/mb/blocks/lessons/spinner-4.jpg) ```blocks
input.onGesture(Gesture.Shake, () => {
let randomArrow = Math.random(8)
if (randomArrow = 3) {
basic.showLeds(`
. . # . .
. # # # .
# # # # #
. . # . .
. . # . .
`)
}
if (randomArrow = 2) {
basic.showLeds(`
. . # . .
. . # . .
# # # # #
. # # # .
. . # . .
`)
}
if (randomArrow = 1) {
basic.showLeds(`
. . # . .
. # # . .
# # # # #
. # # . .
. . # . .
`)
}
})
```
* Do **not** run the code yet because it will not work until you have conditions for every random number. * Do **not** run the code yet because it will not work until you have conditions for every random number.
### Challenge 2 ### Challenge 2
Let's add four more arrows that point diagonally. Let's add more arrows that point diagonally.
```blocks
input.onGesture(Gesture.Shake, () => {
let randomArrow = Math.random(8)
if (randomArrow = 7) {
basic.showLeds(`
. . # . .
. # # # .
# # # # #
. . # . .
. . # . .
`)
}
if (randomArrow = 6) {
basic.showLeds(`
. . # . .
. . # . .
# # # # #
. # # # .
. . # . .
`)
}
if (randomArrow = 5) {
basic.showLeds(`
. . # . .
. # # . .
# # # # #
. # # . .
. . # . .
`)
}
if (randomArrow = 4) {
basic.showLeds(`
. . # . .
. . . # .
# # # # #
. . . # .
. . # . .
`)
}
if (randomArrow = 3) {
basic.showLeds(`
# # # # #
# # # # .
# # # # .
# . . # .
. . . . #
`)
}
if (randomArrow = 2) {
basic.showLeds(`
# # # # #
# # # # #
. . # # #
. # . # #
# . . . #
`)
}
if (randomArrow = 1) {
basic.showLeds(`
# . . . #
# # . # .
# # # . .
# # # # .
# # # # #
`)
}
})
```
![](/static/mb/blocks/lessons/spinner-5.jpg)
* Run your code to see if it works as expected * Run your code to see if it works as expected

View File

@ -6,7 +6,7 @@ a spin the BBC micro:bit game with the input on shake #math #random #docs #shake
## Directions ## Directions
Use this activity document to guide your work in the [spinner tutorial](/microbit/lessons/spinner/tutorial). Use this activity document to guide your work in the [spinner tutorial](/microbit/lessons/spinner/activity).
Answer the questions while completing the tutorial. Pay attention to the dialogues! Answer the questions while completing the tutorial. Pay attention to the dialogues!

View File

@ -12,6 +12,8 @@ For Loop
* [activity](/microbit/lessons/strobe-light/activity) * [activity](/microbit/lessons/strobe-light/activity)
* [challenges](/microbit/lessons/strobe-light/challenges) * [challenges](/microbit/lessons/strobe-light/challenges)
* [quiz](/microbit/lessons/strobe-light/quiz)
* [quiz answers](/microbit/lessons/strobe-light/quiz-answers)
## Documentation ## Documentation

View File

@ -45,7 +45,14 @@ for (let i = 0; i < 5; i++) {
The pause will add a delay between lighting each LED. The pause will add a delay between lighting each LED.
![](/static/mb/blocks/lessons/strobe-light-3.jpg) ```blocks
for (let i = 0; i < 5; i++) {
for (let j = 0; j < 5; j++) {
led.plot(i, j)
basic.pause(200)
}
}
```
### ~avatar avatar ### ~avatar avatar

View File

@ -6,7 +6,7 @@ Learn how to create a blinking LED script with a for loop. #LED #screen #plot #d
## Directions ## Directions
Use this activity document to guide your work in the [strobe light tutorial](/microbit/lessons/strobe-light/tutorial) Use this activity document to guide your work in the [strobe light tutorial](/microbit/lessons/strobe-light/activity)
Answer the questions while completing the tutorial. Pay attention to the dialogues! Answer the questions while completing the tutorial. Pay attention to the dialogues!

View File

@ -10,10 +10,6 @@ Telegraph
* [activity](/microbit/lessons/telegraph/activity) * [activity](/microbit/lessons/telegraph/activity)
## Class
Year 7
## Prior learning/place of lesson in scheme of work ## Prior learning/place of lesson in scheme of work
Learn how to convert your BBC micro:bit into a telegraph using a second BBC micro:bit as well as pin P1, P2, 3V, GND, and crocodile clips (or spring clips). The connect BBC micro:bit uses pins P1, P2, 3V, GND. Learn how to convert your BBC micro:bit into a telegraph using a second BBC micro:bit as well as pin P1, P2, 3V, GND, and crocodile clips (or spring clips). The connect BBC micro:bit uses pins P1, P2, 3V, GND.

View File

@ -12,6 +12,8 @@ If (Conditionals)
* [activity](/microbit/lessons/truth-or-dare/activity) * [activity](/microbit/lessons/truth-or-dare/activity)
* [challenges](/microbit/lessons/truth-or-dare/challenges) * [challenges](/microbit/lessons/truth-or-dare/challenges)
* [quiz](/microbit/lessons/truth-or-dare/quiz)
* [quiz answers](/microbit/lessons/truth-or-dare/quiz-answers)
## Prior learning/place of lesson in scheme of work ## Prior learning/place of lesson in scheme of work

View File

@ -6,7 +6,7 @@ a multi-player game that forces each player to reveal a secret or something funn
## Directions ## Directions
Use this activity document to guide your work in the [truth or dare tutorial](/microbit/lessons/truth-or-dare/tutorial). Use this activity document to guide your work in the [truth or dare tutorial](/microbit/lessons/truth-or-dare/activity).
Answer the questions while completing the tutorial. Pay attention to the dialogues! Answer the questions while completing the tutorial. Pay attention to the dialogues!

View File

@ -12,6 +12,8 @@ Acceleration
* [activity](/microbit/lessons/zoomer/activity) * [activity](/microbit/lessons/zoomer/activity)
* [challenges](/microbit/lessons/zoomer/challenges) * [challenges](/microbit/lessons/zoomer/challenges)
* [quiz](/microbit/lessons/zoomer/quiz)
* [quiz answers](/microbit/lessons/zoomer/quiz-answers)
## Prior learning/place of lesson in scheme of work ## Prior learning/place of lesson in scheme of work
@ -21,12 +23,10 @@ Learn how to get the **acceleration**, `acceleration` in one of three specified
```docs ```docs
basic.forever(() => { basic.forever(() => {
}) })
let x = 0 let x = 0
input.acceleration(Dimension.X) input.acceleration(Dimension.X)
if (true) { if (true) {
} }
input.buttonIsPressed(Button.A) input.buttonIsPressed(Button.A)
basic.showNumber(0) basic.showNumber(0)

View File

@ -14,7 +14,7 @@ Write the line of code to measure the acceleration and then store in it a variab
<br/> <br/>
``` ```blocks
let accX_ = input.acceleration("x") let accX_ = input.acceleration("x")
``` ```
@ -26,9 +26,9 @@ After storing the acceleration in a variable, write the code to show acceleratio
<br/> <br/>
``` ```blocks
let accX = input.acceleration("x") let accX = input.acceleration("x")
basic.showNumber(accX_, 150) basic.showNumber(accX, 150)
``` ```
Note: make sure the same variable name ("acc x" in this case) is the same in both lines of code.. Note: make sure the same variable name ("acc x" in this case) is the same in both lines of code..

View File

@ -6,7 +6,7 @@ Measure the acceleration on the micro:bit in the "z" direction #LED #number #mat
## Directions ## Directions
Use this activity document to guide your work in the [zoomer tutorial](/microbit/lessons/zoomer/tutorial) Use this activity document to guide your work in the [zoomer tutorial](/microbit/lessons/zoomer/activity)
Answer the questions while completing the tutorial. Pay attention to the dialogues! Answer the questions while completing the tutorial. Pay attention to the dialogues!

View File

@ -1,8 +0,0 @@
# catch the egg
Programming a game of 'catch the egg' using the accelerometer in Touch Develop #docs #functions #var
Programming a game of 'catch the egg' using the accelerometer
* [tutorial](/microbit/lessons/catch-the-egg-game/tutorial)
* [challenges](/microbit/lessons/catch-the-egg/challenges)

View File

@ -1,7 +1,3 @@
//% shim=foo::bar
function test() {
}
basic.plotLeds(` basic.plotLeds(`
# # . # # # # . # #
. . # . . . . # . .
@ -10,4 +6,5 @@ basic.plotLeds(`
. # # # . . # # # .
`); `);
basic.pause(300); basic.pause(300);
test(); basic.showString("Hello");
// foo.bar();

View File

@ -1,6 +1,10 @@
#include "BitVM.h"
#include "MicroBitTouchDevelop.h"
namespace foo { namespace foo {
GLUE void bar() //%
void bar()
{ {
micro_bit::scrollNumber(108108, 50); touch_develop::micro_bit::scrollNumber(108108, 50);
} }
} }

View File

@ -6,6 +6,6 @@
], ],
"public": true, "public": true,
"dependencies": { "dependencies": {
"core": "file:../microbit" "microbit": "file:../microbit"
} }
} }

View File

@ -1,3 +1,6 @@
#include "BitVM.h"
/** /**
* Provides access to basic micro:bit functionality. * Provides access to basic micro:bit functionality.
*/ */
@ -10,10 +13,19 @@ namespace basic {
*/ */
//% help=basic/show-number //% help=basic/show-number
//% weight=96 //% weight=96
//% shim=micro_bit::scrollNumber
//% blockId=device_show_number block="show|number %number" blockGap=8 icon="\uf1ec" //% blockId=device_show_number block="show|number %number" blockGap=8 icon="\uf1ec"
//% async //% async
export function showNumber(value: number, interval: number = 150): void { } void showNumber(int value, int interval = 150) {
if (interval < 0)
return;
ManagedString t(value);
if (value < 0 || value >= 10) {
uBit.display.scroll(t, interval);
} else {
uBit.display.print(t.charAt(0), interval * 5);
}
}
/** /**
* Draws an image on the LED screen. * Draws an image on the LED screen.
@ -22,11 +34,12 @@ namespace basic {
*/ */
//% help=basic/show-leds //% help=basic/show-leds
//% weight=95 blockGap=8 //% weight=95 blockGap=8
//% shim=micro_bit::showLeds
//% imageLiteral=1 async //% imageLiteral=1 async
//% blockId=device_show_leds //% blockId=device_show_leds
//% block="show leds" icon="\uf00a" //% block="show leds" icon="\uf00a"
export function showLeds(leds: string, interval: number = 400): void { } void showLeds(ImageLiteral leds, int interval = 400) {
uBit.display.print(MicroBitImage(getbytes(leds)), 0, 0, 0, interval);
}
/** /**
* Display text on the display, one character at a time. If the string fits on the screen (i.e. is one letter), does not scroll. * Display text on the display, one character at a time. If the string fits on the screen (i.e. is one letter), does not scroll.
@ -35,19 +48,32 @@ namespace basic {
*/ */
//% help=basic/show-string //% help=basic/show-string
//% weight=87 blockGap=8 //% weight=87 blockGap=8
//% shim=micro_bit::scrollString async
//% block="show|string %text" icon="\uf031" //% block="show|string %text" icon="\uf031"
//% async //% async
//% blockId=device_print_message //% blockId=device_print_message
export function showString(text: string, interval: number = 150): void { } void showString(StringData *text, int interval = 150) {
if (interval < 0)
return;
ManagedString s(text);
int l = s.length();
if (l == 0) {
uBit.display.clear();
uBit.sleep(interval * 5);
} else if (l > 1) {
uBit.display.scroll(s, interval);
} else {
uBit.display.print(s.charAt(0), interval * 5);
}
}
/** /**
* Turn off all LEDs * Turn off all LEDs
*/ */
//% help=basic/clear-screen weight=79 //% help=basic/clear-screen weight=79
//% shim=micro_bit::clearScreen
//% blockId=device_clear_display block="clear screen" icon="\uf12d" //% blockId=device_clear_display block="clear screen" icon="\uf12d"
export function clearScreen(): void { } void clearScreen() {
uBit.display.image.clear();
}
/** /**
* Shows a sequence of LED screens as an animation. * Shows a sequence of LED screens as an animation.
@ -55,29 +81,48 @@ namespace basic {
* @param interval TODO * @param interval TODO
*/ */
//% help=basic/show-animation shim=micro_bit::showAnimation imageLiteral=1 async //% help=basic/show-animation shim=micro_bit::showAnimation imageLiteral=1 async
export function showAnimation(leds: string, interval: number = 400): void { } void showAnimation(ImageLiteral leds, int interval = 400) {
uBit.display.animate(MicroBitImage(getbytes(leds)), interval, 5, 0);
}
/** /**
* Draws an image on the LED screen. * Draws an image on the LED screen.
* @param leds TODO * @param leds TODO
*/ */
//% help=basic/plot-leds weight=80 shim=micro_bit::plotLeds imageLiteral=1 //% help=basic/plot-leds weight=80 shim=micro_bit::plotLeds
export function plotLeds(leds: string): void { } void plotLeds(ImageLiteral leds) {
MicroBitImage i(getbytes(leds));
uBit.display.print(i, 0, 0, 0, 0);
}
void forever_stub(void *a) {
while (true) {
action::run((Action)a);
uBit.sleep(20);
}
}
/** /**
* Repeats the code forever in the background. On each iteration, allows other codes to run. * Repeats the code forever in the background. On each iteration, allows other codes to run.
* @param body TODO * @param body TODO
*/ */
//% help=basic/forever weight=55 blockGap=8 //% help=basic/forever weight=55 blockGap=8
//% blockId=device_forever block="forever" icon="\uf01e" shim=micro_bit::forever //% blockId=device_forever block="forever" icon="\uf01e"
export function forever(body: () => void): void { } void forever(Action a) {
if (a != 0) {
incr(a);
create_fiber(forever_stub, (void*)a);
}
}
/** /**
* Pause for the specified time in milliseconds * Pause for the specified time in milliseconds
* @param ms how long to pause for, eg: 100, 200, 500, 1000, 2000 * @param ms how long to pause for, eg: 100, 200, 500, 1000, 2000
*/ */
//% help=basic/pause weight=54 //% help=basic/pause weight=54
//% shim=micro_bit::pause async block="pause (ms) %pause" //% async block="pause (ms) %pause"
//% blockId=device_pause icon="\uf110" //% blockId=device_pause icon="\uf110"
export function pause(ms: number): void { } void pause(int ms) {
uBit.sleep(ms);
}
} }

30
libs/microbit/control.cpp Normal file
View File

@ -0,0 +1,30 @@
#include "BitVM.h"
namespace control {
void fiberDone(void *a)
{
decr((Action)a);
release_fiber();
}
/**
* Schedules code that run in the background.
*/
//% help=control/in-background
//% blockId="control_in_background" block="run in background" blockGap=8
void inBackground(Action a) {
if (a != 0) {
incr(a);
create_fiber((void(*)(void*))action::run, (void*)a, fiberDone);
}
}
/**
* Resets the BBC micro:bit.
*/
//% weight=30 async help=control/reset
//% blockId="control_reset" block="reset"
void reset() {
uBit.reset();
}
}

View File

@ -192,26 +192,28 @@ enum EventBusValue {
//% weight=1 color="#333333" //% weight=1 color="#333333"
namespace control { namespace control {
/**
* Schedules code that run in the background.
*/
//% help=control/in-background shim=micro_bit::runInBackground
//% blockId="control_in_background" block="run in background" blockGap=8
export function inBackground(body: Action): void { }
/** /**
* Resets the BBC micro:bit. * Returns the value of a C++ runtime constant
*/ */
//% weight=30 shim=uBit.reset async help=control/reset //% weight=19 weight=19 blockId="control_event_source" block="%id"
//% blockId="control_reset" block="reset" export function eventSource(id: EventBusSource) : number {
export function reset(): void { } return id;
}
/**
* Returns the value of a C++ runtime constant
*/
//% weight=19 weight=19 blockId="control_event_value" block="%id"
export function eventValue(id: EventBusValue) : number {
return id;
}
/** /**
* Raises an event in the event bus. * Raises an event in the event bus.
@param src ID of the MicroBit Component that generated the event e.g. MICROBIT_ID_BUTTON_A. * @param src ID of the MicroBit Component that generated the event e.g. MICROBIT_ID_BUTTON_A.
@param value Component specific code indicating the cause of the event. * @param value Component specific code indicating the cause of the event.
@param mode optional definition of how the event should be processed after construction (default is CREATE_AND_QUEUE). * @param mode optional definition of how the event should be processed after construction (default is CREATE_AND_QUEUE).
*/ */
// shim=micro_bit::busRaiseEvent // shim=micro_bit::busRaiseEvent
//% weight=21 blockGap=12 blockId="control_raise_event" block="raise event|from source %src=control_event_source|with value %value=control_event_value" blockExternalInputs=1 //% weight=21 blockGap=12 blockId="control_raise_event" block="raise event|from source %src=control_event_source|with value %value=control_event_value" blockExternalInputs=1
export function raiseEvent(src: number, value: number, mode: EventCreationMode = EventCreationMode.CreateAndQueue): void { } export function raiseEvent(src: number, value: number, mode: EventCreationMode = EventCreationMode.CreateAndQueue): void { }
@ -223,19 +225,4 @@ namespace control {
//% weight=20 blockGap=8 blockId="control_on_event" block="on event|from %src=control_event_source|with value %value=control_event_value" //% weight=20 blockGap=8 blockId="control_on_event" block="on event|from %src=control_event_source|with value %value=control_event_value"
//% blockExternalInputs=1 blockStatement=1 //% blockExternalInputs=1 blockStatement=1
export function onEvent(src: number, value: number, handler: Action): void { } export function onEvent(src: number, value: number, handler: Action): void { }
/**
* Returns the value of a C++ runtime constant
*/
//% weight=19 shimw=TD_ID weight=19 blockId="control_event_source" block="%id"
export function eventSource(id: EventBusSource) : number {
return 0;
}
/**
* Returns the value of a C++ runtime constant
*/
//% weight=19 shimw=TD_ID weight=19 blockId="control_event_value" block="%id"
export function eventValue(id: EventBusValue) : number {
return 0;
}
} }

View File

@ -7,9 +7,10 @@
"core.d.ts", "core.d.ts",
"mbit.ts", "mbit.ts",
"images.ts", "images.ts",
"basic.ts", "basic.cpp",
"input.ts", "input.ts",
"control.ts", "control.ts",
"control.cpp",
"game.ts", "game.ts",
"led.ts", "led.ts",
"music.ts", "music.ts",

View File

@ -1,6 +1,6 @@
{ {
"name": "kindscript-microbit", "name": "kindscript-microbit",
"version": "0.0.17", "version": "0.2.1",
"description": "BBC micro:bit target for KindScript", "description": "BBC micro:bit target for KindScript",
"keywords": [ "keywords": [
"JavaScript", "JavaScript",
@ -30,6 +30,6 @@
"typescript": "^1.8.7" "typescript": "^1.8.7"
}, },
"dependencies": { "dependencies": {
"kindscript": "0.1.123" "kindscript": "0.2.1"
} }
} }

View File

@ -88,78 +88,6 @@ namespace ks.rt.micro_bit {
throw new Error("PANIC " + code) throw new Error("PANIC " + code)
} }
/* basic */
export function showDigit(v: number) {
if (!quiet)
console.log("DIGIT:", v)
plotLeds(createImageFromString(v.toString()[0]));
}
export function clearScreen() {
board().image.clear();
runtime.queueDisplayUpdate()
}
export function showLeds(leds: micro_bit.Image, delay: number): void {
showAnimation(leds, delay);
}
function scrollImage(leds: micro_bit.Image, interval: number, stride: number): void {
let cb = getResume()
let off = stride > 0 ? 0 : leds.width - 1;
let display = board().image;
board().animationQ.enqueue({
interval: interval,
frame: () => {
if (off >= leds.width || off < 0) return false;
stride > 0 ? display.shiftLeft(stride) : display.shiftRight(-stride);
let c = Math.min(stride, leds.width - off);
leds.copyTo(off, c, display, 5 - stride)
off += stride;
return true;
},
whenDone: cb
})
}
export function showAnimation(leds: micro_bit.Image, interval: number = 400): void {
scrollImage(leds, interval, 5);
}
export function scrollNumber(x: number, interval: number) {
if (interval < 0) return;
let leds = createImageFromString(x.toString());
if (x < 0 || x >= 10) scrollImage(leds, interval, 1);
else showLeds(leds, interval * 5);
}
export function scrollString(s: string, interval: number) {
if (interval < 0) return;
if (s.length == 0) {
clearScreen();
pause(interval * 5);
} else {
let leds = createImageFromString(s);
if (s.length == 1) showLeds(leds, interval * 5)
else scrollImage(leds, interval, 1);
}
}
export function forever(a: RefAction) {
function loop() {
runtime.runFiberAsync(a)
.then(() => Promise.delay(20))
.then(loop)
.done()
}
incr(a)
loop()
}
export var pause = thread.pause;
/* leds */ /* leds */
export function plot(x: number, y: number) { export function plot(x: number, y: number) {
board().image.set(x, y, 255); board().image.set(x, y, 255);
@ -198,20 +126,17 @@ namespace ks.rt.micro_bit {
runtime.queueDisplayUpdate() runtime.queueDisplayUpdate()
} }
/* control */
export var runInBackground = thread.runInBackground;
/* serial */ /* serial */
export function serialSendString(s: string) { export function serialSendString(s: string) {
board().writeSerial(s); board().writeSerial(s);
} }
export function serialReadString() : string { export function serialReadString(): string {
return board().readSerial(); return board().readSerial();
} }
/* input */ /* input */
export function onButtonPressed(button : number, handler: RefAction) : void { export function onButtonPressed(button: number, handler: RefAction): void {
let ens = enums(); let ens = enums();
let b = board(); let b = board();
if (button == ens.MICROBIT_ID_BUTTON_AB && !board().usesButtonAB) { if (button == ens.MICROBIT_ID_BUTTON_AB && !board().usesButtonAB) {
@ -220,7 +145,7 @@ namespace ks.rt.micro_bit {
} }
b.bus.listen(button, ens.MICROBIT_BUTTON_EVT_CLICK, handler); b.bus.listen(button, ens.MICROBIT_BUTTON_EVT_CLICK, handler);
} }
export function isButtonPressed(button: number): boolean { export function isButtonPressed(button: number): boolean {
let ens = enums(); let ens = enums();
let b = board(); let b = board();
@ -233,19 +158,19 @@ namespace ks.rt.micro_bit {
if (button == ens.MICROBIT_ID_BUTTON_B) return bts[1].pressed; if (button == ens.MICROBIT_ID_BUTTON_B) return bts[1].pressed;
return bts[2].pressed || (bts[0].pressed && bts[1].pressed); return bts[2].pressed || (bts[0].pressed && bts[1].pressed);
} }
export function onGesture(gesture: number, handler: RefAction) { export function onGesture(gesture: number, handler: RefAction) {
let ens = enums(); let ens = enums();
let b = board(); let b = board();
b.accelerometer.activate(); b.accelerometer.activate();
if (gesture == 11 && !b.useShake) { // SAKE if (gesture == 11 && !b.useShake) { // SAKE
b.useShake = true; b.useShake = true;
runtime.queueDisplayUpdate(); runtime.queueDisplayUpdate();
} }
b.bus.listen(ens.MICROBIT_ID_GESTURE, gesture, handler); b.bus.listen(ens.MICROBIT_ID_GESTURE, gesture, handler);
} }
export function onPinPressed(pin: Pin, handler: RefAction) { export function onPinPressed(pin: Pin, handler: RefAction) {
pin.isTouched(); pin.isTouched();
onButtonPressed(pin.id, handler); onButtonPressed(pin.id, handler);
@ -283,7 +208,7 @@ namespace ks.rt.micro_bit {
} }
return b.heading; return b.heading;
} }
export function temperature(): number { export function temperature(): number {
var b = board(); var b = board();
if (!b.usesTemperature) { if (!b.usesTemperature) {
@ -292,7 +217,7 @@ namespace ks.rt.micro_bit {
} }
return b.temperature; return b.temperature;
} }
export function getAcceleration(dimension: number): number { export function getAcceleration(dimension: number): number {
let b = board(); let b = board();
let acc = b.accelerometer; let acc = b.accelerometer;
@ -304,8 +229,8 @@ namespace ks.rt.micro_bit {
default: return Math.floor(Math.sqrt(acc.instantaneousAccelerationSquared())); default: return Math.floor(Math.sqrt(acc.instantaneousAccelerationSquared()));
} }
} }
export function setAccelerometerRange(range : number) { export function setAccelerometerRange(range: number) {
let b = board(); let b = board();
b.accelerometer.setSampleRange(range); b.accelerometer.setSampleRange(range);
} }
@ -327,76 +252,76 @@ namespace ks.rt.micro_bit {
export function getCurrentTime(): number { export function getCurrentTime(): number {
return runtime.runningTime(); return runtime.runningTime();
} }
/* pins */ /* pins */
export function digitalReadPin(pin : Pin) : number { export function digitalReadPin(pin: Pin): number {
pin.mode = PinMode.Digital | PinMode.Input; pin.mode = PinMode.Digital | PinMode.Input;
return pin.value > 100 ? 1 : 0; return pin.value > 100 ? 1 : 0;
} }
export function digitalWritePin(pin : Pin, value: number) { export function digitalWritePin(pin: Pin, value: number) {
pin.mode = PinMode.Digital | PinMode.Output; pin.mode = PinMode.Digital | PinMode.Output;
pin.value = value > 0 ? 1023 : 0; pin.value = value > 0 ? 1023 : 0;
runtime.queueDisplayUpdate(); runtime.queueDisplayUpdate();
} }
export function analogReadPin(pin : Pin) : number { export function analogReadPin(pin: Pin): number {
pin.mode = PinMode.Analog | PinMode.Input; pin.mode = PinMode.Analog | PinMode.Input;
return pin.value || 0; return pin.value || 0;
} }
export function analogWritePin(pin : Pin, value: number) { export function analogWritePin(pin: Pin, value: number) {
pin.mode = PinMode.Analog | PinMode.Output; pin.mode = PinMode.Analog | PinMode.Output;
pin.value = value ? 1 : 0; pin.value = value ? 1 : 0;
runtime.queueDisplayUpdate(); runtime.queueDisplayUpdate();
} }
export function setAnalogPeriodUs(pin: Pin, micros:number) { export function setAnalogPeriodUs(pin: Pin, micros: number) {
pin.mode = PinMode.Analog | PinMode.Output; pin.mode = PinMode.Analog | PinMode.Output;
pin.period = micros; pin.period = micros;
runtime.queueDisplayUpdate(); runtime.queueDisplayUpdate();
} }
export function servoWritePin(pin: Pin, value: number) { export function servoWritePin(pin: Pin, value: number) {
setAnalogPeriodUs(pin, 20000); setAnalogPeriodUs(pin, 20000);
// TODO // TODO
} }
export function servoSetPulse(pin: Pin, micros:number) { export function servoSetPulse(pin: Pin, micros: number) {
} }
module AudioContextManager { module AudioContextManager {
var _context : any; // AudioContext var _context: any; // AudioContext
var _vco : any; //OscillatorNode; var _vco: any; //OscillatorNode;
var _vca: any; // GainNode; var _vca: any; // GainNode;
function context() : any { function context(): any {
if (!_context) _context = freshContext(); if (!_context) _context = freshContext();
return _context; return _context;
} }
function freshContext() : any { function freshContext(): any {
(<any>window).AudioContext = (<any>window).AudioContext || (<any>window).webkitAudioContext; (<any>window).AudioContext = (<any>window).AudioContext || (<any>window).webkitAudioContext;
if ((<any>window).AudioContext) { if ((<any>window).AudioContext) {
try { try {
// this call my crash. // this call my crash.
// SyntaxError: audio resources unavailable for AudioContext construction // SyntaxError: audio resources unavailable for AudioContext construction
return new (<any>window).AudioContext(); return new (<any>window).AudioContext();
} catch(e) {} } catch (e) { }
} }
return undefined; return undefined;
} }
export function stop() { export function stop() {
if (_vca) _vca.gain.value = 0; if (_vca) _vca.gain.value = 0;
} }
export function tone(frequency: number, gain: number) { export function tone(frequency: number, gain: number) {
if (frequency <= 0) return; if (frequency <= 0) return;
var ctx = context(); var ctx = context();
if (!ctx) return; if (!ctx) return;
gain = Math.max(0, Math.min(1, gain)); gain = Math.max(0, Math.min(1, gain));
if (!_vco) { if (!_vco) {
try { try {
_vco = ctx.createOscillator(); _vco = ctx.createOscillator();
@ -405,89 +330,165 @@ namespace ks.rt.micro_bit {
_vca.connect(ctx.destination); _vca.connect(ctx.destination);
_vca.gain.value = gain; _vca.gain.value = gain;
_vco.start(0); _vco.start(0);
} catch(e) { } catch (e) {
_vco = undefined; _vco = undefined;
_vca = undefined; _vca = undefined;
return; return;
} }
} }
_vco.frequency.value = frequency; _vco.frequency.value = frequency;
_vca.gain.value = gain; _vca.gain.value = gain;
} }
} }
export function enablePitch(pin: Pin) { export function enablePitch(pin: Pin) {
board().pins.filter(p => !!p).forEach(p => p.pitch = false); board().pins.filter(p => !!p).forEach(p => p.pitch = false);
pin.pitch = true; pin.pitch = true;
} }
export function pitch(frequency: number, ms: number) { export function pitch(frequency: number, ms: number) {
// update analog output // update analog output
let pin = board().pins.filter(pin => !!pin && pin.pitch)[0] || board().pins[0]; let pin = board().pins.filter(pin => !!pin && pin.pitch)[0] || board().pins[0];
pin.mode = PinMode.Analog | PinMode.Output; pin.mode = PinMode.Analog | PinMode.Output;
if (frequency <= 0) { if (frequency <= 0) {
pin.value = 0; pin.value = 0;
pin.period = 0; pin.period = 0;
} else { } else {
pin.value = 512; pin.value = 512;
pin.period = 1000000/frequency; pin.period = 1000000 / frequency;
} }
runtime.queueDisplayUpdate(); runtime.queueDisplayUpdate();
let cb = getResume(); let cb = getResume();
AudioContextManager.tone(frequency, 1); AudioContextManager.tone(frequency, 1);
if (ms <= 0) cb(); if (ms <= 0) cb();
else { else {
setTimeout(() => { setTimeout(() => {
AudioContextManager.stop(); AudioContextManager.stop();
pin.value = 0; pin.value = 0;
pin.period = 0; pin.period = 0;
pin.mode = PinMode.Unused; pin.mode = PinMode.Unused;
runtime.queueDisplayUpdate(); runtime.queueDisplayUpdate();
cb() cb()
}, ms); }, ms);
} }
} }
/* radio */ /* radio */
export function broadcastMessage(msg: number) : void { export function broadcastMessage(msg: number): void {
board().radio.broadcast(msg); board().radio.broadcast(msg);
} }
export function onBroadcastMessageReceived(msg: number, handler: RefAction) : void { export function onBroadcastMessageReceived(msg: number, handler: RefAction): void {
let ens = enums() let ens = enums()
board().bus.listen(ens.MES_BROADCAST_GENERAL_ID, msg, handler); board().bus.listen(ens.MES_BROADCAST_GENERAL_ID, msg, handler);
} }
export function setGroup(id : number) : void { export function setGroup(id: number): void {
board().radio.setGroup(id); board().radio.setGroup(id);
} }
export function setTransmitPower(power: number) : void { export function setTransmitPower(power: number): void {
board().radio.setTransmitPower(power); board().radio.setTransmitPower(power);
} }
export function datagramSendNumbers(value0 : number, value1: number, value2: number, value3: number) : void { export function datagramSendNumbers(value0: number, value1: number, value2: number, value3: number): void {
board().radio.datagram.send([value0, value1, value2, value3]); board().radio.datagram.send([value0, value1, value2, value3]);
} }
export function datagramReceiveNumber() : number { export function datagramReceiveNumber(): number {
return board().radio.datagram.recv().data[0]; return board().radio.datagram.recv().data[0];
} }
export function datagramGetNumber(index : number) : number { export function datagramGetNumber(index: number): number {
return board().radio.datagram.lastReceived.data[index] || 0; return board().radio.datagram.lastReceived.data[index] || 0;
} }
export function datagramGetRSSI() : number { export function datagramGetRSSI(): number {
return board().radio.datagram.lastReceived.rssi; return board().radio.datagram.lastReceived.rssi;
} }
export function onDatagramReceived(handler: RefAction) : void { export function onDatagramReceived(handler: RefAction): void {
let ens = enums(); let ens = enums();
board().bus.listen(ens.MICROBIT_ID_RADIO, ens.MICROBIT_RADIO_EVT_DATAGRAM, handler); board().bus.listen(ens.MICROBIT_ID_RADIO, ens.MICROBIT_RADIO_EVT_DATAGRAM, handler);
} }
} }
namespace ks.rt.basic {
var board = micro_bit.board;
export var pause = thread.pause;
export function showNumber(x: number, interval: number) {
if (interval < 0) return;
let leds = micro_bit.createImageFromString(x.toString());
if (x < 0 || x >= 10) scrollImage(leds, interval, 1);
else showLeds(leds, interval * 5);
}
export function showString(s: string, interval: number) {
if (interval < 0) return;
if (s.length == 0) {
clearScreen();
pause(interval * 5);
} else {
let leds = micro_bit.createImageFromString(s);
if (s.length == 1) showLeds(leds, interval * 5)
else scrollImage(leds, interval, 1);
}
}
export function showLeds(leds: micro_bit.Image, delay: number): void {
showAnimation(leds, delay);
}
export function clearScreen() {
board().image.clear();
runtime.queueDisplayUpdate()
}
function scrollImage(leds: micro_bit.Image, interval: number, stride: number): void {
let cb = getResume()
let off = stride > 0 ? 0 : leds.width - 1;
let display = board().image;
board().animationQ.enqueue({
interval: interval,
frame: () => {
if (off >= leds.width || off < 0) return false;
stride > 0 ? display.shiftLeft(stride) : display.shiftRight(-stride);
let c = Math.min(stride, leds.width - off);
leds.copyTo(off, c, display, 5 - stride)
off += stride;
return true;
},
whenDone: cb
})
}
export function showAnimation(leds: micro_bit.Image, interval: number = 400): void {
scrollImage(leds, interval, 5);
}
export function forever(a: RefAction) {
function loop() {
runtime.runFiberAsync(a)
.then(() => Promise.delay(20))
.then(loop)
.done()
}
incr(a)
loop()
}
}
namespace ks.rt.control {
export var inBackground = thread.runInBackground;
export function reset() {
U.userError("reset not implemented in simulator yet")
}
}