오렌지 보드를 사용해 간단한 알람시계를 만들어 보기

 
[컴퓨터월드] 아두이노는 이탈리어로 ‘친한 친구’라는 뜻을 가진 대표적인 오픈소스 하드웨어다. 딱딱하고 접근하기 힘들었던 임베디드 분야를 누구나 쉽게 접근할 수 있도록 만든 미니 기판이라 할 수 있다. 이번 강좌에 사용하는 아두이노 오렌지보드는 한국형 아두이노라 할 수 있다.

아두이노의 보급은 오픈소스 하드웨어의 확산을 불러일으켰고 메이커 문화의 확산에도 큰 기여를 했다. 최근에는 인텔, 마이크로소프트 등 대형 기업들도 이런 오픈소스 하드웨어시장에 뛰어들기 시작했다. 그 만큼 오픈소스 하드웨어 시장의 잠재력이 커졌다는 얘기이다.

프로젝트 개요

그 동안 연재글에서는 단일 센서 사용에 대한 튜토리얼을 작성했지만 이번 글에서는 센서들을 여러 개 사용하여 간단한 하나의 프로젝트를 만들어 볼 계획이다.

첫 번째로 소개할 프로젝트는 LCD와 피에조부저, 스위치를 사용한 간단한 알람시계 만들기 프로젝트다. 알람시계의 기능에는 시간을 보여주며 사용자가 지정한 시각이 되면 알람이 울리는 기능이 필요하다.

우선 각 센서의 역할에 대해 알아보자. LCD는 시간을 출력하는 역할을 하게 되며, 피에조부저는 알람을 울리는 자명종과 같은 역할을, 스위치는 알람을 끄는 역할을 각각 맡게 된다.

▲ 오렌지 보드를 사용해 만든 알람시계

swRTC라이브러리 소개

각 센서의 기능은 명확하게 정해져 있지만 시계를 만들기 위해서는 시간을 출력하는 하나의 기기가 필요하다. 컴퓨터의 경우 컴퓨터의 전원이 꺼져있어도 내부에서는 CMOS 배터리를 통해 계속적으로 전원을 공급해 시계를 작동한다.

이렇게 외부 전원이 없더라도 내부의 또 다른 배터리를 통해 시간을 정확하게 측정하는 모듈이 필요한데 RTC모듈(Real Time Clock Module)로 검색하면 이런 모듈을 쉽게 찾아볼 수 있다.

▲ 하드웨어RTC

하지만 이번 글에서는 모듈을 사용하지 않고 별도의 라이브러리를 통해 RTC를 사용한다. 위의 모듈은 하드웨어RTC라면 라이브러리를 사용한 RTC는 소프트웨어를 사용하기 때문에 swRTC라 부른다.

하드웨어RTC처럼 별도의 배터리가 포함되어 있지 않기 때문에 외부전원을 차단할 경우 시간이 초기화되고 타이머함수를 사용하는 다양한 아두이노 함수들과는 같이 사용하기 힘든 단점이 있으나, 전원이 공급될 때는 하드웨어RTC와 똑같이 작동하기 때문에 간단한 프로젝트를 구현할 때는 편리하게 사용할 수 있다.


필요한 부품 목록
오렌지보드로 알람시계를 만들어보기 위한 준비물은 아래와 같다. 

 


하드웨어 연결하기
브레드 보드

 


전자 회로도

 

소스코드

우선 코드구현에 swRTC라이브러리가 필요하다. 검색을 통해 구하거나 코코아팹 사이트(Kocoafab.cc)를 통해 쉽게 구할 수 있다.


#include <LiquidCrystal.h>
#include <core_build_options.h>
#include <swRTC.h>

LiquidCrystal lcd(12,11,5,4,3,2);
String lcdString = "";

swRTC rtc;

int piezo = 6;
int switchPin = 9;
int temp;

//AM PM을 구분해 주는 함수
void setAMPM(int hour) {
if(hour >=12)
lcd.print("PM");
else
lcd.print("AM");

lcd.print(hour%12, DEC); //시간 출력
}

//10보다 작은 수를 출력할때 앞에 0을 출력하게 하는 함수
void setLowThanTen(int time) {
if(time < 10) {
lcd.print("0");
lcd.print(time%10);
}
else
lcd.print(time);
}

//유효한 알람시간인지 체크하는 함수
int checkTheAlarmClock(int time) {
if(time/100 < 24 && time %100 < 60) {
Serial.println("Success");
return time;
}
else {
Serial.println("Failed");
return 0;
}
}

//알람이 울릴 시간인지 체크하는 함수
void checkTheAlarmTime(int alarmHour, int alarmMinute) {
if(alarmHour == rtc.getHours() && alarmMinute == rtc.getMinutes()) {
analogWrite(piezo, 128);
}
}

void setup() {
lcd.begin(16,2); //LCD 크기 지정, 2줄 16칸
lcd.clear(); //화면 초기화

rtc.stopRTC(); //정지
rtc.setTime(14,05,0); //시간, 분, 초 초기화
rtc.setDate(24, 8, 2014); //일, 월, 년 초기화
rtc.startRTC(); //시작

pinMode(piezo, OUTPUT);
pinMode(switchPin, INPUT_PULLUP);
Serial.begin(9600); //시리얼 포트 초기화
Serial.begin(9600); //시리얼 통신 초기화
}

void loop() {
int day;
lcd.setCursor(0,0); //커서를 0,0에 지정

//1초 단위로 갱신하며 현재 시간을 LCD에 출력
setAMPM(rtc.getHours());
lcd.print(":");
setLowThanTen(rtc.getMinutes());
lcd.print(":");
setLowThanTen(rtc.getSeconds());
//날짜를 LCD에 출력
lcd.print("[");
setLowThanTen(rtc.getMonth());
lcd.print("/");
setLowThanTen(rtc.getDay());
lcd.print("]");
//세팅된 알람시간을 LCD에 출력
lcd.setCursor(0,1);
lcd.print("Alarm ");
setAMPM(temp/100);
lcd.print(":");
setLowThanTen(temp%100);

//1초마다 LCD갱신
lcdString = ""; //문자열 초기화
lcd.print(" "); //전 글씨 삭제
delay(1000);

//알람이 울릴 시간인지 체크
checkTheAlarmTime(temp/100, temp%100);

//스위치버튼이 눌렸을 경우 피에조센서의 소리를 0으로 하고 알람시간을 초기화 한다
if(!digitalRead(switchPin)) {
temp = 0;
day = 0;
analogWrite(piezo, 0);
Serial.println("Alarm clock initialize");
Serial.println("AM0:00");
}
//시리얼 통신을 통해 알람시간을 입력받고 시리얼 모니터에 출력
char theDay[4];
int i = 0;
if(Serial.available()) {
while(Serial.available()) {
theDay[i] = Serial.read();
i++;
}
day = atoi(theDay);
if(day/100 >= 12) {
Serial.print("PM");
Serial.print((day/100)-12);
}
else {
Serial.print("AM");
Serial.print(day/100);
}
Serial.print(":");
if(day%100 < 10)
Serial.print("0");
Serial.println(day%100);
temp = checkTheAlarmClock(day);
}
}

코드의 기능을 간단히 정리하자면 아래와 같다.

1. 시간을 초기화하고 swRTC를 작동시킨다.
2. 시리얼모니터를 통해 사용자로부터 알람 예약 시간을 입력받는다.
3. 입력받은 시간이 유효한 시간(24시간을 초과하거나 60분을 초과하는 시간 값은 Fail출력)일 경우 알람예약시간으로 등록한다.
4. 시계가 작동하며 알람예약시간과 현재시간을 비교하며 체크한다.


1) 시간 초기화
Setup()함수를 보면 아래와 같은 멤버함수를 볼 수 있다.
setTime()을 통해 초기 시간을 설정하고, setDate()를 통해 연월일을 초기화할 수 있다.
세팅이 완료되고 startRTC를 호출하면 시간이 흐르기 시작한다.

rtc.stopRTC(); //정지
rtc.setTime(14,05,0); //시간, 분, 초 초기화
rtc.setDate(24, 8, 2014); //일, 월, 년 초기화
rtc.startRTC(); //시작


2) 시간 입력
사용자는 시간을 시리얼모니터에 시간을 입력한다. 시간을 입력할때는 24시간 방법으로 시분을 입력하는데, 예를들어 1406을 입력하면 PM02:06이 되고 0930을 입력하면 AM09:30이 된다.

사용자가 입력한 값은 최소 3자리에서 최대 4자리의 숫자로 이루어진 값이 되는데 이를 100으로 나누면 위 두 자리의 ‘시’ 부분만 떼어낼 수 있고 %연산자를 통해 나머지를 구함으로써 ‘분’ 부분만 따로 떼어낼 수 있다.

if(Serial.available()) {
while(Serial.available()) {
theDay[i] = Serial.read();
i++;
}
day = atoi(theDay);
if(day/100 >= 12) {
Serial.print("PM");
Serial.print((day/100)-12);
}
else {
Serial.print("AM");
Serial.print(day/100);
}
Serial.print(":");
if(day%100 < 10)
Serial.print("0");
Serial.println(day%100);
temp = checkTheAlarmClock(day);
}


3) 시간 유효성 검사

사용자는 시간을 시리얼모니터에 시간을 입력할 때, 24시간 이내, 60분 이내로 정확히 입력해야 한다. 하지만 그렇게 입력하지 못할 경우도 있기 때문에 코드 상에서 입력된 값을 검사하여 유효한 시간인지 검사 후 알람 예약을 실행한다.
24시간, 60분을 초과하는 시간을 입력할 경우 입력에 실패하게 된다.

 

int checkTheAlarmClock(int time) {
if(time/100 < 24 && time %100 < 60) {
Serial.println("Success");
return time;
}
else {
Serial.println("Failed");
return 0;
}
}


4) 시간 비교
시간을 입력하면 이제 알람예약시간과 현재 시간을 매 초마다 비교하게 된다. rtc의 getHours()와 getMinutes()는 현재 시와 분을 읽어오는 함수로 두 값이 알람시간과 일치하게 되면 피에조에서 알람이 울리게 된다.

//알람이 울릴 시간인지 체크하는 함수
void checkTheAlarmTime(int alarmHour, int alarmMinute) {
if(alarmHour == rtc.getHours() && alarmMinute == rtc.getMinutes()) {
analogWrite(piezo, 128);
}
}


마치며
처음으로 올라오는 프로젝트 연재글이다. 이번 프로젝트는 이전에 튜토리얼로 작성한 센서부품들을 조합하여 만들어 볼 수 있는 간단한 프로젝트이다. 비록 코드가 복잡하지만 시계를 구현하고, 여러 센서를 조합했기 때문에 길어지는 것일뿐 내용을 자세히 들여다보면 크게 어려운 부분은 없다.

아두이노 알람시계는 위의 소개한 프로젝트 외에도 다양한 프로젝트들이 존재하며 LCD가 아닌 7세그먼트를 사용하여 만들어 볼 수도 있다.

위 프로젝트는 실제로 사용하기에는 swRTC를 사용하는 관계로 어려운점이 있지만, 만약 RTC모듈을 구매하여 장착하고 좀 더 꾸밀 수 있다면 실생활에서 사용할 수 있는 프로젝트로 발전시킬 수 있다. 위 프로젝트에 대한 글은 http://kocoafab.cc에서 확인할 수 있다.
  

 

 코코아팹은 한국 메이커 문화를 만들어가는 온라인 메이커포털이다. 오픈소스 하드웨어 오렌지보드의 생산과 활용법 공개 등 많은 활동을 진행하고 있다.


[Tutorial] Easy-to-follow Orange Board tutorial (1)
Making a Simple Alarm Clock Using Orange Board

Arduino means a close friend in Italian and is a typical open-source hardware. It is a mini board made for anyone to easily access an Embedded field, which has been hard and difficult to approach. The Arduino Orange Board to be used in this tutorial is a Korean version of Arduino boards.

The distribution of Arduino boards triggered the spread of Open Source Hardware (OSHW) and significantly contributed to the spread of Maker Culture as well. Recently, conglomerates such as Intel and Microsoft started to enter this open-source hardware market. This reflects that the potential of open-source hardware market has grown likewise.

Project Overview

In the series so far, we have posted tutorials on using single sensor, but this time, we will use several sensors to make a simple project.

The first project that will be covered is making a simple alarm clock using LCD, Piezo Buzzer, and a switch. As everyone knows, the functions of alarm clock is to show the time, and at the time specified by the user, the alarm rings and tells the time.

First, let's talk about the roles of each sensor. LCD displays the time, Piezo Buzzer acts as an alarm to ring the sound, and switch will turn off the alarm.

▲ Making a Alarm Clock Using Orange Board

 

About swRTC Library

The function of each sensor is clearly determined, but to make a clock, we need a device to display the time. In the case of a computer, even if the power of the computer is turned off, inside, the power is continuously supplied through CMOS battery to operate the clock.

Like this, we need a module to measure time accurately through another battery inside, even if there is no power from outside. If you search RTC Module (Real Time Clock Module), then you can find this kind of module easily.

▲ Hardware RTC

However, in this tutorial, we will not use the module but use RTC through a separate library. The above module is a hardware RTC, but the RTC using the library is called swRTC, because it uses software.

Unlike hardware RTC, it does not include a separate battery, so if outside power is cut off, the time is initialized and hard to use together with various Arduino functions, which uses timer function. However, when the power is supplied, it behaves the same way as hardware RTC, so when trying to implement a simple project, you can use it conveniently.

List of Items Required
The following items are required to make the alarm clock using Orange Board.

 

 
Connecting to a Hardware

Breadboard

 

 Electronics Circuit Diagram

 

 Source Code

First of all, to implement the code, we need swRTC library. You can get it by searching or more easily through the Kocoafab site (Kocoafab.cc).


#include <LiquidCrystal.h>
#include <core_build_options.h>
#include <swRTC.h>

LiquidCrystal lcd(12,11,5,4,3,2);
String lcdString = "";

swRTC rtc;

int piezo = 6;
int switchPin = 9;
int temp;

//A function to distinguish AM & PM
void setAMPM(int hour) {
if(hour >=12)
lcd.print("PM");
else
lcd.print("AM");

lcd.print(hour%12, DEC); // Display time
}

//A function to print leading 0, when displaying a number less than 10,
void setLowThanTen(int time) {
if(time < 10) {
lcd.print("0");
lcd.print(time%10);
}
else
lcd.print(time);
}


//A function to check if the alarm clock time is valid
int checkTheAlarmClock(int time) {
if(time/100 < 24 && time %100 < 60) {
Serial.println("Success");
return time;
}
else {
Serial.println("Failed");
return 0;
}
}


//A function to check if it is time to ring the alarm
void checkTheAlarmTime(int alarmHour, int alarmMinute) {
if(alarmHour == rtc.getHours() && alarmMinute == rtc.getMinutes()) {
analogWrite(piezo, 128);
}
}

void setup() {
lcd.begin(16,2); //Specify the size of LCD, 2 rows of 16 characters
lcd.clear(); //Initialize the screen

rtc.stopRTC(); //Stop
rtc.setTime(14,05,0); //Initialize time, minute, and second
rtc.setDate(24, 8, 2014); //Initialize day, month, and year
rtc.startRTC(); //Start

pinMode(piezo, OUTPUT);
pinMode(switchPin, INPUT_PULLUP);
Serial.begin(9600); //Initialize Serial Port
Serial.begin(9600); //Initialize Serial Communication
}

void loop() {
int day;
lcd.setCursor(0,0); //Set Cursor to (0,0)

//Renew every second, and display the current time to the LCD
setAMPM(rtc.getHours());
lcd.print(":");
setLowThanTen(rtc.getMinutes());
lcd.print(":");
setLowThanTen(rtc.getSeconds());
//Display the Date to the LCD
lcd.print("[");
setLowThanTen(rtc.getMonth());
lcd.print("/");
setLowThanTen(rtc.getDay());
lcd.print("]");
//Display the specified alarm time to the LCD
lcd.setCursor(0,1);
lcd.print("Alarm ");
setAMPM(temp/100);
lcd.print(":");
setLowThanTen(temp%100);

//Renew LCD every second
lcdString = ""; //Initialize the string
lcd.print(" "); //Delete all the characters
delay(1000);

//Check if it is time to ring the alarm
checkTheAlarmTime(temp/100, temp%100);

//When the switch button is pressed, set the sound of Piezo Sensor to 0, and initialize alarm clock time.
if(!digitalRead(switchPin)) {
temp = 0;
day = 0;
analogWrite(piezo, 0);
Serial.println("Alarm clock initialize");
Serial.println("AM0:00");
}
//Receive the input of alarm time through serial communication and display on the serial monitor
char theDay[4];
int i = 0;
if(Serial.available()) {
while(Serial.available()) {
theDay[i] = Serial.read();
i++;
}
day = atoi(theDay);
if(day/100 >= 12) {
Serial.print("PM");
Serial.print((day/100)-12);
}
else {
Serial.print("AM");
Serial.print(day/100);
}
Serial.print(":");
if(day%100 < 10)
Serial.print("0");
Serial.println(day%100);
temp = checkTheAlarmClock(day);
}
}


The function of the code, summarizing briefly, is as follows:
1. Initialize the time, and operate swRTC.
2. Receive the alarm time reservation from the user through serial monitor.
3. If the input time is a valid time (Output fail if the time value exceeds 24 hours or 60 minutes), register it as alarm time reservation.
4. When the clock is operating, check by comparing reserved alarm time and current time.


1)Initialize Time

If you take a look at Setup() function, you can see the following class member functions. You can set initial time through setTime(), and initialize year, month, and day through setDate(). After the setting is completed and startRTC is called, time starts to go.

rtc.stopRTC(); //Stop
rtc.setTime(14,05,0); //Initialize time, minute, and second
rtc.setDate(24, 8, 2014); //Initialize day, month, and year
rtc.startRTC(); //Start

2)Input the Time
The user enters the time in the serial monitor. When entering time, the user should enter the hour and minute in 24-hour format. For example, if the user enters 1406, it is 02:06PM, and when the user enters 0930, it is 09:30AM.

The value entered by the user is a value from minimum of 3 digits to maximum of 4 digits. If it is divided into 100, the "hour" part of the first 2 digits can be separated, and the rest can be calculated using a % operator to separate the "minute" part.

if(Serial.available()) {
while(Serial.available()) {
theDay[i] = Serial.read();
i++;
}
day = atoi(theDay);
if(day/100 >= 12) {
Serial.print("PM");
Serial.print((day/100)-12);
}
else {
Serial.print("AM");
Serial.print(day/100);
}
Serial.print(":");
if(day%100 < 10)
Serial.print("0");
Serial.println(day%100);
temp = checkTheAlarmClock(day);
}

3)Check the Validity of Time
The user, when entering the time to the serial monitor, must enter exactly within 24 hours and within 60 minutes. However, there are instances when the user fails to enter exactly like that, so from the code the entered value is checked to see if it is a valid time before executing alarm time reservation.
If the hour exceeds 24 hours, or if the minute exceeds 60 minutes, it would fail to enter.

<그림5> <Figure 5>
 

int checkTheAlarmClock(int time) {
if(time/100 < 24 && time %100 < 60) {
Serial.println("Success");
return time;
}
else {
Serial.println("Failed");
return 0;
}
}

 

4)Compare Time

If you input the time, the reserved alarm time and current time is compared every second. getHours() and getMinutes() in the RTC are the functions to read current hour and minute, and if the two values coincide with the alarm time, the alarm will sound from Piezo.


//A function to check if it is time to ring the alarm
void checkTheAlarmTime(int alarmHour, int alarmMinute) {
if(alarmHour == rtc.getHours() && alarmMinute == rtc.getMinutes()) {
analogWrite(piezo, 128);
}
}


Conclusion

This is the first post of the project series. This project is a simple project that can be made by combining the sensor parts from the previous tutorials. Even though code looks complicated, it is only long because the clock is implemented and many sensors are combined, and if you look at them closely, there isn't any part that is too difficult.

Arduino alarm clocks have diverse projects in addition to the aforementioned project, and you can make it using 7-segment display instead of LCD.

Regarding the above project, it may be difficult to use in real life because swRTC is used. However, if you purchase RTC module and install it, and make it more sophisticated, you can develop it into a project that can be used in real life. The post regarding the above project can be checked at http://kocoafab.cc.

저작권자 © 아이티데일리 무단전재 및 재배포 금지