

安裝
sudo apt install -y gcc-avr avrdude avr-libc
編譯
先寫一個簡單LED閃爍的程式
/* * Version * Author: WildfootW * GitHub: github.com/WildfootW * Copyright (C) 2019 WildfootW All rights reserved. * */ #ifndef F_CPU #define F_CPU 8000000L // or whatever may be your frequency #endif #include <avr/io.h> // adding header files #include <util/delay.h> // for _delay_ms() int main(void) { DDRD=0b11111111; while(1) { PORTD=0b00000001; _delay_ms(1000); PORTD=0b00000000; _delay_ms(1000); } }
編譯個別的檔案
avr-gcc -c \ -std=gnu99 \ -Os \ -Wall \ -ffunction-sections \ -fdata-sections \ -mmcu=atmega328p \ test.c -o test.o
連結成執行檔
avr-gcc -Os \ -mmcu=atmega328p \ -ffunction-sections \ -fdata-sections \ -Wl,--gc-sections \ test.o -o test.elf
燒錄
這次以 Arduino uno 當作燒錄器,用 ISP 的方式燒錄一個獨立的 Atmega328P
上傳 ArduinoISP 到 uno 上

接線

再來就是用 avr-objcopy
把 elf 檔轉成 hex
avr-objcopy -O ihex \ -R .eeprom \ test.elf test.ihex
使用 avrdude 上傳,stk500v1 是指 ArduinoISP(其實不是這樣說,大家自己查吧)
avrdude -p m328p \ -c stk500v1 \ -b 19200 \ -P /dev/ttyACM0 \ -U flash:w:test.ihex:i

Makefile
最後我寫了一個簡易的 Makefile,有興趣的人可以拿去用
# Makefile # Version # Author: WildfootW # GitHub: github.com/WildfootW # Copyright (C) 2019 WildfootW All rights reserved. # compile MCU_compiler=atmega328p COMPILE_CCCFLAGS=-c -std=c99 -Wall -Os -ffunction-sections -fdata-sections -mmcu=${MCU_compiler} -F_CPU=${F_CPU} LINK_CCCFLAGS=-Os -mmcu=${MCU_compiler} -ffunction-sections -fdata-sections -Wl,--gc-sections CCC=avr-gcc F_CPU=1200000 USB_PORT=/dev/ttyACM0 MCU_dude=m328p OBJCOPY=avr-objcopy PROGRAMMER=stk500v1 # ArduinoISP PROGRAMMER_BAUD=19200 # 19200 for ArduinoISP stk500v1 TARGET=main OBJ := test.o all: link flash link: $(OBJ) $(CCC) ${LINK_CCCFLAGS} $^ -o ${TARGET}.elf $(OBJ): %.o: %.c ${CCC} ${COMPILE_CCCFLAGS} $< -o $@ flash: ${OBJCOPY} -O ihex -R .eeprom ${TARGET}.elf ${TARGET}.ihex avrdude -p ${MCU_dude} -c ${PROGRAMMER} -b ${PROGRAMMER_BAUD} -P ${USB_PORT} -U flash:w:${TARGET}.ihex:i clean: rm -f *.o *.ihex *.elf
注意事項
根據 AVR Microcontroller Hardware Design Considerations (AN2591) 第三章 Connection of RESET Pin on AVR Devices 的內容,最好把你的 RESET Pin 加上一些外部電路如下圖,但這會導致一些功能不能用,關於詳細內容還是請大家自己去看文章內容吧
