<30302E20BEC6C6AEB8E120BDBAC6A9B5F0BFC020BFACBDC0B9AEC1A620C7D8B4E42E687770>

Similar documents
<4D F736F F F696E74202D20B8B6C0CCC5A9B7CEC7C1B7CEBCBCBCAD202834C1D6C2F7207E2038C1D6C2F729>

<4D F736F F F696E74202D20B8B6C0CCC5A9B7CEC7C1B7CEBCBCBCAD202834C1D6C2F7207E2038C1D6C2F729>

UART.h #ifndef _UART_H_ #define _UART_H_ #define DIR_TXD #define DIR_RXD sbi(portd,4) cbi(portd,4) #define CPU_CLOCK_HZ UL UART PORT1 void UAR

슬라이드 1

Microsoft PowerPoint - es-arduino-lecture-03

정보보안 개론과 실습:네트워크

ATmega128

인터럽트 * 인터럽트처리메커니즘 ATmega128 인터럽트 2

<4D F736F F F696E74202D20B8B6C0CCC5A9B7CEC7C1B7CEBCBCBCAD202839C1D6C2F7207E203135C1D6C2F >

lecture4(6.범용IO).hwp


<4D F736F F D20BDBAC5D7C7CE20B6F3C0CEC6AEB7B9C0CCBCADB0ADC1C2202D203420C7C1B7CEB1D7B7A1B9D62E646F63>

[8051] 강의자료.PDF

<4D F736F F F696E74202D20BBB7BBB7C7D15F FBEDFB0A3B1B3C0B05FC1A634C0CFC2F72E BC8A3C8AF20B8F0B5E55D>

Motor

K&R2 Reference Manual 번역본

Section 03 인터럽트활성화와인터럽트서비스루틴연결 34/82 장치에대한인터럽트설정과활성화 내부장치에대한특수레지스터존재 장치의특성을반영한동작설정용또는상태관찰용비트로구성 인터럽트사건의발생패턴을설정해야함 인터럽트활성화비트를 1 로셋하여, 인터럽트발생을허락» 전제, 전역

슬라이드 1

<4D F736F F F696E74202D2037C0E55FC0CEC5CDB7B4C6AEC0C720B5BFC0DB2E707074>

2. GCC Assembler와 AVR Assembler의차이 A. GCC Assembler 를사용하는경우 i. Assembly Language Program은.S Extension 을갖는다. ii. C Language Program은.c Extension 을갖는다.

< E20C6DFBFFEBEEE20C0DBBCBAC0BB20C0A7C7D12043BEF0BEEE20492E707074>

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

슬라이드 1

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

Microsoft PowerPoint - 제5장 인터럽트 (HBE-MCU-Multi AVR).ppt [호환 모드]

PowerPoint 프레젠테이션

< 제누이노스타트키트 > 사용설명서 목차 1. Arduino IDE 설치하기 2. Genuino 연결및 Arduino IDE 셋팅하기 3. 센서설명및연결도, 예제소스 1

<4D F736F F F696E74202D2037C0E55FC0CCC0C0C7F55FBFCFBCBA205BC8A3C8AF20B8F0B5E55D>

<4D F736F F D20C0DBC7B0C6ED5FBDBAC5D7C7CE20B6F3C0CEC6AEB7B9C0CCBCAD20B0B3B9DF2E646F63>

PowerPoint 프레젠테이션

인터럽트 (Interrupt) 범용입출력포트에서입출력의내용을처리하기위해매번입출력을요구하는플래그를검사하는일 (Pollong) 에대하여마이크로컨트롤러에게는상당한시간을소비하게만든다. 인터럽트란 CPU가현재처리하고있는일보다급하게처리해야할사건이발생했을때, 현재수행중인일을중단하고

Microsoft PowerPoint - 08-MP-4-interrupt

<4D F736F F F696E74202D20BBB7BBB7C7D15F FBEDFB0A3B1B3C0B05FC1A638C0CFC2F72E BC8A3C8AF20B8F0B5E55D>

<BDC7C7E83520BFB9BAF1BAB8B0EDBCAD2E687770>

PowerPoint 프레젠테이션

C프로-3장c03逞풚

untitled

2주차: 입출력 제어 복습

<322EBCF8C8AF28BFACBDC0B9AEC1A6292E687770>

비트와바이트 비트와바이트 비트 (Bit) : 2진수값하나 (0 또는 1) 를저장할수있는최소메모리공간 1비트 2비트 3비트... n비트 2^1 = 2개 2^2 = 4개 2^3 = 8개... 2^n 개 1 바이트는 8 비트 2 2

(Asynchronous Mode) ( 1, 5~8, 1~2) & (Parity) 1 ; * S erial Port (BIOS INT 14H) - 1 -

PowerPoint 프레젠테이션

untitled

2009년2학기 임베디드시스템 응용

슬라이드 1

1. 기본설정 목차 1-1. 설치해야할프로그램및파일 1-2. 프로그램올리기 1-3. MAKEFILE 2. 캐릭터 LCD(PORT) 3-1. 개요 3-2. 사용하는레지스터 3-3. Source Code 3-4. 실습사진 3. 타이머카운터및초음파센서활용 (PORT, TIM

Microsoft PowerPoint - [2009] 02.pptx


Microsoft PowerPoint - ch07 - 포인터 pm0415

Microsoft PowerPoint - 08-MP-8-ADC

프로그램을 학교 등지에서 조금이라도 배운 사람들을 위한 프로그래밍 노트 입니다. 저 역시 그 사람들 중 하나 입니다. 중고등학교 시절 학교 도서관, 새로 생긴 시립 도서관 등을 다니며 책을 보 고 정리하며 어느정도 독학으르 공부하긴 했지만, 자주 안하다 보면 금방 잊어

Microsoft PowerPoint - polling.pptx

0. 표지에이름과학번을적으시오. (6) 1. 변수 x, y 가 integer type 이라가정하고다음빈칸에 x 와 y 의계산결과값을적으시오. (5) x = (3 + 7) * 6; x = 60 x = (12 + 6) / 2 * 3; x = 27 x = 3 * (8 / 4

Page 2 of 27 Absolute Maximum Ratings - Supply voltage : 3.5V - Operating Temperature Range : -20 ~ 70 - Storage Temperature Range : -40 ~ 85 위조건을넘어서게

DTS-L300-V2 Specification Page 1 of 14 비접촉온도측정 원거리온도측정 High Accuracy Digital Interface : SPI Arduino UNO 예제코드제공 제품설명 DTS-L300-V2는접촉을하지않고원하는물체표면에온도를 50

목차 1. A/D 컨버터개요 2. ATMega128 의 A/D 컨버터기능 3. A/D 컨버터로광센서읽기

02 C h a p t e r Java

OCW_C언어 기초

<4D F736F F F696E74202D20B8B6C0CCC5A9B7CEC7C1B7CEBCBCBCAD202831C1D6C2F72C2032C1D6C2F729>

Microsoft PowerPoint - 3ÀÏ°_º¯¼ö¿Í »ó¼ö.ppt

BMP 파일 처리

슬라이드 1

Microsoft PowerPoint - es-arduino-lecture-09

졸업작품 2 차보고서 Graduation Project 내자전거를지켜줘! 이름학번연락처이메일 이주희 김민선 지도교수 :

Page 2 of 21 Absolute Maximum Ratings Absolute Maximum Rating 값을초과하는조건에서 DTPML을동작시킬경우치명적인손상을 가할수있습니다. Parameter Symbol Conditions min Typ Max Unit Sup

Microsoft PowerPoint - chap03-변수와데이터형.pptx

Microsoft Word doc

ARDUINO Open Physical Computing Platform 오탈자, 문의및보완이필요한내용은 으로알려주세요.

歯7장.PDF

chap7.PDF

adfasdfasfdasfasfadf

Microsoft PowerPoint - 제3장 GPIO 입출력 제어 (HBE-MCU-Multi AVR)

Microsoft Word - FS_ZigBee_Manual_V1.3.docx

C & System

Poison null byte Excuse the ads! We need some help to keep our site up. List 1 Conditions 2 Exploit plan 2.1 chunksize(p)!= prev_size (next_chunk(p) 3

MODBUS SERVO DRIVER( FDA7000 Series ) STANDARD PROTOCOL (Ver 1.00) 1

시리얼통신 (USART) 범용동기및비동기시리얼수신기와송신기 (USART) 는매우유연한시리얼통신장치이다. 주요특징은다음과같다. w 송수신레지스터가독립적으로운용되는전이중방식. w 비동기또는동기동작. w 마스터또는슬레이브동기동작. w 고해상도전송속도생성기. w 5, 6, 7

KEY 디바이스 드라이버

<4D F736F F F696E74202D E6F312D BCB3C4A12C20C4DAB5F920B1E2C3CA2C20BDC3B8AEBEF3C5EBBDC5>

untitled

아두이노로만드는인형뽑기장치

슬라이드 1

Microsoft PowerPoint - chap13-입출력라이브러리.pptx

Chapter. 14 DAC 를이용한 LED 밝기제어 HBE-MCU-Multi AVR Jaeheung, Lee

금오공대 컴퓨터공학전공 강의자료

Raspberry Pi 입출력디바이스 II 1 제 05 강 입출력디바이스 II 터치스위치자석스위치움직임감지센서부저모듈 LED Array RGB LED 릴레이모듈초음파센서 ( 거리측정 ) 적외선센서및리모콘 ( 미작성 )

Arduino- 서보모터 서울과학기술대학교기계시스템디자인공학과 교수김성환

Microsoft PowerPoint - 03_(C_Programming)_(Korean)_Pointers

chap7.key

PowerPoint 프레젠테이션

C++-¿Ïº®Çؼ³10Àå

T100MD+

PowerPoint Presentation

시프트 레지스터 Shift Resistor 자, 이제 LED MATRIX 8x8 Board를 마이크로컨트롤러에 연결된 3개의 선으 로 제어해 보자. 이는 마이크로컨트롤러의 포트를 확장함과 동시에 프로그램 으로 제어를 더 쉽게 한다는 장점이 있다. 물론 포트를 절약하게

목차 포인터의개요 배열과포인터 포인터의구조 실무응용예제 C 2

<4D F736F F F696E74202D B3E22032C7D0B1E220C0A9B5B5BFECB0D4C0D3C7C1B7CEB1D7B7A1B9D620C1A638B0AD202D20C7C1B7B9C0D320BCD3B5B5C0C720C1B6C0FD>

int main(void) int a; int b; a=3; b=a+5; printf("a : %d \n", a); printf("b : %d \n", b); a b 3 a a+5 b &a(12ff60) &b(12ff54) 3 a 8 b printf(" a : %x \

Transcription:

연습문제해답 3-1 ATmega328P-AU는 TQFP 형태의패키지를가지면 32개의핀을가지고있다. 이중 28개핀은 ATmega328P-PU와동일한기능을가지는핀이며추가된 4개중 2개는 VCC와 GND에해당한다. 나머지 2개는 ADC6과 ADC7에해당한다. ADC6과 ADC7은아날로그입력을받을수있는핀으로 MUX에연결되어있지만다른아날로그입력핀 (ADC0 ~ ADC5) 과다르게디지털입출력핀으로는사용할수없다. - 1 -

4-1 ATmega328P는내부발진회로를사용하여 8MHz로동작할수있으므로내부 8MHz를사용하도록설정된경우에는전원만주어지면동작할수있다. 스케치업로드를위한연결커넥터만연결하면스케치업로드장치를통해전원을공급받을수있으므로별도의전원도필요하지않다. 다만, 스케치업로드가완료된이후독립적으로동작하기위해서는전원을준비하여야한다. 4-2 4종류의마이크로컨트롤러는메모리의크기, 부트로더의지원, 그리고인터럽트벡터크기를제외하면거의동일한사용을가지고있다. 한가지주의할점은마이크로컨트롤러에따라고유의값이정해져있으므로단순히마이크로컨트롤러를교체한다고해서동작하지는않는다는점이다. - 2 -

ATmega48 ATmega88 ATmega168 ATmega328 플래시 (KByte) 4 8 16 32 EEPROM (Byte) 256 512 512 1024 RAM (KByte) 0.5 1 1 2 부트로더지원 인터럽트벡터크기 1 instruction word/vector 1 instruction word/vector 2 instruction word/vector 2 instruction word/vector 5-2 1. AVR에서의부트로더는프로그램메모리영역의특정위치에존재하는프로그램이다. 반면컴퓨터에서의부트로더는전용칩에내장되어있다. 2. AVR이부팅될때부트로더는사용하거나사용하지않도록퓨즈를통해설정될수있다. 반면컴퓨터의부트로더는가장먼저실행된다. 3. AVR의부트로더는부팅시다운로드할새로운프로그램의존재여부를검사하여프로그램을다운로드하고설치하기위해사용된다. 반면컴퓨터의부트로더는하드웨어장치를검사하고운영체제가시작될수있도록하드디스크의특정위치 (boot record) 에서실행이시작되도록하기위해사용된다. 9-2 코드 9-2 #define F_CPU 16000000L #include <avr/io.h> #include <util/delay.h> int main(void) char patterns[] = 0x81, 0x42, 0x24, 0x18, 0x24, 0x42; DDRD = 0xFF; while(1) - 3 -

for(int i = 0; i < 6; i++) PORTD = patterns[i]; _delay_ms(1000); return 1; 9-3 코드 9-3 #define F_CPU 16000000L #include <avr/io.h> #include <util/delay.h> int main(void) DDRD = 0xFF; char pattern_previous = 0x00, pattern_current; while(1) for(int i = 0; i < 8; i++) char p1 = 0x01 << i; char p2 = 0x01 << (7 - i); pattern_current = p1 p2; if(pattern_current == pattern_previous) continue; pattern_previous = pattern_current; - 4 -

PORTD = pattern_current; _delay_ms(1000); return 1; 10-1 TTL 레벨은 CPU에서동작하는전압레벨을그대로사용하여통신하는것을말한다. 따라서 CPU 의종류에따라 TTL 레벨은다를수있다. 아두이노우노에사용된 ATmega328의경우 5V를사용하므로 5V를기준으로통신이이루어진다. TTL 레벨은전압이낮아먼거리로전송이어렵다. 따라서 RS232의경우이를증폭하여먼거리로전송이가능하도록만든것이다. RS232는 1969 년미국 EIA(Electric Industries Association) 에의해직렬통신을위한표준인터페이스로정의되었다. RS232는 3V에서 25V사이의전압을논리 1, +3V에서 +25V 사이의전압을논리 0으로나타내는부논리 (negative logic) 를사용하며일반적으로컴퓨터에서는 +13V와 13V로논리 0과논리 1을표현한다. (a) TTL 레벨 - 5 -

(b) RS-232 레벨 10-2 코드 10-2 #define F_CPU 16000000L #include <avr/io.h> #include <util/delay.h> #include <stdio.h> #include "UART.h" void UART_printFloat(float value, int n) int upper; if((int)value == 0) upper = 1; else upper = log10(value) + 1; char str[21]; // 최대 20자리이하로가정 int value_integer = (int)value; for(int i = upper; i > 0; i--) str[i - 1] = (value_integer % 10) + '0'; value_integer /= 10; - 6 -

str[upper] = '\0'; if(n > 0) float value_below = value - (int)value; str[upper] = '.'; for(int i = 0; i < n; i++) str[upper + 1 + i] = (int)(value_below * 10) + '0'; value_below *= 10; value_below -= (int)value_below; str[upper + 1 + n] = '\0'; UART_printString(str); int main(int argc, char *argv[]) float pi = 3.1415927; UART_INIT(); for(int i = 0; i < 8; i++) UART_printFloat(pi, i); UART_printString("\n"); while (1) return 0; 10-3 - 7 -

코드 10-3. C 스타일 #define F_CPU 16000000L #include <avr/io.h> #include <util/delay.h> #include <string.h> #include "UART.h" int main(void) int counter = 100; int index = 0; int process_data = 0; char buffer[20] = ""; char data; UART_INIT(); UART_printString("Current Counter Value : "); UART_print16bitNumber(counter); UART_printString("\n"); while(1) data = UART_receive(); if(data == '\r' data == '\n') buffer[index] = '\0'; process_data = 1; else buffer[index] = data; index++; - 8 -

if(process_data == 1) if(strlen(buffer) == 0) else if(strcasecmp(buffer, "DOWN") == 0) counter--; UART_printString("Current Counter Value : "); UART_print16bitNumber(counter); UART_printString("\n"); else if(strcasecmp(buffer, "UP") == 0) counter++; UART_printString("Current Counter Value : "); UART_print16bitNumber(counter); UART_printString("\n"); else UART_printString("** Unknown Command **"); UART_printString("\n"); index = 0; process_data = 0; 코드 10-3. 아두이노스타일 boolean process_data = false; int counter = 100; String buffer = ""; void setup() Serial.begin(9600); Serial.print("Current Counter Value : "); - 9 -

Serial.println(counter); void loop() if(serial.available()) char data = Serial.read(); if(data == '\r' data == '\n') process_data = true; else buffer = buffer + data; if(process_data) if(buffer.length() == 0) else if(buffer.equalsignorecase("down")) counter--; Serial.print("Current Counter Value : "); Serial.println(counter); else if(buffer.equalsignorecase("up")) counter++; Serial.print("Current Counter Value : "); Serial.println(counter); else Serial.println("** Unknown Command **"); process_data = false; buffer = ""; - 10 -

11-2 코드 11-2. C 스타일 #define F_CPU 16000000UL #include <avr/io.h> #include <util/delay.h> #include "UART.h" void INIT_PORT(void) DDRD &= 0x0F; int main(void) UART_INIT(); INIT_PORT(); while(1) uint8_t data = PIND; for(int i = 7; i > 3; i--) if(bit_is_set(data, i)) UART_printString("O "); else UART_printString("X "); UART_printString("\n"); _delay_ms(1000); 코드 11-2. 아두이노스타일 - 11 -

void setup() for(int i = 4; i <= 7; i++ ) pinmode(i, INPUT); Serial.begin(9600); void loop() for(int i = 7; i >= 4; i--) if(digitalread(i)) Serial.print("O "); else Serial.print("X "); Serial.println(); delay(1000); 11-3 코드 11-3. C 스타일 #define F_CPU 16000000UL #include <avr/io.h> #include <util/delay.h> void INIT_PORT(void) DDRB = 0x20; PORTB = 0x00; - 12 -

int main(void) uint8_t state = 0; INIT_PORT(); while(1) uint8_t data = PIND; if(data & 0x10) state = 1; _delay_ms(50); if(data & 0x20) state = 0; _delay_ms(50); PORTB = (state << 5); 코드 11-3. 아두이노스타일 boolean state = false; void setup() pinmode(13, OUTPUT); digitalwrite(13, state); void loop() if(digitalread(4)) - 13 -

state = true; delay(50); if(digitalread(5)) state = false; delay(50); digitalwrite(13, state); 12-2 코드 12-2. C 스타일 #define F_CPU 16000000L #include <avr/io.h> #include <util/delay.h> void ADC_INIT(unsigned char channel) ADMUX = 0x40; // AVCC 를기준전압으로선택 ADCSRA = 0x07; ADCSRA = (1 << ADEN); ADCSRA = (1 << ADATE); // 분주비설정 // ADC 활성화 // 자동트리거모드 ADMUX = ((ADMUX & 0xE0) channel);// 채널선택 ADCSRA = (1 << ADSC); // 변환시작 int read_adc(void) while(!(adcsra & (1 << ADIF))); // 변환종료대기 - 14 -

return ADC; // 10 비트값을반환 void PORT_INIT(void) DDRD = 0xFF; int main(void) int value; uint8_t on_off; ADC_INIT(0); PORT_INIT(); while(1) value = read_adc() >> 7; on_off = (0x01 << value); PORTD = on_off; 코드 12-2. 아두이노스타일 int LED_pins[] = 0, 1, 2, 3, 4, 5, 6, 7; void setup() for(int i = 0; i < 8; i++) pinmode(led_pins[i], OUTPUT); - 15 -

digitalwrite(led_pins[i], LOW); void loop() int value = analogread(a0) >> 7; for(int i = 0; i < 8; i++) if(i == value) digitalwrite(led_pins[i], HIGH); else digitalwrite(led_pins[i], LOW); 12-3 코드 12-3 void setup() Serial.begin(9600); void loop() int value1 = analogread(a0); delay(20); value1 = analogread(a0); int value2 = analogread(a1); delay(20); value2 = analogread(a1); - 16 -

Serial.println(String(value1) + " : " + value2 + " ==> " + abs(value1 - value2)); delay(1000); 13-1 코드 13-1 #include <avr/io.h> #define F_CPU 16000000UL #include <util/delay.h> #include <avr/interrupt.h> volatile uint8_t state = 0; ISR(INT0_vect) state = (state + 1) % 2; void INIT_PORT(void) DDRB = 0x20; PORTB = 0x00; DDRD = 0x00; PORTD = 0x04; void INIT_INT0(void) EIMSK = (1 << INT0); - 17 -

EICRA = (1 << ISC00); sei(); int main(void) INIT_PORT(); INIT_INT0(); while(1) if(state == 0) PORTB = 0x20; else PORTB = 0x00; 13-2 코드 13-2 #include <avr/io.h> #define F_CPU 16000000UL #include <util/delay.h> #include <avr/interrupt.h> volatile uint8_t state = 0; ISR(INT0_vect) state = (state + 1) % 2; void INIT_PORT(void) - 18 -

DDRB = 0x20; PORTB = 0x00; DDRD = 0x00; PORTD = 0x04; void INIT_INT0(void) EIMSK = (1 << INT0); EICRA = (1 << ISC01); sei(); int main(void) INIT_PORT(); INIT_INT0(); while(1) if(state == 0) PORTB = 0x00; else PORTB = 0x20; 13-3 코드 13-3 volatile byte count = 0; byte count_previous = 0; ISR(PCINT2_vect) - 19 -

count++; void setup() Serial.begin(9600); pinmode(4, INPUT_PULLUP); pinmode(5, INPUT_PULLUP); PCICR = (1 << PCIE2); PCMSK2 = (1 << PCINT20) (1 << PCINT21); void loop() if(count!= count_previous) Serial.println(String("Current Count : ") + count); count_previous = count; 14-2 코드 14-2 #include <avr/io.h> #include <avr/interrupt.h> volatile uint8_t pattern = 1; ISR(TIMER1_COMPA_vect) - 20 -

TCNT1 = 0; pattern = pattern + 1; if(pattern > 6) pattern = 1; int main(void) DDRD = 0xFF; PORTD = 0; TCCR1B = (1 << CS12) (1 << CS10); OCR1A = 0x2000; TIMSK1 = (1 << OCIE1A); sei(); while(1) int LED_count; if(pattern < 5) LED_count = 2 * pattern; else LED_count = (8 - pattern) * 2; uint8_t on_off = 0; for(int i = 0; i < LED_count; i++) on_off = (1 << i); PORTD = on_off; 15-2 - 21 -

코드 15-2 byte interval_array[] = 2000 / 512, 5000 / 512; volatile byte interval = interval_array[0]; byte index = 0; void change_delay() index = (index + 1) % 2; interval = interval_array[index]; void setup() pinmode(11, OUTPUT); pinmode(2, INPUT_PULLUP); attachinterrupt(0, change_delay, FALLING); void loop() for(int i = 0; i < 256; i++) analogwrite(11, i); delay(interval); for(int i = 254; i > 0; i--) analogwrite(11, i); delay(interval); 17-2 코드 17-2 - 22 -

#include <Wire.h> #define RTC_ADDRESS 0x68 int count = 0; uint8_t bcd_to_decimal(uint8_t bcd) return (bcd >> 4) * 10 + (bcd & 0x0F); uint8_t decimal_to_bcd(uint8_t decimal) return ( ((decimal / 10) << 4) (decimal % 10) ); byte bin2bcd(int n) byte val = 0; int ten = n / 10; int one = n % 10; val = (ten << 4) one; return val; void timesetting(int _year, int _month, int _day, int _hour, int _min, int _sec, int _day_of_week) Wire.beginTransmission(RTC_ADDRESS); Wire.write(0); Wire.write(decimal_to_bcd(_sec)); Wire.write(decimal_to_bcd(_min)); Wire.write(decimal_to_bcd(_hour)); Wire.write(decimal_to_bcd(_day_of_week)); Wire.write(decimal_to_bcd(_day)); Wire.write(decimal_to_bcd(_month)); Wire.write(decimal_to_bcd(_year)); - 23 -

Wire.write(0x10); Wire.endTransmission(); void RTCinterrupt() Serial.println("RTC Interrupt " + String(++count)); void setup() Serial.begin(9600); Wire.begin(); attachinterrupt(0, RTCinterrupt, FALLING); // 2014년 9월 1일 12시 34분 56초월요일로초기화 timesetting(14, 9, 1, 12, 34, 56, 2); void loop() 19-1 코드 19-1 #define F_CPU 16000000L #include <avr/io.h> #include <avr/interrupt.h> #define CLOCKS_PER_MICRO ( F_CPU / 1000000L ) #define CLOCKS_TO_MICROSECONDS(a) ( (a) / CLOCKS_PER_MICRO ) #define MICROSECONDS_PER_TIMER0_OVERFLOW ( CLOCKS_TO_MICROSECONDS(64 * 256) ) - 24 -

#define MILLIS_INCREMENT_PER_OVERFLOW ( MICROSECONDS_PER_TIMER0_OVERFLOW / 1000 ) #define MICROS_INCREMENT_PER_OVERFLOW ( MICROSECONDS_PER_TIMER0_OVERFLOW % 1000 ) volatile unsigned long timer0_millis = 0; volatile int timer0_micros = 0; ISR(TIMER0_OVF_vect) unsigned long m = timer0_millis; int f = timer0_micros; m += MILLIS_INCREMENT_PER_OVERFLOW; f += MICROS_INCREMENT_PER_OVERFLOW; int micro_to_millis = f / 1000; m += micro_to_millis; f = f % 1000; timer0_millis = m; timer0_micros = f; unsigned long millis() unsigned long m; uint8_t oldsreg = SREG; cli(); m = timer0_millis; SREG = oldsreg; return m; - 25 -

int main(void) uint8_t numbers[] = 0xFC, 0x60, 0xDA, 0xF2, 0x66, 0xB6, 0xBE, 0xE4, 0xFE, 0xE6; int count = 0; DDRD = 0xFF; PORTD = numbers[0]; TCCR0B = (1 << CS01) (1 << CS00); TIMSK0 = (1 << TOIE0); sei(); unsigned long time_previous, time_current; time_previous = millis(); while(1) time_current = millis(); if((time_current - time_previous) > 1000) time_previous = time_current; count = count - 1; if(count < 0) count = 9; PORTD = numbers[count]; return 1; 19-2 - 26 -

코드 19-2 #define F_CPU 16000000L #include <avr/io.h> #include <avr/interrupt.h> #define CLOCKS_PER_MICRO ( F_CPU / 1000000L ) #define CLOCKS_TO_MICROSECONDS(a) ( (a) / CLOCKS_PER_MICRO ) #define MICROSECONDS_PER_TIMER0_OVERFLOW ( CLOCKS_TO_MICROSECONDS(64 * 256) ) #define MILLIS_INCREMENT_PER_OVERFLOW ( MICROSECONDS_PER_TIMER0_OVERFLOW / 1000 ) #define MICROS_INCREMENT_PER_OVERFLOW ( MICROSECONDS_PER_TIMER0_OVERFLOW % 1000 ) volatile unsigned long timer0_millis = 0; volatile int timer0_micros = 0; ISR(TIMER0_OVF_vect) unsigned long m = timer0_millis; int f = timer0_micros; m += MILLIS_INCREMENT_PER_OVERFLOW; f += MICROS_INCREMENT_PER_OVERFLOW; int micro_to_millis = f / 1000; m += micro_to_millis; f = f % 1000; timer0_millis = m; timer0_micros = f; unsigned long millis() - 27 -

unsigned long m; uint8_t oldsreg = SREG; cli(); m = timer0_millis; SREG = oldsreg; return m; int main(void) uint8_t numbers[] = 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02; int count = 0; DDRD = 0xFF; PORTD = numbers[0]; TCCR0B = (1 << CS01) (1 << CS00); TIMSK0 = (1 << TOIE0); sei(); unsigned long time_previous, time_current; time_previous = millis(); while(1) time_current = millis(); if((time_current - time_previous) > 200) time_previous = time_current; count = (count + 1) % 6; PORTD = numbers[count]; - 28 -

return 1; 19-3 코드 19-3 int segment_pins[] = 0, 1, 2, 3, 4, 5, 6, 7; uint8_t numbers[] = 0xFC, 0x60, 0xDA, 0xF2, 0x66, 0xB6, 0xBE, 0xE4, 0xFE, 0xE6; unsigned long time_previous, time_current; int button_pin = 8; int count = 0; boolean go_on = true; void setup() for(int i = 0; i < 8; i++) pinmode(segment_pins[i], OUTPUT); pinmode(button_pin, INPUT_PULLUP); time_previous = millis(); void loop() time_current = millis(); if(go_on) if(time_current - time_previous > 1000) - 29 -

time_previous = time_current; for(int i = 0; i < 8; i++) boolean on_off = bitread(numbers[count], i); digitalwrite(segment_pins[i], on_off); count = (count + 1) % 10; else time_previous = time_current; if(!digitalread(button_pin)) go_on =!go_on; delay(100); 20-1 코드 20-1 int rows[] = 2, 3, 4, 5, 6, 7, 8, 9; int cols[] = 10, 11, 12, 13, A0, A1, A2, A3; unsigned long time_previous, time_current; int start_index = 0; byte smile[] = 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, - 30 -

0b00000000, 0b00000000, 0b00111100, 0b01000010, 0b10101001, 0b10000101, 0b10000101, 0b10101001, 0b01000010, 0b00111100, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000 ; void setup() for(int i = 0; i < 8; i++) pinmode(rows[i], OUTPUT); pinmode(cols[i], OUTPUT); time_previous = millis(); void loop() time_current = millis(); if(time_current - time_previous > 500) time_previous = time_current; start_index = (start_index + 1) % 16; for(int i = 0; i < 8; i++) for(int j = 0; j < 8; j++) digitalwrite(rows[j], LOW); - 31 -

byte col_data = ~(1 << i); for(int j = 0; j < 8; j++) digitalwrite(cols[j], (col_data >> j) & 0x01); for(int j = 0; j < 8; j++) digitalwrite(rows[j], (smile[start_index + i] >> (7 - j)) & 0x01); delay(2); 20-2 코드 20-2 int rows[] = 2, 3, 4, 5, 6, 7, 8, 9; int cols[] = 10, 11, 12, 13, A0, A1, A2, A3; unsigned long time_previous, time_current; int index = 0; byte patterns[10][8] = 0x00, 0x7e, 0x81, 0x81, 0x81, 0x81, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x40, 0xff, 0x00, 0x00, 0x00, 0x00, 0x41, 0x83, 0x85, 0x89, 0x91, 0x61, 0x00, 0x00, 0x42, 0x81, 0x91, 0x91, 0x91, 0x6e, 0x00, 0x00, 0x18, 0x28, 0x48, 0x88, 0xff, 0x08, 0x00, 0x00, 0xf1, 0x91, 0x91, 0x91, 0x91, 0x8e, 0x00, 0x00, 0x7e, 0x91, 0x91, 0x91, 0x91, 0x4e, 0x00, 0x00, 0x81, 0x82, 0x84, 0x88, 0x90, 0xe0, 0x00, 0x00, 0x6e, 0x91, 0x91, 0x91, 0x91, 0x6e, 0x00, 0x00, 0x60, 0x91, 0x92, 0x94, 0x98, 0x60, 0x00 ; - 32 -

void setup() for(int i = 0; i < 8; i++) pinmode(rows[i], OUTPUT); pinmode(cols[i], OUTPUT); time_previous = millis(); void loop() time_current = millis(); if(time_current - time_previous > 500) time_previous = time_current; index = (index + 1) % 10; for(int i = 0; i < 8; i++) for(int j = 0; j < 8; j++) digitalwrite(rows[j], LOW); byte col_data = ~(1 << i); for(int j = 0; j < 8; j++) digitalwrite(cols[j], (col_data >> j) & 0x01); for(int j = 0; j < 8; j++) digitalwrite(rows[j], (patterns[index][i] >> (7 - j)) & 0x01); delay(2); 22-1 코드 22-1 - 33 -

const byte ROWS = 2; const byte COLS = 2; char keys[rows][cols] = '1', '2', '3', '4' ; byte rowpins[rows] = 2, 3; byte colpins[cols] = 6, 7; byte pattern[rows][cols]; void setup() for(int i = 0; i < ROWS; i++) pinmode(rowpins[i], INPUT); for(int i = 0; i < COLS; i++) pinmode(colpins[i], OUTPUT); digitalwrite(colpins[i], LOW); Serial.begin(9600); void loop() int row, col, count = 0; for(col = 0; col < COLS; col++) digitalwrite(colpins[col], HIGH); for(row = 0; row < ROWS; row++) pattern[row][col] = digitalread(rowpins[row]); count += pattern[row][col]; digitalwrite(colpins[col], LOW); - 34 -

if(count > 0) for(row = 0; row < ROWS; row++) for(col = 0; col < COLS; col++) if(pattern[row][col]) Serial.write(keys[row][col]); else Serial.write('.'); Serial.write(" "); Serial.write('\n'); Serial.write('\n'); delay(1000); 23-2 코드 23-2 #include <Servo.h> #define ROTATION_DELAY 1000 String buffer = ""; boolean rotateit = false; Servo microservo; int servopin = 9; void setup() Serial.begin(9600); microservo.attach(servopin); - 35 -

void loop() if(serial.available()) char data = Serial.read(); if(data == '\n') rotateit = true; else buffer += data; if(rotateit) rotateit = false; int angle = buffer.toint(); microservo.write(angle); delay(rotation_delay); buffer = ""; 24-1 코드 24-1. C 스타일 #define F_CPU 16000000UL #include <avr/io.h> #include <util/delay.h> uint8_t numbers[] = 0xFC, 0x60, 0xDA, 0xF2, 0x66, 0xB6, 0xBE, 0xE4, 0xFE, 0xE6; void Init_74595(void) DDRB = 0b00111000; - 36 -

void ShiftClock(void) PORTB = 0b00100000; PORTB &= 0b11011111; void LatchClock(void) PORTB = 0b00010000; PORTB &= 0b11101111; void ByteDataWrite(uint8_t data) for(uint8_t i = 0; i < 8; i++) if(data & 0b10000000) PORTB = 0b00001000; else PORTB &= 0b11110111; ShiftClock(); data = data << 1; LatchClock(); int main(void) uint8_t index = 0; Init_74595(); while(1) index = (index + 1) % 10; - 37 -

ByteDataWrite(numbers[index]); _delay_ms(1000); 코드 24-1. 아두이노스타일 int datapin = 11; int latchclockpin = 12; int shiftclockpin = 13; uint8_t numbers[] = 0xFC, 0x60, 0xDA, 0xF2, 0x66, 0xB6, 0xBE, 0xE4, 0xFE, 0xE6; int index = 0; void setup() pinmode(datapin, OUTPUT); pinmode(shiftclockpin, OUTPUT); pinmode(latchclockpin, OUTPUT); void loop() index = (index + 1) % 10; shiftout(datapin, shiftclockpin, MSBFIRST, numbers[index]); digitalwrite(latchclockpin, HIGH); digitalwrite(latchclockpin, LOW); delay(1000); - 38 -

24-2 코드 24-2 #define SEGMENT_DELAY 5 int datapin = 11; int latchclockpin = 12; int shiftclockpin = 13; int digit_pins[] = 2, 3, 4, 5; uint8_t numbers[] = 0xFC, 0x60, 0xDA, 0xF2, 0x66, 0xB6, 0xBE, 0xE4, 0xFE, 0xE6; unsigned long time_previous, time_current; int count = 1000; void setup() pinmode(datapin, OUTPUT); pinmode(shiftclockpin, OUTPUT); pinmode(latchclockpin, OUTPUT); for(int i = 0; i < 4; i++) pinmode(digit_pins[i], OUTPUT); digitalwrite(digit_pins[i], HIGH); time_previous = millis(); void show_digit(int position, int number) for(int i = 0; i < 4; i++) if(i + 1 == position) digitalwrite(digit_pins[i], LOW); else digitalwrite(digit_pins[i], HIGH); shiftout(datapin, shiftclockpin, MSBFIRST, numbers[number]); - 39 -

digitalwrite(latchclockpin, HIGH); digitalwrite(latchclockpin, LOW); delay(segment_delay); void loop() int thousands, hundreds, tens, ones; thousands = count / 1000; hundreds = count / 100 % 10; tens = count / 10 % 10; ones = count % 10; show_digit(1, thousands); show_digit(2, hundreds); show_digit(3, tens); show_digit(4, ones); time_current = millis(); if(time_current - time_previous > 100) time_previous = time_current; count++; if(count == 10000) count = 1000; 25-1 코드 25-1 int temp_pin = A1; int input_value; - 40 -

float input_voltage; float temperature; int LED_pins[] = 4, 5, 6, 7; void setup() for(int i = 0; i < 4; i++) pinmode(led_pins[i], OUTPUT); digitalwrite(led_pins[i], LOW); Serial.begin(9600); void loop() input_value = analogread(temp_pin); input_voltage = 5.0 * input_value / 1023.0; temperature = (input_voltage - 0.5) * 100.0; Serial.println(temperature); int LEDcount = map(temperature, 20, 30, 1, 4); if(ledcount < 1) LEDcount = 1; if(ledcount > 4) LEDcount = 4; for(int i = 0; i < 4; i++) if(i < LEDcount) digitalwrite(led_pins[i], HIGH); else digitalwrite(led_pins[i], LOW); delay(1000); 25-2 - 41 -

코드 25-2 int temp_pin = A1; int input_value; float input_voltage; float temperature; int LED_pins[] = 4, 5, 6, 7; boolean hightemperature = false; boolean LEDstate = false; unsigned long time_previous1, time_current1, time_previous2, time_current2; float THRESHOLD = 27.0; void setup() for(int i = 0; i < 4; i++) pinmode(led_pins[i], OUTPUT); digitalwrite(led_pins[i], LOW); Serial.begin(9600); time_previous1 = millis(); time_previous2 = time_previous1; void loop() time_current1 = millis(); time_current2 = time_current1; input_value = analogread(temp_pin); input_voltage = 5.0 * input_value / 1023.0; temperature = (input_voltage - 0.5) * 100.0; if(temperature >= THRESHOLD) hightemperature = true; else hightemperature = false; if(hightemperature) - 42 -

if(time_current2 - time_previous2 > 500) time_previous2 = time_current2; LEDstate =!LEDstate; for(int i = 0; i < 4; i++) digitalwrite(led_pins[i], LEDstate); else for(int i = 0; i < 4; i++) digitalwrite(led_pins[i], LOW); if(time_current1 - time_previous1 > 1000) time_previous1 = time_current1; Serial.println(temperature); 25-3 코드 25-3 int distance; int triggerpin = A0; int echopin = A1; int LED_pins[] = 4, 5, 6, 7; unsigned long time_previous, time_current, time_previous1, time_current1; boolean objectclose = false; boolean LEDstate = false; void setup() for(int i = 0; i < 4; i++) pinmode(led_pins[i], OUTPUT); - 43 -

digitalwrite(led_pins[i], LOW); Serial.begin(9600); pinmode(triggerpin, OUTPUT); pinmode(echopin, INPUT); time_previous = millis(); time_previous1 = time_previous; void loop() time_current = millis(); time_current1 = time_current; digitalwrite(triggerpin, HIGH); delaymicroseconds(10); digitalwrite(triggerpin, LOW); distance = pulsein(echopin, HIGH) / 58; if(time_current1 - time_previous1 > 1000) time_previous1 = time_current1; Serial.println("Distance(cm) = " + String(distance)); if(distance <= 20) objectclose = true; else objectclose = false; if(objectclose) if(time_current - time_previous > 500) time_previous = time_current; LEDstate =!LEDstate; for(int i = 0; i < 4; i++) digitalwrite(led_pins[i], LEDstate); - 44 -

else for(int i = 0; i < 4; i++) digitalwrite(led_pins[i], LOW); 26-2 코드 26-2 #define F_CPU 16000000L #include <avr/io.h> #include <util/delay.h> #include "UART.h" int main(void) uint8_t data; UART_INIT(); DDRB = 0x20; PORTB = 0x00; while(1) data = UART_receive(); // 데이터수신 if(data == '0') PORTB = 0x00; else if(data == '1') PORTB = 0x20; - 45 -

26-3 코드 26-3 char buffer[5] = ""; int index = 0; boolean process = false; int LED_pins[] = 4, 5, 6, 7; void setup() Serial.begin(9600); for(int i = 0; i < 4; i++) pinmode(led_pins[i], OUTPUT); digitalwrite(led_pins[i], LOW); void loop() if(serial.available()) byte data = Serial.read(); if(data == '1' data == '0') buffer[index++] = data; if(index == 4) index = 0; process = true; if(process) process = false; for(int i = 0; i < 4; i++) if(buffer[i] == '0') digitalwrite(led_pins[i], LOW); else if(buffer[i] == '1') digitalwrite(led_pins[i], HIGH); - 46 -

27-2 코드 27-2 #include <avr/io.h> #include <avr/eeprom.h> #include "UART.h" void eeprom_write_int(int address, int value) eeprom_update_byte((uint8_t*)address, (uint8_t)((value & 0xFF00) >> 8)); eeprom_update_byte((uint8_t*)(address + 1), (uint8_t)(value & 0x00FF)); int eeprom_read_int(int address) uint8_t upper = eeprom_read_byte((uint8_t*)address); uint8_t lower = eeprom_read_byte((uint8_t*)(address + 1)); return ((upper << 8) + lower); int main(void) int data = 1023; int address = 0; UART_INIT(); - 47 -

eeprom_write_int(address, data); int readdata = eeprom_read_int(address); UART_print16bitNumber(readData); while(1); return 0; 29-1 하이퓨즈로퓨즈확장퓨즈 16MHz 0xDE 0xFF 0x05 8MHz 0xDE 0xE2 0x05 8MHz 클록을사용하는경우변경되는값은로퓨즈값이다. 내부 8MHz 클록사용을위한 CKSEL 값은 0010 이며이에따른가장긴초기구동시간은 SUT 값이 10인경우이다. 비트이름비트설명 16MHz 8MHz 번호클록을내부적으로 1 1 CKDIV8 7 8로나눔 ( 클록을낮추지않음 ) ( 클록을낮추지않음 ) 클록을포트 B의 0번 CKOUT 6 1 1 핀으로출력 SUT1 5 1 1 초기구동시간 SUT0 4 1 0 CKSEL3 3 1 0 CKSEL2 2 1 0 클록소스 CKSEL1 1 1 1 CKSEL0 0 1 0-48 -