슬라이드 1

Save this PDF as:
 WORD  PNG  TXT  JPG

Size: px
Start display at page:

Download "슬라이드 1"

Transcription

1 임베디드시스템개론 : AVR MCU & Arduino 활용 Lecture #09: 시리얼통신 (Serial Comm.)

2 강의목차 시러얼통신개요 I2C 통신개요 I2C 통신실험 I2C Text LCD DS1307 / DS1302 RTC 2

3 3 1. Serial Communication

4 아두이노통신 아두이노통신개요 아두이노 MCU 와 on-board 장치또는외부연결장치간의통신 통신프로토콜에따른데이터송수신을위해개별적인통신장치 ( 모듈 ) 을사용 외부와의통신을위해별도의통신장치가필요 MCU 내장또는외부확장통신장치등 통신모듈의지원여부에따른분류 : MCU 내장통신장치 ( 모듈 ) - I2C, SPI, UART 외부통신장치 ( 모듈 ) - USB, Ethernet, Wifi, Zigbee, Bluetooth, IR 등 4

5 시리얼통신 (1) 시리얼통신개요 장치간에비트단위로데이터를전송하는통신 비동기 (Asynchronous) & 동기 (Synchronous) 통신방식존재시리얼통신프로토콜 I2C(Inter-Integrated Circuit) SPI(Serial Peripheral Interface) UART(Universal Asynchronous Receive-Transmit) 5

6 시리얼통신 (2) 시리얼통신개요 : 비동기및동기전송비교 Asynchronous No Clock 정해진시간에맞추어전송신호를 HIGH/LOW 로설정하여데이터를표현 발신과수신을위해별도의선을사용 단지두개의장치간에통신하고자하고상호전송속도를같게설정되어있을때에유용 Synchronous With Clock clock 변화에맞추어전송신호를 HIGH/LOW 로설정하여데이터를표현 Clock 신호와전송방향별로별도의선을사용 일반적으로빠른전송속도가필요할때에유용 6

7 시리얼통신 (3) 시리얼통신개요 : 비동기및동기전송비교 7

8 8 2. UART(Universal Asynchronous Receiver/Transmitter)

9 UART (1) UART(Universal Asynchronous Receiver Transmitter) 대표적인비동기시리얼통신규약 정해진통신속도 (baud rate) 에맞추어병렬데이터를비트단위로직렬전송하고, 수신된직렬데이터를병렬데이터를변환하는기능을지원 기본적으로 Tx(Transmitter)/Rx(Receiver) 2 개의통신라인을사용 필요에따라 handshake 라인 (DTS/DTR) 을사용하기도함 별도의동기화메커니즘을사용하지않으므로통신하기전에송수신측에서동일한통신파라미터를설정하여야함. 통신속도 (Baud Rate) 9600~ bsp Start bit 0, 1, 2 Data bit 7, 8 Stop bit 0, 1 Parity bit none, odd, even 9

10 UART (2) 아두이노 UART Arduino Mega MCU(Atmega-2560) 에서는최대 4 개의 UART 장치를지원 Serial(pin0/pin1), Serial1(pin19/pin18), Serial2(pin17/pin16), Serial3(pin15/pin14) Arduino library 에서 UART 통신을위한 API 지원 Serial 내장객체 (Serial, Serial1, Serial2, Serial3) 통신메소드 begin(), end(), available(), read(), peek(), flush(), print(), println(), write(), SerialEvent() 참조 : 10

11 UART (3) RS-232 표준 (1) 비동기직렬통신에필요한전기적인신호특성 ( 전압, 타이밍등 ) 과기계적특성 ( 커넥터모양, 핀배치 ) 등모든사양을규정 미국 Electronic Industries Association (EIA) 에서정한표준 주로 PC 및통신장비의콘솔통신을위해사용하는직렬포트용 DB-9 커넥터의모양및핀배치표준도규정 송신신호 (TxD) 와수신신호 (RxD) 이외에도다른용도의여러신호들도정의함 데이터흐름제어 (flow control) 나반송파검출 (carrier detection) 등의다른기능은사용하지않고순수하게통신만하겠다면 TxD 와 RxD 두신호로충분 11

12 UART (4) RS-232 표준 (2) UART 장치가있으면비동기통신이가능하지만 UART 의송수신핀을 PC 의직렬포트 (RS-232 포트 ) 에바로연결할수는없다. RS-232 표준에서규정하고있는전압레벨은 TTL 호환 (TTL compatible) 이아니기때문 RS-232 표준은논리 1 에해당하는전압의범위를 -3 V ~ -15 V 로, 논리 0 에해당하는전압의범위를 +3 V ~ +15 V 로규정한다. RS-232 Transceiver RS-232 표준을따르기위해서는 0 V ~ 3 V ( 또는 3.3 V 또는 5 V) 범위의 TTL 신호를 RS-232 레벨신호로변환하고또그반대방향으로도전압을변환해주는전용회로 ( 또는 IC) 가필요 Maxim 사의 MAX232 가대표적인예 12

13 13 3. I2C(IIC)

14 I2C (1) I2C(Inter-Integrated Circuit) Bus 데이터라인을공유하는동기시리얼통신버스하나의버스에 127 장치까지연결가능 1Mbps 전송속도까지가능간단한통신프로토콜이장점대부분의 MCU에 I2C 통신제어장치내장참조 : 14

15 I2C (2) I2C(Inter-Integrated Circuit) Bus 마이크로프로세서와저속주변장치사이의통신을위한용도로 Philips 에서개발한규격 TWI (Two Wire Interface) I2C 버스는양방향오픈드레인선인 SCK(serial clock) 과 SDA(serial data) 로이루어져있으며마스터 - 슬레이브형태로동작한다. SCK 은통신동기를위한클럭선, SDA 는데이터선 마스터는 SCK 로동기를위한클럭을출력하며, 슬레이브는 SCK 로출력되는클럭에맞추어 SDA 를통해데이터를출력하거나입력받는다. SDA 한선으로만데이터를주고받기때문에반이중 (half duplex) 통신만가능 15

16 I2C (3) I2C(Inter-Integrated Circuit) Bus SCK 선과 SDA 선은모두오픈드레인이므로두선에는각각풀업저항을연결해주어야한다. 16

17 I2C (4) I2C(Inter-Integrated Circuit) Bus 17

18 I2C (4) I2C(Inter-Integrated Circuit) Bus 통신프로토콜 18

19 19 4. I2C 통신실험

20 I2C Text LCD (1) I2C Text LCD I2C Converter 모듈을이용하여 I2C 통신인터페이스를이용하여출력이가능한 Text LCD 20

21 I2C Text LCD (2) I2C LCD 모듈 (I2C Converter) 기존의 16*2 Character LCD 에결합하여사용할수있는 breakout board 형태의모듈 I2C interface 를사용해 LCD 제어가가능 2 개의디지털핀만사용 아두이노에연결하여제어할경우두개의 AnalogPin(SDA, SCL) 으로제어가가능 주요사양 1 줄 16 개문자, 2 줄제어가능 동작전압 : 5V I2C 주소 (Address) : 0x20, 0x27 문자선명도 : 가변저항을통해문자의선명도조절가능 backlight : 점퍼스위치를통해 backlight On / Off 21

22 I2C Text LCD (3) I2C LCD 모듈 (I2C Converter) I2C Address 주소설정핀 (or Solder Pads): A0, A1, A2 Not-connected 1 / Connected - 0 (or 0x3F) 22

23 I2C Text LCD (4) Arduino I2C Library (1) Wire Library 주요 APIs: begin() requestfrom() begintransmission() endtransmission() write() available() read() SetClock() onreceive() onrequest() 23

24 I2C Text LCD (5) Arduino I2C Library (2) Wire Library 예제 : master writer / slaver receiver Master Slaver 24 #include <Wire.h> void setup() { Wire.begin(); // join i2c bus (address optional for master) byte x = 0; void loop() { Wire.beginTransmission(8); // transmit to device #8 Wire.write("x is "); // sends five bytes Wire.write(x); // sends one byte Wire.endTransmission(); // stop transmitting x++; delay(500); #include <Wire.h> void setup() { Wire.begin(8); // join i2c bus with address #8 Wire.onReceive(receiveEvent); // register event Serial.begin(9600); // start serial for output void loop() { delay(100); void receiveevent(int howmany) { while (1 < Wire.available()) { // loop through all but the last char c = Wire.read(); // receive byte as a character Serial.print(c); // print the character int x = Wire.read(); // receive byte as an integer Serial.println(x); // print the integer

25 I2C Text LCD (6) I2C Text LCD Library (1) 라이브러리다운로드사이트 : LiquidCrystal-I2C KyJ56OlEcJZmN4UWwtX2hydDg/view?usp=sharing LiquidCrystal-I2C Library API LiquidCrystal Library API 와상당히유사 문서참조 25

26 26 lcd.begin(); lcd.display(); lcd.nodisplay(); lcd.setcursor(col,row); lcd.cursor(); lcd.nocursor(); lcd.home(); lcd.blink(); lcd.noblink(); lcd.backlight(); lcd.nobacklight(); lcd.write(val); lcd.print(val); lcd.clear(); lcd.scrolldisplayright(); lcd.scrolldisplayleft(); lcd.autoscroll(); LCD 를사용을시작 LCD 에내용을표시 LCD 에내용을숨김 row, col 의좌표로커서를위치 LCD 에커서를표시 LCD 에커서를숨김 커서의위치를 0,0 으로이동 커서를깜빡임 커서를깜빡이지않음 LCD backlight 을킴 LCD backlight 를끔 LCD 화면에 val 출력 ( 아스키코드입력시에는아스키코드에해당하는문자출력 ) LCD 화면에 val 출력 LCD 화면의모든내용지움 내용을우측으로 1 칸이동 내용을좌측으로 1 칸이동 내용을자동으로우에서좌로스크롤

27 I2C Text LCD (7) I2C Text LCD Library (2) LiquidCrystal-I2C Library API Cursor 제어함수에서 Cursor 의 row 와 col( 줄과행 ) 좌표참고 27

28 I2C Text LCD (8) I2C Text LCD 주소테스트 (1) I2C Text LCD 주소를확인하여출력 참조 회로구성 28

29 I2C Text LCD (9) I2C Text LCD 주소테스트 (2) 아두이노프로그램 #include <Wire.h> void setup() { Serial.begin (115200); Serial.println ("I2C scanner. Scanning..."); byte count = 0; Wire.begin(); for (byte i = 8; i < 120; i++) { Wire.beginTransmission (i); if (Wire.endTransmission () == 0) { Serial.print ("Found address: "); Serial.print (i, DEC); Serial.print (" (0x"); Serial.print (i, HEX); Serial.println (")"); count++; delay (1); // maybe unneeded? // end of good response // end of for loop serial.println ("Done."); Serial.print ("Found "); Serial.print (count, DEC); Serial.println (" device(s)."); // end of setup void loop() { // no operations 출력결과 : 0x3F 29

30 I2C Text LCD (10) I2C Text LCD 출력테스트 (1) Hello, World! 텍스트출력 회로구성 앞실험과동일 30

31 I2C Text LCD (11) I2C Text LCD 출력테스트 (2) 아두이노프로그램 #include <Wire.h> #include <LiquidCrystal_I2C.h> // Set the LCD address to 0x27 for a 16 chars and 2 line display LiquidCrystal_I2C lcd(0x3f, 16, 2); // I2C LCD 객체선언 Void setup() { // initialize the LCD lcd.begin(); // lcd 를사용을시작합니다. lcd.backlight(); // backlight 를 On 시킵니다. lcd.print( Hello, world! ); // 화면에 Hello, world! 를출력합니다. void loop(){ 31

32 I2C Text LCD (12) I2C Text LCD 기능테스트 예제참조 예제기능 시리얼모니터로입력받은데이터에따라아래와같이동작 - 1 을입력받았을때 : backlight 가 1 초가소등되었다가점등됩니다. - 2 를입력받았을때 : LCD 에표시된글자가 1 초간사라졌다가나타납니다. - 3 을입력받았을때 : Cursor 가 1 초간깜빡이다가사라집니다. - 4 를입력받았을때 : 커서가 1 초간화면에나타났다가사라집니다. - 5 를입력받았을때 : 화면에표시된내용이 1 초간우측으로 1 칸이동후원래자리로돌아옵니다. - 6 을입력받았을때 : 커서가화면에표시된후커서위치가 col 0 부터 16 까지이동후에사라집니다. 32

33 DS1307 RTC 를이용한시계 (1) 참고 Sites tronixstuff.wordpress.com/tutorials Ch. 20 & 21 Arduino Wire Library 33

34 DS1307 RTC 를이용한시계 (2) DS1307 IC 34

35 DS1307 RTC 를이용한시계 (3) DS1307 IC 35

36 DS1307 RTC 를이용한시계 (4) 회로도 36

37 DS1307 RTC 를이용한시계 (5) 회로구성 37

38 DS1307 RTC 를이용한시계 (6) DS1307 Pulse 출력 (1) Arduino Wire Library 사용레지스터 #07 설정하여펄스출력 38 /* DS1307 Square-wave machine Used to demonstrate the four different square-wave outputs from Maxim DS1307 See page nine of data sheet for more information John Boxall - tronixstuff.wordpress.com */ #include "Wire.h" #define DS1307_I2C_ADDRESS 0x68 // each I2C object has a unique bus address, the DS1307 is 0x68 void setup() { Wire.begin(); void sqw1() // set to 1Hz { Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write(0x07); // move pointer to SQW address Wire.write(0x10); // sends 0x10 (hex) (binary) Wire.endTransmission();

39 DS1307 RTC 를이용한시계 (7) DS1307 Pulse 출력 (2) void sqw2() // set to khz { Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write(0x07); // move pointer to SQW address Wire.write(0x11); // sends 0x11 (hex) (binary) Wire.endTransmission(); void sqw3() // set to khz { Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write(0x07); // move pointer to SQW address Wire.write(0x12); // sends 0x12 (hex) (binary) Wire.endTransmission(); 39 void sqw4() // set to khz (the crystal frequency) { Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write(0x07); // move pointer to SQW address Wire.write(0x13); // sends 0x13 (hex) (binary) Wire.endTransmission();

40 DS1307 RTC 를이용한시계 (8) DS1307 Pulse 출력 (3) void sqwoff() // turns the SQW off { Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write(0x07); // move pointer to SQW address Wire.write(0x00); // turns the SQW pin off Wire.endTransmission(); 40 void loop() { sqw1(); delay(5000); sqw2(); delay(5000); sqw3(); delay(5000); sqw4(); delay(5000); sqwoff(); delay(5000);

41 DS1307 RTC 를이용한시계 (9) DS1307 시계출력 (1) #include "Wire.h" #define DS1307_I2C_ADDRESS 0x68 // Convert normal decimal numbers to binary coded decimal byte dectobcd(byte val) { return ( (val/10*16) + (val%10) ); // Convert binary coded decimal to normal decimal numbers byte bcdtodec(byte val) { return ( (val/16*10) + (val%16) ); 41

42 DS1307 RTC 를이용한시계 (10) DS1307 시계출력 (2) 42 // 1) Sets the date and time on the ds1307 // 2) Starts the clock // 3) Sets hour mode to 24 hour clock // Assumes you're passing in valid numbers void setdateds1307(byte second, // 0-59 byte minute, // 0-59 byte hour, // 1-23 byte dayofweek, // 1-7 byte dayofmonth, // 1-28/29/30/31 byte month, // 1-12 byte year) // 0-99 { Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write(0); Wire.write(decToBcd(second)); // 0 to bit 7 starts the clock Wire.write(decToBcd(minute)); Wire.write(decToBcd(hour)); Wire.write(decToBcd(dayOfWeek)); Wire.write(decToBcd(dayOfMonth)); Wire.write(decToBcd(month)); Wire.write(decToBcd(year)); Wire.write( ); // sends 0x10 (hex) (binary) to control register - turns on square wave Wire.endTransmission();

43 DS1307 RTC 를이용한시계 (11) DS1307 시계출력 (3) 43 // Gets the date and time from the ds1307 void getdateds1307(byte *second, byte *minute, byte *hour, byte *dayofweek, byte *dayofmonth, byte *month, byte *year) { // Reset the register pointer Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write(0); Wire.endTransmission(); Wire.requestFrom(DS1307_I2C_ADDRESS, 7); // A few of these need masks because certain bits are control bits *second = bcdtodec(wire.read() & 0x7f); *minute = bcdtodec(wire.read()); *hour = bcdtodec(wire.read() & 0x3f); // Need to change this if 12 hour am/pm *dayofweek = bcdtodec(wire.read()); *dayofmonth = bcdtodec(wire.read()); *month = bcdtodec(wire.read()); *year = bcdtodec(wire.read());

44 DS1307 RTC 를이용한시계 (12) DS1307 시계출력 (4) void setup() { byte second, minute, hour, dayofweek, dayofmonth, month, year; Wire.begin(); Serial.begin(9600); // Change these values to what you want to set your clock to. // You probably only want to set your clock once and then remove // the setdateds1307 call. second = 0; minute = 54; hour = 14; dayofweek = 4; dayofmonth = 9; month = 5; year = 10; setdateds1307(second, minute, hour, dayofweek, dayofmonth, month, year); 44

45 DS1307 RTC 를이용한시계 (13) DS1307 시계출력 (5) 45 void loop() { byte second, minute, hour, dayofweek, dayofmonth, month, year; getdateds1307(&second, &minute, &hour, &dayofweek, &dayofmonth, &month, &year); Serial.print(hour, DEC);// convert the byte variable to a decimal number when being displayed Serial.print(":"); if (minute<10) { Serial.print("0"); Serial.print(minute, DEC); Serial.print(":"); if (second<10) { Serial.print("0"); Serial.print(second, DEC); Serial.print(" "); Serial.print(dayOfMonth, DEC); Serial.print("/"); Serial.print(month, DEC); Serial.print("/"); Serial.print(year, DEC);

46 DS1307 RTC 를이용한시계 (14) DS1307 시계출력 (6) Serial.print(" Day of week:"); switch(dayofweek){ case 1: Serial.println("Sunday"); break; case 2: Serial.println("Monday"); break; case 3: Serial.println("Tuesday"); break; case 4: Serial.println("Wednesday"); break; case 5: Serial.println("Thursday"); break; case 6: Serial.println("Friday"); break; case 7: Serial.println("Saturday"); break; // Serial.println(dayOfWeek, DEC); delay(1000); 46

47 DS1307 RTC 를이용한시계 (15) RTC 라이브러리활용 DS1307 IC 를이용한 RTC 기능을구현한라이브러리 RTClib 압축파일을다운로드하여풀고 RTClib 라는이름으로아두이노라이브러리디렉토리에설치 47

48 DS1307 RTC 를이용한시계 (16) RTC 라이브러리예제실행 LCD 출력확장 48

49 DS1302 RTC 를이용한시계 (1) DS1302 RTC 모듈 DS1302 RTC IC 를사용한모듈 DS1307 RTC 모듈과유사한기능지원 현재시간및날짜지원 Pulse 출력기능은지원하지않음 일반적인 I2C 인터페이스가아닌 3-wire 인터페이스지원 49

50 DS1302 RTC 를이용한시계 (2) DS1302 IC (1) 주전원공급 Trickle charger 전원 50

51 DS1302 RTC 를이용한시계 (3) DS1302 IC (2) 51

52 DS1302 RTC 를이용한시계 (4) DS1302 RTC 모듈제어 직접입출력제어 (1) 디지털입출력기능을이용하여 DS1302 IC 의레지스터의직접입출력제어 시간및날짜에대해설정및읽기수행 참조 유의사항 : During reading, the clock could rollover. That would result in bad clock data. To prevent that, the DS1302 has a buffer to store the clock data. That buffer can be read in a single communication session, called a "burst" mode. Any valid program should use that "burst" mode to read the clock data. The Year data of the DS1302 is only two digits (0-99). The Year '0' is 2000, and not 1970 or It has a Leap-Year compensation from 2000 up to 2099 (for a value of 0-99). 52

53 DS1302 RTC 를이용한시계 (5) DS1302 RTC 모듈제어 직접입출력제어 (2) DS1302 IC 인터페이스구성 : 3-wire interface - 디지털입출력핀사용 : // Set your own pins with these defines! #define DS1302_SCLK_PIN 4 // Arduino pin for the Serial Clock #define DS1302_IO_PIN 3 // Arduino pin for the Data I/O #define DS1302_CE_PIN 2 // Arduino pin for the Chip Enable : 53

54 DS1302 RTC 를이용한시계 (6) DS1302 RTC 모듈제어 직접입출력제어 (3) 실습회로구성 Arduino Mega D2 D3 D4 RTC DS1302 CE(RST) DAT CLK 54

55 DS1302 RTC 를이용한시계 (7) DS1302 RTC 모듈제어 직접입출력제어 (4) 아두이노예제프로그램 Burst mode I/O : void DS1302_clock_burst_read( uint8_t *p) { int i; _DS1302_start(); // Instead of the address, // the CLOCK_BURST_READ command is issued // the I/O-line is released for the data _DS1302_togglewrite( DS1302_CLOCK_BURST_READ, true); for( i=0; i<8; i++) { *p++ = _DS1302_toggleread(); _DS1302_stop(); : 55

56 DS1302 RTC 를이용한시계 (8) DS1302 RTC 모듈제어 직접입출력제어 (5) 아두이노예제프로그램 Burst mode I/O : void DS1302_clock_burst_write( uint8_t *p) { int i; _DS1302_start(); // Instead of the address, // the CLOCK_BURST_WRITE command is issued. // the I/O-line is not released _DS1302_togglewrite( DS1302_CLOCK_BURST_WRITE, false); for( i=0; i<8; i++) { // the I/O-line is not released _DS1302_togglewrite( *p++, false); _DS1302_stop(); : 56

57 DS1302 RTC 를이용한시계 (9) DS1302 RTC 모듈제어 라이브러리활용 (1) DS1302RTC 라이브러리 참조 intended for use with the Arduino Time.h library, support the additional features of the DS1302: 1. Real Time Clock read/write (8 bytes) 2. Battery backed RAM read/write (31 bytes) 3. Power save mode manipulation (start/stop clock) 4. Trickle charger setup 5. Burst mode read/write hour format only (12 hour format is function Time library) 57

58 DS1302 RTC 를이용한시계 (10) DS1302 RTC 모듈제어 라이브러리활용 (2) 실습회로 앞의실습과동일 DS1302 RTC 모듈시간 / 날짜설정 DS1302RTC 라이브러리예제프로그램 setserial 활용 - Stringming5 Library 필요 58

59 DS1302 RTC 를이용한시계 (11) DS1302 RTC 모듈제어 라이브러리활용 (3) 59 DS1302 RTC 모듈출력프로그램 현재시간을시리얼모니터에출력한다. 시리얼모니터에서새로운시간을입력하면 RTC 모듈에새로설정한다. #include <DS1302RTC.h> #include <Time.h> // Set pins: CE(reset), IO(dat),CLK DS1302RTC RTC(2, 3, 4); void setup(void) { Serial.begin(115200); // Activate RTC module digitalwrite(ds1302_gnd_pin, LOW); pinmode(ds1302_gnd_pin, OUTPUT); digitalwrite(ds1302_vcc_pin, HIGH); pinmode(ds1302_vcc_pin, OUTPUT); Serial.println("RTC module activated"); delay(500);

60 if (RTC.haltRTC()) { Serial.println("The DS1302 is stopped. Please set time"); Serial.println("to initialize the time and begin running."); Serial.println(); if (!RTC.writeEN()) { Serial.println("The DS1302 is write protected. This normal."); Serial.println(); delay(5000); //setsyncprovider() causes the Time library to synchronize with the //external RTC by calling RTC.get() every five minutes by default. setsyncprovider(rtc.get); Serial.println("RTC Sync"); if (timestatus() == timeset) Serial.println(" Ok!"); else Serial.println(" FAIL!"); Serial.println(); void loop(void) { static time_t tlast; time_t t; tmelements_t tm; 60

61 //check for input to set the RTC, minimum length is 12, i.e. yy,m,d,h,m,s if (Serial.available() >= 12) { //note that the tmelements_t Year member is an offset from 1970, //but the RTC wants the last two digits of the calendar year. //use the convenience macros from Time.h to do the conversions. int y = Serial.parseInt(); if (y >= 100 && y < 1000) Serial.println("Error: Year must be two digits or four digits!"); else { if (y >= 1000) tm.year = CalendarYrToTm(y); else //(y < 100) tm.year = y2kyeartotm(y); tm.month = Serial.parseInt(); tm.day = Serial.parseInt(); tm.hour = Serial.parseInt(); tm.minute = Serial.parseInt(); tm.second = Serial.parseInt(); t = maketime(tm); if(rtc.set(t) == 0) { // Success settime(t); Serial.println("RTC set to: "); printdatetime(t); Serial.println(); else Serial.println(); //use the time_t value to ensure // correct weekday is set 61 Serial.println("RTC set failed!"); //dump any extraneous input while (Serial.available() > 0) Serial.read();

62 t = now(); if (t!= tlast) { tlast = t; printdatetime(t); Serial.println(); //print date and time to Serial void printdatetime(time_t t) { printdate(t); Serial.println(" "); printtime(t); //print time to Serial void printtime(time_t t) { printi00(hour(t), ':'); printi00(minute(t), ':'); printi00(second(t), ' '); //print date to Serial void printdate(time_t t) { printi00(day(t), 0); Serial.print(monthShortStr(month(t))); Serial.println(year(t), DEC); 62

63 //Print an integer in "00" format (with leading zero), //followed by a delimiter character to Serial. //Input value assumed to be between 0 and 99. void printi00(int val, char delim) { if (val < 10) Serial.print("0"); Serial.print(val, DEC); if (delim > 0) Serial.print(delim); return; 참조 :

64 과제물 #3 과제내용 DS1302, 조도센서그리고 I2C Text LCD 장치를이용하여다음의동작을수행하는프로그램을작성하여라. A. 조도크기를 Text LCD 장치에출력한다 B. 현재시간과날짜를 Text LCD 장치에출력한다 제출물 회로도, 프로그램소스, 실행예 ( 사진 ) 제출일 차주수업시간 64