Toyomasa Watarai
/
melodic_keyboard
Melodic keyboard using 4ch PWMs
main.cpp
- Committer:
- MACRUM
- Date:
- 2015-05-04
- Revision:
- 1:2c75ba53ee40
- Parent:
- 0:30b446b0af9a
File content as of revision 1:2c75ba53ee40:
#include "mbed.h" #if !defined(TARGET_LPC1549) #error This program uses 4ch PWMs of the LPC1549 platfrom #endif DigitalIn btn_0(D0); DigitalIn btn_1(D1); DigitalIn btn_2(D2); DigitalIn btn_3(D3); DigitalIn btn_4(D4); DigitalIn btn_5(D5); DigitalIn btn_6(D6); DigitalIn btn_7(D7); DigitalIn btn_8(D8); DigitalIn btn_9(D9); DigitalIn btn_10(D10); DigitalIn btn_11(D11); DigitalIn btn_12(D12); PwmOut tone_0(A0); PwmOut tone_1(A1); PwmOut tone_2(A2); PwmOut tone_3(A3); const int tone_table_us[] = { 0, 3820, // C 1 3610, // C# 2 3410, // D 3 3210, // D# 4 3030, // E 5 2860, // F 6 2700, // F# 7 2550, // G 8 2410, // G# 9 2270, // A 10 2150, // A# 11 2020, // B 12 1910 // C 13 }; #define MAX_PWM_CHANNEL 4 #define NUM_KEYS 13 int ch[MAX_PWM_CHANNEL] = {0}; PwmOut *tone[MAX_PWM_CHANNEL]; int key_index[NUM_KEYS]; DigitalIn *key[NUM_KEYS]; int getFreeChannel() { for (int i = 0; i <MAX_PWM_CHANNEL; i++) { if (ch[i] == 0) { ch[i] = 1; return i; } } return -1; } int main() { memset(key_index, -1, (NUM_KEYS)*4); tone_0.period(0); tone_1.period(0); tone_2.period(0); tone_3.period(0); tone[0] = &tone_0; tone[1] = &tone_1; tone[2] = &tone_2; tone[3] = &tone_3; key[0] = &btn_0; key[1] = &btn_1; key[2] = &btn_2; key[3] = &btn_3; key[4] = &btn_4; key[5] = &btn_5; key[6] = &btn_6; key[7] = &btn_7; key[8] = &btn_8; key[9] = &btn_9; key[10] = &btn_10; key[11] = &btn_11; key[12] = &btn_12; while(1) { for (int i=0; i<NUM_KEYS; i++) { volatile uint32_t dummy = key[i]->read(); if (key[i]->read() != 1) { if (key_index[i] == -1) { int num = getFreeChannel(); if (num != -1) { key_index[i] = num; tone[num]->period_us(tone_table_us[i+1]); tone[num]->write(0.5f); } } } else { if (key_index[i] != -1) { tone[key_index[i]]->period(0); ch[key_index[i]] = 0; key_index[i] = -1; } } } } }