# apt-get install gcc-avr # apt-get install binutils-avr # apt-get install avr-libc # apt-get install avrdude |
LED点滅プログラムについて
ATmega168/328マイコンボード回路図を見るとマイコンのPB5端子の先にLEDが接続されています。PB5にHを出力すればLEDが点灯します。このLEDを点滅するプログラムを書いてみます。
リスト1 blink_LED.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | /* * LED 点滅プログラム * * K-04590 (ATMEGA168/328用マイコンボード) * */ #include <avr/io.h> #include <util/delay.h> #define PB5_LED 5 // H: LED ON | L: LED OFF int main( void ) { DDRB = _BV(PB5_LED); // Port B bit 5の方向を出力に設定 PORTB |= _BV(PB5_LED); // Port B bit 5にHを出力(LED点灯) while (1) { _delay_ms(500); // 0.5秒待つ PORTB ^= _BV(PB5_LED); // Port B bit5を0/1反転 } } |
F_CPUについて
_delay_ms()を使うには事前にマクロ"F_CPU"を定義しておく必要があります。F_CPUにはCPUのクロック周波数を設定します。ソースコードの中に書いても良いのですが、ここではMakefileの中に定義しました。マイコンのクロック周波数は1MHzです。これは工場出荷時はクロックソースとしてマイコン内蔵オシレータ(8MHz)が選択されており、さらにCKDIV8オプションが設定されているため、1MHz(=8MHz÷8)になっているためです。したがってF_CPU=1000000を設定します。
リスト2 Makefile
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | PROG=blink_LED OBJS=${PROG}.o MCU=atmega168p F_CPU=1000000UL # internal 8MHz clock & CKDIV8 fuse bit enabled #-------- ELF=$(PROG) IHEX=$(PROG).ihex CC=avr-gcc CFLAGS=-g2 -O1 -mmcu=$(MCU) -DF_CPU=$(F_CPU) -Wall LDFLAGS=-g2 -mmcu=$(MCU) OBJCOPY=avr-objcopy all: $(IHEX) $(IHEX): $(ELF) $(ELF): $(OBJS) %.ihex: % $(OBJCOPY) -j .text -j .data -O ihex $< $@ clean: -$(RM) $(ELF) $(IHEX) $(OBJS) flash: sudo avrdude -c avrispmkII -P usb -p atmega168p -U flash:w:$(IHEX) .PHONY: all clean |
リスト3 コンパイル&マイコン書き込み
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | $ make avr-gcc -g2 -O1 -mmcu=atmega168p -DF_CPU=1000000UL -Wall -c -o blink_LED.o blink_LED.c avr-gcc -g2 -mmcu=atmega168p blink_LED.o -o blink_LED avr-objcopy -j .text -j .data -O ihex blink_LED blink_LED.ihex $ make flash sudo avrdude -c avrispmkII -P usb -p atmega168p -U flash:w:blink_LED.ihex avrdude: AVR device initialized and ready to accept instructions Reading | ################################################## | 100% 0.01s avrdude: Device signature = 0x1e940b avrdude: NOTE: FLASH memory has been specified, an erase cycle will be performed To disable this feature, specify the -D option. avrdude: erasing chip avrdude: reading input file "blink_LED.ihex" avrdude: input file blink_LED.ihex auto detected as Intel Hex avrdude: writing flash (166 bytes): Writing | ################################################## | 100% 0.05s avrdude: 166 bytes of flash written avrdude: verifying flash memory against blink_LED.ihex: avrdude: load data flash data from input file blink_LED.ihex: avrdude: input file blink_LED.ihex auto detected as Intel Hex avrdude: input file blink_LED.ihex contains 166 bytes avrdude: reading on-chip flash data: Reading | ################################################## | 100% 0.05s avrdude: verifying ... avrdude: 166 bytes of flash verified avrdude: safemode: Fuses OK avrdude done. Thank you. $ |
0 件のコメント:
コメントを投稿