排列に格納したいくつかの音を順番に鳴らす / FGからパルスを送り込んで一定のテンポで鳴らす

https://github.com/ti-nspire/AVR/tree/master/Music_Box_Pulse

今度は、スイッチでLHを切り換える代わりにFGからパルスを送り込んでみる。プログラムは、パルス入力用に全面的に書き換えることはせずに、排列に格納したいくつかの音を順番に鳴らす -で作ったプログラムを以下のように変更するにとどめた。

  • ディジタル入力を内部プルアップしない。
  • ディジタル入力のロジックを反転する(H有意にする)。

f:id:ti-nspire:20190527114141p:plain:h250

#include <avr/io.h>
#include <util/delay.h>
#include "scale16.h"

void playNote(uint16_t period, uint16_t duration, uint8_t whichPort, uint8_t whichPin) {
    for (int elapsed = 0; elapsed < duration; elapsed += period) {
        for (int i = 0; i < period; i++) {
            _delay_us(1);
        }
        switch(whichPort){
            //case 'B': PORTB ^= (1 << whichPin); break;
            //case 'C': PORTC ^= (1 << whichPin); break;
            case 'D': PORTD ^= (1 << whichPin); break;
            default: break;
        }
    }
}

int main(void) {
    // behind the mask, ymo
    const uint16_t Notes[] = {F5 , F5 , A5 , A5 , C6 , C6 , F5 , F5 , A5, A5, C6 , C6 , F5 , F5 , A5, A5,
                              Cx5, Cx5, F5 , F5 , Gx5, Gx5, Cx5, Cx5, F5, F5, Gx5, Gx5, Cx5, Cx5, F5, F5,
                              Dx5, Dx5, G5 , G5 , Ax5, Ax5, Dx5, Dx5, G5, G5, Ax5, Ax5, Dx5, Dx5, G5, G5,
                              C5 , C5 , Dx5, Dx5, G5 , G5,  C5 , C5 , E5, E5, G5 , G5 , C5 , C5 , E5, E5,};
                              
    const uint8_t NumOfNotes = (sizeof(Notes) / sizeof(uint16_t)); // ノートの数を取得しておく。
    uint8_t whichNote = -1;
    uint8_t wasPressed = 1;

    DDRD  |= (1 << PD6); // PD6のIOをOUTに設定し、そこにスピーカーをつなぐ。
    //PORTD |= (1 << PD2); // PD2を内部プルアップし、そこに押しボタンをつないでディジタル入力として使う。

    while (1) {
        if (bit_is_set(PIND, PD2)) {
            if (wasPressed) {
                wasPressed = 0;
                whichNote++;
                if (whichNote == NumOfNotes) {whichNote = 0;}
                //whichNote %= NumOfNotes;
            }
            playNote(Notes[whichNote], 1600, 'D', PD6);
        } else {
            wasPressed = 1;
        }
    }
    
    return 0;
}