아두이노 와이파이 이용 mqtt통신 무한재연결

조회수 540회

저는 아두이노 uno wifi rev2 제품을 사용중이고 wifi를 이용한 mqtt통신 코드를 테스트하는중 오류가 발생했습니다. 서버는 node-red로 구현했습니다. publish나 subscribe를 하면 무한재연결을 하기시작합니다. publish나 subscribe를 제거하면 한번 연결되고 반복되지 않습니다.

esp32 에선 같은코드여도(헤더파일만다르고 코드는 동일) 잘작동하는데 정말 이상합니다.... 전문가 분들의 도움이 필요합니다 ㅠㅠ

#include <SPI.h>
#include <WiFiNINA.h>
#include <PubSubClient.h>


//pin
int ledc = 1;
#define ledB 10
#define ledG 8
#define ledR 9
#define photo A0
const char* mqtt_server = "test.mosquitto.org";

WiFiClient noClient;
PubSubClient client(noClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup_wifi();

void callback(char* topic, byte* payload, unsigned int length){
  Serial.print("message arrived[");
  Serial.print(topic);
  Serial.println("]");
  for (int i=0;i<length;i++) {
    Serial.println("payload=");
    Serial.print((char)payload[i]);
    Serial.println("\n");
}
if ((char)payload[0] == '1') {
 ledc=1;
}
else if((char)payload[0] == '2'){
  ledc=0;
}
}

int led_set() {            // 조도센서 입력에 따라 바뀌는 LED 출력 함수
  int light;
  ledc=1;
  if(ledc==1){         // LED ON
    int photo_r = analogRead(photo);    // 조도센서 값 입력지정
    light =100 -map(photo_r,0,1023,0, 255); // 조도센서 값 범위 설정
    analogWrite(ledR,light);     // LED 출력
    analogWrite(ledG,light);
    analogWrite(ledB,light);
  }
  else if(ledc==0){            //LED OFF
    analogWrite(ledR,0);     
    analogWrite(ledG,0);
    analogWrite(ledB,0);
  }
  int zodo1=analogRead(photo);
  return zodo1;
}

void setup() {
  pinMode(ledG,OUTPUT);
  pinMode(ledB,OUTPUT);
  pinMode(ledR,OUTPUT);
  Serial.begin(115200);
  Serial.println("connecting");
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);


}

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println("sunkunho");

  WiFi.begin("sunkunho", "@sun0324");

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}


void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...\n");
    // Attempt to connect

    String clientid = "arduinoREV2client";
    clientid += String(random(0xffff),HEX);

    if (client.connect(clientid.c_str())) {
      Serial.println("connected");  
      client.subscribe("ledcontrol");

    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  int zodo2 = led_set();
  client.publish("sensor / light",char(zodo2));

}

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)