11
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TypeScript を使って obniz で Lチカ

Last updated at Posted at 2019-06-04

obniz SDK v2.1.0 がリリースされました!
https://github.com/obniz/obniz/releases/tag/v2.1.0

今回から型定義が導入されたため、TypeScript での開発が捗ります!

こんな感じで...!!

ということで早速 TypeScript を使って obniz で Lチカをします。

開発環境

  • PC: MacOS High Sierra 10.13.6
  • Node.js: v10.15.1
  • npm: 6.9.0 (or yarn: 1.15.2)
  • TypeScript: 3.5.1

Node プロジェクトの準備

  1. 作業ディレクトリ作成

    $ mkdir work
    $ cd work
    
  2. Node プロジェクト作成

    $ yarn init
    yarn init v1.15.2
    # package.json の設定は適当に連打
    question name (work): 
    question version (1.0.0): 
    question description: 
    question entry point (index.js): 
    question repository url: 
    question author: 
    question license (MIT): 
    question private: 
    
  3. Node モジュールをインストール

    $ yarn add obniz
    $ yarn add -D typescript @types/node
    
  4. tsconfig.json を準備

    tsconfig.json
    {
      "compilerOptions": {
        "sourceMap": true,
        "outDir": "dist",
        "target": "es6",
        "module": "commonjs",
        "moduleResolution": "node",
        "lib": ["es2018", "dom"]
      }
    }
    
  5. npm scripts を準備 (規模が小さいので不要だけど)

    package.json
      ...
      },
    + "scripts": {
    +   "build": "tsc",
    +   "start": "node dist/main.js"
    +   "clean": "rm -rf dist"
    + }
    
  6. ソースコードを準備

    $ mkdir src
    $ touch src/main.ts
    

最終的なディレクトリツリー

.
├── node_modules
├── package.json
├── src
│   └── main.ts
├── tsconfig.json
└── yarn.lock

Hello World!

src/main.ts
import * as Obniz from 'obniz';

const OBNIZ_ID = '1234-5678';

const obniz = new Obniz(OBNIZ_ID);
obniz.onconnect = async () => {
  obniz.display.clear();
  obniz.display.print('Hello World!');
};

実行

$ npm run build
$ npm run start

結果

Lチカ

src/main.ts
import * as Obniz from 'obniz';

const OBNIZ_ID = '1234-5678';

const obniz = new Obniz(OBNIZ_ID);
obniz.onconnect = async () => {
  const led = obniz.wired('LED', { anode: 0, cathode: 1 });
  led.on();

  setTimeout(() => {
    led.off();
  }, 3000);
};

実行

$ npm run build
$ npm run start

結果

最後に

本記事の内容は、
以下のリポジトリを clone すれば試せるはず...
https://github.com/chibi929/obnizxts

obnizパーツライブラリ が豊富でサンプルコードも充実しているので簡単!
TypeScript でより開発が捗る

11
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?