use timer1 ctc mode instead of util/delay functions

This commit is contained in:
Vineet K 2024-04-17 10:07:39 -04:00 committed by Shokara Kou
parent 9d751dc020
commit 8f258e4e02
2 changed files with 41 additions and 31 deletions

View File

@ -2,6 +2,8 @@ CC = avr-gcc
CFLAGS = -O2 -Wall -Wextra -Werror -mmcu=atmega328p
OBJCOPY = avr-objcopy
PORT ?= /dev/ttyACM0
all:
${CC} ${CFLAGS} main.c
${OBJCOPY} -j .text -j .data -O ihex a.out main.hex

64
main.c
View File

@ -1,43 +1,42 @@
/*
* EEL4746C - AVR Piano - Speaker Section
* speaker is connected to PD2 and ground
* buttons are connected to PB0-5, PC0-5, PD3-7
, PD3-7
* the LCD Arduino UNO is connected to TX/RX (PD0/1)
*/
#include <avr/io.h>
#include <avr/interrupt.h>
#define F_CPU 16000000UL
#define __DELAY_BACKWARD_COMPATIBLE__ /* to use variables with _delay_u/ms */
#include <util/delay.h>
#define T1_PRESCALAR 8
#define FREQ(f) (16e6 / f / T1_PRESCALAR / 2)
#define P_RX 0
#define P_TX 1
#define P_SPKR 2
unsigned short freqs[] = {
1 / 100 * 1e6 / 2,
1 / 200 * 1e6 / 2,
1 / 250 * 1e6 / 2,
1 / 300 * 1e6 / 2,
1 / 350 * 1e6 / 2,
1 / 400 * 1e6 / 2,
1 / 500 * 1e6 / 2,
1 / 600 * 1e6 / 2,
1 / 700 * 1e6 / 2,
1 / 750 * 1e6 / 2,
1 / 1000 * 1e6 / 2,
1 / 1250 * 1e6 / 2,
1 / 1500 * 1e6 / 2,
1 / 1750 * 1e6 / 2,
1 / 2000 * 1e6 / 2,
1 / 3000 * 1e6 / 2,
1 / 4000 * 1e6 / 2,
1 / 5000 * 1e6 / 2,
1 / 6000 * 1e6 / 2,
1 / 7000 * 1e6 / 2,
1 / 8000 * 1e6 / 2
FREQ(100),
FREQ(200),
FREQ(250),
FREQ(300),
FREQ(350),
FREQ(400),
FREQ(500),
FREQ(600),
FREQ(700),
FREQ(750),
FREQ(1000),
FREQ(1250),
FREQ(1500),
FREQ(1750),
FREQ(2000),
FREQ(3000),
FREQ(4000),
FREQ(5000),
FREQ(6000),
FREQ(7000),
FREQ(8000),
};
unsigned char note = 8;
unsigned char buttonpressed = 1;
@ -54,15 +53,24 @@ main(void)
PCMSK2 = ~(1 | (1 << 1) | (1 << 2));
PCICR = (1 << PCIE0) | (1 << PCIE1) | (1 << PCIE2);
TCCR1A = 0x00; // use timer1 CTC mode
TCCR1B = 1 << WGM12; // already prescaled by 8 in table
sei();
//for (;;);
for (unsigned char n = 0;; n = (n + 1) % 2) {
if (!buttonpressed && n == 0) continue;
_delay_us(freqs[note]);
// _delay_us(714.2857);
// _delay_us(70);
TCNT1 = 1;
OCR1A = freqs[note];
TCCR1B |= 1 << CS11;
while ((TIFR1 & (1 << OCF1A)) == 0);
PORTD ^= 1 << P_SPKR;
TIFR1 |= 1 << OCF1A;
TCCR1B &= ~(1 << CS11);
}
}