diff --git a/notes.c b/notes.c index c677c9a..3f93cc5 100644 --- a/notes.c +++ b/notes.c @@ -41,6 +41,9 @@ unsigned short freqs[] = { [255] = 0 // used as a 'silent' note }; unsigned char note = 0; +// 0 = buttons write note+cycles+\xff to UART +// 1 = buttons don't do anything, speaker reads note+cycles+\xff from UART +unsigned char mode = 0; ISR (PCINT0_vect) { @@ -121,33 +124,60 @@ main(void) // Sends Square wave to the Speaker When a Button is Pressed unsigned short cycles = 0; - unsigned char last_note = 0; - for (unsigned char n = 0;; n = (n + 1) % 2) { + unsigned char tmp = 0; + for (;;) { // check if any buttons are pressed, otherwise don't play a note if (((PINB & PCMSK0) | (PINC & PCMSK1) | (PIND & PCMSK2)) == 0) { // if a button was released, then send note and cycles played if (cycles > 0) { - usart_send(last_note); + usart_send(tmp); usart_send(HIGH(cycles)); usart_send(LOW(cycles)); - usart_send('\xff'); + usart_send(0xff); cycles = 0; + } else { + if (UCSR0A & (1 << RXC0)) { + mode = UDR0; + usart_send(mode); + } } continue; } - // Prepare Timer/Counter - TCNT1 = 1; - last_note = note; - OCR1A = freqs[note]; - TCCR1B |= 1 << CS11; + if (mode == 0) { + // Prepare Timer/Counter + TCNT1 = 1; + tmp = note; + OCR1A = freqs[note]; + TCCR1B |= 1 << CS11; - while ((TIFR1 & (1 << OCF1A)) == 0); // Monitor OutPut Compare Flag + // Monitor OutPut Compare Flag + while ((TIFR1 & (1 << OCF1A)) == 0); - // Toggles port For Speaker - PORTD ^= 1 << P_SPKR; - TIFR1 |= 1 << OCF1A; - TCCR1B &= ~(1 << CS11); - cycles = (cycles + 1) % 0xffff; + // Toggles port For Speaker + PORTD ^= 1 << P_SPKR; + TIFR1 |= 1 << OCF1A; + TCCR1B &= ~(1 << CS11); + cycles = (cycles + 1) % 0xffff; + } else if (mode == 0xb0) { + note = usart_read(); + tmp = usart_read(); + cycles = tmp << 8; + tmp = usart_read(); + cycles |= tmp; + (void)usart_read(); + + for (unsigned char i = 0; i < cycles; i++) { + TCNT1 = 1; + OCR1A = freqs[note]; + TCCR1B |= 1 << CS11; + + while ((TIFR1 & (1 << OCF1A)) == 0); + + PORTD ^= 1 << P_SPKR; + TIFR1 |= 1 << OCF1A; + TCCR1B &= ~(1 << CS11); + } + } } }