티스토리 뷰

이거 무선으로 해도된다.

외장 배터리를 사용했을 때 wifi 자동연결안되서.. 하루 보냄..

#include <WiFiNINA.h>
#include <ArduinoMqttClient.h>

char ssid[] = "와이파이아이디";    // your network SSID (name)
char pass[] = "비번";    // your network password (use for WPA, or use as key for WEP)

int count = 0;
const long interval = 1000;
unsigned long previousMillis = 0;

int ledPin = 13;

WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);

const char broker[] = "test.mosquitto.org";
int port = 1883;
const char topic[] = "arduino/led";

void setup() {
  pinMode(ledPin, OUTPUT);
  
  // attempt to connect to WiFi network
  while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
    delay(1000);
    Serial.println("WiFi try...");
    // 와이파이 연결 중 표시를 위해 LED를 깜박입니다.
    digitalWrite(ledPin, HIGH);
    delay(100);
    digitalWrite(ledPin, LOW);
  }
  
  // 와이파이에 연결되었음을 표시하기 위해 LED를 3번 깜박입니다.
  for (int i = 0; i < 3; i++) {
    digitalWrite(ledPin, HIGH);
    delay(50);
    digitalWrite(ledPin, LOW);
    delay(50);
  }
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  if (!mqttClient.connect(broker, port)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());

    while (1);
  }
}

void loop() {
    if (WiFi.status() == WL_CONNECTED) {
    digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
    delay(1000);              // wait for a second
    digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
    delay(1000);              // wait for a second
  }
  mqttClient.poll();


  unsigned long currentMillis = millis();
  
  if (currentMillis - previousMillis >= interval) {
    // save the last time a message was sent
    previousMillis = currentMillis;

    Serial.print("Sending message to topic: ");
    Serial.println(topic);
    Serial.print("hello ");
    Serial.println(count);

    // send message, the Print interface can be used to set the message contents
    mqttClient.beginMessage(topic);
    mqttClient.print("hello ");
    mqttClient.print(count);
    mqttClient.endMessage();

    Serial.println();

    count++;
  }
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함