아두이노:WIFI
둘러보기로 이동
검색으로 이동
아두이노 관련 정보를 모으기 위한 틀. 틀:아두이노
- 아두이노:개요
- 아두이노:하드웨어
- 아두이노:코드
- 아두이노:핀 사용
- 아두이노:시리얼 통신
- 아두이노:편의함수
- 센서 사용
- 아두이노:LCD 사용
- 아두이노:스위치 사용
- 아두이노:릴레이
- 통신 관련, 정보 교환
- 아두이노:해결되지 않은 다양한 의문들
- 수업용 간단 실습
- 아두이노 모터 출력
- 미완문서
- 분류:아두이노 프로젝트
개요[편집 | 원본 편집]
아두이노에서 현재 시간을 받거나 데이터를 보낼 때 와이파이를 다루어야 할 필요가 생긴다.
ps. 와이파이를 쓰려면..[편집 | 원본 편집]
- 처음부터 ESP8266 NodeMCU나 Wemos D1 mini 처럼 와이파이 통합 보드를 쓰는 편이 간편하고 좋다.
- 모듈을 따로 사서 붙이는 것보다 싸다.
- 새로 덧붙일 필요도 없고.(모듈만 사서 덧붙이는 게, 좀 귀찮은 작업이 필요하다. 저항 달고, 빵판 필요하고;;)
- 그러나 학습용으로 기존 보드에 붙이는 용이라면 ESP8266 ESP-01 모듈이 좋다.
기종별 와이파이 사용법[편집 | 원본 편집]
아두이노 우노 R4[편집 | 원본 편집]
아두이노 R4엔 ESP32-S3가 내장되어 있다.
아래는 와이파이를 이용해 현재시간을 불러오는 방법이다.
- 라이브러리에서 wifi 검색, Arduino Uno WIFI Dev Ed Library 설치.
- 라이브러리에서 NTPClient 설치.(시간을 가져오는 라이브러리)
#include <WiFi.h>
#include <WiFiUdp.h>
#include <NTPClient.h>
#include <time.h>
// WiFi 정보
const char* ssid = "kwsh";
const char* password = "khsh9700#";
// NTP 클라이언트 설정
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
void setup() {
Serial.begin(9600); // 시리얼 통신 속도 설정
WiFi.begin(ssid, password);
// WiFi 연결 시도
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi network");
timeClient.begin();
timeClient.setTimeOffset(32400); // 서울 시간(UTC+9)으로 변환하기 위한 오프셋 설정
}
void loop() {
timeClient.update();
String fromattedTime = timeClient.getFormattedTime();
Serial.print("Current time: ");
Serial.print(fromattedTime.substring(0,2));
Serial.print(":");
Serial.println(fromattedTime.substring(3,5));
delay(1000);
}
ESP32류[편집 | 원본 편집]
일단 ESP-C6에서 작동 확인
#include <WiFi.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h> // https 요청용.
#include <ArduinoJson.h> // JSON 데이터 생성용
// ====== WiFi 설정 ======
const char* ssid = "wi1_gwe";
const char* password = "Gwe1234!#@";
// ====== 서버 설정 ======
const char* serverUrl = "https://jinhan.site/";
const char* apiToken = "3VOS0zMJhN...";
b
// ====== 전송 간격 설정 ======
const unsigned long sendInterval = 1000; // 1초마다 데이터 전송
unsigned long lastSendTime = 0;
// ====== WiFi 재연결 간격 설정 ======
const unsigned long reconnectInterval = 10000; // 10초마다 재시도
unsigned long lastReconnectAttempt = 0;
WiFiClientSecure client;
HTTPClient http;
// ====== WiFi 연결 함수 ======
void connectWiFi() {
Serial.printf("\n📶 WiFi 연결 시도: %s\n", ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < 20) {
delay(500);
Serial.print(".");
attempts++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("\n✅ WiFi 연결 성공!");
Serial.print("IP 주소: ");
Serial.println(WiFi.localIP());
} else {
Serial.println("\n❌ WiFi 연결 실패. 나중에 다시 시도합니다.");
}
}
// ====== 데이터 전송 함수 ======
void sendData(float temp, float humid) {
StaticJsonDocument<200> doc;
doc["temp"] = temp;
doc["humid"] = humid;
String jsonData;
serializeJson(doc, jsonData);
client.setInsecure(); // SSL 인증서 검증 비활성화 (테스트용)
http.begin(client, serverUrl);
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", apiToken);
int httpCode = http.POST(jsonData);
if (httpCode >= 200 && httpCode < 300) {
Serial.printf("✅ 전송 성공 | 온도: %.2f°C | 습도: %.2f%%\n", temp, humid);
} else {
Serial.printf("❌ 전송 실패 | HTTP 코드: %d\n", httpCode);
}
http.end();
}
// ====== 초기 설정 ======
void setup() {
Serial.begin(115200);
delay(100);
Serial.println("\n\n=================================");
Serial.println("실시간 과학실험 데이터 전송 시작 (ESP32-C6)");
Serial.println("=================================\n");
connectWiFi();
}
// ====== 메인 루프 ======
void loop() {
unsigned long now = millis();
if (WiFi.status() != WL_CONNECTED) {
if (now - lastReconnectAttempt >= reconnectInterval) {
lastReconnectAttempt = now;
Serial.println("⚠️ WiFi 연결 끊김. 재연결 시도...");
WiFi.disconnect(true);
delay(1000);
connectWiFi();
}
return;
}
if (now - lastSendTime >= sendInterval) {
lastSendTime = now;
float temp = random(200, 350) / 10.0; // 예: 20.0 ~ 35.0℃
float humid = random(400, 900) / 10.0; // 예: 40.0 ~ 90.0%
sendData(temp, humid);
}
}