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
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#include <DHT.h>                      // 온습도 센서 라이브러리 사용 
#include <U8glib.h>                   // OLED 디스플레이 라이브러리 사용
 
#define DHT_PIN         4             // 온습도 센서 연결 Pin 번호
#define DHT_TYPE        DHT22         // 온습도 센서 타입
#define VOC_PIN         A0            // VOC 센서 연결 Pin 번호
#define CO2_PIN         A1            // Co2 센서 연결 Pin 번호
#define DUST_PIN        2             // 미세먼지 연결 Pin 번호
#define BTN_PIN         6             // BTN 연결 Pin 번호
#define BTN_LED_PIN     5             // BTN LED연결 Pin 번호
 
#define CHANGE_COUNT     3
 
// 객체 선언
DHT dht(DHT_PIN, DHT_TYPE);
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_DEV_0 | U8G_I2C_OPT_NO_ACK | U8G_I2C_OPT_FAST);
 
// OLED Bitmap 아이콘(40*40) 배열
const unsigned char badIcon [] PROGMEM = {
  0x000x000x000x000x000x000x000x000x000x000x000x000x000x000x000x00,
  0x000x000x000x000x000xff0xff0xff0x800x070xff0xff0xff0xe00x0f0xff,
  0xff0xff0xf00x0c0x000x000x000x380x1c0x000x000x000x180x180x000x00,
  0x000x180x180x000x000x000x180x180x000x000x000x180x180x000x000x00,
  0x180x180x000x000x000x180x180x000x000x000x180x180x0e0x000x700x18,
  0x180x1f0x000xf80x180x180x1f0x000xf80x180x180x1f0x000xf80x180x18,
  0x0e0x000x700x180x180x000x000x000x180x180x000x000x000x180x180x00,
  0x000x000x180x180x000x000x000x180x180x000x3c0x000x180x180x070xff,
  0xe00x180x180x0f0xff0xf00x180x180x180x000x080x180x180x000x000x00,
  0x180x180x000x000x000x180x180x000x000x000x180x1c0x000x000x000x18,
  0x0c0x000x000x000x380x0f0x000x000x000x700x070xff0xff0xff0xe00x01,
  0xff0xff0xff0x800x000x000x000x000x000x000x000x000x000x000x000x00,
  0x000x000x000x000x000x000x000x00,
};
 
const unsigned char goodIcon [] PROGMEM = {
  0x000x000x000x000x000x000x000x000x000x000x000x000x000x000x000x00,
  0x000x000x000x000x000xff0xff0xff0x800x070xff0xff0xff0xe00x0f0xff,
  0xff0xff0xf00x0c0x000x000x000x380x1c0x000x000x000x180x180x000x00,
  0x000x180x180x000x000x000x180x180x000x000x000x180x180x000x000x00,
  0x180x180x000x000x000x180x180x000x000x000x180x180x0e0x000x700x18,
  0x180x1f0x000xf80x180x180x1f0x000xf80x180x180x1f0x000xf80x180x18,
  0x0e0x000x700x180x180x000x000x000x180x180x000x000x000x180x180x00,
  0x000x000x180x180x000x000x000x180x180x000x000x000x180x180x180x00,
  0x180x180x180x0f0xe70xf00x180x180x030xff0xc00x180x180x000x3c0x00,
  0x180x180x000x000x000x180x180x000x000x000x180x1c0x000x000x000x18,
  0x0c0x000x000x000x380x0f0x000x000x000x700x070xff0xff0xff0xe00x01,
  0xff0xff0xff0x800x000x000x000x000x000x000x000x000x000x000x000x00,
  0x000x000x000x000x000x000x000x00
};
 
 
float gasRo = 0;                              // Co2 센서 초기 저항 값
unsigned long dustStartTime = 0;              // 미세먼지 측정 시작 시간
unsigned long sampletimeMS = 30000;           // 미세먼지 샘플링 설정 시간
unsigned long lowPulseOccupancy = 0;          // 미세먼지 Pulse 합계
 
float humidity, temperature;                  // 온습도 값
float dustugm3;                               // 미세먼지 농도값
float vocppm;                                 // Voc 농도값
float co2ppm;                                 // Co2 농도값
bool enable = true;                           // 디바이스 On/Off 상태 값
int changeCnt;                                // 디스플레이 전환 카운트
int slideNum;                                 // 슬라이드 번호
bool pleasable = false;                       // 기준 수치 적정성
 
 
void setup() {
  Serial.begin(115200);
  dht.begin();                                // 온습도 센서 활성화
  u8g.begin();                                // OLED 모듈 활성화
 
  pinMode(BTN_PIN, INPUT);                    // 버튼 모듈 Pin 모드 설정
  pinMode(BTN_LED_PIN, OUTPUT);
  pinMode(DUST_PIN, INPUT);                   // 미세먼지 센서 Pin 모드 설정
 
  initConfig();                               // 초기 환경 설정
  clearOLED();                                // OLED 지우기
 
  Serial.println("## Start Air Quality Monitoring ##");
}
 
void loop() {
  btnEvent();                                               // 버튼 모듈 클릭 이벤트 함수 호출
 
  if (enable) {                                             // 디바이스 On 전환 시,
    measureVOC();                                                 // VOC 수치 측정
    measureCo2();                                                 // Co2 수치 측정
    measureDust();                                                // 미세먼지 수치 측정
    measureDHT();                                                 // 온도, 습도 수치 측정
 
    changeCnt--;                                                  // 전환 카운트 감소
    if (changeCnt <= 0) {                                           // 카운트 0 도달 시,
      slideNum = slideNum >= 5 ? 1 : slideNum + 1;                  // 슬라이드 번호 지정
      showOLED();                                                   // OLED 정보 출력
      changeCnt = CHANGE_COUNT;                                     // 전환 카운트 초기화
    }
    delay(1000);
  }
  delay(50);
}
 
 
// OLED 종료 함수 (기존 출력 정보 지우기)
void clearOLED() {
  u8g.firstPage();
  do {
    // Null
  } while ( u8g.nextPage() );
}
 
// OLED 출력 함수
void showOLED() {
  u8g.firstPage();
  do {
    switch (slideNum) {
      case 1:             // 슬라이드 번호 1 = 온도 정보 출력
        pleasable = temperature > 16 && temperature < 28;   // 측정 온도 기준 적정성 판단
        u8g.setFont(u8g_font_fub14);                        // 폰트 설정
        u8g.drawStr(6422"Temp");                        // 온도 정보 출력
        u8g.drawStr(6454, String(temperature).c_str());
        break;
      case 2:             // 슬라이드 번호 2 = 습도 정보 출력
        pleasable = humidity > 30 && humidity < 70;         // 측정 습도 기준 적정성 판단
        u8g.setFont(u8g_font_fub14);                        // 폰트 설정
        u8g.drawStr(6422"Humi");                        // 습도 정보 출력
        u8g.drawStr(6454, String(humidity).c_str());
        break;
      case 3:             // 슬라이드 번호 3 = 미세먼지 정보 출력
        pleasable = dustugm3 < 35;                          // 측정 미세먼지 기준 적정성 판단
        u8g.setFont(u8g_font_fub14);                        // 폰트 설정
        u8g.drawStr(6422"Dust");                        // 미세먼지 정보 출력
        u8g.drawStr(6454, String(dustugm3).c_str());
        break;
      case 4:             // 슬라이드 번호 4 = VOC 정보 출력
        pleasable = vocppm < 6;                            // 측정 VOC 기준 적정성 판단
        u8g.setFont(u8g_font_fub14);                        // 폰트 설정
        u8g.drawStr(6422"Voc");                         // VOC 정보 출력
        u8g.drawStr(6454, String(vocppm).c_str());
        break;
      case 5:             // 슬라이드 번호 5 = Co2 정보 출력
        pleasable = co2ppm < 20;                            // 측정 CO2 기준 적정성 판단
        u8g.setFont(u8g_font_fub14);                        // 폰트 설정
        u8g.drawStr(6422"Co2");                         // Co2 정보 출력
        u8g.drawStr(6454, String(co2ppm).c_str());
        break;
    }
    u8g.drawBitmapP(812540, pleasable ? goodIcon : badIcon);      // 기준 수치 적정성에 따른 상태 아이콘 출력
  } while ( u8g.nextPage() );
}
 
// 버튼 클릭 이벤트 함수
void btnEvent() {
  if (digitalRead(BTN_PIN)) {                   // 버튼 클릭 시,
    while (digitalRead(BTN_PIN)) {
      delay(100);
    }
    enable = !enable;                           // 동작 활성화 상태 전환
    if (enable) {                                   // 동작 활성화 시,
      initConfig();                                     // 초기 환경 설정
    } else {                                        // 동작 비활성화 시,
      clearOLED();                                      // OLED 출력 종료
    }
    digitalWrite(BTN_LED_PIN, enable);          // 동작 상태에 따라 버튼 LED 상태 설정
  }
}
 
 
// 초기 환경 설정 함수
void initConfig() {
  dustStartTime = millis();                   // 미세먼지 측정 시작 시간 설정
  changeCnt = CHANGE_COUNT;                   // 전환 카운트 갱신(초기화) 
  slideNum = 0;                               // 슬라이드 시작 번호 초기화
  lowPulseOccupancy = 0;                      // 미세먼지 Pulse 합계 초기화
}
 
 
// 온습도 측정 함수
void measureDHT() {
  humidity = dht.readHumidity();                  // 습도 측정
  temperature = 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 = concentration * 100 / 1300;
    Serial.print("Dust(ug/m3) : ");
    Serial.println(dustugm3);
    lowPulseOccupancy = 0;
    dustStartTime = millis();
  }
}
 
 
// CO2 측정 함수
void measureCo2() {
  // 가스 센서 측정 참조 - https://thestempedia.com/tutorials/interfacing-mq-2-gas-sensor-with-evive/
  float vOut = analogRead(CO2_PIN) * 5.0 / 1023.0;
  float gasRs = (5.0 - vOut) / vOut;
 
  if (gasRo == 0) {
    gasRo = gasRs / 9.9;
    Serial.print("Gas Ro : ");
    Serial.print(gasRo);
    Serial.println(" kohm");
  } else {
    float ratio = gasRs / gasRo;
    co2ppm = pow(10, (log(ratio) - 1.51/ -0.34);
    Serial.print("(Co2) Vout : ");
    Serial.print(vOut);
    Serial.print("\t ppm : ");
    Serial.println(co2ppm);
  }
}
 
 
// VOC 측정 함수
void measureVOC() {
  // VOC 센서 측정 참조 - https://datasheetspdf.com/pdf/1418387/Ogam/GSBT11/1
  float vOut = analogRead(VOC_PIN) * 5.0 / 1023.0;
  vocppm = pow(10-0.867 + 1.274 * vOut);
  Serial.print("(Formaldehyde) Vout : ");
  Serial.print(vOut);
  Serial.print("\t ppm : ");
  Serial.println(vocppm);
}
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#include <DHT.h>                      // 온습도 센서 라이브러리 사용 
#include <Adafruit_NeoPixel.h>        // LED 링 라이브러리 사용
#include <U8glib.h>                   // OLED 디스플레이 라이브러리 사용
 
#define DHT_PIN         4             // 온습도 센서 연결 Pin 번호
#define DHT_TYPE        DHT22         // 온습도 센서 타입
#define CDS_PIN         A0            // 조도 센서 연결 Pin 번호
#define LED_PIN         2             // LED Ring 연결 Pin 번호
#define BTN_PIN         6             // BTN 연결 Pin 번호
#define BTN_LED_PIN     5             // BTN LED연결 Pin 번호
 
#define LED_PIXELs_SIZE   12          // LED Ring 픽셀 수
 
 
#define ORANGE_START_POS  10          // 온습도 수치에 따라 주황/초록/파랑 계열 색상 범위(Position 기준 수치) 지정
#define ORANGE_END_POS    40
#define GREEN_START_POS   45
#define GREEN_END_POS     95
#define BLUE_START_POS    105
#define BLUE_END_POS      160
 
// 객체 선언
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);
 
// OLED Bitmap 아이콘(32*32) 배열
const unsigned char humiIcon [] PROGMEM = {
  0x000x000x000x000x000x000x000x000x000x000x000x000x000x000x000x00,
  0x000x000x000x000x000x010x800x000x000x030xc00x000x000x060x600x00,
  0x000x0c0x300x000x000x080x180x000x000x180x080x000x000x300x0c0x00,
  0x000x240x060x000x000x600x020x000x000xc00x030x000x000x900x010x00,
  0x000x800x010x800x010x800x000x800x010x800x000x800x010x800x000x80,
  0x010x800x000x800x010x800x010x800x000x800x010x800x000xc00x030x00,
  0x000x600x060x000x000x3c0x3c0x000x000x1f0xf80x000x000x070xe00x00,
  0x000x000x000x000x000x000x000x000x000x000x000x000x000x000x000x00
};
const unsigned char tempIcon [] PROGMEM = {
  0x000x000x000x000x000x000x000x000x000x030x800x000x000x070xe00x00,
  0x000x0f0xe00x000x000x0c0x300x000x000x080x300x000x000x080x300x00,
  0x000x080x300x000x000x090xb00x000x000x0b0xb00x000x000x0b0xb00x00,
  0x000x0b0xb00x000x000x0b0xb00x000x000x0b0xb00x000x000x1b0xb80x00,
  0x000x3b0x9c0x000x000x730x8e0x000x000x670xe60x000x000xef0xe60x00,
  0x000xcf0xf30x000x000xdf0xf30x000x000xdf0xf30x000x000xcf0xf30x00,
  0x000xef0xe60x000x000x670xc60x000x000x700x0c0x000x000x3c0x3c0x00,
  0x000x1f0xf00x000x000x070xc00x000x000x000x000x000x000x000x000x00
};
 
float tempLowValue = 15;              // 온도 상태 기준 수치
float tempHighValue = 25;
float humiLowValue = 20;              // 습도 상태 기준 수치
float humiHighValue = 70;
 
int lux;                                      // LED 세기 값
float humidity, temperature;                  // 온습도 값
long loopInterval = 100;                      // Loop 간격
long loopTime;                                // Loop 측정 시간
int sensingDelay = 20;                        // 센싱 간격(횟수)
int sensingCnt = 0;                           // 센싱 동작 카운트
int colorPos, startPos, endPos;               // LED Color Position 값
bool isPosIncrement = true;                   // Color Position 증가 상태값
bool enable = false;                          // On/Off 상태 값
 
void setup() {
  Serial.begin(115200);
  dht.begin();                                // 온습도 센서 활성화
  pixels.begin();                             // LED 링 모듈 활성화
  u8g.begin();                                // OLED 모듈 활성화
 
  pinMode(BTN_PIN, INPUT);                    // 버튼 모듈 Pin 모드 설정
  pinMode(BTN_LED_PIN, OUTPUT);
  
  clearOLED();                                
  clearLed();
    
  Serial.println("## Mood Lighting Setup ##");
}
 
void loop() {
  btnEvent();                                               // 버튼 모듈 클릭 이벤트 함수 호출
 
  if (enable) {                                             // LED등 상태 활성화,
    if (millis() - loopTime > loopInterval) {               // 설정된 Loop 시간 초과,
      if (sensingCnt == 0 || sensingCnt > sensingDelay) {   // 초기 센싱 상태 또는 센싱 동작 카운트가 기준 횟수 초과 시, 
        measureSensor();                                        // 온습도 수치 측정
        showOLED();                                             // 온습도 값 & 아이콘 OLED 출력
        setColorRange();                                        // LED 출력 Color Position 범위 설정
        sensingCnt = 0;                                         // 센싱 동작 카운트 초기화
      }
      sensingCnt++;                                         // 센싱 동작 카운트 증가
      showLed();                                            // LED 등 출력
      loopTime = millis();                                  // Loop 측정 시간 초기화
    }
  }
  delay(50);
}
 
// 버튼 클릭 이벤트 함수
void btnEvent() {
  if (digitalRead(BTN_PIN)) {                   // 버튼 클릭 시,
    while (digitalRead(BTN_PIN)) {
      delay(100);
    }
    enable = !enable;                           // 동작 활성화 상태 전환
    if (enable) {                                   // 동작 활성화 시,
      colorPos = 0;                                     // Color Position 초기화
      isPosIncrement = true;                            // Color Position 증가 설정
    } else {                                        // 동작 비활성화 시, 
      clearOLED();                                      // OLED 출력 종료
      clearLed();                                       // LED 출력 종료
    }
    digitalWrite(BTN_LED_PIN, enable);          // 동작 상태에 따라 버튼 LED 상태 설정 
  }
}
 
// OLED 종료 함수 (기존 출력 정보 지우기)
void clearOLED() {
  u8g.firstPage();
  do {
    // Null
  } while ( u8g.nextPage() );
}
 
// OLED 출력 함수 (온습도 정보 출력)
void showOLED() {
  u8g.firstPage();
  do {
    u8g.drawBitmapP( 120432, humiIcon);             // 비트맵 아이콘 출력
    u8g.drawBitmapP( 1232432, tempIcon);
    u8g.setFont(u8g_font_profont22r);                     // 폰트 설정
    u8g.drawStr(5222, String(humidity).c_str());        // 온습도 수치 출력
    u8g.drawStr(5254, String(temperature).c_str());
  } while ( u8g.nextPage() );
}
 
// 센서 측정 함수
void measureSensor() {
  humidity = dht.readHumidity();                  // 습도 측정 
  temperature = dht.readTemperature();            // 온도 측정 
 
  if (isnan(humidity) || isnan(temperature)) {
    Serial.println("DHT sensor error!");
    return;
  }
 
  float cdsValue = analogRead(CDS_PIN);           // 조도 센서값 측정
  lux = map(cdsValue, 0102310020);          // 조도 수치에 따른 LED 밝기 설정
}
 
// LED Color Position 범위 설정 함수
void setColorRange() {
  if (temperature < tempLowValue || humidity > humiHighValue) {     
    // 측정된 온도 수치가 LOW 온도 보다 낮거나 습도 수치가 HIGH 습도 보다 높으면 파랑 계열 색상 범위 설정
    startPos = BLUE_START_POS;
    endPos = BLUE_END_POS;
  } else if (temperature > tempHighValue || humidity < humiLowValue) {
    // 측정된 온도 수치가 HIGH 온도 보다 높거나 습도 수치가 LOW 습도 보다 낮으면 주황 계열 색상 범위 설정
    startPos = ORANGE_START_POS;
    endPos = ORANGE_END_POS;
  } else {
    // 이외의 수치는 초록 계열 색상 범위 설정
    startPos = GREEN_START_POS;
    endPos = GREEN_END_POS;
  }
}
 
 
// 무드등 출력 비활성화 (모든 LED 픽셀을 검정색으로 출력)
void clearLed() {
  for (int i = 0; i < LED_PIXELs_SIZE; i ++) {
    pixels.setPixelColor(i,  pixels.Color(000));
  }
  pixels.show();
}
 
// 무드등 LED 출력
void showLed() {
  isPosIncrement ? colorPos++ : colorPos--;               // Color Position 증가 여부에 따라 현재값 +/- 
  
  for (int i = 0; i < pixels.numPixels(); i++) {          // 현재 Color Position에 대한 RGB 색상 출력
    pixels.setPixelColor(i, getRGBColor(colorPos));
  }
  
  if (colorPos >= endPos) {                               // 현재 Color Position이 종료 범위에 도달하면 
    isPosIncrement = false;                                   // isPosIncrement를 False로 설정하여 Color Position 감소 
  } else if (colorPos <= startPos) {                      // 시작 범위에 도달하면 
    isPosIncrement = true;                                    // isPosIncrement를 True로 설정하여 Color Position 증가
  }
 
  pixels.setBrightness(lux);                              // LED 밝기 설정
  pixels.show();                                          // 지정된 LED 색상 출력
}
 
// Color Position에 따른 RGB 색상 반환 함수
uint32_t getRGBColor(byte pos) {
  pos = 255 - pos;
  if (pos < 85) {
    return pixels.Color(255 - pos * 30, pos * 3);
  }
  if (pos < 170) {
    pos -= 85;
    return pixels.Color(0, pos * 3255 - pos * 3);
  }
  pos -= 170;
  return pixels.Color(pos * 3255 - pos * 30);
}
cs

 

+ Recent posts