feat(ex04): full ex04

This commit is contained in:
Maix0 2026-04-13 15:10:20 +02:00
parent cd8984fa29
commit 8b8e8e083d
2 changed files with 108 additions and 0 deletions

53
ex04/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

55
ex04/main.c Normal file
View file

@ -0,0 +1,55 @@
#include <avr/io.h>
#include <stdint.h>
#include <util/delay.h>
#include <stdbool.h>
#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);
}
}