https://github.com/ti-nspire/AVR/tree/master/timerAudio
pp.184-188
タイマーカウンター0、CTCモード、トグル出力を試す -の続き。
https://ti-nspire.hatenablog.com/entry/2019/04/16/100444
https://ti-nspire.hatenablog.com/entry/2019/05/25/113241
https://ti-nspire.hatenablog.com/entry/2019/05/27/114456
で使ったplayNote()
函数を、タイマーカウンターを使って改善する。コンペア値でトグル周波数(音程)を変化させる。
#include <avr/io.h> #include <util/delay.h> #include "scale16.h" static inline void initTimer(){ TCCR0A |= (1 << WGM01); // タイマーカウンター0をCTCモードにする。 TCCR0A |= (1 << COM0A0); // OC0A (PD6)端子からトグル出力する。 TCCR0B |= (1 << CS01) | (1 << CS00); // システムクロックを64分周する。 } static inline void playNote(uint8_t note, uint16_t duration) { OCR0A = note; // コンペア値を設定して、 DDRD |= (1 << PD6); // 実際にトグル出力して、 while(duration){ // 一定の期間だけトグル出力を続けて、 _delay_ms(1); duration--; } DDRD &= ~(1 << PD6); // トグル出力を停止する。 } int main(void) { // silent song const uint8_t Notes[] = {C8,G7,B7,G7,A7,G7,B7,G7, C8,F7,B7,F7,A7,F7,B7,F7, C8,E7,B7,E7,A7,E7,B7,E7, D7,G7,E7,G7,D7,G7,E7,G7,}; const uint8_t NumOfNotes = (sizeof(Notes) / sizeof(uint8_t)); // ノートの数を取得しておく。 initTimer(); while(1){ for(int i=0; i<NumOfNotes; i++){ playNote(Notes[i],180); } } return 0; }