PIC16F1789 & MPUトレーナー 12 / PWM を使ったビープ音で音階を発生する

参考: 定番!ARMキット&PIC用Cプログラムでいきなりマイコン制御[DVD-ROM付き] (マイコン活用シリーズ), pp.143-148



main.c

#include "mcc_generated_files/mcc.h"

volatile int msCnt = 0;
void delay_ms(int cnt) {
	msCnt = cnt;
	while(msCnt);
}

void SetBeep(int val) {
	TMR2_LoadPeriodRegister(val);
	PWM1_LoadDutyValue(val << 1);
}

void main(void) {
	int Note[] = {
		0x011C, // 0, A3
		0x010C, // 1, B3♭
		0x00FD, // 2, B3
		0x00EE, // 3, C4
		0x00E1, // 4, D4♭
		0x00D4, // 5, D4
		0x00C8, // 6, E4♭
		0x00BD, // 7, E4
		0x00B2, // 8, F4
		0x00A8, // 9, G4♭
		0x009F, //10, G4
		0x0096, //11, A4♭
		0x008E, //12, A4
		0x0086, //13, B4♭
		0x007E, //14, B4
		0x0077, //15, C5
		0x0070, //16, D5♭
		0x006A, //17, D5
		0x0064, //18, E5♭
		0x005E, //19, E5
		0x0059, //20, F5
		0x0054, //21, G5♭
		0x004F, //22, G5
		0x004B, //23, A5♭
		0x0047, //24, A5
		0x0043, //25, B5♭
		0x003F, //26, B5
		0x003B, //27, C6
	};
	
	int Scale[] = {
		 3,  7, 10, 15, 17, 15, 10,  7, //C
		 5, 12, 17, 19, 21, 19, 17, 12, //D
		10, 17, 22, 24, 26, 24, 22, 17, //G
		 7, 17, 21, 22, 26, 22, 21, 17, //Em
	};
	
	int numOfNotes = (sizeof Scale)/(sizeof(int));
	int noteNo = 0;
	
	SYSTEM_Initialize();
	INTERRUPT_GlobalInterruptEnable();
	INTERRUPT_PeripheralInterruptEnable();

	while(1) {
		SetBeep(Note[Scale[noteNo]]);
		delay_ms(100);
		noteNo++;
		if(noteNo > (numOfNotes - 1)) {
			noteNo = 0;
		}
	}
}