micro:bit に入力したパルスのパルス幅を測る / H も L も測る / ポーリング方式

今度は H、L の両方を同時に測ってみる。

#include "MicroBit.h"
MicroBit uBit;

int pulseIn(int OneZero){
    uint32_t start;
    uint32_t end;
    uint32_t elapsedTime;

    while(uBit.io.P0.getDigitalValue() == OneZero){} // H (L) の途中だったら一旦 L (H) になるまで待つ。
    while(uBit.io.P0.getDigitalValue() != OneZero){} // あらためて H (L) になるのを待つ。
    start = us_ticker_read();                        // H (L)になったら時間を取得して、
    while(uBit.io.P0.getDigitalValue() == OneZero){} // L (H) になるまで待って、
    end = us_ticker_read();                          // L (H)になったらまた時間を取得して、
    elapsedTime = end - start;                       // H (L) の持続時間を計算して、
    return elapsedTime;                              // 返す。
}

int main(void){
    uBit.init();
    while(1) {
        printf("%d , %d\n\r", pulseIn(1), pulseIn(0)); // H (1)、L (0) の両方の持続時間を表示する。
    }
    return 0;
}

f:id:ti-nspire:20180516120948p:plain
周波数 1 kHz、デューティー 33% のパルスを micro:bit の P0 端子に入力している。
値は左が H の持続時間、右が L の持続時間。単位はマイクロ秒。