오래간만에 만드는 ESP32 IOT 장치

반응형

우리집 거실에서는 ...

이렇게 생긴 스위치를 전등에 달아서 사용한다.

 

우리방의 불은 진짜 스위치를 뜯어서 개조해서 사용했는데

거실은 위의 장치를 이용하기 때문에 새롭게 알아보고 만들었다. 

 

처음에 위의 스위치가 IR을 이용한 방식인 줄 앍고

IR신호를 알아내기 위해

아두이노 우노를 이용하여 신호를 잡으려 헀으나...

좌- 새로 알리에서 주문한 수신기(VS1638B) 우- 원래  있던 수신기

어떤 신호도 안잡히길래 확인해보니... 고장!

그래서 알리에서 다른 센서 묶음으로 주문하고 일주일 정도 후에

배송을 받고 신호확인!

 


아두이노 IRremote  수신 방법


⌘ 아두이노 IR receiver 코드 ⌘

#include <IRremote.hpp>
int IR_RECEIVE_PIN = 9;
void setup()
{
  Serial.begin(9600);
  IrReceiver.begin(IR_RECEIVE_PIN, ENABLE_LED_FEEDBACK); // Start the receiver
}

void loop() {
  if (IrReceiver.decode()) {
      Serial.println(IrReceiver.decodedIRData.decodedRawData, HEX); // Print "old" raw data
      // USE NEW 3.x FUNCTIONS
      IrReceiver.printIRResultShort(&Serial); // Print complete received data in one line
      IrReceiver.printIRSendUsage(&Serial);   // Print the statement required to send this data
      IrReceiver.resume(); // Enable receiving of the next value
  }
}

위 그대로 실행하면 잘 나온다. IRremote-Arduino깃허브에서 복사한 거임.

예전 irremote 방법으로 사용하면 FFFFFF만 나온다.

더보기

이런거

#include <IRremote.h>
 
int IR_RECV_PIN = 9;
 
IRrecv irrecv(IR_RECV_PIN);
decode_results results;
 
void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}
 
void loop()
{
   readIR();
}

void readIR()
{
   if (irrecv.decode( &results ))
   {
      unsigned long IRval = results.value;
      /*
      if (IRval == 0xffffffff)
      {
         irrecv.resume();
         return;
      }
      */
      Serial.println( results.value, HEX );
      irrecv.resume();
   }
}

https://github.com/Arduino-IRremote/Arduino-IRremote

 

GitHub - Arduino-IRremote/Arduino-IRremote: Infrared remote library for Arduino: send and receive infrared signals with multiple

Infrared remote library for Arduino: send and receive infrared signals with multiple protocols - GitHub - Arduino-IRremote/Arduino-IRremote: Infrared remote library for Arduino: send and receive in...

github.com

 

  ir 적외선으로 켜는 줄 알았으나... 라디오 무선 방식이네... ㅎ  

그래도 포기는 금물이지 ㅋ

스위치를 트랜지스터로 작동하면 되니까

 

 

그래도 배송까지 해서 확인을 헀는데... 그래서 로봇청소기 컨트롤 기능을 추가하기로 했다 ㅎㅎ

시리얼모니터를 확인하면 

 

BB445540
Protocol=NEC Address=0x5540 Command=0x44 Raw-Data=0xBB445540 32 bits LSB first
Send with: IrSender.sendNEC(0x5540, 0x44, <numberOfRepeats>);
11EE5540
Protocol=NEC Address=0x5540 Command=0xEE Raw-Data=0x11EE5540 32 bits LSB first
Send with: IrSender.sendNEC(0x5540, 0xEE, <numberOfRepeats>);
EE115540
Protocol=NEC Address=0x5540 Command=0x11 Raw-Data=0xEE115540 32 bits LSB first
Send with: IrSender.sendNEC(0x5540, 0x11, <numberOfRepeats>);
66995540
Protocol=NEC Address=0x5540 Command=0x99 Raw-Data=0x66995540 32 bits LSB first
Send with: IrSender.sendNEC(0x5540, 0x99, <numberOfRepeats>);

친절하게 보내는 신호 보내는 법도 알려주는데

....

모르겠엉

 

그래서 깃허브를 뒤져서 

찾아낸 간단한 IRremote 송신 방법!

#include "TinyIRSender.hpp"

const int irLED = 19;

void Home() {
  sendNECMinimal(irLED, 0x5540, 0x11, 1);
}

위 시리얼 모니터 값을 보면 우리집 로봇 청소기가 사용한 protocol은 NEC다 .

그리고 친절하게 Address, Command를 알려준다.

 

그래서

sendNECMinimal(핀번호, Address, Command, 반복횟수);

를 입력하고 테스트하면 성공!

 

후해해해해해해햏

해해해해해해ㅐ햏

헤헤헤헤헤헤헿

후후후후후후후

히히히히히히히

 


트랜지스터 스위치로 사용하는 방법(3.3v)


요론 식으로 연결을 했다.

저 구리 표면은 테스터로 확인용인 점이다.

칼로 그 표면을 긁은 뒤 납땜을 해서 붙이면 잘 붙는다.(후라이팬에 계란 달라붙는것 같은 효과?)

 

집에 전에 사용하던 리모컨이 하나 더 있어서 그 리모컨을 개조 했는데 둘다 뜯으면 

해당 부분이 다른데 이걸로 신호를 조절하는 것 같아 현재 사용하는 리모컨처럼 똑같이 만드어주고

 

작동확인을 하니 똑같은 리모컨처럼 작동을 했다.

 

트랜지스터는 예전 장난감에 붙어있던 것을 뽑아서 사용했다.

datasheet로 스펙을 확인한 뒤 

붙였다 

 

트랜지스터 작동확인을 위해서 

빠르게 esp32에 연결한 뒤 

void setup()
{
	pinMode(18, OUTPUT);
    digitalWrite(18, HIGH);
}

로 설정한 뒤 확인하니 잘 작동했다 ㅎㅎ

 

이제 빠르게 원래 사용하던 dht11이랑 IR LED도 붙여준 다음 빠르게 진행하면! 신셰계

아 참고로 빛감지 센서는 작동을 안하더라... 고장 났어... 확인도 안해보고 달았거든...

 

마지막으로 홈어시스턴트에 추가하면 끝!

난 홈킷을 사용해서 시리한테 시킬거라 엔티티 추가를 했는데

 

홈어시스턴트만 이용할 거면 lovelace.yaml에 추가만 하면 돼!

더보기
#난 커스텀 버튼카드를 추가해서 아래처럼 작성했엏
  - type: horizontal-stack
        cards:
          - type: 'custom:button-card'
            icon: "mdi:chandelier"
            aspect_ratio: '1/1'
            size: 80%
            name: "거실등"
            tap_action: 
                action: call-service
                service: mqtt.publish
                service_data:
                    qos: 2
                    topic: "livingRoom/switch"
                    payload: "livSwitch"
                haptic: 'light'
            styles:
                card:
                  - background: rgba(255,240,170,0.8)
                    border-radius: 10%
                    padding: 10%
                grid:
                  - grid-template-areas: '"i" "n" "s"'
                  - grid-template-columns: 1fr                  
                  - grid-template-rows: 1fr min-content min-content
                icon:
                  - color: rgb(242, 151, 39)
                name:                  
                  - justify-self: start
                  - color: white
                  - font-weight: bold
                  - align-self: start
                  - text-shadow: 0px 0px 5px black
                  - width: 100%

 


전체 아두이노 코드


#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
#include "TinyIRSender.hpp"

#define DHTPIN 4
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

const char *ssid =  "olleh_WiFi_BA83";   
const char *password =  "0000002583"; 

const char* ID = "테스트";  // Name of our device, must be unique
const char* TOPIC1 = "house/temper";
const char* TOPIC2 = "house/hum";
const char* TOPIC3 = "livingRoom/light";
const char* INTOPIC = "livingRoom/switch";
const char* mqttUser = "dragon";
const char* mqttPassword = "qazwsxedcrfvtgbyhnujm";
const char* broker = "172.30.1.48";

WiFiClient wclient;
PubSubClient client(wclient); 
String msg = "";
char messages[50];
char val[20];
const int irLED = 19;
const int livingRoomSwitch = 18;
const int lightCheck = 13;
int lightVal = 0;
float oldTemp = 0;

// Connect to WiFi network
void setup_wifi() {
  Serial.print("\nConnecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password); 
  while (WiFi.status() != WL_CONNECTED) { 
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Received messages: ");
  Serial.print(INTOPIC);
  msg = "";
  for(int i=0; i<length; i++){
    //Serial.println((char)payload[i]);
    msg += (char)payload[i];
  }
  Serial.println(msg);
  Serial.println();
  if (msg == "vclean") {
    vClean();
  } else if (msg == "livSwitch") {
    livOn();
  } else if (msg == "home") {
    Home();
  }
}

void Home() {
  sendNECMinimal(irLED, 0x5540, 0x11, 1);
}

void vClean() {
  //IrSender.sendNEC(0x5540, 0x44, 1);
  sendNECMinimal(irLED, 0x5540, 0x44, 1);
}

void livOn() {
  digitalWrite(livingRoomSwitch, HIGH);
  delay(500);
  digitalWrite(livingRoomSwitch, LOW);
}
// Reconnect to client
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(ID, mqttUser, mqttPassword)) {
      Serial.println("connected");
      Serial.print("Publishing to: ");
      Serial.println(TOPIC1);
      Serial.println('\n');
      client.subscribe(INTOPIC);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println("\n try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  pinMode(livingRoomSwitch ,OUTPUT);
  pinMode(irLED, OUTPUT);
  Serial.begin(115200); 
  delay(100);
  dht.begin();
  setup_wifi(); // Connect to network
  client.setServer(broker, 1883);
  client.setCallback(callback);
}

void loop() {
  if (!client.connected()){
    reconnect();
  }
  client.loop();
  float humi = dht.readHumidity();
  float temp = dht.readTemperature();
  if (oldTemp != temp) {
    Serial.print("Temperature: ");
    Serial.print(temp);
    Serial.print("ºC ");
    Serial.print("Humidity: ");
    Serial.print(humi);
    Serial.println("% ");
  //dtostrf(temp, 5, 1, val);
    snprintf(messages, 75, "%.1f", temp);
    client.publish(TOPIC1, messages);
  //dtostrf(humi, 5, 1, val);
    snprintf(messages, 75, "%.1f", humi);
    client.publish(TOPIC2, messages);
    oldTemp = temp;
  }
/*
  lightVal = analogRead(lightCheck);
  Serial.print("checkLight: ");
  Serial.println(lightVal);
  
  if (analogRead(lightCheck) > 2000) {
    snprintf(messages, 75, "%s", "on");
    client.publish(TOPIC3, messages);
  } else {
    snprintf(messages, 75, "%s", "off");
    client.publisj j j          j h(TOPIC3, messages);
  }
  */
  delay(1000);
}

mqtt나 다른 HomeAssistant 관련글은 블로그에서 알아서 찾아보도록!

반응형