Receive an Event

Next, we will create a program that will receive an event from obnizOS when we go online and light up the LED when we are online.

event

By using obniz.onEvent(), you can make it call a function when it is triggered to connect to the Internet or to the cloud.

If you have an ESP32-DevKitC and an LED, connect the anode of the LED (the longer leg) to pin 12 and the cathode of the LED (the shorter leg) to GND.

#include <obniz.h>
#define LED_IO 12
bool onlineFlg = false;

void onEvent(os_event_t event, uint8_t* data, uint16_t length) {
  switch (event) {
  case PLUGIN_EVENT_NETWORK_CLOUD_CONNECTED:
    Serial.println("cloud Connected");
    onlineFlg = true;
    break;
  case PLUGIN_EVENT_NETWORK_CLOUD_DISCONNECTED:
    Serial.println("cloud Disconnected");
    onlineFlg = false;
    break;
  }
}

void setup() {
  Serial.begin(115200);
  Serial.println("online led start!");
  obniz.onEvent(onEvent);
  obniz.start();
  obniz.pinReserve(LED_IO);
  pinMode(LED_IO, OUTPUT);
}
void loop() {
  digitalWrite(LED_IO, onlineFlg);
  delay(500);
}

Let's write this code to the ESP32 board using the ArduinoIDE in environment.

Make sure you are connected to the network in advance.

After a while, you should see "cloud Connected" on the serial monitor and the LED should light up.

This time, we are only using the event when we are able to connect to the obniz cloud, but there are several other events as well. Please refer to the documentation for details.

関連の質問