diff --git a/module01/ex01/Makefile b/module01/ex01/Makefile new file mode 100644 index 0000000..56b54a5 --- /dev/null +++ b/module01/ex01/Makefile @@ -0,0 +1,43 @@ +# frequency of the CPU (in Hz) +F_CPU = 16000000UL +TARGET = main +CC = avr-gcc + +AVRGCC_MCU_TYPE = atmega328p +AVRDUDE_MCU_TYPE = m328p +BAUD_RATE = 115200 +SERIAL_PORT = /dev/ttyUSB0 +PROGRAMMER_ID = arduino +DUMP_ORI = ../../ressources/dump_atmega328p_ori.hex + + +all: hex flash + + +hex: $(TARGET).hex + + +# https://gcc.gnu.org/onlinedocs/gcc/AVR-Options.html +$(TARGET).bin: $(TARGET).c + $(CC) -mmcu=$(AVRGCC_MCU_TYPE) -D F_CPU=$(F_CPU) $(TARGET).c -Os -o $(TARGET).bin + + +# https://linux.die.net/man/1/avr-objcopy +$(TARGET).hex: $(TARGET).bin + avr-objcopy -O ihex $(TARGET).bin $(TARGET).hex + + +# AVR Downloader/UploaDEr https://avrdudes.github.io/avrdude (v6.3 https://download-mirror.savannah.gnu.org/releases/avrdude/avrdude-doc-6.3.pdf) +flash: + avrdude -p $(AVRDUDE_MCU_TYPE) -c $(PROGRAMMER_ID) -b $(BAUD_RATE) -P $(SERIAL_PORT) -U flash:w:$(TARGET).hex + + +restore: + avrdude -p $(AVRDUDE_MCU_TYPE) -c $(PROGRAMMER_ID) -b $(BAUD_RATE) -P $(SERIAL_PORT) -U flash:w:$(DUMP_ORI) + + +clean: + rm -f main.hex main.bin + + +.PHONY : all clean hex flash restore \ No newline at end of file diff --git a/module01/ex01/main.c b/module01/ex01/main.c new file mode 100644 index 0000000..8fa7bad --- /dev/null +++ b/module01/ex01/main.c @@ -0,0 +1,57 @@ +#include +#include + +// #define FIRST_LETTER_IMPL(x) #x[0] +// #define FIRST_LETTER(x) FIRST_LETTER_IMPL(x) +// #define PORT_LETTER(PIN) FIRST_LETTER(PIN) + +// global registers +#define SET(register, bit) register |= 1 << bit +#define CLEAR(register, bit) register &= ~(1 << bit) +#define TEST(register, bit) register & 1 << bit +#define TOGGLE(register, bit) register ^= 1 << bit + +// actions on ports +#define TEST_PIN(port, bit) TEST(PIN ## port, bit) +#define TOGGLE_PIN(port, bit) SET(PIN ## port, bit) +#define MODE_INPUT(port, bit) CLEAR(DDR ## port, bit) +#define MODE_OUTPUT(port, bit) SET(DDR ## port, bit) +#define IS_PIN_SET(port, bit) (TEST_PIN(port, bit)) == 0 +#define IS_PIN_CLEAR(port, bit) (TEST_PIN(port, bit)) == 1 +#define TURN_ON(_PORT, BIT) SET(PORT ## _PORT, BIT) +#define TURN_OFF(_PORT, BIT) CLEAR(PORT ## _PORT, BIT) + +// LEDs +#define TURN_ON_LED(bit) SET(PORTB, bit) +#define TURN_OFF_LED(bit) CLEAR(PORTB, bit) +#define TOGGLE_LED(led) TOGGLE_PIN(B, led) + + +#define D1 0 +#define D2 1 +#define D3 2 +#define D4 4 +#define SW1 2 +#define SW2 4 + +#define PRESCALE_VALUE 1024 +#define TIME(ms) (((F_CPU / PRESCALE_VALUE) * ms) / 1000) + +int main() { + MODE_OUTPUT(B, D2); + TURN_OFF_LED(D2); + + TCCR1B |= ((1 << CS10 ) | (1 << CS12 ) ); // set timer with prescale + + while(1) { + if ( TCNT1 >= TIME(500)) { + TOGGLE_LED(D2); + TCNT1 = 0; // reset timer value + } + } +} + + + + +