티스토리 뷰
제가 2차 체험단 프로젝트로 진행하면서 사용한 RTC모듈을 설명해보려고 합니다!
RTC모듈이란
Real Time Clock의 약자로, 컴퓨터 또는 보드에 전원이 끊어져도 시간을 계속 카운팅하는 모듈입니다!
제가 사용할 모듈은 Tiny RTC I2C 모듈(DS1307)입니다.
보통 시간을 측정할 용도로 사용한다면 SCL, SDA, VCC, GND만 연결해줍시다.
그 외 핀의 용도로는
내장된 온도센서를 이용하려면 DS핀을 사용하여 온도 값을 받아들일 수 있고,
배터리 잔량은 BAT핀을 사용하여 알 수 있습니다.
건전지를 넣어줘야 보드에서의 전원이 공급되지 않을 때에도 시간을 카운팅할 수 있겠죠?!
그럼 한 번 사용해보겠습니다.
일단 다음과 같은 라이브러리가 설치되야 합니다!
<TimeLib.h>
<DS1307RTC.h>
그 다음 DS1307RTC 예제 SetTime을 불러오겠습니다!
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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | #include <Wire.h> #include <Time.h> #include <DS1307RTC.h> const char *monthName[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; tmElements_t tm; void setup() { bool parse=false; bool config=false; // get the date and time the compiler was run if (getDate(__DATE__) && getTime(__TIME__)) { parse = true; // and configure the RTC with this info if (RTC.write(tm)) { config = true; } } Serial.begin(9600); while (!Serial) ; // wait for Arduino Serial Monitor delay(200); if (parse && config) { Serial.print("DS1307 configured Time="); Serial.print(__TIME__); Serial.print(", Date="); Serial.println(__DATE__); } else if (parse) { Serial.println("DS1307 Communication Error :-{"); Serial.println("Please check your circuitry"); } else { Serial.print("Could not parse info from the compiler, Time=\""); Serial.print(__TIME__); Serial.print("\", Date=\""); Serial.print(__DATE__); Serial.println("\""); } } void loop() { } bool getTime(const char *str) { int Hour, Min, Sec; if (sscanf(str, "%d:%d:%d", &Hour, &Min, &Sec) != 3) return false; tm.Hour = Hour; tm.Minute = Min; tm.Second = Sec; return true; } bool getDate(const char *str) { char Month[12]; int Day, Year; uint8_t monthIndex; if (sscanf(str, "%s %d %d", Month, &Day, &Year) != 3) return false; for (monthIndex = 0; monthIndex < 12; monthIndex++) { if (strcmp(Month, monthName[monthIndex]) == 0) break; } if (monthIndex >= 12) return false; tm.Day = Day; tm.Month = monthIndex + 1; tm.Year = CalendarYrToTm(Year); return true; } | cs |
<DS1307RTC 예제 SetTime>
이 코드를 업로드 하게 되면 RTC모듈에 현재 컴퓨터의 시간이 입력되고, 이 시간을 기준으로 실제 시간과 동일하게
시간이 카운팅됩니다.
getDate 를 이용해 현재 컴퓨터의 날짜를, getTime을 이용해 현재 컴퓨터의 시간을 입력받는답니다!
★만약 컴파일 중 tm이라는 객체에 대한 에러가 발생한다면? ★
Time.h 헤더를 TimeLib.h 로 변경하여 다시 컴파일 해보세요!
코드를 업로드 후 시리얼 모니터를 한번 켜볼까요?
위와 같이 출력된다면 시간 설정 완료!
그럼 실제로 잘 카운팅이 되고 있는지 확인 해볼까요?
DS1307RTC 예제 ReadTest를 실행해보겠습니다.
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 40 41 42 43 44 45 | #include <Wire.h> #include <TimeLib.h> #include <DS1307RTC.h> void setup() { Serial.begin(9600); } void loop() { tmElements_t tm; if (RTC.read(tm)) { Serial.print("Ok, Time = "); print2digits(tm.Hour); Serial.write(':'); print2digits(tm.Minute); Serial.write(':'); print2digits(tm.Second); Serial.print(", Date (D/M/Y) = "); Serial.print(tm.Day); Serial.write('/'); Serial.print(tm.Month); Serial.write('/'); Serial.print(tmYearToCalendar(tm.Year)); Serial.println(); } else { if (RTC.chipPresent()) { Serial.println("The DS1307 is stopped. Please run the SetTime"); Serial.println("example to initialize the time and begin running."); Serial.println(); } else { Serial.println("DS1307 read error! Please check the circuitry."); Serial.println(); } delay(9000); } delay(1000); } void print2digits(int number) { if (number >= 0 && number < 10) { Serial.write('0'); } Serial.print(number); } | cs |
<DS1307RTC 예제 ReadTest>
이 코드는 굉장히 쉽습니다!
RTC.read()함수를 실행한 후
tm이라는 객체가 가지고 있는 변수 Hour, Minute, Second 등을 이용하면 쉽게 현재 시간을 읽을 수 있습니다.
그리고 print2digits라는 함수를 이용해 한자리 숫자를 출력할 땐 앞에 0을 먼저 출력하여 이쁘게 나타낼 수도 있죠!
이 코드를 업로드한 후 시리얼 모니터를 열어보겠습니다!
delay를 1000으로 설정해놓았기 때문에 1초 간격으로 시간을 읽어볼 수 있습니다.
그럼 한 번 ! MODLINK와 결합해 웹에서 시간을 받아볼까요?
일단 문자열을 서버로 보내는 방법을 알아야합니다!
아래 링크에 설명이 잘 되어있으니 보고 오시길 바랍니다!
(http://cafe.naver.com/arduinoguide/1008)
그럼 간단하게 버튼을 눌렀을 때 웹에서 눌린 시간을 표시하는 예제를 실행 해보겠습니다.
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 40 41 42 | #include <Wire.h> #include <TimeLib.h> #include <DS1307RTC.h> #include <VitconBrokerComm.h> using namespace vitcon; #define ITEM_COUNT 2 char msg[50]; tmElements_t tm; void buttonStatus(bool val){ if( val ){ msg[0] = 0; char tmp[10] = {0}; if (RTC.read(tm)) { itoa(tm.Hour,tmp,10); strcat(msg,tmp); itoa(tm.Minute,tmp,10); strcat(msg,tmp); itoa(tm.Second,tmp,10); strcat(msg,tmp); } } } IOTItemStr str; IOTItemBin button(buttonStatus); IOTItem *items[ITEM_COUNT] = { &str, &button}; const char device_id[] = " 자신의 장비 ID "; BrokerComm comm(&Serial, device_id, items, ITEM_COUNT); void setup() { Serial.begin(250000); comm.SetInterval(200); } void loop() { str.Set(msg); comm.Run(); } | cs |
버튼이 눌릴 때 마다
itoa 함수를 이용해 숫자를 문자열로 바꿔주고,
strcat함수를 이용해 msg라는 문자열에 갖다 붙여줍시다!
Set함수를 이용해 웹에 보내주면 끝!!
C언어에서 문자열을 공부했다면 쉽지만, 안했다면!
지금하시면 됩니당!
20시 27분 58초를 나타냅니다.
문자열만 잘 처리하면 원하는 방식으로 정보를 받아볼 수 있겠네요.
이 모듈은 MODLINK와 결합해 IoT로 활용한다면 정말 많은 프로젝트에 사용될 수 있을 것 같습니다.
자! 이제 우리의 요구에 맞게 코드를 잘 다듬어서 사용할 일만 남았습니다!
화이팅!
'IOT-MODLINK' 카테고리의 다른 글
[Project – 스마트 도어락] [완성] 코드 리뷰, 설치 그리고 작동 영상 (0) | 2017.12.20 |
---|---|
[Project – 스마트 도어락] 4. 출입 로그 관리 & 케이스 제작 (0) | 2017.12.19 |
[IoT-MODLINK] 웹/앱 UI를 더 이쁘게 꾸미자! (0) | 2017.12.19 |
[Project – 스마트 도어락] 4. 조명 효과 & 외부 전원 공급하기 (0) | 2017.12.17 |
[Project – 스마트 도어락] 3. 열림/닫힘 상태 확인하기 (0) | 2017.12.17 |