Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save genya0407/bf130395eecea685a63c727909c3f7b5 to your computer and use it in GitHub Desktop.
Save genya0407/bf130395eecea685a63c727909c3f7b5 to your computer and use it in GitHub Desktop.
Enter file contents here#include <pic.h>
/*
* 以下のdefineについては、全て、50μsを掛けた値であると読む。
* */
/*
* N: 二分音符の音の長さ
* S: 四分音符の音の長さ
* H: 八分音符の音の長さ
* */
#define N 17647
#define S 8824
#define H 4412
/*
* DO: 「ド」の音の周期の半分
* LE: 「レ」の音の周期の半分
* 以下同様
* */
#define DO 19
#define LE 17
#define MI 15
#define FA 14
#define SO 13
#define LA 11
#define SI 10
#define DO_ 9
// 休符
#define Q 0
void main(){
int i = 0;
int flg = 0;
int length_cntr, freq_cntr;
int score[2][17] = {
{ SO, LA, SI , Q , FA, FA, DO_, Q , SI, SO-1, SO-1, SO-1, SO-1, SO-1, LA, SI , Q },
{ H , H , H+N, H , H , H , H+N, S , H , H , H , H , S , H , S , H+N, H }
};
OPTION = 0b11011000;
//TRISA = 0b00011011;
TRISA = 0b11011111;
while(1){ // 曲が終わったら始めからもう一度演奏する
for(i=0; i<17; i++){ // 楽譜(score変数)を走査する
/*
* 50マイクロ秒経過するごとに、length_cntrとfreq_cntrをカウントアップする。
* freq_cntrは、一つの音の中で、ONとOFFを切り替えるタイミングを決めるカウンタ。
* length_cntrは、一つの音をどれだけの長さ鳴らすかを決めるカウンタ。
*
* 例えば、440Hzの音を出す時、その周期は1/440(sec)であり、
* 1/440/2(sec)ごとに音のONとOFFを切り替えれば良い。
* 1/440/2(sec)とは、1/440/2/(50*10^(-6))回 T0IFが1になるのにかかる時間である。
*
* 従って、T0IFが1になる度にfreq_cntrをカウントアップしてやり、
* freq_cntrが 1/440/2/(50*10^(-6)) を超えた時に、スピーカーのONとOFFを切り替えてやれば良い。
*
* length_cntrについても同様である。
* length_cntrが規定の回数を超えた時にwhile文を抜けるようにしてある。
* */
RA5 = 0b0;
length_cntr = 0;
freq_cntr = 0;
while(length_cntr < score[1][i]){
// 50μs待つ
T0IF = 0;
while(T0IF == 0);
length_cntr++;
freq_cntr++;
// 休符なら何もしない
if(score[0][i] != Q){
if(freq_cntr > score[0][i]){
// スピーカーの出力を反転
if(flg){
RA5 = 0;
flg = 0;
}else{
RA5 = 1;
flg = 1;
}
freq_cntr = 0;
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment