0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Microbit用GP2Y0A21YK拡張機能を作ってみた!

0
Posted at

はじめに

この記事では、秋月電子通商のGP2Y0A21YK

を micro:bit で使うための拡張機能を紹介します。

拡張機能の読み込み

MakeCode の「拡張機能」→「URL から追加」で以下を入力します。

https://github.com/keikyufun/GP2Y0A21YK#v0
IMG_2017.png

使えるブロック

・GP2Y0A21YK 距離(cm) ピン(ピンを選択する)

実装コード(main.ts)

//% color=#2E8BFF icon="\uf2db" block="GP2Y0A21YK"
namespace GP2Y0A21YK {

    // GP2Y0A21YK の有効距離範囲
    const MIN_CM = 10
    const MAX_CM = 80

    //% block="GP2Y0A21YK 距離(cm) ピン %pin"
    export function distanceCm(pin: AnalogPin): number {
        const adc = pins.analogReadPin(pin)

        // アナログ値が小さすぎると計算不能
        if (adc <= 20) return -1

        // 近似式(逆比例)
        let cm = 4800 / (adc - 20)

        // 有効範囲外は -1
        if (cm < MIN_CM || cm > MAX_CM) return -1

        return cm
    }

    //% block="GP2Y0A21YK 生のアナログ値 ピン %pin"
    export function rawAnalog(pin: AnalogPin): number {
        return pins.analogReadPin(pin)
    }

    //% block="GP2Y0A21YK 有効距離か? ピン %pin"
    export function inRange(pin: AnalogPin): boolean {
        const d = distanceCm(pin)
        return d >= MIN_CM && d <= MAX_CM
    }
}

おまけ

この拡張機能は自分で取ったデータを元に作りました。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?