From 88320ae5782c6406376c4c77720639a44f5f84d2 Mon Sep 17 00:00:00 2001 From: PlexSheep Date: Mon, 30 Oct 2023 09:47:13 +0100 Subject: [PATCH] timer --- alarm/main.c | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++ timer/main.c | 39 +++++++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+) create mode 100644 alarm/main.c create mode 100644 timer/main.c diff --git a/alarm/main.c b/alarm/main.c new file mode 100644 index 0000000..5614053 --- /dev/null +++ b/alarm/main.c @@ -0,0 +1,61 @@ +/* + * Control PB5 with the two buttons. One button disables, the other enables. + * The board uses interrupts for this. PB5 will quickly oscilate between on and + * off to make cool sounds with a summer. + */ +#define F_CPU 16000000UL +#define __AVR_ATmega328P__ +#include +#include +#include + +#define MINUTE 60 * 1000 +const int TIME = 45 * MINUTE; + +int volatile reset = 0; + +int alarm(); + +// code for INT0 +ISR(INT0_vect) { reset = 1; } + +int main(void) { + + DDRB = 0xff; // write to B + DDRD = 0; // read from D + + PORTD |= (1 << PORTD2) | (1 << PORTD3); // pull up D2 and D3 + + PORTB = 0; // pull down port B + + // enable external interruprs + EIMSK |= (1 << INT0); + EIMSK |= (1 << INT1); + + // trigger when anything changes + EICRA |= (1 << ISC00); // for INT0 + EICRA |= (1 << ISC10); // for INT1 + + sei(); // interrupt magic macro + while (1) { + _delay_ms(TIME); + alarm(); + } +} + +int alarm(void) { + int sound = 0; + while (!reset) { + PORTB |= (1 << PORTB5); + _delay_us(sound); + PORTB &= ~(1 << PORTB5); + _delay_us(sound); + sound++; + if (sound > 1000) { + sound = 0; + } + } + reset = 0; + PORTB &= ~(1 << PORTB5); + return 0; +} diff --git a/timer/main.c b/timer/main.c new file mode 100644 index 0000000..7863bfd --- /dev/null +++ b/timer/main.c @@ -0,0 +1,39 @@ +/* + * Use the timer to produce a sound in a speaker. + * + * Formular for the frequency: + * (F_CPU/Prescaler)/(wanted_frequency*2)+1 + * + * Cut off the decimal part and see which is + * closer to the wanted frequency. + */ +#define F_CPU 16000000UL +#define __AVR_ATmega328P__ +#include +#include +#include + +#define MINUTE 60 * 1000 +const int TIME = 45 * MINUTE; + +ISR(TIMER0_COMPA_vect) { PORTB ^= (1 << PORTB5); } + +int main(void) { + + DDRB = 0xff; // write to B + DDRD = 0; // read from D + + // Timer 0 + // Mode: Overflow, Interrupt + // Prescaler: /256 + // max: 70 + TCCR0A |= (1 << WGM01); // CTC Mode + OCR0A = 70; // max value for timer + TIMSK0 |= (1 << OCIE0A); // enable interrupt ISR_COMPA_vect + + sei(); // magic interrupt macro + + TCCR0B |= (1 << CS02); // enable with prescaler 256 + while (1) { + } +}