利用 PXT 自訂積木(霹靂燈、振動馬達) 來玩 taiwanbit

動機:可否自訂 PXT 的積木(霹靂燈、振動馬達)來玩 taiwan:bit

準備環境
1.Windows 10 / MacBook Pro筆電
2.taiwan:bit(插USB數據線)

示意模擬動畫(示範霹靂燈):

實作步驟
1.先到 PXT ( https://makecode.microbit.org/ ) 編寫程式,如下圖


2.確認 JavaScript程式 在 模擬動畫效果 一致後,開始自訂積木,先到左下方 Explorer 點按 ,再按下 + ,如下圖



3.按下 Go ahead 可以看到積木多了一個 Custom 及 左下方 多了一個檔案 custom.ts ,如下圖



4.接下來,我在 custom.ts 程式,依據網頁 ( https://pxt.microbit.org/blocks/custom ) 指示 及 TypeScript 的語法,自編積木並存檔,如下圖


示範程式,如下
/**
* Use this file to define custom functions and blocks.
* Read more at https://makecode.microbit.org/blocks/custom
*/
enum MyEnum {
//% block="one"
One,
//% block="two"
Two
}
/**
* Taibit blocks
*/
//% weight=100 color=#0fbc11 icon=""
namespace taibit {
/** function */
function delay_LED(item: number) {
led.plot(item, 2)
basic.pause(200)
led.unplot(item, 2)
}
/**
* Show LED Matrix to back and forth => run for many times
* @param ts describe parameter here, eg: 100
*/
//% blockId="delayleds_times" block="delayleds for times| %ts"
export function delayleds(ts: number) {
while (ts > 0) {
for (let i = 0; i <= 4; i++) {
delay_LED(i)
}
for (let i = 4; i >= 0; i--) {
delay_LED(i)
}
ts = ts - 1
}
}
/** function - Vibration Motor */
function vibration_Motor(sw: number) {
if (sw > 1) {
return
}
pins.digitalWritePin(DigitalPin.P12, sw)
}
/**
* Control Vibration Motor (pin12) => on | off
* @param to describe parameter here, eg: 0
*/
//% block
export function vibrationMotor(to: number) {
vibration_Motor(to)
}
/**
* Control Vibration Motor (pin12) => pause millisecond
* @param ms describe parameter here, eg: 100
*/
//% blockId="vibration_motor_pause" block="vibration motor pause (ms)| %ms"
export function vibrationMotorPause(ms: number) {
vibration_Motor(1)
basic.pause(ms)
vibration_Motor(0)
}
}
view raw custom.ts hosted with ❤ by GitHub


5.最後,就可以使用 自定積木 Custom -> delayleds 了,如下圖


6.示範積木,如下圖


7.存檔並flash .hex至taiwanbit,如下影片
https://www.facebook.com/dvsseed/videos/1752610928085044/
8.Taiwan:bit有振動馬達(pin12),加其控制積木(1:開,0:關)並示範,如下影片
https://www.facebook.com/dvsseed/videos/1753607124652091/

如果要匯入 Taibit積木,請至 Add Package 輸入網址: https://makecode.microbit.org/_g1EXiEYjd5Ci
即可...如下圖





Editor



後記:參攷網頁 https://pxt.microbit.org/blocks/custom 及 https://makecode.com/defining-blocks 可以做到許多的效果...

參攷
1.TypeScript新手入門,https://hackmd.io/s/rkITEOYX

留言