PHYSIs Beacon 모듈 - iBeacon 예제

Beacon 모듈의 경우, 아두이노와 모듈 간의 소프트웨어 통신을 활용하여 설정합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <PHYSIs_Master.h>                  // PHYSIs_Master 라이브러리 추가
 
PHYSIs_Beacon beacon(65);                // 비콘 객체 선언 (Rx, Tx)
 
void setup() {
  Serial.begin(115200);
 
  if (beacon.begin()) {                     // 비콘 모듈 연결    
    beacon.init();                                  // 모듈 고장 초기화
    delay(1000);
    beacon.reboot();                                // 모듈 재시작
    delay(1000);
    if (beacon.isConnected()) {                     // 모듈 연결 확인      
      delay(1000);
      Serial.print("iBeacon Address : ");
      Serial.println(beacon.getAddress());          // 모듈 MAC 주소 출력
      delay(1000);
      beacon.setADInterval('5');                    // 신호 출력 간격 설정 ( '1 '~ 'F' )
      delay(1000);
      beacon.setDeviceName("P_Beacon");             // 디바이스 이름 설정
      delay(1000);
      beacon.setBeaconMode();                       // 비콘 모드 설정
      delay(1000);
      beacon.setOnlyBroadcast();                    // 단일 신호 출력 모드 설정
      delay(1000);
      beacon.setAutoSleepStatus(true);              // 오토 슬립 모드 설정
      delay(1000);
      beacon.reboot();                              // 모듈 재시작
    }
  }
}
 
void loop() {
 
}
cs

PHYSIs 메이커보드 - Beacon Scanner(도난 방지기) 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <PHYSIs_Master.h>
#include <Adafruit_NeoPixel.h>        // LED 라이브러리 추가
 
#define BUZZER_PIN    4               // 부저 연결 Pin 번호
#define LED_PIN       2               // LED Ring 연결 Pin 번호
#define LED_PIXELs_SIZE   12          // LED Ring 픽셀 수
 
// 객체 선언
PHYSIs_Beacon beacon(109); // Rx, Tx
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(LED_PIXELs_SIZE, LED_PIN, NEO_GRB + NEO_KHZ800);
 
String targetAddr = "C8FD198E4D15";          // 탐색 대상 비콘 주소값
uint32_t distColor;                          // 거리 상태 색상
int nonfindCnt = 0;                          // 검색 오류 카운트
 
long waringTime = 0;
 
void setup() {
  Serial.begin(115200);
  pixels.begin();                                      // LED 링 모듈 활성화
  pixels.setBrightness(75);
 
  if (beacon.begin()) {                                // 비콘 모듈 연결
    beacon.init();                                        // 모듈 고장 초기화
    delay(1000);
    beacon.reboot();                                      // 모듈 재시작
    delay(1000);
    if (beacon.isConnected()) {                           // 모듈 연결 확인
      beacon.setBeaconScanner();                          // 비콘 스캔 모드 설정
      beacon.beaconScanResult = &beaconScanResult;        // 비콘 검색 결과 콜백 함수 지정
    }
  }
}
 
void loop() {
  beacon.beaconDiscovery();                     // 비콘 검색
 
 
  if (nonfindCnt > 5)                           // 대상 비콘이 5회 이상 검색되지 않으면
  {
    if (millis() - waringTime > 1000) {                               // 1초 마다 부저음 출력
      digitalWrite(BUZZER_PIN, !digitalRead(BUZZER_PIN));
      waringTime = millis();
    }
  }
}
 
// 비콘 검색 결과 콜백 함수
void beaconScanResult(String addr, int rssi) {
  Serial.print(addr);
  Serial.print(", ");
  Serial.println(rssi);
  if (addr.equals(targetAddr)) {                      // 대상 비콘이 검색될 경우,
    nonfindCnt = 0;                                         // 검색 오류 카운트 초기화
    showStatusLed(rssi);                                    // 비콘 거리 상태 LED 출력
  } else {                                            // 대상 비콘이 아닌 경우,
    nonfindCnt++;                                           // 검색 오류 카운트 증가
  }
}
 
// 비콘 거리 상태 LED 출력
void showStatusLed(int rssi) {
  distColor = rssi > -50 ? pixels.Color(02550) : pixels.Color(2552550);
  for (int i = 0; i < pixels.numPixels(); i++) {
    pixels.setPixelColor(i, distColor);
  }
  pixels.show();
}
 
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <PHYSIs_Master.h>
#include <DHT.h>                      // 온습도 센서 라이브러리 사용 
#include <Adafruit_NeoPixel.h>
 
#define DUST_PIN        2             // 미세먼지 연결 Pin 번호 
#define DHT_PIN         4             // 온습도 센서 연결 Pin 번호
#define DHT_TYPE        DHT22         // 온습도 센서 타입
#define LED_PIN         5
 
 
PHYSIs_WiFi physisWiFi;
DHT dht(DHT_PIN, DHT_TYPE);
Adafruit_NeoPixel strip = Adafruit_NeoPixel(12, LED_PIN, NEO_GRB + NEO_KHZ800);
 
const String WIFI_SSID     = "your wifi";             // WiFi 명
const String WIFI_PWD      = "your password";         // WiFi 비밀번호
const String SERIAL_NUMBER = "your serial number";    // PHYSIs KIT 시리얼번호
const String PUB_TOPIC     = "Sensing";               // Publish Topic
 
unsigned long sensingTime = 0;                // 센서 측정 시간
unsigned long sensingInterval = 2000;         // 센서 측정 간격
unsigned long dustStartTime = 0;              // 미세먼지 측정 시작 시간
unsigned long sampletimeMS = 10000;           // 미세먼지 샘플링 설정 시간
unsigned long lowPulseOccupancy = 0;          // 미세먼지 Pulse 합계
int humidity, temperature;                    // 온습도 값
int dustugm3;                                 // 미세먼지 농도값
uint32_t ledColor;
 
void setup() {
  Serial.begin(115200);
  dht.begin();                                // 온습도 센서 활성화
  strip.begin();
  
  physisWiFi.enable();                             // WiFi 모듈 활성화
 
  physisWiFi.connectWiFi(WIFI_SSID, WIFI_PWD);     // 지정 WiFi에 대한 연결 요청
  Serial.print("# WiFi Connecting..");
  delay(1000);
  while (!physisWiFi.isWiFiStatus()) {             // WiFi가 연결될때 까지 반복해서 연결상태를 확인
    Serial.print(".");
    delay(1000);
  }
  Serial.println(F("Connected..."));
 
  Serial.print("# MQTT Connecting..");
  if (physisWiFi.connectMQTT()) {                  // PHYSIs 플랫폼의 MQTT Broker와 연결
    Serial.println("Success...");
  } else {
    Serial.print("Fail...");
  }
 
  strip.setBrightness(50);
  strip.show();                                   // LED 초기화
}
 
void loop() {
  if (millis() - sensingTime >= sensingInterval) {        // 센서 측정 시간이 측정 간격을 초과하였을 경우,
    measureDust();                                            // 미세먼지 측정
    measureDHT();                                             // 온습도 측정
    setDustLedColor();                                        // 미세먼지 상태 LED 색상 설정
    sendSensingData();                                        // 미세먼지, 온습도 정보 전송
    sensingTime = millis();                                   // 센서 측정 시간 재설정
  }
  
  showLedEffect();                                      // 미세먼지 상태 LED 출력
}
 
 
// 미세먼지 농도에 따른 LED 색상 설정 함수
void setDustLedColor(){
  if(dustugm3 > 35){
    ledColor = strip.Color(25500);
  }else if (dustugm3 < 15){    
    ledColor = strip.Color(00255);
  }else{    
    ledColor = strip.Color(02550);
  }
}
 
// LED 효과 출력 함수 
void showLedEffect() {
  for (int i = 0; i < 3; i++) {                            
    for (int j = 0; j < strip.numPixels(); j = j + 3) {    
      strip.setPixelColor(j + i, ledColor);                // LED 색상 출력
    }
    strip.show();
    delay(100);
    for (int j = 0; j < strip.numPixels(); j = j + 3) {
      strip.setPixelColor(j + i, 0);                       // 이전 LED 색상 초기화
    }
  }
}
 
 
// 센싱(미세먼지, 온/습도) 정보 전송 함수
void sendSensingData() {
  String data = String(dustugm3) + "," + String(temperature) + "," + String(humidity);
  physisWiFi.publish(SERIAL_NUMBER, PUB_TOPIC, data);       // MQTT 메시지 전송
}
 
// 온습도 측정 함수
void measureDHT() {
  humidity = (int)dht.readHumidity();                  // 습도 측정
  temperature = (int)dht.readTemperature();            // 온도 측정
 
  if (isnan(humidity) || isnan(temperature)) {
    Serial.println("DHT sensor error!");
    return;
  }
  Serial.print("DHT : (Temp) ");
  Serial.print(temperature);
  Serial.print("\t (Humi) ");
  Serial.println(humidity);
}
 
 
// 미세먼지 측정 함수
void measureDust() {
  // 미세먼지 센서(Grove-Dust Sensor) 측정 참조 - https://wiki.seeedstudio.com/Grove-Dust_Sensor/
  lowPulseOccupancy += pulseIn(DUST_PIN, LOW);
  if (millis() - dustStartTime >= sampletimeMS) {
    float ratio = lowPulseOccupancy / (sampletimeMS * 10.0);
    float concentration = 1.1 * pow(ratio, 3- 3.8 * pow(ratio, 2+ 520 * ratio + 0.62;
    dustugm3 = (int)(concentration * 100 / 1300);
    Serial.print("Dust(ug/m3) : ");
    Serial.println(dustugm3);
    lowPulseOccupancy = 0;
    dustStartTime = millis();
  }
}
cs

PHYSIs_Dust_Monitor.aia
0.12MB

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <PHYSIs_Master.h>            // Physis 전용 라이브러리 추가
 
#define C_PIN       2                 // 터치 센서 핀 번호
#define D_PIN       3
#define E_PIN       4
#define F_PIN       5
#define G_PIN       A0
#define A_PIN       A1
#define B_PIN       A2
#define C_H_PIN     A4
 
PHYSIs_BLE physisBLE;                 // Physis BLE 객체 선언
 
String oldData;                       // 기존 입력 정보 값
 
void setup() {
  Serial.begin(115200);
 
  if (!physisBLE.enable()) {                  // BLE 모듈 활성화 시도
    while (1) {
      delay(1000);                            // 모듈 활성화 실패 시, 다음 단계 진행 X
    }
  }
 
  Serial.print(F("# BLE Address : "));
  Serial.println(physisBLE.getAddress());     // Physis 메이커보드의 주소정보 호출 & 출력
 
  pinMode(C_PIN, INPUT);                      // 디지털 핀을 사용하는 터치 센서 핀 모드 설정
  pinMode(D_PIN, INPUT);
  pinMode(E_PIN, INPUT);
  pinMode(F_PIN, INPUT);
}
 
void loop() {
  inputReader();                              // 터치 입력 검출 함수 호출
  delay(50);
}
 
 
void inputReader() {
  // 터치 센서의 각각의 입력 상태를 확인
  bool c = digitalRead(C_PIN);                    
  bool d = digitalRead(D_PIN);
  bool e = digitalRead(E_PIN);
  bool f = digitalRead(F_PIN);
  bool g = analogRead(G_PIN) == 1023;
  bool a = analogRead(A_PIN) == 1023;
  bool b = analogRead(B_PIN) == 1023;
  bool ch = analogRead(C_H_PIN) == 1023;
 
  // 현재 입력에 대한 상태 문자열 생성
  String newData = String(c) + String(d) + String(e) + String(f) +
                   String(g) + String(a) + String(b) + String(ch);
 
  // 상태정보와 기존 입력 정보를 비교
  if (!newData.equals(oldData)) {           // 입력상태가 변경되었을 경우,
    physisBLE.sendMessage(newData);             // 현재 상태를 블루투스 메시지로 전송.
    oldData = newData;                          // 기존 입력 정보 갱신.
  }
}
cs

 

 

Physis_Piano.aia
0.35MB

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <DHT.h>                      // 온습도 센서 라이브러리 사용 
#include <Adafruit_NeoPixel.h>        // LED 링 라이브러리 사용
#include <U8glib.h>                   // OLED 디스플레이 라이브러리 사용
 
 
#define DHT_PIN         4             // 온습도 센서 연결 Pin 번호
#define DHT_TYPE        DHT22         // 온습도 센서 타입
#define LED_PIN         2             // LED Ring 연결 Pin 번호
#define CDS_PIN         A0            // 조도 센서 연결 Pin 번호
#define LVL_PIN         A1            // 수위(레벨) 센서 연결 Pin 번호
 
#define LED_PIXELs_SIZE   12          // LED Ring 픽셀 수
 
 
// 객체 선언
DHT dht(DHT_PIN, DHT_TYPE);
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(LED_PIXELs_SIZE, LED_PIN, NEO_GRB + NEO_KHZ800);
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_DEV_0 | U8G_I2C_OPT_NO_ACK | U8G_I2C_OPT_FAST);
 
int lux;                                      // 조도 값
float humidity, temperature;                  // 온습도 값
int waterLvl;                                 // 수위 값
uint32_t levelColor;                          // 수위(레벨) 상태 색상
int ledStep = 0;
int oledStage = 0;
int measureCnt = 0;                           // 센서 측정 카운트
 
void setup() {
  Serial.begin(115200);
  dht.begin();                                // 온습도 센서 활성화
  pixels.begin();                             // LED 링 모듈 활성화
  u8g.begin();                                // OLED 모듈 활성화
 
  measureCnt = 10;
 
}
 
void loop() {
  if (measureCnt == 10) {
    setLevelColor();
    measureSensors();
    showOLED();
    measureCnt = 0;
  }
  measureCnt++;
  showDotLed();
  delay(200);
}
 
 
void showOLED() {
  u8g.firstPage();
  do {
    u8g.setFont(u8g_font_unifont);
    u8g.undoScale();
    switch (oledStage) {
      case 0:
        u8g.drawStr(816"Water Level(%)");                    // 텍스트(Title) 출력
        u8g.setScale2x2();                                        // 폰트 스케일 증가
        u8g.drawStr(2426, String(waterLvl).c_str());
        break;
      case 1:
        u8g.drawStr(816"Temperature('C)");                    // 텍스트(Title) 출력
        u8g.setScale2x2();                                        // 폰트 스케일 증가
        u8g.drawStr(2426, String(temperature).c_str());
        break;
      case 2:
        u8g.drawStr(816"Humidity(%)");                    // 텍스트(Title) 출력
        u8g.setScale2x2();                                        // 폰트 스케일 증가
        u8g.drawStr(2426, String(humidity).c_str());
        break;
      default:
        u8g.drawStr(816"Light(Lux)");                    // 텍스트(Title) 출력
        u8g.setScale2x2();                                        // 폰트 스케일 증가
        u8g.drawStr(2426, String(lux).c_str());
    }
  } while ( u8g.nextPage() );
  oledStage = oledStage == 3 ? 0 : oledStage + 1;
}
 
void measureSensors() {
  humidity = dht.readHumidity();                  // 습도 측정
  temperature = dht.readTemperature();            // 온도 측정
  lux = analogRead(CDS_PIN);                      // 조도 측정
}
 
void setLevelColor() {
  int val = analogRead(LVL_PIN);
  waterLvl = map(val, 010230100);
 
  levelColor = waterLvl < 20 ? pixels.Color(25500) :
               (waterLvl < 80 ? pixels.Color(02550) : pixels.Color(00255));
}
 
void showDotLed() {
  for (int i = 0; i < pixels.numPixels(); i++) {
    if (i % 3 == ledStep)
      pixels.setPixelColor(i, levelColor);
    else
      pixels.setPixelColor(i, 0);
  }
  pixels.show();
  ledStep = ledStep == 2 ? 0 : ledStep + 1;
}
cs

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#include <IRremote.h>                 // IR Remote (ver 2.5.0) 라이브러리 사용
#include <Servo.h>                    // Servo 라이브러리 사용
#include <U8glib.h>                   // OLED 디스플레이 라이브러리 사용
 
#define IR_PIN      2                 // IR 수신 센서 Pin 번호
#define SERVO_PIN   3                 // 서보모터 Pin 번호
#define BUZZER_PIN  4                 // 피에조 부저 Pin 번호
 
#define EFFECT_WAKE_UP    1           // 부저 효과음 - 입력 활성화
#define EFFECT_UNLOCK     2           // 잠금해제
#define EFFECT_KEY_ERR    3           // 키 오류
#define EFFECT_INPUT_NUM  4           // 키 입력
 
// 객체 선언
IRrecv ir(IR_PIN);
Servo servo;
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_DEV_0 | U8G_I2C_OPT_NO_ACK | U8G_I2C_OPT_FAST);
 
// IR 리모컨 신호 리스트
long irSignalList[] = {
  167124451672876516732845,
  1673845516750695167568151672417516718055,
  1674304516716015167262151673488516730805,
};
 
// IR 신호별 문자 리스트
String irCharList[] = {
  "OK""*""#",
  "1""2""3""4""5""6""7""8""9""0",
};
 
 
bool isWakeup, isLock;            // 입력 활성화, 잠금 상태 값
String receiveStr = "";           // IR 신호 문자 값
String inputStr = "";             // 입력 키 값
long inputTime;                   // 입력 동작 시간
long timeOut = 1000 * 10;         // 입력 종료 시간
 
String unlockStr = "2021";        // 잠금해제 키 값
 
void setup() {
  Serial.begin(115200);
  u8g.begin();                                // OLED 모듈 활성화
  servo.attach(SERVO_PIN, 0180);            // 서보 모터 초기화
 
  pinMode(BUZZER_PIN, OUTPUT);                // 부저 모듈 Pin 모드 설정
 
  servo.write(0);                             // 서보모터 초기 각도 제어
  ir.enableIRIn();                            // IR 수신 활성화
 
  showLockState();                            // 잠금상태 OLED 출력
}
 
void loop() {
  irReceiver();                               // IR 신호 수신
  setLockStatus();                            // 잠금 상태 설정
 
  // 입력 가능 시간 체크
  if (isWakeup && millis() - inputTime > timeOut) {           // 입력이 활성화된 상태에서 지정 시간만큼 시간이 지나면
    isWakeup = false;                                               // 입력 비활성화 상태로 전환
    inputStr = "";                                                  // 입력 키 정보 초기화
    showLockState();                                                // 잠금상태 OLED 출력
  }
  delay(50);
}
 
// 잠금 상태 설정 함수
void setLockStatus() {
  if (receiveStr != "") {                                 // 지정된 문자에 대한 IR 신호 수신 시,
    if (receiveStr.equals("*")) {                                     // "*" 문자 수신 시, 입력 활성화 설정                        
      isWakeup = !isWakeup;                                                     // 입력 활성화 상태 변경
      inputStr = "";                                                            // 입력 키 정보 초기화              
      isWakeup ? showInputNumber() : showLockState();                           // 활성화 상태에 따른 OLED 정보 출력
      soundEffect(EFFECT_WAKE_UP);                                              // 입력 활성화 효과음 출력
      
    } else if (receiveStr.equals("#"&& isLock) {                    // "#" 문자 수신 및 잠금해제 상태 시, 잠금 설정    
      servo.write(0);                                                           // 서보 모터 각도 초기화
      isLock = isWakeup = false;                                                // 잠금 상태, 입력 비활성화 상태 설정
      showLockState();                                                          // 잠금상태 OLED 출력
      
    } else if (isWakeup) {                                            // 입력 활성화 상태 시,
      inputStr += receiveStr;                                                   // 입력 키 정보에 IR 신호 문자 추가
      showInputNumber();                                                        // 입력 키 정보 OLED 출력
      soundEffect(EFFECT_INPUT_NUM);                                            // 키 입력 효과음 출력
      
      if (inputStr.length() == 4) {                                             // 4자리 키 정보 입력 시,
        delay(300);
        if (inputStr.equals(unlockStr)) {                                               // 잠금해제 키 정보와 일치할 경우,
          isLock = true;                                                                      // 잠금 해제 상태로 설정
          isWakeup = false;                                                                   // 입력 비활성화 설정
          soundEffect(EFFECT_UNLOCK);                                                         // 잠금 해제 효과음 출력
          showLockState();                                                                    // 잠금상태 OLED 출력
          servo.write(180);                                                                   // 서보 모터 각도 제어
          
        } else {                                                                        // 잠금해제 키 정보와 불일치할 경우,
          inputStr = "";                                                                      // 입력 키 정보 초기화
          soundEffect(EFFECT_KEY_ERR);                                                        // 키 오류 효과음 출력
          showInputNumber();                                                                  // 입력 키 정보 OLED 출력
        }
      }
    }
    inputTime = millis();                                    // 입력 시작 시간 초기화
    receiveStr = "";                                         // IR 수신 문자 초기화
  }
}
 
// 입력 키 정보 OLED 출력 함수
void showInputNumber() {
  u8g.firstPage();
  do {
    u8g.setFont(u8g_font_unifont);                            // 폰트 설정
    u8g.undoScale();                                          // 폰트 스케일 초기화
    u8g.drawStr(1416"INPUT NUMBER");                      // 텍스트(Title) 출력
    u8g.setScale2x2();                                        // 폰트 스케일 증가
    String showNum = "";
    for (int i = 0; i < inputStr.length(); i++) {                         // 입력 키 문자열 길이만큼 반복문 실행
      showNum += i > 0 ? " " + String(inputStr[i]) : inputStr[i];             // 첫번째 문자 이후부터 공백 " " 추가 
    }
    u8g.drawStr(326, showNum.c_str());                      // 입력 키 정보 출력
  } while ( u8g.nextPage() );
}
 
// 잠금 상태 정보 OLED 출력 함수
void showLockState() {
  u8g.firstPage();
  do {
 
    u8g.setFont(u8g_font_unifont);                            // 폰트 설정
    u8g.undoScale();                                          // 폰트 스케일 초기화
    u8g.drawStr(3816"IR LOCK");                           // 텍스트(Title) 출력
    u8g.setScale2x2();                                        // 폰트 스케일 증가
    if (isLock) {                                             // 잠금 상태에 따른 텍스트 출력
      u8g.drawStr(1626"OPEN");
    } else {
      u8g.drawStr(1226"CLOSE");
    }
  } while ( u8g.nextPage() );
}
 
// IR 신호 수신 함수
void irReceiver() {
  decode_results res;
  if (ir.decode(&res))                                          // IR 신호 수신 시,
  {
    if (res.decode_type == 3 && res.bits == 32) {                        // 지정 IR 타입 및 크기(32Bit)의 신호 수신 시,
      int irPos = -1;
      for (int i = 0; i < sizeof(irSignalList); i++) {                   // IR 리모컨 신호 리스트에서 해당 신호의 인덱스 검출
        if (res.value == irSignalList[i]) {
          irPos = i;
          break;
        }
      }
      receiveStr = irPos != -1 ? irCharList[irPos] : "";                 // IR 신호 리스트의 인덱스 기준 IR 문자 호출 및 저장 
    }
    ir.resume();                                                // IR 신호 수신 대기
  }
}
 
// 피에조 부저 효과음 출력 함수
void soundEffect(int type) {
  if (type == EFFECT_WAKE_UP) {                                 // 입력 활성화 효과음
    digitalWrite(BUZZER_PIN, HIGH);
    delay(100);
    digitalWrite(BUZZER_PIN, LOW);
    delay(50);
    digitalWrite(BUZZER_PIN, HIGH);
    delay(100);
    digitalWrite(BUZZER_PIN, LOW);
  } else if (type == EFFECT_UNLOCK) {                           // 잠금 해제 효과음
    digitalWrite(BUZZER_PIN, HIGH);
    delay(300);
    digitalWrite(BUZZER_PIN, LOW);
    delay(50);
    digitalWrite(BUZZER_PIN, HIGH);
    delay(100);
    digitalWrite(BUZZER_PIN, LOW);
    delay(50);
    digitalWrite(BUZZER_PIN, HIGH);
    delay(100);
    digitalWrite(BUZZER_PIN, LOW);
  } else if (type == EFFECT_KEY_ERR) {                           // 입력 키 오류 효과음
    digitalWrite(BUZZER_PIN, HIGH);
    delay(500);
    digitalWrite(BUZZER_PIN, LOW);
  } else {                                                       // 키 입력 효과음
    digitalWrite(BUZZER_PIN, HIGH);
    delay(100);
    digitalWrite(BUZZER_PIN, LOW);
  }
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#define BTN_PIN         5               // 버튼 연결 Pin 번호
#define BTN_LED_PIN     4               // 버튼 LED 연결 Pin 번호
#define DIODE_LED_PIN   3               // 다이오드 LED 연결 Pin 번호
 
bool enable = false;
 
void setup() {
  Serial.begin(115200);
 
  pinMode(BTN_PIN, INPUT);              // 버튼 Pin을 입력모드로 설정
  pinMode(BTN_LED_PIN, OUTPUT);         // 버튼 LED Pin을 출력모드로 설정
  pinMode(DIODE_LED_PIN, OUTPUT);       // 다이오드 LED Pin을 출력모드로 설정
}
 
void loop() {
  if(digitalRead(BTN_PIN) == HIGH){                   // 버튼 클릭 상태일 때,
      while(digitalRead(BTN_PIN) == HIGH){                // 버튼이 클릭이 종료될 때까지 대기.
        delay(100);
      }
      enable = !enable;                               // 다이오드 LED 상태 전환 
  }
 
  digitalWrite(DIODE_LED_PIN, enable);                // 다이오드 LED 상태 설정  
  digitalWrite(BTN_LED_PIN, !enable);                 // 다이오드 LED 상태와 반대로 버튼 LED 상태 제어
  
  delay(50);
}
cs

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#define CDS_PIN   A0                          // 조도 센서 아닐로그 Pin 번호
#define LED_PIN   3
 
float cdsValue;                              
 
void setup() {
  pinMode(LED_PIN, OUTPUT);       // LED 핀 모드 설정
}
 
void loop() {
  float cdsValue = analogRead(CDS_PIN);                 // 조도 센서 저항값(세기) 읽기
  int ledLux = map(cdsValue, 010232550);          // 조도 세기를 기준으로 LED 출력 세기(0~255) 환산
 
  analogWrite(LED_PIN, ledLux);                         // LED PWM 제어
  
  delay(1000);
}
cs

 

 

<주의> 아두이노 업로드를 위해 IDE에 <DHT.h>와 <LiquidCrystal_I2C.h> 라이브러리가 추가되어 있어야합니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <DHT.h>                                  // DHT 라이브러리 추가
#include <LiquidCrystal_I2C.h>                    // I2C LCD 라이브러리 추가
 
#define DHT_PIN   2                               // 온습도 센서 연결 디지털 핀 번호
#define DHT_TYPE  DHT22                           // DHT 센서 종류
#define LCD_ADDR  0x3F                            // I2C LCD 주소 0x3F or 0x27
 
DHT dht(DHT_PIN, DHT_TYPE);                       // DHT 객체 선언
LiquidCrystal_I2C lcd(LCD_ADDR, 162);           // 16 * 2 LCD 객체 선언
 
void setup() {
  dht.begin();                                // DHT 센서 활성화
  lcd.init();                                 // LCD 초기화
  lcd.backlight();                            // LCD 백라이트 ON
}
 
void loop() {
  float humidity = dht.readHumidity();            // 습도값 읽기 & 저장
  float temperature = dht.readTemperature();      // 온도값 읽기 & 저장
 
  lcd.setCursor(00);        // x, y 커서 좌표 설정
  lcd.print("Temp:");         // 설정 좌표에 데이터 출력
  lcd.setCursor(01);
  lcd.print("Humi:");
 
  lcd.setCursor(60);        
  lcd.print(temperature);
  lcd.setCursor(61);
  lcd.print(humidity);
 
  delay(2000);
}
cs

 

 

+ Recent posts