initial avr projects (blink + interrupts)
This commit is contained in:
24
LED Blink Input Output/Makefile
Normal file
24
LED Blink Input Output/Makefile
Normal file
@@ -0,0 +1,24 @@
|
||||
MCU = atmega328p
|
||||
F_CPU = 16000000UL
|
||||
CC = C:\Users\sharm\Desktop\our main folder\avrprojects\avr8-gnu-toolchain-win32_x86_64\bin\avr-gcc
|
||||
OBJCOPY = C:\Users\sharm\Desktop\our main folder\avrprojects\avr8-gnu-toolchain-win32_x86_64\bin\avr-objcopy
|
||||
AVRDUDE = ../avrdude
|
||||
AVRDUDE_PROGRAMMER = arduino
|
||||
AVRDUDE_PORT = COM8
|
||||
AVRDUDE_BAUD = 115200
|
||||
|
||||
CFLAGS = -mmcu=$(MCU) -DF_CPU=$(F_CPU) -Os -Wall
|
||||
|
||||
all: main.hex
|
||||
|
||||
main.elf: main.c delay.h
|
||||
$(CC) $(CFLAGS) main.c -o main.elf
|
||||
|
||||
main.hex: main.elf
|
||||
$(OBJCOPY) -O ihex -R .eeprom main.elf main.hex
|
||||
|
||||
upload: main.hex
|
||||
$(AVRDUDE) -c $(AVRDUDE_PROGRAMMER) -p $(MCU) -P $(AVRDUDE_PORT) -b $(AVRDUDE_BAUD) -D -U flash:w:main.hex:i
|
||||
|
||||
clean:
|
||||
rm -f main.elf main.hex
|
||||
35
LED Blink Input Output/delay.h
Normal file
35
LED Blink Input Output/delay.h
Normal file
@@ -0,0 +1,35 @@
|
||||
#ifndef DELAY_H
|
||||
#define DELAY_H
|
||||
|
||||
#include <avr/io.h>
|
||||
#include <stdint.h>
|
||||
|
||||
// Call this ONCE in main() before using delay_ms()
|
||||
static inline void timer1_init(void) {
|
||||
// Configure Timer1 in CTC mode
|
||||
TCCR1B |= (1 << WGM12);
|
||||
|
||||
// Set compare match for 1ms delay (16MHz / 64 prescaler)
|
||||
OCR1A = 249;
|
||||
|
||||
// Start Timer1 with prescaler 64
|
||||
TCCR1B |= (1 << CS11) | (1 << CS10);
|
||||
|
||||
// Reset timer count
|
||||
TCNT1 = 0;
|
||||
}
|
||||
|
||||
// Delay function assumes timer already initialized
|
||||
static inline void delay_ms(uint16_t ms) {
|
||||
for (uint16_t i = 0; i < ms; i++) {
|
||||
// Clear compare flag
|
||||
TIFR1 |= (1 << OCF1A);
|
||||
|
||||
// Wait for compare match flag
|
||||
while (!(TIFR1 & (1 << OCF1A))) {
|
||||
// Busy wait
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // DELAY_H
|
||||
28
LED Blink Input Output/main.c
Normal file
28
LED Blink Input Output/main.c
Normal file
@@ -0,0 +1,28 @@
|
||||
#include "delay.h"
|
||||
|
||||
int main(void) {
|
||||
// PC2 as output (LED), PC3 as input (button)
|
||||
timer1_init();
|
||||
|
||||
DDRB |= (1<<PB2);
|
||||
DDRB &= ~(1<<PB3);
|
||||
|
||||
// enable internal pull-up on PC3 (important)
|
||||
PORTB |= (1<<PB3);
|
||||
|
||||
timer1_init();
|
||||
|
||||
while(1) {
|
||||
// Button pressed -> pin reads LOW because of pull-up
|
||||
if (PINB & (1<<PB3)) {
|
||||
for (int i=0;i<=20;i++){
|
||||
PORTB |= (1<<PB2); // LED ON
|
||||
delay_ms(200);
|
||||
PORTB &= ~(1<<PB2);
|
||||
delay_ms(200);
|
||||
}
|
||||
} else {
|
||||
PORTB &= ~(1<<PB2); // LED OFF
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user