임베디드시스템개론 - silla.ac.krmclab.silla.ac.kr/lecture/201801/es/es-lecture-09.pdf ·...
Transcript of 임베디드시스템개론 - silla.ac.krmclab.silla.ac.kr/lecture/201801/es/es-lecture-09.pdf ·...
임베디드시스템개론: AVR MCU & Arduino 활용
Lecture #09: 시리얼 통신(Serial Comm.)
강의 목차
시러얼 통신 개요
I2C 통신 개요
I2C 통신 실험
I2C Text LCD
DS1307 / DS1302 RTC
2
1. Serial Communication
3
아두이노 통신
아두이노 통신 개요 아두이노 MCU와 on-board 장치 또는 외부 연결 장치 간의 통신
통신 프로토콜에 따른 데이터 송수신을 위해 개별적인 통신 장치(모듈)을 사용
외부와의 통신을 위해 별도의 통신 장치가 필요
MCU 내장 또는 외부 확장 통신 장치 등
통신 모듈의 지원 여부에 따른 분류 :
MCU 내장 통신 장치(모듈) - I2C, SPI, UART
외부 통신 장치(모듈) - USB, Ethernet, Wifi, Zigbee, Bluetooth, IR 등
4
시리얼 통신 (1)
시리얼 통신 개요 장치 간에 비트 단위로 데이터를 전송하는 통신
비동기(Asynchronous) & 동기(Synchronous) 통신 방식 존재
시리얼 통신 프로토콜
I2C(Inter-Integrated Circuit)
SPI(Serial Peripheral Interface)
UART(Universal Asynchronous Receive-Transmit)
5
시리얼 통신 (2)
시리얼 통신 개요 : 비동기 및 동기 전송 비교
6
Asynchronous – No Clock
정해진 시간에 맞추어 전송 신호를HIGH/LOW로 설정하여 데이터를표현
발신과 수신을 위해 별도의 선을사용
단지 두 개의 장치간에 통신하고자하고 상호 전송속도를 같게 설정되어 있을 때에 유용
Synchronous – With Clock
“clock” 변화에 맞추어 전송신호를HIGH/LOW로 설정하여 데이터를표현
Clock 신호와 전송 방향 별로 별도의 선을 사용
일반적으로 빠른 전송 속도가 필요할 때에 유용
시리얼 통신 (3)
시리얼 통신 개요 : 비동기 및 동기 전송 비교
7
2. UART(Universal Asynchronous
Receiver/Transmitter)
8
UART (1)
UART(Universal Asynchronous Receiver Transmitter)
대표적인 비동기 시리얼 통신 규약
정해진 통신 속도(baud rate)에 맞추어 병렬 데이터를 비트 단위로직렬 전송하고, 수신된 직렬 데이터를 병렬 데이터를 변환하는 기능을 지원
기본적으로Tx(Transmitter)/Rx(Receiver) 2개의 통신 라인을 사용
필요에 따라 handshake 라인(DTS/DTR)을 사용하기도 함
별도의 동기화 메커니즘을 사용하지 않으므로 통신하기 전에 송수신 측에서 동일한 통신 파라미터를 설정하여야 함.
통신 속도(Baud Rate) – 9600~115200 bsp
Start bit – 0, 1, 2
Data bit – 7, 8
Stop bit – 0, 1
Parity bit – none, odd, even
9
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()
참조: http://arduino.cc/en/Reference/Serial
10
UART (3)
RS-232 표준 (1)
비동기 직렬 통신에 필요한 전기적인 신호 특성 (전압, 타이밍 등)과기계적 특성 (커넥터 모양, 핀 배치) 등 모든 사양을 규정
미국 Electronic Industries Association (EIA)에서 정한 표준
주로 PC 및 통신 장비의 콘솔 통신을 위해 사용하는 직렬 포트용DB-9 커넥터의 모양 및 핀 배치 표준도 규정
송신 신호 (TxD)와 수신 신호 (RxD) 이외에도 다른 용도의 여러 신호들도 정의함
데이터 흐름 제어 (flow control)나 반송파 검출 (carrier detection) 등의 다른 기능은 사용하지 않고 순수하게 통신만 하겠다면TxD와 RxD 두 신호로 충분
11
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
3. I2C(IIC)
13
I2C (1)
I2C(Inter-Integrated Circuit) Bus
데이터 라인을 공유하는 동기 시리얼 통신 버스
하나의 버스에 127 장치까지 연결 가능
1Mbps 전송 속도까지 가능
간단한 통신 프로토콜이 장점
대부분의 MCU에 I2C 통신 제어장치 내장
참조: http://tronixstuff.files.wordpress.com/2010/10/nxp_i2c.pdf
14
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
I2C (3)
I2C(Inter-Integrated Circuit) Bus
SCK 선과 SDA 선은 모두 오픈 드레인이므로 두 선에는 각각 풀업저항을 연결해 주어야 한다.
16
I2C (4)
I2C(Inter-Integrated Circuit) Bus
17
I2C (4)
I2C(Inter-Integrated Circuit) Bus
통신 프로토콜
18
4. I2C 통신 실험
19
I2C Text LCD (1)
20
I2C Text LCD
I2C Converter 모듈을 이용하여 I2C 통신 인터페이스를 이용하여 출력이 가능한 Text LCD
I2C Text LCD (2)
21
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
I2C Text LCD (3)
22
I2C LCD 모듈(I2C Converter)
I2C Address
주소 설정 핀(or Solder Pads): A0, A1, A2
Not-connected – 1 / Connected - 0
(or 0x3F)
I2C Text LCD (4)
23
Arduino I2C Library (1)
Wire Library
https://www.arduino.cc/en/Reference/Wire
주요 APIs:
begin()
requestFrom()
beginTransmission()
endTransmission()
write()
available()
read()
SetClock()
onReceive()
onRequest()
I2C Text LCD (5)
24
Arduino I2C Library (2)
Wire Library 예제 : master writer / slaver receiver
#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 #8Wire.write("x is "); // sends five bytesWire.write(x); // sends one byteWire.endTransmission(); // stop transmitting
x++;delay(500);
}
#include <Wire.h>
void setup() {Wire.begin(8); // join i2c bus with address #8Wire.onReceive(receiveEvent); // register eventSerial.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 characterSerial.print(c); // print the character
}int x = Wire.read(); // receive byte as an integerSerial.println(x); // print the integer
}
Master Slaver
I2C Text LCD (6)
25
I2C Text LCD Library (1)
라이브러리 다운로드 사이트: LiquidCrystal-I2C
https://drive.google.com/file/d/0B-
KyJ56OlEcJZmN4UWwtX2hydDg/view?usp=sharing
LiquidCrystal-I2C Library API
LiquidCrystal Library API와 상당히 유사
https://www.arduino.cc/en/Reference/LiquidCrystal
https://programmingelectronics.com/liquidcrystal-library-functions-tour-
part-1/
https://kocoafab.cc/tutorial/view/689 문서 참조
26
lcd.begin(); LCD를 사용을 시작
lcd.display(); LCD에 내용을 표시
lcd.noDisplay(); LCD에 내용을 숨김
lcd.setCursor(col,row); row, col의 좌표로 커서를 위치
lcd.cursor(); LCD에 커서를 표시
lcd.noCursor(); LCD에 커서를 숨김
lcd.home(); 커서의 위치를 0,0으로 이동
lcd.blink(); 커서를 깜빡임
lcd.noBlink(); 커서를 깜빡이지 않음
lcd.backlight(); LCD backlight을 킴
lcd.noBacklight(); LCD backlight를 끔
lcd.write(val);LCD 화면에 val 출력(아스키 코드 입력 시에는 아스키 코
드에 해당하는 문자 출력)
lcd.print(val); LCD 화면에 val 출력
lcd.clear(); LCD 화면의 모든 내용 지움
lcd.scrollDisplayRight(); 내용을 우측으로 1칸 이동
lcd.scrollDisplayLeft(); 내용을 좌측으로 1칸 이동
lcd.autoscroll(); 내용을 자동으로 우에서 좌로 스크롤
I2C Text LCD (7)
27
I2C Text LCD Library (2)
LiquidCrystal-I2C Library API
Cursor 제어 함수에서 Cursor의 row와 col(줄과 행) 좌표 참고
I2C Text LCD (8)
28
I2C Text LCD 주소 테스트 (1)
I2C Text LCD 주소를 확인하여 출력
http://www.ardumotive.com/i2clcden.html 참조
회로 구성
I2C Text LCD (9)
29
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
I2C Text LCD (10)
30
I2C Text LCD 출력 테스트 (1)
“Hello, World!” 텍스트 출력
회로 구성
앞 실험과 동일
I2C Text LCD (11)
31
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(){
}
I2C Text LCD (12)
32
I2C Text LCD 기능 테스트
https://kocoafab.cc/tutorial/view/689 예제 참조
예제 기능
시리얼 모니터로 입력받은 데이터에 따라 아래와 같이 동작
- 1을 입력 받았을 때 : backlight가 1초가 소등되었다가 점등됩니다.
- 2를 입력 받았을 때 : LCD에 표시된 글자가 1초간 사라졌다가 나타납니다.
- 3을 입력 받았을 때 : Cursor가 1초간 깜빡이다가 사라집니다.
- 4를입력 받았을 때 : 커서가 1초간 화면에 나타났다가 사라집니다.
- 5를 입력 받았을 때 : 화면에 표시된 내용이 1초간 우측으로 1칸 이동 후 원래 자리로 돌아옵니다.
- 6을 입력 받았을 때 : 커서가 화면에 표시된 후 커서 위치가 col 0부터 16까지 이동 후에 사라집니다.
DS1307 RTC를 이용한 시계 (1)
33
참고 Sites
http://learn.adafruit.com/ds1307-real-time-clock-breakout-
board-kit
tronixstuff.wordpress.com/tutorials
Ch. 20 & 21
Arduino Wire Library
DS1307 RTC를 이용한 시계 (2)
34
DS1307 IC
DS1307 RTC를 이용한 시계 (3)
35
DS1307 IC
DS1307 RTC를 이용한 시계 (4)
36
회로도
DS1307 RTC를 이용한 시계 (5)
37
회로 구성
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) 00010000 (binary)
Wire.endTransmission();
}
DS1307 RTC를 이용한 시계 (7)
DS1307 Pulse 출력 (2)
39
void sqw2() // set to 4.096 kHz
{
Wire.beginTransmission(DS1307_I2C_ADDRESS);
Wire.write(0x07); // move pointer to SQW address
Wire.write(0x11); // sends 0x11 (hex) 00010001 (binary)
Wire.endTransmission();
}
void sqw3() // set to 8.192 kHz
{
Wire.beginTransmission(DS1307_I2C_ADDRESS);
Wire.write(0x07); // move pointer to SQW address
Wire.write(0x12); // sends 0x12 (hex) 00010010 (binary)
Wire.endTransmission();
}
void sqw4() // set to 32.768 kHz (the crystal frequency)
{
Wire.beginTransmission(DS1307_I2C_ADDRESS);
Wire.write(0x07); // move pointer to SQW address
Wire.write(0x13); // sends 0x13 (hex) 00010011 (binary)
Wire.endTransmission();
}
DS1307 RTC를 이용한 시계 (8)
DS1307 Pulse 출력 (3)
40
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();
}
void loop()
{
sqw1();
delay(5000);
sqw2();
delay(5000);
sqw3();
delay(5000);
sqw4();
delay(5000);
sqwOff();
delay(5000);
}
DS1307 RTC를 이용한 시계 (9)
DS1307 시계 출력 (1)
41
#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) );
}
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(00010000); // sends 0x10 (hex) 00010000 (binary) to control register - turns on square wave
Wire.endTransmission();
}
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());
}
DS1307 RTC를 이용한 시계 (12)
DS1307 시계 출력 (4)
44
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);
}
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);
DS1307 RTC를 이용한 시계 (14)
DS1307 시계 출력 (6)
46
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);
}
DS1307 RTC를 이용한 시계 (15)
RTC 라이브러리 활용
http://learn.adafruit.com/ds1307-real-time-clock-breakout-board-
kit/overview
https://github.com/adafruit/RTClib
DS1307 IC를 이용한 RTC 기능을 구현한 라이브러리
RTClib 압축 파일을 다운로드하여 풀고 “RTClib”라는 이름으로아두이노 라이브러리 디렉토리에 설치
47
DS1307 RTC를 이용한 시계 (16)
RTC 라이브러리 예제 실행
LCD 출력 확장
48
DS1302 RTC를 이용한 시계 (1) DS1302 RTC 모듈
DS1302 RTC IC를 사용한 모듈
DS1307 RTC 모듈과 유사한 기능 지원
현재 시간 및 날짜 지원
Pulse 출력 기능은 지원하지 않음
일반적인 I2C 인터페이스가 아닌 3-wire 인터페이스 지원
49
DS1302 RTC를 이용한 시계 (2)
DS1302 IC (1)
50
주전원공급
Trickle
charger
전원
DS1302 RTC를 이용한 시계 (3)
DS1302 IC (2)
51
DS1302 RTC를 이용한 시계 (4)
DS1302 RTC 모듈 제어 – 직접 입출력 제어 (1)
디지털 입출력 기능을 이용하여 DS1302 IC의 레지스터의 직접 입출력 제어
시간 및 날짜에 대해 설정 및 읽기 수행
https://playground.arduino.cc/Main/DS1302 참조
유의 사항:
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 1980. It has a Leap-Year compensation from 2000 up to 2099
(for a value of 0-99).
52
DS1302 RTC를 이용한 시계 (5)
DS1302 RTC 모듈 제어 – 직접 입출력 제어 (2)
DS1302 IC 인터페이스 구성:
53
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
:
DS1302 RTC를 이용한 시계 (6)
DS1302 RTC 모듈 제어 – 직접 입출력 제어 (3)
실습 회로 구성
54
Arduino Mega RTC DS1302
D2 CE(RST)
D3 DAT
D4 CLK
DS1302 RTC를 이용한 시계 (7)
DS1302 RTC 모듈 제어 – 직접 입출력 제어 (4)
아두이노 예제 프로그램
https://playground.arduino.cc/Main/DS1302?action=sourceblock&num=1
Burst mode I/O
55
:
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();
}
:
DS1302 RTC를 이용한 시계 (8)
DS1302 RTC 모듈 제어 – 직접 입출력 제어 (5)
아두이노 예제 프로그램
Burst mode I/O
56
:
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();
}
:
DS1302 RTC를 이용한 시계 (9)
DS1302 RTC 모듈 제어 – 라이브러리 활용 (1)
DS1302RTC 라이브러리
https://playground.arduino.cc/Main/DS1302RTC 참조
intended for use with the Arduino Time.h
library, http://www.arduino.cc/playground/Code/Time
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
6. 24 hour format only (12 hour format is function Time library)
57
DS1302 RTC를 이용한 시계 (10)
DS1302 RTC 모듈 제어 – 라이브러리 활용 (2)
실습 회로 – 앞의 실습과 동일
DS1302 RTC 모듈 시간/날짜 설정
DS1302RTC 라이브러리 예제 프로그램 setSerial 활용
http://arduiniana.org/libraries/streaming/ - Stringming5 Library 필요
58
DS1302 RTC를 이용한 시계 (11)
DS1302 RTC 모듈 제어 – 라이브러리 활용 (3)
DS1302 RTC 모듈 출력 프로그램
현재 시간을 시리얼 모니터에 출력한다.
시리얼 모니터에서 새로운 시간을 입력하면 RTC 모듈에 새로 설정한다.
59
#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;
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); //use the time_t value to ensure
// correct weekday is set
if(RTC.set(t) == 0) { // Success
setTime(t);
Serial.println("RTC set to: ");
printDateTime(t);
Serial.println();
}
else
Serial.println();
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);
}
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;
}
참조:
1. http://webnautes.tistory.com/975
2. https://www.pjrc.com/teensy/td_libs_Time.html
과제물 #3
과제 내용
DS1302, 조도 센서 그리고 I2C Text LCD 장치를 이용하여 다음의 동작을 수행하는 프로그램을 작성하여라.
A. 조도 크기를Text LCD 장치에 출력한다
B. 현재 시간과 날짜를Text LCD 장치에 출력한다
제출물 회로도, 프로그램 소스, 실행 예(사진)
제출일 차주 수업 시간
64