feat(ex02): full ex02

This commit is contained in:
Maix0 2026-04-13 13:56:47 +02:00
parent 90c358409a
commit bb779a3778
2 changed files with 74 additions and 0 deletions

53
ex02/Makefile Normal file
View file

@ -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

21
ex02/main.c Normal file
View file

@ -0,0 +1,21 @@
#include <avr/io.h>
#include <util/delay.h>
#include <stdbool.h>
#define LED_PORT PORTB0
#define BTN_PORT PIND2
int main(void) {
// set pin to output
DDRB |= (_BV(LED_PORT));
while (true) {
bool cur = (PIND & _BV(BTN_PORT));
if (!cur)
PORTB |= (_BV(LED_PORT));
else
PORTB &= ~(_BV(LED_PORT));
_delay_ms(20.f);
}
}