12주차 아두이노 클라우드와 OLED 디스플레이 사용하기 - hyunwoo14/SmartDevice GitHub Wiki
- 아두이노 클라우드
- 회로
- 클라우드 설정
- 코드
- 업로드
- 실행 결과
- OLED 디스플레이
- 회로
- 라이브러리 설치
- 코드
- 실행 결과
- 후기
https://cloud.arduino.cc/ 에 로그인 하고 오른쪽 상단의 메뉴를 통해 Cloud 사이트로 이동한다.

Things에서 CREATE THING 버튼을 클릭한다.
프로젝트의 이름을 입력하고 ADD 버튼을 클릭한다.
LED 상태를 제어하는 led_state 변수를 추가한다.

온습도 센서를 모니터링 하기 위해 temperature변수를 추가한다.

Associated Device 에서 Select Device 버튼을 클릭한다.
SET UP NEW DEVICE를 선택하고 ESP32를 사용하므로 3rd Party를 클릭한다.

ESP32를 선택하고 메뉴에서 "DOIT ESP32 DEVKIT V1"을 선택한뒤 디바이스의 이름도 정해준다.

"Device ID"와 "Security Key"를 복사해 둔다.
Network에서 Configure 버튼을 클릭한다.
네트워크 이름, 암호, "Security Kay"를 입력하고 저장한다.
Sketch 탭으로 가서 코드를 입력한다.
#include "thingProperties.h"
#include "DHT.h"
int led_pin = 23;
int dh11_pin = 13;
DHT dht(dh11_pin, DHT11);
void setup() {
pinMode(led_pin, OUTPUT);
dht.begin();
// Initialize serial and wait for port to open:
Serial.begin(9600);
// This delay gives the chance to wait for a Serial Monitor without blocking if none is found
delay(1500);
// Defined in thingProperties.h
initProperties();
// Connect to Arduino IoT Cloud
ArduinoCloud.begin(ArduinoIoTPreferredConnection);
/*
The following function allows you to obtain more information
related to the state of network and IoT Cloud connection and errors
the higher number the more granular information you’ll get.
The default is 0 (only errors).
Maximum is 4
*/
setDebugMessageLevel(2);
ArduinoCloud.printDebugInfo();
}
void loop() {
ArduinoCloud.update();
// Your code here
// Read temperature as Celsius (the default)
temperature = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(temperature)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
Serial.print(F("Temperature: "));
Serial.println(temperature);
delay(1000);
}
/*
Since LedState is READ_WRITE variable, onLedStateChange() is
executed every time a new value is received from IoT Cloud.
*/
void onLedStateChange() {
// Add your code here to act upon LedState change
Serial.print("LED state is changed : ");
Serial.println(led_state);
if (led_state) {
digitalWrite(led_pin, HIGH);
}
else {
digitalWrite(led_pin, LOW);
}
}
위 코드를 입력하고 업로드 한다.
Dashboard 메뉴로 가서 Dashboard를 생성한다.
시각적으로 볼 수 있는 위젯을 만든다.
먼저 led_state 변수를 제어할 switch 위젯을 선택한뒤 디바이스(ESP32)와 변수(led_state)를 선택하여 위젯에 연결해준다.


다음에는 temperature를 모니터링 할 Chart 위젯도 추가한 뒤 디바이스(ESP32)와 변수(temperature)를 선택하여 위젯에 연결해준다.


위젯은 이곳에서 편집할 수 있다.
Switch 위젯의 상태에 따라 LED가 켜지고 꺼진다.
OFF
ON
Adafruit_SSD1306 라이브러리를 설치하고 종속성 설치도 모두 설치해준다.

#include
#include
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
void setup() {
Serial.begin(9600);
// OLED 디스플레이 초기화
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println("SSD1306 오류");
while (true);
}
// OLED 디스플레이 클리어
display.clearDisplay();
}
void loop() {
// "Hello, World!"를 크기가 다른 세 개의 텍스트로 표시
display.clearDisplay();
// 크기 6의 폰트로 텍스트 표시
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0, 0);
display.println("Hello, World!");
// 크기 8의 폰트로 텍스트 표시
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(0, 15);
display.println("Hello, World");
display.display();
delay(2000);
}
코드를 업로드하면 OLED 디스플레이에 Hello, World! 문자가 나온다.
회로는 위의 실습과 동일하다.
#include // WiFi 통신을 위한 라이브러리
#include // 시간과 관련된 함수를 위한 라이브러리
#include // 디스플레이를 위한 그래픽 라이브러리
#include // SSD1306 OLED 디스플레이를 위한 라이브러리
// SSD1306 디스플레이 객체 초기화
Adafruit_SSD1306 display = Adafruit_SSD1306(128, 32, &Wire, -1);
const char* ssid = "Your_SSID"; // 여기에 사용하는 WiFi 네트워크 이름 (SSID)을 입력하세요
const char* password = "Your_Password"; // 여기에 사용하는 WiFi 네트워크 비밀번호를 입력하세요
int GMTOffset = 60 * 60 * 9; // 시간 오프셋 설정, 한국은 UTC/GMT +9입니다.
int daylightOffset = 0; // 국가에서 서머타임을 사용하는 경우 오프셋 값을 설정하세요.
const String weekDays[7] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; // 요일 이름 배열
void setup() {
Serial.begin(115200); // 디버깅을 위한 시리얼 통신 시작
// SSD1306 디스플레이 초기화
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 초기화 실패"));
while (1)
; // 디스플레이 초기화에 실패하면 프로그램 실행 중지
}
delay(2000); // 2초 동안 대기
display.clearDisplay(); // 디스플레이 지우기
display.setTextSize(1); // 텍스트 크기를 1로 설정
display.setCursor(0, 0); // 커서 위치를 디스플레이 왼쪽 위 모서리로 설정
display.setTextColor(WHITE); // 텍스트 색상을 흰색으로 설정
WiFi.begin(ssid, password); // 제공된 SSID와 비밀번호를 사용하여 WiFi 네트워크에 연결
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting...");
}
Serial.println("Connected to Wi-Fi!");
// 시간 설정을 위한 NTP 서버 설정
configTime(GMTOffset, daylightOffset, "pool.ntp.org", "time.nist.gov");
}
void loop() {
// 현재 시간 가져오기
time_t rawtime = time(nullptr);
struct tm* timeinfo = localtime(&rawtime);
// 시리얼 모니터에 날짜 출력
Serial.print(timeinfo->tm_mday);
Serial.print("/");
Serial.print(timeinfo->tm_mon + 1);
Serial.print("/");
Serial.print(timeinfo->tm_year + 1900);
Serial.print(" ");
// 시리얼 모니터에 시간 출력
Serial.print("Time: ");
Serial.print(timeinfo->tm_hour);
Serial.print(":");
Serial.print(timeinfo->tm_min);
Serial.print(":");
Serial.println(timeinfo->tm_sec);
// OLED 디스플레이 초기화
display.clearDisplay();
display.setTextSize(3);
display.setTextColor(WHITE);
display.setCursor(0, 0);
// 시간 출력
if (timeinfo->tm_hour < 10)
display.print("0");
display.print(timeinfo->tm_hour);
display.print(":");
if (timeinfo->tm_min < 10)
display.print("0");
display.print(timeinfo->tm_min);
display.print(":");
// 초 출력
display.setTextSize(2);
display.setCursor(102, 5);
if (timeinfo->tm_sec < 10)
display.print("0");
display.print(timeinfo->tm_sec);
// 날짜 출력
display.setTextSize(1);
display.setCursor(0, 25);
display.print(timeinfo->tm_mday);
display.print("/");
display.print(timeinfo->tm_mon + 1);
display.print("/");
display.print(timeinfo->tm_year + 1900);
display.print(" ");
display.print(weekDays[timeinfo->tm_wday]);
// 디스플레이에 표시
display.display();
delay(1000);
}
상단에 시간을 표시하고 하단에 날짜와 요일을 표시하는 시계가 완성되었다.
이번 실습은 비교적 쉬웠고, 아두이노 클라우드를 직접 사용해보며 클라우드의 개념도 알 수 있었으며 OLED 시계를 만드는 과정에서 다른 사이트의 시간을 가져와서 OLED에 나타내는 실습을 하며 시간을 가져오는 방식에 대해서도 알 수 있게 되었다.























