산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Manufacturing Technology >> 제조공정

RTC 기반 시계

구성품 및 소모품

Arduino Nano R3
× 1
실시간 시계(RTC)
저는 ds1307 기반의 RTC 모듈을 사용했습니다. 작업이 훨씬 쉬워집니다. 하지만 스스로 아주 ​​쉽게 만들 수 있습니다.
× 1
4자리 7세그먼트 LED 디스플레이
× 1
암컷 헤더 단일 행
× 3
다공판
이 프로젝트를 납땜하여 표시 가능하게 만들고 싶다면 이것을 얻으십시오. 납땜을 쉽게 하려면 빵판과 같은 흔적이 있는 납땜판을 구입하십시오.
× 1
점퍼 와이어(일반)
× 25
남성 헤더 40 위치 1 행(0.1")
× 1

필요한 도구 및 기계

납땜 인두(일반)
멀티미터
모든 프로젝트에는 멀티미터가 필요합니다. 따라서 표준 쌍에 투자하십시오. 최소 4년 동안 작동하며 수리 방법을 안다면 훨씬 더 오래 사용할 수 있습니다. 납땜 연결을 확인하고 회로에 의해 유입되는 전류를 확인하려면 이것이 필요합니다.

앱 및 온라인 서비스

Arduino IDE
Arduino Fritzing

이 프로젝트 정보

이것은 RTC DS1307 IC를 사용하여 만든 정말 간단하고 조립하기 쉬운 디지털 시계입니다. LCD 디스플레이 포함. 그것은 단순히 4자리 7세그먼트 디스플레이에 시간을 표시합니다. 코드를 쉽게 조정하여 알람과 같은 추가 기능을 제공할 수도 있습니다. 약간의 상상력과 독창성만 있으면 됩니다. 이 프로젝트는 더 좋고 더 복잡한 것들을 위한 디딤돌로 만들어졌으며, 더 나아가 내 방에 전시할 멋진 것을 만들고 싶었습니다.

충분히 말하지만, PCB에 납땜하는 동안 발생한 문제와 이러한 문제를 해결한 방법을 포함하여 이 게시물에 모든 세부 사항을 포함할 것입니다.

1단계:구성요소

RTC 모듈

DS1307 칩은 전원이 꺼진 시간에도 시간을 추적할 수 있는 기능이 있기 때문에 정말 훌륭합니다. Arduino와 인터페이스하기 쉽고 이 모듈로 작업하는 데 사용할 수 있는 라이브러리가 많이 있습니다. RTC는 I2C 프로토콜을 통해 Arduino와 인터페이스합니다. 프로토콜의 세부 사항에 대해 걱정하지 마십시오. Arduino nano의 핀 A4 및 A5는 I2C 통신에 사용됩니다.

<울>
  • SDA - A4
  • <울>
  • SCL - A5
  • 이 프로젝트에는 DS 핀이 필요하지 않습니다.

    유일한 단점은 우리가 원하는 만큼 정확하지 않다는 것입니다. 칩은 시간 표류에 매우 취약하며 온도에 따라 실제 시간에서 매우 쉽게 표류합니다.

    참고 - GND 및 Vcc 핀을 올바르게 연결했는지 확인하십시오. Vcc는 GND 핀 앞에 (모듈에서) 배치됩니다. 나는 내 것을 역 극성으로 여러 번 연결했고 매우 빨리 뜨거워졌습니다. 따라서 극성을 반대로 연결하는 경우 전원을 켤 때 코인 셀을 터치하기만 하면 되고 뜨거워지면 빠르게 끄십시오.

    시프트 레지스터(74HC595)

    <울>
  • 시프트 레지스터 74HC595는 멀티플렉싱 기술 덕분에 가능하게 한 칩이었습니다. 초심자는 이 무섭게 생긴 용어를 두려워하지 않고 재미있고 배우게 되어 기쁠 것입니다.
  • <울>
  • 595에는 16개의 핀이 있으며 2개의 시프트 레지스터를 사용하여 4자리 7세그먼트 디스플레이와 상호 작용할 것입니다.
  • <울>
  • 첫 번째 시프트 레지스터는 세그먼트를 밝히는 데 사용되며 두 번째 시프트 레지스터는 어떤 숫자를 밝힐지 선택하는 데 사용됩니다.
  • <울>
  • 다중화 기술 덕분에 숫자 간 전환이 매우 빠르게 이루어집니다. 모든 숫자가 동시에 표시되는 것처럼 보입니다.
  • 참고:이 칩은 매우 안정적이지만 몇 가지 결함이 있는 칩을 얻었습니다. 일부 칩에서는 Q0과 Q1이 작동하지 않았습니다. 일부는 Q3를 내부적으로 접지했습니다(건설 실수). 지금 내 프로젝트에 있는 것들도 완전히 완벽하지는 않습니다. 그 중 하나는 Q7에 결함이 있어서 함께 작업할 때 연결이 정확한지 확인해야 했고 여전히 작동하지 않을 때 멀티 미터의 연속성 기능을 사용하여 핀을 확인했습니다. 프로젝트를 하는 동안 작은 장애물을 극복하는 방법을 배우는 것이 모든 수단이기 때문에 나는 불평하지 않습니다.

    4자리 7세그먼트 디스플레이

    일반 4자리 세그먼트(공통 양극 ). 12개의 핀이 있습니다. 번호는 왼쪽 하단에서 시작하여 왼쪽 상단 핀에서 끝납니다. 각 세그먼트는 숫자와 소수점을 표시할 수 있습니다. 그래서 디지털 시계에서 볼 수 있는 멋진 콜론이 없기 때문에 두 번째 숫자의 소수점으로 처리해야 했습니다. 이것은 주요 목표가 숫자를 표시하는 것일 때 훌륭한 디스플레이입니다.

    참고:세그먼트 a-g가 같은 줄에 있지 않기 때문에 초보자가 작업하기에는 상당히 까다로울 수 있습니다. 전류 제한 저항 없이 5v 전원을 연결하지 않도록 주의하십시오.

    이에 대한 개략도와 설명이 포함되어 있습니다.

    Schematic에는 내가 프로젝트에서 사용한 것과 같은 유형의 디스플레이가 없으므로 여기 시프트 레지스터에서 세그먼트로의 핀 연결이 있습니다.

    세그먼트 핀 번호 디스플레이 시프트 레지스터 핀

    A 11 15

    B 7 1

    씨 4 2

    디 2 3

    전자 1 4

    F 10 5

    지 5 6

    소수점 3 7

    D1 12 15(2차 595)

    D2 9 1(2nd 595)

    D3 8 2(2nd 595)

    D4 6 3(2nd 595)

    이 프로젝트는 저렴하고 만들기 쉽지만 약간의 인내와 인내가 필요합니다(즉, PCB에 납땜하기 위해 더 많은 노력을 기울일 의향이 있는 경우). 그냥 재미삼아 해보고 싶다면 2시간도 채 걸리지 않습니다.

    이를 개선할 수 있는 방법과 게시물에 명확하게 언급되지 않은 사항이 있으면 피드백을 보내주십시오.

    <섹션 클래스="섹션 컨테이너 섹션 축소 가능" id="코드">

    코드

    <울>
  • 시계 코드
  • 시간 설정
  • RealTimeClockDS1307.cpp
  • 추가 정보
  • RealTimeClockDS1307.h
  • 다른 파일
  • RTClib 파일
  • library.properties(이름)
  • RTClib
  • RTClib
  • README.md
  • RTClib.cpp
  • RTClib.h
  • 시계 코드 Arduino
    이 코드는 RTC 라이브러리와 I2C 라이브러리를 사용합니다. 프로그램을 실행하려면 이러한 라이브러리가 필요합니다. 이 프로그램은 Common Anode 방식 디스플레이용입니다.
    #include #include#include RTC_DS1307 RTC;int temp, inc, hour1, minut, add =11;int HOUR, MINUT, SECOND;int 래치핀 =3; //595 o3의 12번 핀 3int dataPin =4; //595 또는 4int의 14번 핀 clockPin =2; //595 또는 2의 11번 핀 시프트 =256;int 단위, 십, 백, 천;int x;int y;const int alarmHour =17;const int alarmMinute =26;void setup() { Serial.begin(9600 ); 핀모드(래치핀, 출력); 핀모드(데이터핀, 출력); 핀모드(시계핀, 출력); 핀모드(13, 출력); Wire.begin(); RTC.begin(); if (!RTC.isrunning()) { RTC.adjust(DateTime(__DATE__, __TIME__)); }} 무효 루프() { int temp =0, val =1, temp4; 지금 날짜 시간 =RTC.now(); HOUR =now.hour(); MINUT =지금.분(); //Serial.println(MINUT); if (시간 <10) { 수백 =시간; 천 =HOUR/10; } else if (시간>=10 &&시간 <24) { 수백 =시간 % 10; 수천 =HOUR / 10; } if (MINUT <=9) { 단위 =MINUT; 십 =MINUT/10; } else if (MINUT> 9 &&MINUT <=60) { 단위 =MINUT % 10; 십 =MINUT / 10; } 스위치(단위) { 경우 0://0 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 8>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 8 + 192 ); digitalWrite(래치핀, 높음); 부서지다; 경우 1://1 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 8>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 8 + 249); digitalWrite(래치핀, 높음); 부서지다; 사례 2://2 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 8>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 8 + 164); digitalWrite(래치핀, 높음); 부서지다; 사례 3://3 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 8>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 8 + 176); digitalWrite(래치핀, 높음); 부서지다; 사례 4://4 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 8>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 8 + 153); digitalWrite(래치핀, 높음); 부서지다; 사례 5://5 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 8>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 8 + 146); digitalWrite(래치핀, 높음); 부서지다; 사례 6://6 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 8>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 8 + 130); digitalWrite(래치핀, 높음); 부서지다; 사례 7://7 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 8>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 8 + 248); digitalWrite(래치핀, 높음); 부서지다; 사례 8://8 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 8>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 8 + 128); digitalWrite(래치핀, 높음); 부서지다; 사례 9://9 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 8>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 8 + 144); digitalWrite(래치핀, 높음); 부서지다; } 지연(1); 스위치(십) { 경우 0://0 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 4>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 4 + 192 ); digitalWrite(래치핀, 높음); 부서지다; 경우 1://1 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 4>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 4 + 249); digitalWrite(래치핀, 높음); 부서지다; 사례 2://2 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 4>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 4 + 164); digitalWrite(래치핀, 높음); 부서지다; 사례 3://3 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 4>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 4 + 176); digitalWrite(래치핀, 높음); 부서지다; 사례 4://4 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 4>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 4 + 153); digitalWrite(래치핀, 높음); 부서지다; 사례 5://5 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 4>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 4 + 146); digitalWrite(래치핀, 높음); 부서지다; } 지연(1); 스위치(백) { 경우 0://0 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 2>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 2 + 64 ); digitalWrite(래치핀, 높음); 부서지다; 경우 1://1 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 2>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 2 + 121); digitalWrite(래치핀, 높음); 부서지다; 사례 2://2 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 2>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 2 + 36); digitalWrite(래치핀, 높음); 부서지다; 사례 3://3 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 2>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 2 + 48); digitalWrite(래치핀, 높음); 부서지다; 사례 4://4 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 2>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 2 + 25); digitalWrite(래치핀, 높음); 부서지다; 사례 5://5 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 2>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 2 + 18); digitalWrite(래치핀, 높음); 부서지다; 사례 6://6 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 2>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 2 + 2); digitalWrite(래치핀, 높음); 부서지다; 사례 7://7 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 2>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 2 + 120); digitalWrite(래치핀, 높음); 부서지다; 사례 8://8 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 2>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 2 + 0); digitalWrite(래치핀, 높음); 부서지다; 사례 9://9 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift * 2>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift * 2 + 16); digitalWrite(래치핀, 높음); 부서지다; } 지연(1); 스위치 (천) { 경우 0://0 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift + 192 ); digitalWrite(래치핀, 높음); //지연(500); 부서지다; 경우 1://1 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift + 249); digitalWrite(래치핀, 높음); //지연(500); 부서지다; 사례 2://2 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift + 164); digitalWrite(래치핀, 높음); //지연(500); 부서지다; 사례 3://3 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift + 176); digitalWrite(래치핀, 높음); //지연(500); 부서지다; 사례 4://4 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift + 153); digitalWrite(래치핀, 높음); //지연(500); 부서지다; 사례 5://5 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift + 146); digitalWrite(래치핀, 높음); //지연(500); 부서지다; 사례 6://6 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift + 130); digitalWrite(래치핀, 높음); //지연(500); 부서지다; 사례 7://7 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift + 248); digitalWrite(래치핀, 높음); //지연(500); 부서지다; 사례 8://8 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift + 128); digitalWrite(래치핀, 높음); 부서지다; 사례 9://9 digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, shift>> 8 ); shiftOut(dataPin, clockPin, MSBFIRST, shift + 152); digitalWrite(래치핀, 높음); 부서지다; } 지연(1); //알람 섹션 ​​if (HOUR ==alarmHour &&MINUT ==alarmMinute) { digitalWrite(13, HIGH); } else { digitalWrite(13, LOW); }}
    시간 설정Arduino
    ds1307은 정확한 시간에서 벗어날 수 있기 때문입니다. 이 프로그램을 사용하면 시리얼 모니터를 통해 시간을 설정할 수 있습니다. 시간이 올바르지 않다는 것을 알게 되면 rtc 모듈을 arduino에 플러그인하고 이 프로그램을 업로드하기만 하면 됩니다. 그런 다음 직렬 모니터에 들어가 정확한 날짜, 월, 년, 시간을 설정하십시오. 그런 다음 다른 프로그램을 업로드하기만 하면 7 세그먼트 디스플레이에 정확한 시간이 표시됩니다.
    /* RealTimeClockDS1307 - DS1307 RTC 모듈을 제어하는 ​​라이브러리 Copyright (c) 2011 David H. Brown. 판권 소유 John Waters와 Maurice Ribble의 초기 작업과 매우 유용한 작업에 대해 많은 감사를 드립니다(그들의 코드를 사용하지 않더라도):- http://combustory.com/wiki/index.php/RTC1307_ -_Real_Time_Clock - http://www.glacialwanderer.com/hobbyrobotics/?p=12 이 라이브러리는 무료 소프트웨어입니다. 자유 소프트웨어 재단(Free Software Foundation)에서 발행한 GNU 약소 일반 공중 라이선스(GNU Lesser General Public License) 조건에 따라 이를 재배포 및/또는 수정할 수 있습니다. 라이선스 버전 2.1 또는 (귀하의 선택에 따라) 이후 버전. 이 라이브러리는 유용할 것이라는 희망으로 배포되지만 어떠한 보증도 하지 않습니다. 상품성 또는 특정 목적에의 적합성에 대한 묵시적 보증도 없이. 자세한 내용은 GNU 약소 일반 공중 사용 허가서를 참조하십시오. 이 라이브러리와 함께 GNU Lesser General Public License 사본을 받았어야 합니다. 그렇지 않은 경우 Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA*/#include #include //RealTimeClock RTC;// =new RealTimeClock();#define Display_Clock_Every_N_Seconds 1#define Display_ShortHelp_Every_N_Seconds 25//#define TEST_Squarewave//#define TEST_StopStart//#define TEST_1224Switchint count=0;char formatted[0] ="0; 무효 설정() {// Wire.begin(); Serial.begin(9600);} 무효 루프() { if(Serial.available()) { processCommand(); } 지연(1000); RTC.readClock(); 카운트++; if(count % Display_Clock_Every_N_Seconds ==0){ Serial.print(count); Serial.print(":"); RTC.getFormatted(포맷됨); Serial.print(포맷됨); 직렬.println(); } if(count % Display_ShortHelp_Every_N_Seconds ==0) { Serial.println("명령 목록을 보려면 ?를 보내십시오."); }#ifdef TEST_Squarewaveif(count%10 ==0){ switch(count/10 % 6) { case 0:Serial.print("구형파 비활성화(낮은 임피던스):"); RTC.sqwDisable(0); Serial.println((int) RTC.readData(7)); 부서지다; case 1:Serial.print("구형파 비활성화(고임피던스):"); RTC.sqwDisable(1); Serial.println((int) RTC.readData(7)); 부서지다; case 2:Serial.println("구형파는 1Hz에서 활성화됨"); RTC.sqwEnable(RTC.SQW_1Hz); 부서지다; 사례 3:Serial.println("4.096kHz에서 구형파 활성화"); RTC.sqwEnable(RTC.SQW_4kHz); 부서지다; case 4:Serial.println("8.192kHz에서 구형파 활성화"); RTC.sqwEnable(RTC.SQW_8kHz); 부서지다; 사례 5:Serial.println("구형파는 32.768kHz에서 활성화됨"); RTC.sqwEnable(RTC.SQW_32kHz); 부서지다; 기본값:Serial.println("구형파 테스트가 정의되지 않았습니다."); }//switch}#endif#ifdef TEST_StopStartif(count%10 ==0){ if(!RTC.isStopped()) { if(RTC.getSeconds() <45) { Serial.println("10초 동안 시계 중지 "); RTC.stop(); }//시간이 충분하다면 } else { RTC.setSeconds(RTC.getSeconds()+11); RTC.start(); Serial.println("11초를 추가하고 시계를 다시 시작합니다."); }}//10 카운트의 배수인 경우#endif#ifdef TEST_1224Switch if(count%10 ==0) { if(count %20 ==0) { Serial.println("12시간제로 전환"); RTC.switchTo12h(); RTC.setClock(); } else { Serial.println("24시간제로 전환"); RTC.switchTo24h(); RTC.setClock(); } }#endif} 무효 processCommand() { if(!Serial.available()) { 반환; } 문자 명령 =Serial.read(); int in,in2; switch(command) { case 'H':case 'h':in=SerialReadPosInt(); RTC.setHours(in); RTC.setClock(); Serial.print("시간을 "로 설정"); Serial.println(입력); 부서지다; 케이스 'I':케이스 'i':in=SerialReadPosInt(); RTC.setMinutes(in); RTC.setClock(); Serial.print("분을 "로 설정"); Serial.println(입력); 부서지다; 케이스 'S':케이스 's':in=SerialReadPosInt(); RTC.setSeconds(인); RTC.setClock(); Serial.print("초를 "로 설정"); Serial.println(입력); 부서지다; 케이스 'Y':케이스 'y':in=SerialReadPosInt(); RTC.setYear(in); RTC.setClock(); Serial.print("연도를 "로 설정"); Serial.println(입력); 부서지다; 케이스 'M':케이스 'm':in=SerialReadPosInt(); RTC.setMonth(in); RTC.setClock(); Serial.print("월을 "로 설정"); Serial.println(입력); 부서지다; 케이스 'D':케이스 'd':in=SerialReadPosInt(); RTC.setDate(입력); RTC.setClock(); Serial.print("날짜를 "로 설정); Serial.println(입력); 부서지다; case 'W':Serial.print("요일은 "); Serial.println((int) RTC.getDayOfWeek()); 부서지다; 케이스 'w':in=SerialReadPosInt(); RTC.setDayOfWeek(인); RTC.setClock(); Serial.print("요일을 "로 설정"); Serial.println(입력); 부서지다; 케이스 't':케이스 'T':if(RTC.is12hour()) { RTC.switchTo24h(); Serial.println("24시간제로 전환합니다."); } else { RTC.switchTo12h(); Serial.println("12시간제로 전환합니다."); } RTC.setClock(); 부서지다; 케이스 'A':케이스 'a':if(RTC.is12hour()) { RTC.setAM(); RTC.setClock(); Serial.println("오전 설정."); } else { Serial.println("(24시간제 모드에서만 시간을 설정합니다.)"); } 부서지다; 케이스 'P':케이스 'p':if(RTC.is12hour()) { RTC.setPM(); RTC.setClock(); Serial.println("오후를 설정합니다."); } else { Serial.println("(24시간제 모드에서만 시간을 설정합니다.)"); } 부서지다; 경우 'q':RTC.sqwEnable(RTC.SQW_1Hz); Serial.println("구형파 출력을 1Hz로 설정했습니다."); 부서지다; 경우 'Q':RTC.sqwDisable(0); Serial.println("구형파 출력 비활성화(낮음)"); 부서지다; 케이스 'z':RTC.start(); Serial.println("클럭 오실레이터가 시작되었습니다."); 부서지다; 케이스 'Z':RTC.stop(); Serial.println("시계 오실레이터가 멈췄습니다."); 부서지다; 경우 '>':in=SerialReadPosInt(); in2=SerialReadPosInt(); RTC.writeData(in,in2); Serial.print("등록에 쓰기 "); Serial.print(입력); Serial.print("값 "); 직렬.println(in2); 부서지다; 케이스 '<':in=SerialReadPosInt(); in2=RTC.readData(in); Serial.print("레지스터에서 읽기 "); Serial.print(입력); Serial.print("값 "); 직렬.println(in2); 부서지다; 기본값:Serial.println("알 수 없는 명령입니다. 다음을 시도하십시오:"); Serial.println(" h## - 시간 설정 d## - 날짜 설정"); Serial.println(" i## - mInutes m## 설정 - 월 설정"); Serial.println(" s## - 초 설정 y## - 연도 설정"); Serial.println(" w## - 임의의 요일 설정"); Serial.println(" t - 24시간 모드 전환"); Serial.println(" a - AM p 설정 - PM 설정"); 직렬.println(); Serial.println(" z - 시계 시작 Z - 시계 중지"); Serial.println(" q - SQW/OUT =1Hz Q - SQW/OUT 중지"); 직렬.println(); Serial.println(">##,### - 레지스터에 쓰기 ## 값 ###"); Serial.println(" <## - 레지스터 ##의 값을 읽습니다."); }//명령 스위치 켜기 }//다른 무언가가 있을 때까지//또는 serial.int에서 더 이상 데이터를 사용할 수 없을 때까지 숫자를 읽습니다. SerialReadPosInt() { int i =0; 부울 완료=거짓; while(Serial.available() &&!done) { char c =Serial.read(); if (c>='0' &&c <='9') { i =i * 10 + (c-'0'); } else { 완료 =참; } } 리턴 i;}
    RealTimeClockDS1307.cppC/C++
    이것은 실시간 시계의 라이브러리 파일 중 하나입니다. "RealTimeClockDS1307"이라는 폴더를 만들고 이 폴더에 복사합니다. 그게 다야. 컴파일할 필요가 없습니다.
    /* RealTimeClockDS1307 - DS1307 RTC 모듈을 제어하는 ​​라이브러리 Copyright (c) 2011 David H. Brown. 판권 소유 v0.92 Arduino 1.00용으로 업데이트됨; 이전 버전에서 다시 테스트하지 않았습니다. John Waters와 Maurice Ribble의 초기 작업과 매우 유용한 작업에 감사드립니다(그들의 코드를 사용하지 않더라도):- http://combustory.com/wiki/index .php/RTC1307_-_Real_Time_Clock - http://www.glacialwanderer.com/hobbyrobotics/?p=12 이 라이브러리는 무료 소프트웨어입니다. 자유 소프트웨어 재단(Free Software Foundation)에서 발행한 GNU 약소 일반 공중 라이선스(GNU Lesser General Public License) 조건에 따라 이를 재배포 및/또는 수정할 수 있습니다. 라이선스 버전 2.1 또는 (귀하의 선택에 따라) 이후 버전. 이 라이브러리는 유용할 것이라는 희망으로 배포되지만 어떠한 보증도 하지 않습니다. 상품성 또는 특정 목적에의 적합성에 대한 묵시적 보증도 없이. 자세한 내용은 GNU 약소 일반 공중 사용 허가서를 참조하십시오. 이 라이브러리와 함께 GNU Lesser General Public License 사본을 받았어야 합니다. 그렇지 않은 경우 Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA*/ /******************** ************************************************** ***** * 포함 **************************************** **************************************/#include "RealTimeClockDS1307.h#include <와이어 .h>/************************************************ ***************************** * 정의 **************** ************************************************** *********/#define DS1307_I2C_ADDRESS 0x68 // 이것은 I2C 주소입니다/************************ ************************************************** *** * 생성자 ********************************************* *********************************/RealTimeClockDS1307::RealTimeClockDS1307(){ Wire.begin(); //Wire.begin()이 호출되지 않은 // 전에 시계 읽기를 시도해서는 안 됩니다. readClock()이 중단됩니다. //다행히 Wire.begin()을 //여러 번 호출해도 역효과가 없는 것 같습니다.} /************************** ************************************************** ***** * 사용자 API ****************************************** *********************************//***** 칩 읽기/쓰기 *** ***/void RealTimeClockDS1307::readClock(){ // 레지스터 포인터 재설정 Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write((uint8_t) 0x00); Wire.endTransmission(); Wire.requestFrom(DS1307_I2C_ADDRESS, 8); _reg0_sec =Wire.read(); _reg1_min =Wire.read(); _reg2_hour =Wire.read(); _reg3_day =Wire.read(); _reg4_date =Wire.read(); _reg5_month =Wire.read(); _reg6_year =Wire.read(); _reg7_sqw =Wire.read();}void RealTimeClockDS1307::setClock(){ //편집증이 되기 위해 먼저 시계를 멈출 것입니다. //우리가 작성하는 동안 롤오버가 발생하지 않도록 // 쓰기 데이터(0,0x80); //이제 두 번째 Wire.beginTransmission(DS1307_I2C_ADDRESS)을 *제외하고* 모든 것을 작성할 것입니다. Wire.write((uint8_t) 0x01); Wire.write(_reg1_min); Wire.write(_reg2_hour); Wire.write(_reg3_day); Wire.write(_reg4_date); Wire.write(_reg5_month); Wire.write(_reg6_year); Wire.endTransmission(); //이제 초를 씁니다. //_reg0_sec이 우리가 원하는 것을 이미 알고 있기 때문에 시계가 이미 실행 중인지 여부를 //추적할 필요가 없었습니다. // 새 초 값을 쓸 때 시계를 다시 시작합니다. 쓰기 데이터(0,_reg0_sec); }void RealTimeClockDS1307::stop(){ //"레지스터 0의 비트 7은 클럭 정지(CH) 비트입니다. //이 비트가 1로 설정되면 오실레이터가 비활성화됩니다." _reg0_sec =_reg0_sec | 0x80; writeData(0,_reg0_sec);}void RealTimeClockDS1307::start(){ //"레지스터 0의 비트 7은 클럭 정지(CH) 비트입니다. //이 비트가 1로 설정되면 발진기가 비활성화됩니다." _reg0_sec =_reg0_sec &~0x80; writeData(0,_reg0_sec);}RealTimeClockDS1307::writeData(바이트 regNo, 바이트 값){ if(regNo> 0x3F) { 반환; } Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write(regNo); Wire.write(값); Wire.endTransmission();} void RealTimeClockDS1307::writeData(byte regNo, void * 소스, int 길이){ char * p =(char*) 소스; if(regNo> 0x3F || 길이> 0x3F) { 반환; } Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write(regNo); for(int i=0; i<길이; i++) { Wire.write(*p); p++; } Wire.endTransmission();}byte RealTimeClockDS1307::readData(byte regNo){ if(regNo> 0x3F) { return 0xff; } Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write(regNo); Wire.endTransmission(); Wire.requestFrom(DS1307_I2C_ADDRESS, 1); return Wire.read();} 무효 RealTimeClockDS1307::readData(바이트 regNo, 무효 * 대상, 정수 길이){ char * p =(char*) 대상; if(regNo> 0x3F || 길이> 0x3F) { 반환; } Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write(regNo); Wire.endTransmission(); Wire.requestFrom(DS1307_I2C_ADDRESS, 길이); for(int i=0; i<길이; i++) { *p=Wire.read(); p++; }}무효 RealTimeClockDS1307::sqwEnable(바이트 주파수){ if(주파수> 3) { 반환; } //비트 4는 활성화(0x10)입니다. //비트 7은 비활성화된 경우 현재 출력 상태입니다. _reg7_sqw =_reg7_sqw &0x80 | 0x10 | 빈도; writeData(0x07, _reg7_sqw);}void RealTimeClockDS1307::sqwDisable(boolean outputLevel){ //비트 7 0x80 출력 + 비트 4 0x10 둘 다 0으로 활성화, //부울을 비트 7로 이동한 OR _reg7_sqw =_reg7 0x90 | (출력레벨 <<7); 쓰기 데이터(0x07, _reg7_sqw); //참고:데이터 시트에 따라 "OUT(출력 제어):이 비트는 // 구형파 출력이 비활성화될 때 // SQW/OUT 핀의 출력 레벨을 제어합니다. SQWE =0인 경우 논리 레벨 //SQW/OUT 핀은 OUT =1이면 1이고 OUT =0이면 0입니다." //"SQW/OUT 핀은 오픈 드레인이며 외부 풀업 저항이 // 필요합니다." //Sparkfun 브레이크아웃 보드 //BOB-00099에서 //Vcc+5V에 대한 저항을 통해 SQW 핀에 연결된 LED는 OUT=0일 때 조명이 켜지고 OUT=1일 때 어두웠음을 언급할 가치가 있습니다. /오픈 드레인이라는 것을 기억할 때까지 내가 예상한 것과 반대입니다(필요한 경우 Google에서 검색). 기본적으로 //높거나 낮은 접지(드레인)에 대한 *임피던스*를 의미하므로 논리 레벨(예:+3.3V rel Gnd)을 의미하지는 않습니다. 따라서 High는 기본적으로 //개방형 스위치입니다. 낮음은 접지에 연결됩니다.}/****** GETTERS ******/boolean RealTimeClockDS1307::is12hour() { //12시간 모드는 시간 레지스터의 비트 6이 높음 반환((_reg2_hour &0x40)으로 설정됨 ==0x40);}부울 RealTimeClockDS1307::isPM(){ //12시간 모드이지만 5시 레지스터가 PM을 나타내는 경우 if(is12hour()) { return ((_reg2_hour &0x20) ==0x20); } //그렇지 않으면 시간이>11인 시간을 PM으로 간주해 보겠습니다. return (getHours()> 11);}boolean RealTimeClockDS1307::isStopped(){ //초 레지스터의 비트 7은 높은 반환 값일 때 시계를 멈춥니다. ((_reg0_sec &0x80) ==0x80);}int RealTimeClockDS1307::getHours(){ if(is12hour()) { //비트 5를 포함하지 않음, am/pm 표시기는 bcdToDec(_reg2_hour &0x1f)를 반환합니다. } //비트 4-5는 수십 시간입니다. return bcdToDec(_reg2_hour &0x3f);}int RealTimeClockDS1307::getMinutes(){ //0x7f로 마스킹할 수 있지만 bcdToDec(_reg1_min);}int RealTimeClockDS1307을 반환할 필요는 없습니다. :getSeconds(){ //오실레이터 시작/중지 비트 7을 마스크해야 함 return bcdToDec(_reg0_sec &0x7f);}int RealTimeClockDS1307::getYear(){ return bcdToDec(_reg6_year);}int RealTimeClockDS1307::getMonth(){ 0x1f로 마스킹할 수 있지만 bcdToDec(_reg5_month);}int RealTimeClockDS1307::getDate(){ // 0x3f로 마스킹할 수 있지만 bcdToDec(_reg4_date);}int RealTimeClockDS1307::getDay( ){ return getDate();}int RealTimeClockDS1307::getDayOfWeek(){ // 0x07로 마스크할 수 있지만 bcdToDec(_reg3_day)를 반환할 필요는 없습니다.}void RealTimeClockDS1307::getFormatted(char * buffer){ int i=0; //대상 문자열 형식:YY-MM-DD HH:II:SS 버퍼[i++]=highNybbleToASCII(_reg6_year); 버퍼[i++]=lowNybbleToASCII(_reg6_year); 버퍼[i++]='-'; 버퍼[i++]=highNybbleToASCII(_reg5_month &0x1f); 버퍼[i++]=lowNybbleToASCII(_reg5_month); 버퍼[i++]='-'; 버퍼[i++]=highNybbleToASCII(_reg4_date &0x3f); 버퍼[i++]=lowNybbleToASCII(_reg4_date); 버퍼[i++]=' '; if(is12hour()) { 버퍼[i++]=highNybbleToASCII(_reg2_hour &0x1f); } else { 버퍼[i++]=highNybbleToASCII(_reg2_hour &0x3f); } 버퍼[i++]=lowNybbleToASCII(_reg2_hour); 버퍼[i++]=':'; 버퍼[i++]=highNybbleToASCII(_reg1_min &0x7f); 버퍼[i++]=lowNybbleToASCII(_reg1_min); 버퍼[i++]=':'; buffer[i++]=highNybbleToASCII(_reg0_sec &0x7f); buffer[i++]=lowNybbleToASCII(_reg0_sec); if(is12hour()) { if(isPM()) { buffer[i++]='P'; } else { buffer[i++]='A'; } } buffer[i++]=0x00;}void RealTimeClockDS1307::getFormatted2k(char * buffer){ buffer[0]='2'; buffer[1]='0'; getFormatted(&buffer[2]);}/**** SETTERS *****/void RealTimeClockDS1307::setSeconds(int s){ if (s <60 &&s>=0) { //need to preserve oscillator bit _reg0_sec =decToBcd(s) | (_reg0_sec &0x80); }}void RealTimeClockDS1307::setMinutes(int m){ if (m <60 &&m>=0) { _reg1_min =decToBcd(m); }}void RealTimeClockDS1307::setHours(int h){ if (is12hour()) { if (h>=1 &&h <=12) { //preserve 12/24 and AM/PM bits _reg2_hour =decToBcd(h) | (_reg2_hour &0x60); } } else { if (h>=0 &&h <=24) { //preserve 12/24 bit _reg2_hour =decToBcd(h) | (_reg2_hour &0x40); } }//else}//setHoursvoid RealTimeClockDS1307::set24h(){ //"Bit 6 of the hours register is defined as the //"12- or 24-hour mode select bit. //"When high, the 12-hour mode is selected" //So, mask the curent value with the complement turn off that bit:_reg2_hour =_reg2_hour &~0x40; }void RealTimeClockDS1307::setAM(){ //"In the 12-hour mode, bit 5 is the AM/PM bit with logic high being PM" //so we need to OR with 0x40 to set 12-hour mode and also //turn off the PM bit by masking with the complement _reg2_hour =_reg2_hour &~0x20 | 0x40;}void RealTimeClockDS1307::setPM(){ //"In the 12-hour mode, bit 5 is the AM/PM bit with logic high being PM" //so we need to OR with 0x40 and 0x20 to set 12-hour mode and also //turn on the PM bit:_reg2_hour =_reg2_hour | 0x60;}void RealTimeClockDS1307::switchTo12h(){ if(is12hour()) { return; } int h =getHours(); if (h <12) { setAM(); } else { h =h-12; setPM(); } if (h==0) { h=12; } setHours(h);}void RealTimeClockDS1307::switchTo24h(){ if(!is12hour()) { return; } int h =getHours(); if(h==12) {//12 PM is just 12; 12 AM is 0 hours. h =0; } if (isPM()) {//if it was 12 PM, then h=0 above and so we're back to 12:h =h+12; } set24h(); setHours(h);}void RealTimeClockDS1307::setDayOfWeek(int d){ if (d> 0 &&d <8) { _reg3_day =decToBcd(d); }}void RealTimeClockDS1307::setDate(int d){ if (d> 0 &&d <32) { _reg4_date =decToBcd(d); }}void RealTimeClockDS1307::setDay(int d){ setDate(d);}void RealTimeClockDS1307::setMonth(int m){ if (m> 0 &&m <13) { _reg5_month =decToBcd(m); }}void RealTimeClockDS1307::setYear(int y){ if (y>=0 &&y <100) { _reg6_year =decToBcd(y); }}/***************************************** * Private methods *****************************************/byte RealTimeClockDS1307::decToBcd(byte b){ return ( ((b/10) <<4) + (b%10) );}// Convert binary coded decimal to normal decimal numbersbyte RealTimeClockDS1307::bcdToDec(byte b){ return ( ((b>> 4)*10) + (b%16) );}char RealTimeClockDS1307::lowNybbleToASCII(byte b) { b =b &0x0f; if(b <10) { //0 is ASCII 48 return 48+b; } //A is ASCII 55 return 55+b;}char RealTimeClockDS1307::highNybbleToASCII(byte b){ return lowNybbleToASCII(b>> 4);}/***** INSTANCE *******/RealTimeClockDS1307 RTC =RealTimeClockDS1307();
    ReadmeClojure
    Copy this also into the same folder you created named "RealTimeClockDS1307".
    My goal in creating yet another DS1307 library was to provideeasy access to some of the other functions I needed from the chip,specifically its square wave output and its battery-backed RAM.## Documentation@todo Mostly comments in `RealTimeClockDS1307.h`## Examples (in /examples folder)- `RealTimeClockDS1307_Test.pde` allow you to turn the clock on/off,set date/time, set 12/24h, [de]activate the square wave, andread/write memory from the Serial Monitor.- `RealTimeClockDS1307.fz` is a Fritzing breadboard layout showingthe basic hookup of the Sparkfun RTC module to an Arduino. Includedis an optional resistor+LED to show the square wave (note that it'san open drain, so you hook up to it rather differently than, say, pin 13).## Changelog##### Version 0.95* Reverse renaming of getDate() and setDate(), now getDay() is calling getDate() and setDay() is calling setDate()* Readme improvements##### Version 0.94* changed getDate() to getDay() and setDate() to setDay()* updated keywords.txt* updated example##### Version 0.93* added keywords.txt for syntax highlighting##### Version 0.92 RC* Updated for Arduino 1.00; testing with Andreas Giemza (hurik)##### Version 0.91* added multi-byte read/write##### Version 0.9 RC* initial release## Future - web page documentation## CreditsMuch thanks to John Waters and Maurice Ribble for theirearlier and very helpful work (even if I didn't wind upusing any of their code):- [http://combustory.com/wiki/index.php/RTC1307_-_Real_Time_Clock](http://combustory.com/wiki/index.php/RTC1307_-_Real_Time_Clock)- [http://www.glacialwanderer.com/hobbyrobotics/?p=12](http://www.glacialwanderer.com/hobbyrobotics/?p=12)## CopyrightRealTimeClockDS1307 - library to control a DS1307 RTC moduleCopyright (c) 2011 David H. Brown. All rights reserved## License This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 상품성 또는 특정 목적에의 적합성에 대한 묵시적 보증도 없이. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
    RealTimeClockDS1307.hC/C++
    This is the main header file of the real time clock. Copy this also into the folder you previously created named "RealTimeClockDS1307". Now you have all the files for the Real Time Clock. Enter the arduino ide and under the 'Sketch' menu click on the 'include library' option and then search your folder under the 'Add .ZIP Library". This will do the trick and you will now be able to set the time in the RTC module.
    /* RealTimeClockDS1307 - library to control a DS1307 RTC module Copyright (c) 2011 David H. Brown. All rights reserved v0.92 Updated for Arduino 1.00; not re-tested on earlier versions Much thanks to John Waters and Maurice Ribble for their earlier and very helpful work (even if I didn't wind up using any of their code):- http://combustory.com/wiki/index.php/RTC1307_-_Real_Time_Clock - http://www.glacialwanderer.com/hobbyrobotics/?p=12 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 상품성 또는 특정 목적에의 적합성에 대한 묵시적 보증도 없이. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA*/#ifndef RealTimeClockDS1307_h#define RealTimeClockDS1307_h #if defined(ARDUINO) &&ARDUINO>=100 #include "Arduino.h" #else #include "WProgram.h" #endif//#include //#include  //need/want 'boolean' and 'byte' types used by Arduino//#undef round is required to avoid a compile-time//"expected unqualified-id before 'double'" error in math.h//see:http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1247924528/3#undef round #include #define ARDUINO_PIN_T uint8_tclass RealTimeClockDS1307{ private:byte _reg0_sec; byte _reg1_min; byte _reg2_hour; byte _reg3_day; byte _reg4_date; byte _reg5_month; byte _reg6_year; byte _reg7_sqw; byte decToBcd(byte); byte bcdToDec(byte); char lowNybbleToASCII(byte); char highNybbleToASCII(byte); public:RealTimeClockDS1307(); void readClock();//read registers (incl sqw) to local store void setClock();//update clock registers from local store void stop();//immediate; does not require setClock(); void start();//immediate; does not require setClock(); void sqwEnable(byte);//enable the square wave with the specified frequency void sqwDisable(boolean);//disable the square wave, setting output either high or low void writeData(byte, byte);//write a single value to a register void writeData(byte, void *, int);//write several values consecutively byte readData(byte);//read a single value from a register void readData(byte, void *, int);//read several values into a buffer int getHours(); int getMinutes(); int getSeconds(); int getYear(); int getMonth(); int getDate(); int getDay(); int getDayOfWeek(); boolean is12hour(); boolean isPM(); boolean isStopped(); //getFormatted writes into a char array provided by you. Format is:// YY-MM-DD HH:II:SS ... plus "A" or "P" if in 12-hour mode //and of course a NULL terminator. So, [18] for 24h or [19] for 12h void getFormatted(char *);//see comment above void getFormatted2k(char *);//as getFormatted, but with "20" prepended //must also call setClock() after any of these //before next readClock(). Note that invalid dates are not //corrected by the clock. All the clock knows is when it should //roll over to the next month rather than the next date in the same month. void setSeconds(int); void setMinutes(int); //setHours rejects values out of range for the current 12/24 mode void setHours(int); void setAM();//does not consider hours; see switchTo24() void setPM();//does not consider hours; see switchTo24() void set24h();//does not consider hours; see switchTo24() void switchTo24h();//returns immediately if already 24h void switchTo12h();//returns immediately if already 12h void setDayOfWeek(int);//incremented at midnight; not set by date (no fixed meaning) void setDate(int);//allows 1-31 for *all* months. void setDay(int); void setMonth(int); void setYear(int); //squarewave frequencies:static const byte SQW_1Hz=0x00; static const byte SQW_4kHz=0x01;//actually 4.096kHz static const byte SQW_8kHz=0x02;//actually 8.192kHz static const byte SQW_32kHz=0x03;//actually 32.768kHz};extern RealTimeClockDS1307 RTC;#endif
    another fileC/C++
    add this to the 'RealTimeClockDS1307' folder.
    ########################################## Syntax Coloring Map RealTimeClockDS1307################################################################################# Instances (KEYWORD2)#######################################RTC KEYWORD2########################################## Methods and Functions (KEYWORD2)#########################################readClock KEYWORD2setClock KEYWORD2stop KEYWORD2start KEYWORD2sqwEnable KEYWORD2sqwDisable KEYWORD2writeData KEYWORD2readData KEYWORD2getHours KEYWORD2getMinutes KEYWORD2getSeconds KEYWORD2getYear KEYWORD2getMonth KEYWORD2getDate KEYWORD2getDay KEYWORD2getDayOfWeek KEYWORD2is12hour KEYWORD2isPM KEYWORD2isStopped KEYWORD2getFormatted KEYWORD2getFormatted2k KEYWORD2setSeconds KEYWORD2setMinutes KEYWORD2setHours KEYWORD2setAM KEYWORD2setPM KEYWORD2set24h KEYWORD2switchTo24h KEYWORD2switchTo12h KEYWORD2setDayOfWeek KEYWORD2setDate KEYWORD2setDay KEYWORD2setMonth KEYWORD2setYear KEYWORD2########################################## Constants (LITERAL1)#########################################SQW_1Hz LITERAL1SQW_4kHz LITERAL1SQW_8kHz LITERAL1SQW_32kHz LITERAL1
    RTClib filesC#
    create a folder named 'RTClib' and add the following files into it
    ########################################## Syntax Coloring Map RealTimeClockDS1307################################################################################# Instances (KEYWORD2)#######################################RTC KEYWORD2########################################## Methods and Functions (KEYWORD2)#########################################readClock KEYWORD2setClock KEYWORD2stop KEYWORD2start KEYWORD2sqwEnable KEYWORD2sqwDisable KEYWORD2writeData KEYWORD2readData KEYWORD2getHours KEYWORD2getMinutes KEYWORD2getSeconds KEYWORD2getYear KEYWORD2getMonth KEYWORD2getDate KEYWORD2getDay KEYWORD2getDayOfWeek KEYWORD2is12hour KEYWORD2isPM KEYWORD2isStopped KEYWORD2getFormatted KEYWORD2getFormatted2k KEYWORD2setSeconds KEYWORD2setMinutes KEYWORD2setHours KEYWORD2setAM KEYWORD2setPM KEYWORD2set24h KEYWORD2switchTo24h KEYWORD2switchTo12h KEYWORD2setDayOfWeek KEYWORD2setDate KEYWORD2setDay KEYWORD2setMonth KEYWORD2setYear KEYWORD2########################################## Constants (LITERAL1)#########################################SQW_1Hz LITERAL1SQW_4kHz LITERAL1SQW_8kHz LITERAL1SQW_32kHz LITERAL1
    library.properties(name)C/C++
    add this to the RTClib folder
    My goal in creating yet another DS1307 library was to provideeasy access to some of the other functions I needed from the chip,specifically its square wave output and its battery-backed RAM.## Documentation@todo Mostly comments in `RealTimeClockDS1307.h`## Examples (in /examples folder)- `RealTimeClockDS1307_Test.pde` allow you to turn the clock on/off,set date/time, set 12/24h, [de]activate the square wave, andread/write memory from the Serial Monitor.- `RealTimeClockDS1307.fz` is a Fritzing breadboard layout showingthe basic hookup of the Sparkfun RTC module to an Arduino. Includedis an optional resistor+LED to show the square wave (note that it'san open drain, so you hook up to it rather differently than, say, pin 13).## Changelog##### Version 0.95* Reverse renaming of getDate() and setDate(), now getDay() is calling getDate() and setDay() is calling setDate()* Readme improvements##### Version 0.94* changed getDate() to getDay() and setDate() to setDay()* updated keywords.txt* updated example##### Version 0.93* added keywords.txt for syntax highlighting##### Version 0.92 RC* Updated for Arduino 1.00; testing with Andreas Giemza (hurik)##### Version 0.91* added multi-byte read/write##### Version 0.9 RC* initial release## Future - web page documentation## CreditsMuch thanks to John Waters and Maurice Ribble for theirearlier and very helpful work (even if I didn't wind upusing any of their code):- [http://combustory.com/wiki/index.php/RTC1307_-_Real_Time_Clock](http://combustory.com/wiki/index.php/RTC1307_-_Real_Time_Clock)- [http://www.glacialwanderer.com/hobbyrobotics/?p=12](http://www.glacialwanderer.com/hobbyrobotics/?p=12)## CopyrightRealTimeClockDS1307 - library to control a DS1307 RTC moduleCopyright (c) 2011 David H. Brown. All rights reserved## License This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 상품성 또는 특정 목적에의 적합성에 대한 묵시적 보증도 없이. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
    RTClibC/C++
    add this to the RTClib folder
    /* RealTimeClockDS1307 - library to control a DS1307 RTC module Copyright (c) 2011 David H. Brown. All rights reserved v0.92 Updated for Arduino 1.00; not re-tested on earlier versions Much thanks to John Waters and Maurice Ribble for their earlier and very helpful work (even if I didn't wind up using any of their code):- http://combustory.com/wiki/index.php/RTC1307_-_Real_Time_Clock - http://www.glacialwanderer.com/hobbyrobotics/?p=12 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 상품성 또는 특정 목적에의 적합성에 대한 묵시적 보증도 없이. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA*/ /****************************************************************************** * Includes ******************************************************************************/#include "RealTimeClockDS1307.h"#include /****************************************************************************** * Definitions ******************************************************************************/#define DS1307_I2C_ADDRESS 0x68 // This is the I2C address/****************************************************************************** * Constructors ******************************************************************************/RealTimeClockDS1307::RealTimeClockDS1307(){ Wire.begin(); //must NOT attempt to read the clock before //Wire.begin() has not been called; readClock() will hang. //Fortunately, it seems that you can call Wire.begin() //multiple times with no adverse effect).} /****************************************************************************** * User API ******************************************************************************//***** CHIP READ/WRITE ******/void RealTimeClockDS1307::readClock(){ // Reset the register pointer Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write((uint8_t) 0x00); Wire.endTransmission(); Wire.requestFrom(DS1307_I2C_ADDRESS, 8); _reg0_sec =Wire.read(); _reg1_min =Wire.read(); _reg2_hour =Wire.read(); _reg3_day =Wire.read(); _reg4_date =Wire.read(); _reg5_month =Wire.read(); _reg6_year =Wire.read(); _reg7_sqw =Wire.read();}void RealTimeClockDS1307::setClock(){ //to be paranoid, we're going to first stop the clock //to ensure we don't have rollovers while we're //writing:writeData(0,0x80); //now, we'll write everything *except* the second Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write((uint8_t) 0x01); Wire.write(_reg1_min); Wire.write(_reg2_hour); Wire.write(_reg3_day); Wire.write(_reg4_date); Wire.write(_reg5_month); Wire.write(_reg6_year); Wire.endTransmission(); //now, we'll write the seconds; we didn't have to keep //track of whether the clock was already running, because //_reg0_sec already knows what we want it to be. This //will restart the clock as it writes the new seconds value. writeData(0,_reg0_sec); }void RealTimeClockDS1307::stop(){ //"Bit 7 of register 0 is the clock halt (CH) bit. //When this bit is set to a 1, the oscillator is disabled." _reg0_sec =_reg0_sec | 0x80; writeData(0,_reg0_sec);}void RealTimeClockDS1307::start(){ //"Bit 7 of register 0 is the clock halt (CH) bit. //When this bit is set to a 1, the oscillator is disabled." _reg0_sec =_reg0_sec &~0x80; writeData(0,_reg0_sec);}void RealTimeClockDS1307::writeData(byte regNo, byte value){ if(regNo> 0x3F) { return; } Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write(regNo); Wire.write(value); Wire.endTransmission();}void RealTimeClockDS1307::writeData(byte regNo, void * source, int length){ char * p =(char*) source; if(regNo> 0x3F || length> 0x3F) { return; } Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write(regNo); for(int i=0; i 0x3F) { return 0xff; } Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write(regNo); Wire.endTransmission(); Wire.requestFrom(DS1307_I2C_ADDRESS, 1); return Wire.read();}void RealTimeClockDS1307::readData(byte regNo, void * dest, int length){ char * p =(char*) dest; if(regNo> 0x3F || length> 0x3F) { return; } Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.write(regNo); Wire.endTransmission(); Wire.requestFrom(DS1307_I2C_ADDRESS, length); for(int i=0; i 3) { return; } //bit 4 is enable (0x10); //bit 7 is current output state if disabled _reg7_sqw =_reg7_sqw &0x80 | 0x10 | frequency; writeData(0x07, _reg7_sqw);}void RealTimeClockDS1307::sqwDisable(boolean outputLevel){ //bit 7 0x80 output + bit 4 0x10 enable both to zero, //the OR with the boolean shifted up to bit 7 _reg7_sqw =_reg7_sqw &~0x90 | (outputLevel <<7); writeData(0x07, _reg7_sqw); //note:per the data sheet, "OUT (Output control):This bit controls //the output level of the SQW/OUT pin when the square wave //output is disabled. If SQWE =0, the logic level on the //SQW/OUT pin is 1 if OUT =1 and is 0 if OUT =0." //"The SQW/OUT pin is open drain and requires an external //pull-up resistor." //It is worth mentioning that on the Sparkfun breakout board, //BOB-00099, a LED connected to the SQW pin through a resistor to //Vcc+5V illuminated when OUT=0 and was dark when OUT=1, the //opposite of what I expected until I remembered that it is //an open drain (google it if you need to). Basically, they don't //so much mean a logic level (e.g., +3.3V rel Gnd) as they mean //high or low *impeadance* to ground (drain). So High is basically //an open switch. Low connects to ground.}/***** GETTERS ******/boolean RealTimeClockDS1307::is12hour() { //12-hour mode has bit 6 of the hour register set high return ((_reg2_hour &0x40) ==0x40);}boolean RealTimeClockDS1307::isPM(){ //if in 12-hour mode, but 5 of the hour register indicates PM if(is12hour()) { return ((_reg2_hour &0x20) ==0x20); } //otherwise, let's consider any time with the hour>11 to be PM:return (getHours()> 11);}boolean RealTimeClockDS1307::isStopped(){ //bit 7 of the seconds register stopps the clock when high return ((_reg0_sec &0x80) ==0x80);}int RealTimeClockDS1307::getHours(){ if(is12hour()) { //do not include bit 5, the am/pm indicator return bcdToDec(_reg2_hour &0x1f); } //bits 4-5 are tens of hours return bcdToDec(_reg2_hour &0x3f);}int RealTimeClockDS1307::getMinutes(){ //could mask with 0x7f but shouldn't need to return bcdToDec(_reg1_min);}int RealTimeClockDS1307::getSeconds(){ //need to mask oscillator start/stop bit 7 return bcdToDec(_reg0_sec &0x7f);}int RealTimeClockDS1307::getYear(){ return bcdToDec(_reg6_year);}int RealTimeClockDS1307::getMonth(){ //could mask with 0x1f but shouldn't need to return bcdToDec(_reg5_month);}int RealTimeClockDS1307::getDate(){ //could mask with 0x3f but shouldn't need to return bcdToDec(_reg4_date);}int RealTimeClockDS1307::getDay(){ return getDate();}int RealTimeClockDS1307::getDayOfWeek(){ //could mask with 0x07 but shouldn't need to return bcdToDec(_reg3_day);}void RealTimeClockDS1307::getFormatted(char * buffer){ int i=0; //target string format:YY-MM-DD HH:II:SS buffer[i++]=highNybbleToASCII(_reg6_year); buffer[i++]=lowNybbleToASCII(_reg6_year); buffer[i++]='-'; buffer[i++]=highNybbleToASCII(_reg5_month &0x1f); buffer[i++]=lowNybbleToASCII(_reg5_month); buffer[i++]='-'; buffer[i++]=highNybbleToASCII(_reg4_date &0x3f); buffer[i++]=lowNybbleToASCII(_reg4_date); buffer[i++]=' '; if(is12hour()) { buffer[i++]=highNybbleToASCII(_reg2_hour &0x1f); } else { buffer[i++]=highNybbleToASCII(_reg2_hour &0x3f); } buffer[i++]=lowNybbleToASCII(_reg2_hour); buffer[i++]=':'; buffer[i++]=highNybbleToASCII(_reg1_min &0x7f); buffer[i++]=lowNybbleToASCII(_reg1_min); buffer[i++]=':'; buffer[i++]=highNybbleToASCII(_reg0_sec &0x7f); buffer[i++]=lowNybbleToASCII(_reg0_sec); if(is12hour()) { if(isPM()) { buffer[i++]='P'; } else { buffer[i++]='A'; } } buffer[i++]=0x00;}void RealTimeClockDS1307::getFormatted2k(char * buffer){ buffer[0]='2'; buffer[1]='0'; getFormatted(&buffer[2]);}/**** SETTERS *****/void RealTimeClockDS1307::setSeconds(int s){ if (s <60 &&s>=0) { //need to preserve oscillator bit _reg0_sec =decToBcd(s) | (_reg0_sec &0x80); }}void RealTimeClockDS1307::setMinutes(int m){ if (m <60 &&m>=0) { _reg1_min =decToBcd(m); }}void RealTimeClockDS1307::setHours(int h){ if (is12hour()) { if (h>=1 &&h <=12) { //preserve 12/24 and AM/PM bits _reg2_hour =decToBcd(h) | (_reg2_hour &0x60); } } else { if (h>=0 &&h <=24) { //preserve 12/24 bit _reg2_hour =decToBcd(h) | (_reg2_hour &0x40); } }//else}//setHoursvoid RealTimeClockDS1307::set24h(){ //"Bit 6 of the hours register is defined as the //"12- or 24-hour mode select bit. //"When high, the 12-hour mode is selected" //So, mask the curent value with the complement turn off that bit:_reg2_hour =_reg2_hour &~0x40; }void RealTimeClockDS1307::setAM(){ //"In the 12-hour mode, bit 5 is the AM/PM bit with logic high being PM" //so we need to OR with 0x40 to set 12-hour mode and also //turn off the PM bit by masking with the complement _reg2_hour =_reg2_hour &~0x20 | 0x40;}void RealTimeClockDS1307::setPM(){ //"In the 12-hour mode, bit 5 is the AM/PM bit with logic high being PM" //so we need to OR with 0x40 and 0x20 to set 12-hour mode and also //turn on the PM bit:_reg2_hour =_reg2_hour | 0x60;}void RealTimeClockDS1307::switchTo12h(){ if(is12hour()) { return; } int h =getHours(); if (h <12) { setAM(); } else { h =h-12; setPM(); } if (h==0) { h=12; } setHours(h);}void RealTimeClockDS1307::switchTo24h(){ if(!is12hour()) { return; } int h =getHours(); if(h==12) {//12 PM is just 12; 12 AM is 0 hours. h =0; } if (isPM()) {//if it was 12 PM, then h=0 above and so we're back to 12:h =h+12; } set24h(); setHours(h);}void RealTimeClockDS1307::setDayOfWeek(int d){ if (d> 0 &&d <8) { _reg3_day =decToBcd(d); }}void RealTimeClockDS1307::setDate(int d){ if (d> 0 &&d <32) { _reg4_date =decToBcd(d); }}void RealTimeClockDS1307::setDay(int d){ setDate(d);}void RealTimeClockDS1307::setMonth(int m){ if (m> 0 &&m <13) { _reg5_month =decToBcd(m); }}void RealTimeClockDS1307::setYear(int y){ if (y>=0 &&y <100) { _reg6_year =decToBcd(y); }}/***************************************** * Private methods *****************************************/byte RealTimeClockDS1307::decToBcd(byte b){ return ( ((b/10) <<4) + (b%10) );}// Convert binary coded decimal to normal decimal numbersbyte RealTimeClockDS1307::bcdToDec(byte b){ return ( ((b>> 4)*10) + (b%16) );}char RealTimeClockDS1307::lowNybbleToASCII(byte b) { b =b &0x0f; if(b <10) { //0 is ASCII 48 return 48+b; } //A is ASCII 55 return 55+b;}char RealTimeClockDS1307::highNybbleToASCII(byte b){ return lowNybbleToASCII(b>> 4);}/***** INSTANCE *******/RealTimeClockDS1307 RTC =RealTimeClockDS1307();
    RTClibC/C++
    add this to the RTClib folder. Now you have all the necessary files for the RTClib. Now do the same as I told you with the 'RealTimeClockDS1307' library file.
    /* RealTimeClockDS1307 - library to control a DS1307 RTC module Copyright (c) 2011 David H. Brown. All rights reserved v0.92 Updated for Arduino 1.00; not re-tested on earlier versions Much thanks to John Waters and Maurice Ribble for their earlier and very helpful work (even if I didn't wind up using any of their code):- http://combustory.com/wiki/index.php/RTC1307_-_Real_Time_Clock - http://www.glacialwanderer.com/hobbyrobotics/?p=12 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 상품성 또는 특정 목적에의 적합성에 대한 묵시적 보증도 없이. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA*/#ifndef RealTimeClockDS1307_h#define RealTimeClockDS1307_h #if defined(ARDUINO) &&ARDUINO>=100 #include "Arduino.h" #else #include "WProgram.h" #endif//#include //#include  //need/want 'boolean' and 'byte' types used by Arduino//#undef round is required to avoid a compile-time//"expected unqualified-id before 'double'" error in math.h//see:http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1247924528/3#undef round #include #define ARDUINO_PIN_T uint8_tclass RealTimeClockDS1307{ private:byte _reg0_sec; byte _reg1_min; byte _reg2_hour; byte _reg3_day; byte _reg4_date; byte _reg5_month; byte _reg6_year; byte _reg7_sqw; byte decToBcd(byte); byte bcdToDec(byte); char lowNybbleToASCII(byte); char highNybbleToASCII(byte); public:RealTimeClockDS1307(); void readClock();//read registers (incl sqw) to local store void setClock();//update clock registers from local store void stop();//immediate; does not require setClock(); void start();//immediate; does not require setClock(); void sqwEnable(byte);//enable the square wave with the specified frequency void sqwDisable(boolean);//disable the square wave, setting output either high or low void writeData(byte, byte);//write a single value to a register void writeData(byte, void *, int);//write several values consecutively byte readData(byte);//read a single value from a register void readData(byte, void *, int);//read several values into a buffer int getHours(); int getMinutes(); int getSeconds(); int getYear(); int getMonth(); int getDate(); int getDay(); int getDayOfWeek(); boolean is12hour(); boolean isPM(); boolean isStopped(); //getFormatted writes into a char array provided by you. Format is:// YY-MM-DD HH:II:SS ... plus "A" or "P" if in 12-hour mode //and of course a NULL terminator. So, [18] for 24h or [19] for 12h void getFormatted(char *);//see comment above void getFormatted2k(char *);//as getFormatted, but with "20" prepended //must also call setClock() after any of these //before next readClock(). Note that invalid dates are not //corrected by the clock. All the clock knows is when it should //roll over to the next month rather than the next date in the same month. void setSeconds(int); void setMinutes(int); //setHours rejects values out of range for the current 12/24 mode void setHours(int); void setAM();//does not consider hours; see switchTo24() void setPM();//does not consider hours; see switchTo24() void set24h();//does not consider hours; see switchTo24() void switchTo24h();//returns immediately if already 24h void switchTo12h();//returns immediately if already 12h void setDayOfWeek(int);//incremented at midnight; not set by date (no fixed meaning) void setDate(int);//allows 1-31 for *all* months. void setDay(int); void setMonth(int); void setYear(int); //squarewave frequencies:static const byte SQW_1Hz=0x00; static const byte SQW_4kHz=0x01;//actually 4.096kHz static const byte SQW_8kHz=0x02;//actually 8.192kHz static const byte SQW_32kHz=0x03;//actually 32.768kHz};extern RealTimeClockDS1307 RTC;#endif
    README.mdC/C++
    add this to the RTClib library
    This is a fork of JeeLab's fantastic real time clock library for Arduino.For details on using this library with an RTC module like the DS1307, see the guide at:https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/overviewTo download. click the DOWNLOADS button to the right, and rename the uncompressed folder RTClib.Place the RTClib folder in your *arduinosketchfolder*/libraries/ folder. You may need to create the libraries subfolder if its your first library. Restart the IDE.## CompatibilityMCU | Tested Works | Doesn't Work | Not Tested | Notes------------------ | :----------:| :----------:| :---------:| -----Atmega328 @ 16MHz | 엑스 | | | Atmega328 @ 12MHz | 엑스 | | | Atmega32u4 @ 16MHz | 엑스 | | | Use SDA/SCL on pins D3 & D2Atmega32u4 @ 8MHz | 엑스 | | | Use SDA/SCL on pins D3 & D2ESP8266 | 엑스 | | | SDA/SCL default to pins 4 & 5 but any two pins can be assigned as SDA/SCL using Wire.begin(SDA,SCL)Atmega2560 @ 16MHz | 엑스 | | | Use SDA/SCL on Pins 20 & 21ATSAM3X8E | 엑스 | | | Use SDA1 and SCL1ATSAM21D | 엑스 | | | ATtiny85 @ 16MHz | 엑스 | | | ATtiny85 @ 8MHz | 엑스 | | | Intel Curie @ 32MHz | | | 엑스 | STM32F2 | | | 엑스 | * ATmega328 @ 16MHz :Arduino UNO, Adafruit Pro Trinket 5V, Adafruit Metro 328, Adafruit Metro Mini * ATmega328 @ 12MHz :Adafruit Pro Trinket 3V * ATmega32u4 @ 16MHz :Arduino Leonardo, Arduino Micro, Arduino Yun, Teensy 2.0 * ATmega32u4 @ 8MHz :Adafruit Flora, Bluefruit Micro * ESP8266 :Adafruit Huzzah * ATmega2560 @ 16MHz :Arduino Mega * ATSAM3X8E :Arduino Due * ATSAM21D :Arduino Zero, M0 Pro * ATtiny85 @ 16MHz :Adafruit Trinket 5V * ATtiny85 @ 8MHz :Adafruit Gemma, Arduino Gemma, Adafruit Trinket 3V
    RTClib.cppC/C++
    name it as above and add it to the RTClib library
    // Code by JeeLabs http://news.jeelabs.org/code/// Released to the public domain! Enjoy!#include #include "RTClib.h"#ifdef __AVR__ #include #elif defined(ESP8266) #include #elif defined(ARDUINO_ARCH_SAMD)// nothing special needed#elif defined(ARDUINO_SAM_DUE) #define PROGMEM #define pgm_read_byte(addr) (*(const unsigned char *)(addr)) #define Wire Wire1#endif#if (ARDUINO>=100) #include  // capital A so it is error prone on case-sensitive filesystems // Macro to deal with the difference in I2C write functions from old and new Arduino versions. #define _I2C_WRITE write #define _I2C_READ read#else #include  #define _I2C_WRITE send #define _I2C_READ receive#endifstatic uint8_t read_i2c_register(uint8_t addr, uint8_t reg) { Wire.beginTransmission(addr); Wire._I2C_WRITE((byte)reg); Wire.endTransmission(); Wire.requestFrom(addr, (byte)1); return Wire._I2C_READ();}static void write_i2c_register(uint8_t addr, uint8_t reg, uint8_t val) { Wire.beginTransmission(addr); Wire._I2C_WRITE((byte)reg); Wire._I2C_WRITE((byte)val); Wire.endTransmission();}////////////////////////////////////////////////////////////////////////////////// utility code, some of this could be exposed in the DateTime API if neededconst uint8_t daysInMonth [] PROGMEM ={ 31,28,31,30,31,30,31,31,30,31,30,31 };// number of days since 2000/01/01, valid for 2001..2099static uint16_t date2days(uint16_t y, uint8_t m, uint8_t d) { if (y>=2000) y -=2000; uint16_t days =d; for (uint8_t i =1; i  2 &&y % 4 ==0) ++days; return days + 365 * y + (y + 3) / 4 - 1;}static long time2long(uint16_t days, uint8_t h, uint8_t m, uint8_t s) { return ((days * 24L + h) * 60 + m) * 60 + s;}////////////////////////////////////////////////////////////////////////////////// DateTime implementation - ignores time zones and DST changes// NOTE:also ignores leap seconds, see http://en.wikipedia.org/wiki/Leap_secondDateTime::DateTime (uint32_t t) { t -=SECONDS_FROM_1970_TO_2000; // bring to 2000 timestamp from 1970 ss =t % 60; t /=60; mm =t % 60; t /=60; hh =t % 24; uint16_t days =t / 24; uint8_t leap; for (yOff =0;; ++yOff) { leap =yOff % 4 ==0; if (days <365 + leap) break; days -=365 + leap; } for (m =1;; ++m) { uint8_t daysPerMonth =pgm_read_byte(daysInMonth + m - 1); if (leap &&m ==2) ++daysPerMonth; if (days =2000) year -=2000; yOff =year; m =month; d =day; hh =hour; mm =min; ss =sec;}DateTime::DateTime (const DateTime©):yOff(copy.yOff), m(copy.m), d(copy.d), hh(copy.hh), mm(copy.mm), ss(copy.ss){}static uint8_t conv2d(const char* p) { uint8_t v =0; if ('0' <=*p &&*p <='9') v =*p - '0'; return 10 * v + *++p - '0';}// A convenient constructor for using "the compiler's time":// DateTime now (__DATE__, __TIME__);// NOTE:using F() would further reduce the RAM footprint, see below.DateTime::DateTime (const char* date, const char* time) { // sample input:date ="Dec 26 2009", time ="12:34:56" yOff =conv2d(date + 9); // Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec switch (date[0]) { case 'J':m =date[1] =='a' ? 1 :m =date[2] =='n' ? 6 :7; 부서지다; case 'F':m =2; 부서지다; case 'A':m =date[2] =='r' ? 4 :8; 부서지다; case 'M':m =date[2] =='r' ? 3 :5; 부서지다; case 'S':m =9; 부서지다; case 'O':m =10; 부서지다; case 'N':m =11; 부서지다; case 'D':m =12; 부서지다; } d =conv2d(date + 4); hh =conv2d(time); mm =conv2d(time + 3); ss =conv2d(time + 6);}// A convenient constructor for using "the compiler's time":// This version will save RAM by using PROGMEM to store it by using the F macro.// DateTime now (F(__DATE__), F(__TIME__));DateTime::DateTime (const __FlashStringHelper* date, const __FlashStringHelper* time) { // sample input:date ="Dec 26 2009", time ="12:34:56" char buff[11]; memcpy_P(buff, date, 11); yOff =conv2d(buff + 9); // Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec switch (buff[0]) { case 'J':m =buff[1] =='a' ? 1 :m =buff[2] =='n' ? 6 :7; 부서지다; case 'F':m =2; 부서지다; case 'A':m =buff[2] =='r' ? 4 :8; 부서지다; case 'M':m =buff[2] =='r' ? 3 :5; 부서지다; case 'S':m =9; 부서지다; case 'O':m =10; 부서지다; case 'N':m =11; 부서지다; case 'D':m =12; 부서지다; } d =conv2d(buff + 4); memcpy_P(buff, time, 8); hh =conv2d(buff); mm =conv2d(buff + 3); ss =conv2d(buff + 6);}uint8_t DateTime::dayOfTheWeek() const { uint16_t day =date2days(yOff, m, d); return (day + 6) % 7; // Jan 1, 2000 is a Saturday, i.e. returns 6}uint32_t DateTime::unixtime(void) const { uint32_t t; uint16_t days =date2days(yOff, m, d); t =time2long(days, hh, mm, ss); t +=SECONDS_FROM_1970_TO_2000; // seconds from 1970 to 2000 return t;}long DateTime::secondstime(void) const { long t; uint16_t days =date2days(yOff, m, d); t =time2long(days, hh, mm, ss); return t;}DateTime DateTime::operator+(const TimeSpan&span) { return DateTime(unixtime()+span.totalseconds());}DateTime DateTime::operator-(const TimeSpan&span) { return DateTime(unixtime()-span.totalseconds());}TimeSpan DateTime::operator-(const DateTime&right) { return TimeSpan(unixtime()-right.unixtime());}////////////////////////////////////////////////////////////////////////////////// TimeSpan implementationTimeSpan::TimeSpan (int32_t seconds):_seconds(seconds){}TimeSpan::TimeSpan (int16_t days, int8_t hours, int8_t minutes, int8_t seconds):_seconds((int32_t)days*86400L + (int32_t)hours*3600 + (int32_t)minutes*60 + seconds){}TimeSpan::TimeSpan (const TimeSpan©):_seconds(copy._seconds){}TimeSpan TimeSpan::operator+(const TimeSpan&right) { return TimeSpan(_seconds+right._seconds);}TimeSpan TimeSpan::operator-(const TimeSpan&right) { return TimeSpan(_seconds-right._seconds);}////////////////////////////////////////////////////////////////////////////////// RTC_DS1307 im plementationstatic uint8_t bcd2bin (uint8_t val) { return val - 6 * (val>> 4); }static uint8_t bin2bcd (uint8_t val) { return val + 6 * (val / 10); }boolean RTC_DS1307::begin(void) { Wire.begin(); return true;}uint8_t RTC_DS1307::isrunning(void) { Wire.beginTransmission(DS1307_ADDRESS); Wire._I2C_WRITE((byte)0); Wire.endTransmission(); Wire.requestFrom(DS1307_ADDRESS, 1); uint8_t ss =Wire._I2C_READ(); return !(ss>>7);}void RTC_DS1307::adjust(const DateTime&dt) { Wire.beginTransmission(DS1307_ADDRESS); Wire._I2C_WRITE((byte)0); // start at location 0 Wire._I2C_WRITE(bin2bcd(dt.second())); Wire._I2C_WRITE(bin2bcd(dt.minute())); Wire._I2C_WRITE(bin2bcd(dt.hour())); Wire._I2C_WRITE(bin2bcd(0)); Wire._I2C_WRITE(bin2bcd(dt.day())); Wire._I2C_WRITE(bin2bcd(dt.month())); Wire._I2C_WRITE(bin2bcd(dt.year() - 2000)); Wire.endTransmission();}DateTime RTC_DS1307::now() { Wire.beginTransmission(DS1307_ADDRESS); Wire._I2C_WRITE((byte)0); Wire.endTransmission(); Wire.requestFrom(DS1307_ADDRESS, 7); uint8_t ss =bcd2bin(Wire._I2C_READ() &0x7F); uint8_t mm =bcd2bin(Wire._I2C_READ()); uint8_t hh =bcd2bin(Wire._I2C_READ()); Wire._I2C_READ(); uint8_t d =bcd2bin(Wire._I2C_READ()); uint8_t m =bcd2bin(Wire._I2C_READ()); uint16_t y =bcd2bin(Wire._I2C_READ()) + 2000; return DateTime (y, m, d, hh, mm, ss);}Ds1307SqwPinMode RTC_DS1307::readSqwPinMode() { int mode; Wire.beginTransmission(DS1307_ADDRESS); Wire._I2C_WRITE(DS1307_CONTROL); Wire.endTransmission(); Wire.requestFrom((uint8_t)DS1307_ADDRESS, (uint8_t)1); mode =Wire._I2C_READ(); mode &=0x93; return static_cast(mode);}void RTC_DS1307::writeSqwPinMode(Ds1307SqwPinMode mode) { Wire.beginTransmission(DS1307_ADDRESS); Wire._I2C_WRITE(DS1307_CONTROL); Wire._I2C_WRITE(mode); Wire.endTransmission();}void RTC_DS1307::readnvram(uint8_t* buf, uint8_t size, uint8_t address) { int addrByte =DS1307_NVRAM + address; Wire.beginTransmission(DS1307_ADDRESS); Wire._I2C_WRITE(addrByte); Wire.endTransmission(); Wire.requestFrom((uint8_t) DS1307_ADDRESS, size); for (uint8_t pos =0; pos >=3; mode &=0x7; return static_cast(mode);}void RTC_PCF8523::writeSqwPinMode(Pcf8523SqwPinMode mode) { Wire.beginTransmission(PCF8523_ADDRESS); Wire._I2C_WRITE(PCF8523_CLKOUTCONTROL); Wire._I2C_WRITE(mode <<3); Wire.endTransmission();}////////////////////////////////////////////////////////////////////////////////// RTC_DS3231 implementationboolean RTC_DS3231::begin(void) { Wire.begin(); return true;}bool RTC_DS3231::lostPower(void) { return (read_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG)>> 7);}void RTC_DS3231::adjust(const DateTime&dt) { Wire.beginTransmission(DS3231_ADDRESS); Wire._I2C_WRITE((byte)0); // start at location 0 Wire._I2C_WRITE(bin2bcd(dt.second())); Wire._I2C_WRITE(bin2bcd(dt.minute())); Wire._I2C_WRITE(bin2bcd(dt.hour())); Wire._I2C_WRITE(bin2bcd(0)); Wire._I2C_WRITE(bin2bcd(dt.day())); Wire._I2C_WRITE(bin2bcd(dt.month())); Wire._I2C_WRITE(bin2bcd(dt.year() - 2000)); Wire.endTransmission(); uint8_t statreg =read_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG); statreg &=~0x80; // flip OSF bit write_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG, statreg);}DateTime RTC_DS3231::now() { Wire.beginTransmission(DS3231_ADDRESS); Wire._I2C_WRITE((byte)0); Wire.endTransmission(); Wire.requestFrom(DS3231_ADDRESS, 7); uint8_t ss =bcd2bin(Wire._I2C_READ() &0x7F); uint8_t mm =bcd2bin(Wire._I2C_READ()); uint8_t hh =bcd2bin(Wire._I2C_READ()); Wire._I2C_READ(); uint8_t d =bcd2bin(Wire._I2C_READ()); uint8_t m =bcd2bin(Wire._I2C_READ()); uint16_t y =bcd2bin(Wire._I2C_READ()) + 2000; return DateTime (y, m, d, hh, mm, ss);}Ds3231SqwPinMode RTC_DS3231::readSqwPinMode() { int mode; Wire.beginTransmission(DS3231_ADDRESS); Wire._I2C_WRITE(DS3231_CONTROL); Wire.endTransmission(); Wire.requestFrom((uint8_t)DS3231_ADDRESS, (uint8_t)1); mode =Wire._I2C_READ(); mode &=0x93; return static_cast(mode);}void RTC_DS3231::writeSqwPinMode(Ds3231SqwPinMode mode) { uint8_t ctrl; ctrl =read_i2c_register(DS3231_ADDRESS, DS3231_CONTROL); ctrl &=~0x04; // turn off INTCON ctrl &=~0x18; // set freq bits to 0 if (mode ==DS3231_OFF) { ctrl |=0x04; // turn on INTCN } else { ctrl |=mode; } write_i2c_register(DS3231_ADDRESS, DS3231_CONTROL, ctrl); //Serial.println( read_i2c_register(DS3231_ADDRESS, DS3231_CONTROL), HEX);}
    RTClib.hC/C++
    that's the name. add it to the RTClib library. Now you have all the files for the RTClib library. Do the same steps to add this to the arduino libraries.
    // Code by JeeLabs http://news.jeelabs.org/code/// Released to the public domain! Enjoy!#ifndef _RTCLIB_H_#define _RTCLIB_H_#include class TimeSpan;#define PCF8523_ADDRESS 0x68#define PCF8523_CLKOUTCONTROL 0x0F#define PCF8523_CONTROL_3 0x02#define DS1307_ADDRESS 0x68#define DS1307_CONTROL 0x07#define DS1307_NVRAM 0x08#define DS3231_ADDRESS 0x68#define DS3231_CONTROL 0x0E#define DS3231_STATUSREG 0x0F#define SECONDS_PER_DAY 86400L#define SECONDS_FROM_1970_TO_2000 946684800// Simple general-purpose date/time class (no TZ / DST / leap second handling!)class DateTime {public:DateTime (uint32_t t =0); DateTime (uint16_t year, uint8_t month, uint8_t day, uint8_t hour =0, uint8_t min =0, uint8_t sec =0); DateTime (const DateTime©); DateTime (const char* date, const char* time); DateTime (const __FlashStringHelper* date, const __FlashStringHelper* time); uint16_t year() const { return 2000 + yOff; } uint8_t month() const { return m; } uint8_t day() const { return d; } uint8_t hour() const { return hh; } uint8_t minute() const { return mm; } uint8_t second() const { return ss; } uint8_t dayOfTheWeek() const; // 32-bit times as seconds since 1/1/2000 long secondstime() const; // 32-bit times as seconds since 1/1/1970 uint32_t unixtime(void) const; DateTime operator+(const TimeSpan&span); DateTime operator-(const TimeSpan&span); TimeSpan operator-(const DateTime&right);protected:uint8_t yOff, m, d, hh, mm, ss;};// Timespan which can represent changes in time with seconds accuracy.class TimeSpan {public:TimeSpan (int32_t seconds =0); TimeSpan (int16_t days, int8_t hours, int8_t minutes, int8_t seconds); TimeSpan (const TimeSpan©); int16_t days() const { return _seconds / 86400L; } int8_t hours() const { return _seconds / 3600 % 24; } int8_t minutes() const { return _seconds / 60 % 60; } int8_t seconds() const { return _seconds % 60; } int32_t totalseconds() const { return _seconds; } TimeSpan operator+(const TimeSpan&right); TimeSpan operator-(const TimeSpan&right);protected:int32_t _seconds;};// RTC based on the DS1307 chip connected via I2C and the Wire libraryenum Ds1307SqwPinMode { OFF =0x00, ON =0x80, SquareWave1HZ =0x10, SquareWave4kHz =0x11, SquareWave8kHz =0x12, SquareWave32kHz =0x13 };class RTC_DS1307 {public:boolean begin(void); static void adjust(const DateTime&dt); uint8_t isrunning(void); static DateTime now(); static Ds1307SqwPinMode readSqwPinMode(); static void writeSqwPinMode(Ds1307SqwPinMode mode); uint8_t readnvram(uint8_t address); void readnvram(uint8_t* buf, uint8_t size, uint8_t address); void writenvram(uint8_t address, uint8_t data); void writenvram(uint8_t address, uint8_t* buf, uint8_t size);};// RTC based on the DS3231 chip connected via I2C and the Wire libraryenum Ds3231SqwPinMode { DS3231_OFF =0x01, DS3231_SquareWave1Hz =0x00, DS3231_SquareWave1kHz =0x08, DS3231_SquareWave4kHz =0x10, DS3231_SquareWave8kHz =0x18 };class RTC_DS3231 {public:boolean begin(void); static void adjust(const DateTime&dt); bool lostPower(void); static DateTime now(); static Ds3231SqwPinMode readSqwPinMode(); static void writeSqwPinMode(Ds3231SqwPinMode mode);};// RTC based on the PCF8523 chip connected via I2C and the Wire libraryenum Pcf8523SqwPinMode { PCF8523_OFF =7, PCF8523_SquareWave1HZ =6, PCF8523_SquareWave32HZ =5, PCF8523_SquareWave1kHz =4, PCF8523_SquareWave4kHz =3, PCF8523_SquareWave8kHz =2, PCF8523_SquareWave16kHz =1, PCF8523_SquareWave32kHz =0 };class RTC_PCF8523 {public:boolean begin(void); void adjust(const DateTime&dt); boolean initialized(void); static DateTime now(); Pcf8523SqwPinMode readSqwPinMode(); void writeSqwPinMode(Pcf8523SqwPinMode mode);};// RTC using the internal millis() clock, has to be initialized before use// NOTE:this clock won't be correct once the millis() timer rolls over (>49d?)class RTC_Millis {public:static void begin(const DateTime&dt) { adjust(dt); } static void adjust(const DateTime&dt); static DateTime now();protected:static long offset;};#endif // _RTCLIB_H_

    회로도

    This is the schematic of the project. 7segmentClock.fzz

    제조공정

    1. 다리미판
    2. 뻐꾸기 시계
    3. 인쇄 회로 기판
    4. 서프보드
    5. Arduino+Raspberry Pi 로봇 플랫폼을 만드는 방법
    6. RaspiRobot 보드 V2
    7. Arduino 관점 시계
    8. 무한 거울 시계
    9. 완벽한 인쇄 회로 기판을 만드는 데에는 한 가지 이상의 이유가 있습니다.
    10. 엔진 구성 이해