From 8b8e8e083d53c90ea07c6875bc40aea8794eaeac Mon Sep 17 00:00:00 2001 From: Maix0 <39835848+Maix0@users.noreply.github.com> Date: Mon, 13 Apr 2026 15:10:20 +0200 Subject: [PATCH] feat(ex04): full ex04 --- ex04/Makefile | 53 +++++++++++++++++++++++++++++++++++++++++++++++++ ex04/main.c | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 108 insertions(+) create mode 100644 ex04/Makefile create mode 100644 ex04/main.c diff --git a/ex04/Makefile b/ex04/Makefile new file mode 100644 index 0000000..d0f7e1f --- /dev/null +++ b/ex04/Makefile @@ -0,0 +1,53 @@ +AVR_LIBC_DIR=/tmp/avr-libc + +# Makefile +MCU=atmega328p +F_CPU=16000000 +CC=avr-gcc +OBJCOPY=avr-objcopy +CFLAGS=-nostdlib -std=c99 -Wall -Wextra -g -Os -mmcu=$(MCU) -DF_CPU=$(F_CPU) -I. -I$(AVR_LIBC_DIR)/include +TARGET=main +SERIAL=-P /dev/ttyUSB0 -b 115200 + + +SRC_DIR=. +OBJ_DIR=build + +SRC_FILES=main.c +OBJ_FILES=$(patsubst %.c,%.o,$(SRC_FILES)) + +SRC=$(addprefix $(SRC_DIR)/,$(SRC_FILES)) +OBJ=$(addprefix $(OBJ_DIR)/,$(OBJ_FILES)) + +all: flash + +re: fclean all + +fclean: clean +clean: + rm -rf $(OBJ_DIR) + rm -f $(TARGET).hex + +hex: $(TARGET).hex + +flash: hex + avrdude -p $(MCU) -c arduino -U flash:w:$(TARGET).hex:i $(SERIAL) + +$(OBJ_DIR)/$(TARGET).bin: $(OBJ) + $(CC) $(CFLAGS) $(OBJ) -o $@ + +$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c $(AVR_LIBC_DIR)/.CACHETAG + mkdir -p $(shell dirname $@) + $(CC) $(CFLAGS) -c $< -o $@ + + +$(TARGET).hex: $(OBJ_DIR)/$(TARGET).bin + $(OBJCOPY) -j .text -j .data -O ihex $< $@ + +$(AVR_LIBC_DIR)/.CACHETAG: + rm -rf $(AVR_LIBC_DIR) + git clone --depth=1 https://github.com/avrdudes/avr-libc/ $(AVR_LIBC_DIR) + cd $(AVR_LIBC_DIR) && ./bootstrap + cd $(AVR_LIBC_DIR) && ./configure --build=`./config.guess` --host=avr + cd $(AVR_LIBC_DIR) && make -j + touch $(AVR_LIBC_DIR)/.CACHETAG diff --git a/ex04/main.c b/ex04/main.c new file mode 100644 index 0000000..2ab4dd0 --- /dev/null +++ b/ex04/main.c @@ -0,0 +1,55 @@ +#include +#include +#include + +#include + +#define D1 PB0 +#define D2 PB1 +#define D3 PB2 +#define D4 PB4 + +#define SW1 PD2 +#define SW2 PD4 + +int main(void) { + DDRB |= _BV(D4); + DDRB |= _BV(D3); + DDRB |= _BV(D2); + DDRB |= _BV(D1); + + DDRD &= ~(_BV(SW1)); + DDRD &= ~(_BV(SW2)); + + PORTB |= _BV(D4); + + uint8_t prev = 0; + uint8_t value = 0; + while (true) { + uint8_t cur = (PIND & (_BV(SW1) | _BV(SW2))); + if (prev & (_BV(SW1)) && !(cur & (_BV(SW1)))) { + value++; + } + if (prev & (_BV(SW2)) && !(cur & (_BV(SW2)))) { + value--; + } + prev = cur; + if (value & 0b0001) + PORTB |= (_BV(D1)); + else + PORTB &= ~(_BV(D1)); + if (value & 0b0010) + PORTB |= (_BV(D2)); + else + PORTB &= ~(_BV(D2)); + if (value & 0b0100) + PORTB |= (_BV(D3)); + else + PORTB &= ~(_BV(D3)); + if (value & 0b1000) + PORTB |= (_BV(D4)); + else + PORTB &= ~(_BV(D4)); + _delay_ms(20); + } +}