mqtt 초음파 센서 활용 iot 코드
본문 바로가기
카테고리 없음

mqtt 초음파 센서 활용 iot 코드

by 하고싶은거하는여자 2024. 11. 17.
728x90
반응형
#include <WiFi.h>
#include <PubSubClient.h>

const char* ssid = "iot2024";
const char* password = "a123456789";
const int trigPin = 12;
const int echoPin = 14;
const char* mqtt_server = "test.mosquitto.org";
const int mqttPort = 1883;

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsgTime = 0;

float readultrasonicSensor() {
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  pinMode(echoPin, INPUT);
  float duration = pulseIn(echoPin, HIGH);
  float distance = duration * 0.0343 / 2.0;
  Serial.println(distance);
  return distance;
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("MQTT 연결 시도 중...");
    String clientId = "ESP32Client-"; // 랜덤 클라이언트 ID 생성
    clientId += String(random(0xffff), HEX);
    Serial.print("클라이언트 ID: ");
    Serial.println(clientId);
    if (client.connect(clientId.c_str())) { // 연결 시도
      Serial.println("연결됨");
    } else {
      Serial.print("실패, rc=");
      Serial.print(client.state());
      Serial.println(" 5초 후 다시 시도");
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200); // 시리얼 통신 초기화 (보드 속도 115200bps)
  WiFi.begin(ssid, password); // Wi-Fi 연결 시작 (SSID와 비밀번호 필요)

  while (WiFi.status() != WL_CONNECTED) { // Wi-Fi 연결 될 때까지 대기
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.println("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP()); // 연결된 Wi-Fi 네트워크의 IP 주소 출력

  delay(5000); // 5초 대기

  client.setServer(mqtt_server, mqttPort); // MQTT 서버 설정
  pinMode(echoPin, INPUT); // echoPin을 입력 모드로 설정
  pinMode(trigPin, OUTPUT); // trigPin을 출력 모드로 설정
  digitalWrite(trigPin, LOW); // trigPin을 LOW 상태로 설정
  delayMicroseconds(2); // 2마이크로초 대기
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop(); // 클라이언트가 메시지를 처리하고 서버와의 연결을 유지
  long now = millis();
  if (now - lastMsgTime > 1000) { // 1초 간격
    lastMsgTime = now;
    float sensorValue = readultrasonicSensor();
    char sensorString[8];
    dtostrf(sensorValue, 1, 2, sensorString);
    client.publish("jo0788/iot-esp32/ultra", sensorString);
  }
}
728x90
반응형

댓글