Igor Mishkovski, PHD Faculty of Computer Science and Engineering

Download as pdf or txt
Download as pdf or txt
You are on page 1of 66
At a glance
Powered by AI
The key takeaways are that the code is publishing sensor temperature and humidity data to MQTT topics, connecting to WiFi, and includes a function to reconnect to the MQTT broker if the connection is lost.

The code publishes the temperature and humidity values to MQTT topics using the client.publish function, specifying the topic names and sensor values. It includes debug print statements to confirm the values were sent.

The code delays briefly, prints connecting messages, calls WiFi.begin to connect with the SSID and password, and waits in a while loop until the connection status is WL_CONNECTED.

Персонални и ад-хок мрежи

ESP32

Igor Mishkovski, PhD


Faculty of Computer Science and Engineering
Intro
 ESP32 is a series of low-cost, low-power system on a
chip microcontrollers with integrated Wi-Fi and dual-
mode Bluetooth.
 The ESP32 series employs a Tensilica Xtensa
LX6 microprocessor in both dual-core and single-
core variations and includes built-in antenna switches,
RF balun, power amplifier, low-noise receive amplifier,
filters, and power-management modules.

2 The 6LoWPAN Format


Features
 CPU: Xtensa dual-core (or single-core) 32-bit LX6
microprocessor, operating at 160 or 240 MHz
 Ultra low power (ULP) co-processor
 Memory: 520 KiB SRAM
 Wireless connectivity:
 Wi-Fi: 802.11 b/g/n
 Bluetooth: v4.2 BR/EDR and BLE
 Security
 Power Management
 5μA deep sleep current
 Wake up from GPIO interrupt, timer, ADC measurements,
capacitive touch sensor interrupt

3 The 6LoWPAN Format


Features

4 The 6LoWPAN Format


Peripherals
 18 Analog-to-Digital Converter (ADC) channels
 3 SPI interfaces
 3 UART interfaces
 2 I2C interfaces
 16 PWM output channels
 2 Digital-to-Analog Converters (DAC)
 2 I2S interfaces
 10 Capacitive sensing GPIOs

5 The 6LoWPAN Format


Peripherals

6 The 6LoWPAN Format


Pins
 Input only pins
 GPIO 34
 GPIO 35
 GPIO 36
 GPIO 39
 SPI flash integrated on the ESP-WROOM-32
 GPIO 6 (SCK/CLK)
 GPIO 7 (SDO/SD0)
 GPIO 8 (SDI/SD1)
 GPIO 9 (SHD/SD2)
 GPIO 10 (SWP/SD3)
 GPIO 11 (CSC/CMD)

7 The 6LoWPAN Format


Pins
 Capacitive touch GPIOs
 10 internal capacitive touch sensors.
 These can sense variations in anything that holds an electrical
charge, like the human skin.
 So they can detect variations induced when touching the
GPIOs with a finger.
 These pins can be easily integrated into capacitive pads, and
replace mechanical buttons.
 T0 (GPIO 4), T1 (GPIO 0), T2 (GPIO 2), T3 (GPIO 15), T4
(GPIO 13), T5 (GPIO 12), T6 (GPIO 14), T7 (GPIO 27), T8
(GPIO 33), T9 (GPIO 32)

8 The 6LoWPAN Format


9 The 6LoWPAN Format
Capacitive touch GPIOs (example)
// set pin numbers
const int touchPin = 4;
const int ledPin = 16;

// change with your threshold value


const int threshold = 20;
// variable for storing the touch pin value
int touchValue;

void setup(){
Serial.begin(115200);
delay(1000); // give me time to bring up serial monitor
// initialize the LED pin as an output:
pinMode (ledPin, OUTPUT);
}

10 The 6LoWPAN Format


Capacitive touch GPIOs (example)
void loop(){
// read the state of the pushbutton value:
touchValue = touchRead(touchPin);
Serial.print(touchValue);
// check if the touchValue is below the threshold
// if it is, set ledPin to HIGH
if(touchValue < threshold){
// turn LED on
digitalWrite(ledPin, HIGH);
Serial.println(" - LED on");
}
else{
// turn LED off
digitalWrite(ledPin, LOW);
Serial.println(" - LED off");
}
delay(500);
}

11 The 6LoWPAN Format


Pins
 Analog to Digital Converter (ADC)
 The ESP32 has 18 x 12 bits ADC input channels
 Compared it to Arduino?
 ADC1_CH0 (GPIO 36), ADC1_CH1 (GPIO 37), ADC1_CH2
(GPIO 38), ADC1_CH3 (GPIO 39), ADC1_CH4 (GPIO 32),
ADC1_CH5 (GPIO 33), ADC1_CH6 (GPIO 34), ADC1_CH7
(GPIO 35), ADC2_CH0 (GPIO 4), ADC2_CH1 (GPIO 0),
ADC2_CH2 (GPIO 2), ADC2_CH3 (GPIO 15), ADC2_CH4
(GPIO 13), ADC2_CH5 (GPIO 12), ADC2_CH6 (GPIO 14),
ADC2_CH7 (GPIO 27), ADC2_CH8 (GPIO 25), ADC2_CH9
(GPIO 26)
 ADC2 pins cannot be used when Wi-Fi is used
 Analog readings ranging from 0 to 4095, in which 0
corresponds to 0V and 4095 to 3.3V.

12 The 6LoWPAN Format


ADC problems

13 The 6LoWPAN Format


ADC Example
 Other useful functions
 analogReadResolution(resolution):
 set the sample bits and resolution. It can be a value between 9 (0 –
511) and 12 bits (0 – 4095). Default is 12-bit resolution.
 analogSetCycles(cycles):
 set the number of cycles per sample. Default is 8. Range: 1 to 255.
 analogSetClockDiv(attenuation):
 set the divider for the ADC clock. Default is 1. Range: 1 to 255.

14 The 6LoWPAN Format


ADC Example

15 The 6LoWPAN Format


ADC Example
// Potentiometer is connected to GPIO 34 (Analog ADC1_CH6)
const int potPin = 34;

// variable for storing the potentiometer value


int potValue = 0;

void setup() {
Serial.begin(115200);
delay(1000);
}

void loop() {
// Reading potentiometer value
potValue = analogRead(potPin);
Serial.println(potValue);
delay(500);
}

16 The 6LoWPAN Format


Pins
 Digital to Analog Converter (DAC)
 There are 2 x 8 bits DAC channels on the ESP32 to convert digital
signals into analog voltage signal outputs
 DAC1 (GPIO25)
 DAC2 (GPIO26)
 RTC GPIO
 The GPIOs routed to the RTC low-power subsystem can be used when
the ESP32 is in deep sleep.
 These RTC GPIOs can be used to wake up the ESP32 from deep sleep
when the Ultra Low Power (ULP) co-processor is running
 RTC_GPIO0 (GPIO36), RTC_GPIO3 (GPIO39), RTC_GPIO4 (GPIO34),
RTC_GPIO5 (GPIO35), RTC_GPIO6 (GPIO25), RTC_GPIO7 (GPIO26),
RTC_GPIO8 (GPIO33), RTC_GPIO9 (GPIO32), RTC_GPIO10 (GPIO4),
RTC_GPIO11 (GPIO0), RTC_GPIO12 (GPIO2), RTC_GPIO13
(GPIO15), RTC_GPIO14 (GPIO13), RTC_GPIO15 (GPIO12),
RTC_GPIO16 (GPIO14), RTC_GPIO17 (GPIO27)

17 The 6LoWPAN Format


Introducing Deep Sleep Mode
 The ESP32 can switch between different power modes:
 Active mode
 Modem Sleep mode
 Light Sleep mode
 Deep Sleep mode
 Hibernation mode

18 The 6LoWPAN Format


Introducing Deep Sleep Mode
 While the ESP32 is in deep sleep mode the RTC memory
also remains powered on, so we can write a program for
the ULP co-processor and store it in the RTC memory to
access peripheral devices, internal timers, and internal
sensors.
 Wake Up Sources:
 You can use the timer, waking up your ESP32 using predefined
periods of time;
 You can use the touch pins;
 You can use two possibilities of external wake up: you can
use either one external wake up, or several different external
wake ups;

19 The 6LoWPAN Format


TimerWakeUp
#define uS_TO_S_FACTOR 1000000 /* Conversion factor for micro seconds to seconds */
#define TIME_TO_SLEEP 5 /* Time ESP32 will go to sleep (in seconds) */

RTC_DATA_ATTR int bootCount = 0;

/*
Method to print the reason by which ESP32
has been awaken from sleep
*/
void print_wakeup_reason(){
esp_sleep_wakeup_cause_t wakeup_reason;

wakeup_reason = esp_sleep_get_wakeup_cause();

switch(wakeup_reason)
{
case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break;
case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL");
break;
case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break;
case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break;
case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break;
default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break;
}
}

20 The 6LoWPAN Format


TimerWakeUp
void setup(){
Serial.begin(115200);
delay(1000); //Take some time to open up the Serial Monitor

//Increment boot number and print it every reboot


++bootCount;
Serial.println("Boot number: " + String(bootCount));

//Print the wakeup reason for ESP32


print_wakeup_reason();

/*
First we configure the wake up source
We set our ESP32 to wake up every 5 seconds
*/
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
Serial.println("Setup ESP32 to sleep for every " + String(TIME_TO_SLEEP)
+
" Seconds");

21 The 6LoWPAN Format


Serial.println("Going to sleep now");
delay(1000);
Serial.flush();
esp_deep_sleep_start();
Serial.println("This will never be printed");
}

void loop(){
//This is not going to be called
}

22 The 6LoWPAN Format


Testing the Timer Wake Up

23 The 6LoWPAN Format


Touch WakeUp
#define Threshold 40 /* Greater the value, more the sensitivity */

RTC_DATA_ATTR int bootCount = 0;


touch_pad_t touchPin;
/*
Method to print the reason by which ESP32
has been awaken from sleep
*/
void print_wakeup_reason(){
esp_sleep_wakeup_cause_t wakeup_reason;

wakeup_reason = esp_sleep_get_wakeup_cause();

switch(wakeup_reason)
{
case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break;
case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL");
break;
case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break;
case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break;
case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break;
default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break;
}
}

24 The 6LoWPAN Format


Touch WakeUp
/*
Method to print the touchpad by which ESP32
has been awaken from sleep
*/
void print_wakeup_touchpad(){
touch_pad_t pin;

touchPin = esp_sleep_get_touchpad_wakeup_status();

switch(touchPin)
{
case 0 : Serial.println("Touch detected on GPIO 4"); break;
case 1 : Serial.println("Touch detected on GPIO 0"); break;
case 2 : Serial.println("Touch detected on GPIO 2"); break;
case 3 : Serial.println("Touch detected on GPIO 15"); break;
case 4 : Serial.println("Touch detected on GPIO 13"); break;
case 5 : Serial.println("Touch detected on GPIO 12"); break;
case 6 : Serial.println("Touch detected on GPIO 14"); break;
case 7 : Serial.println("Touch detected on GPIO 27"); break;
case 8 : Serial.println("Touch detected on GPIO 33"); break;
case 9 : Serial.println("Touch detected on GPIO 32"); break;
default : Serial.println("Wakeup not by touchpad"); break;
}
}

void callback(){
//placeholder callback function
}

25 The 6LoWPAN Format


Touch WakeUp
void setup(){
Serial.begin(115200);
delay(1000); //Take some time to open up the Serial Monitor

//Increment boot number and print it every reboot


++bootCount;
Serial.println("Boot number: " + String(bootCount));

//Print the wakeup reason for ESP32 and touchpad too


print_wakeup_reason();
print_wakeup_touchpad();

//Setup interrupt on Touch Pad 3 (GPIO15)


touchAttachInterrupt(T3, callback, Threshold);

//Configure Touchpad as wakeup source


esp_sleep_enable_touchpad_wakeup();

//Go to sleep now


Serial.println("Going to sleep now");
delay(1000);
esp_deep_sleep_start();
Serial.println("This will never be printed");
}

void loop(){
//This will never be reached
}

26 The 6LoWPAN Format


Attach Interrupts
 If the ESP32 is asleep and you touch T3, the ESP will wake
up – the callback() function won’t be executed if you just
press and release the touch pin;
 If the ESP32 is awake and you touch T3, the callback
function will be executed. So, if you want to execute
the callback() function when you wake up the ESP32, you
need to hold the touch on that pin for a while, until the
function is executed.

27 The 6LoWPAN Format


Testing Touch WakeUp

28 The 6LoWPAN Format


External WakeUP
 You have two possibilities of external wake up: ext0, and
ext1.
 Ext0:
 RTC peripherals will be kept on during deep sleep if this wake
up source is requested.
 esp_sleep_enable_ext0_wakeup(GPIO_NUM_X, level)
 This function accepts as first argument the pin you want to use, in this
format GPIO_NUM_X, in which X represents the GPIO number of
that pin.
 The second argument, level, can be either 1 or 0. This represents the
state of the GPIO that will trigger wake up.

29 The 6LoWPAN Format


External WakeUP
 You have two possibilities of external wake up: ext0, and
ext1.
 Ext1:
 This wake up source allows you to use multiple RTC GPIOs
 two different logic functions:
 Wake up the ESP32 if any of the pins you’ve selected are high;
 Wake up the ESP32 if all the pins you’ve selected are low.
 RTC peripherals and RTC memories can be powered off in this
mode.
 esp_sleep_enable_ext1_wakeup(bitmask, mode)
 A bitmask of the GPIO numbers that will cause the wake up;
 Mode
 ESP_EXT1_WAKEUP_ALL_LOW: wake up when all GPIOs go low;
 ESP_EXT1_WAKEUP_ANY_HIGH: wake up if any of the GPIOs go high.

30 The 6LoWPAN Format


ExternalWakeUp
#define BUTTON_PIN_BITMASK 0x200000000 // 2^33
in hex

RTC_DATA_ATTR int bootCount = 0;

/*
Method to print the reason by which ESP32
has been awaken from sleep
*/
void print_wakeup_reason(){
esp_sleep_wakeup_cause_t wakeup_reason;

wakeup_reason = esp_sleep_get_wakeup_cause();

31 The 6LoWPAN Format


ExternalWakeUp
switch(wakeup_reason)
{
case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup
caused by external signal using RTC_IO"); break;
case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup
caused by external signal using RTC_CNTL"); break;
case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup
caused by timer"); break;
case ESP_SLEEP_WAKEUP_TOUCHPAD :
Serial.println("Wakeup caused by touchpad"); break;
case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup
caused by ULP program"); break;
default : Serial.printf("Wakeup was not caused by deep
sleep: %d\n",wakeup_reason); break;
}
}

32 The 6LoWPAN Format


ExternalWakeUp
void setup(){
Serial.begin(115200);
delay(1000); //Take some time to open up the Serial
Monitor

//Increment boot number and print it every reboot


++bootCount;
Serial.println("Boot number: " + String(bootCount));

//Print the wakeup reason for ESP32


print_wakeup_reason();

33 The 6LoWPAN Format


ExternalWakeUp
esp_sleep_enable_ext0_wakeup(GPIO_NUM_33,1); //1 =
High, 0 = Low
//If you were to use ext1, you would use it like

//esp_sleep_enable_ext1_wakeup(BUTTON_PIN_BITMASK,ES
P_EXT1_WAKEUP_ANY_HIGH);
//Go to sleep now
Serial.println("Going to sleep now");
delay(1000);
esp_deep_sleep_start();
Serial.println("This will never be printed");
}

void loop(){
//This is not going to be called
}

34 The 6LoWPAN Format


ExternalWakeUp (ext0)

35 The 6LoWPAN Format


External Wake Up – Multiple GPIOs
 Mask for several GPIOs
 If you want to use GPIO 2 and GPIO 15 as a wake up source,
you should do the following:
 Calculate 2^2 + 2^15.You should get 32772
 Convert that number to hex.You should get: 8004
 Replace that number in the BUTTON_PIN_BITMASK as follows:
 #define BUTTON_PIN_BITMASK 0x8004
 Identifying the GPIO used as a wake up source
 which pin caused the wake up
 esp_sleep_get_ext1_wakeup_status()
 returns a number of base 2
 GPIO = log(GPIO_NUMBER)/log(2)

36 The 6LoWPAN Format


External Wake Up – Multiple GPIOs

37 The 6LoWPAN Format


PWM
 The ESP32 LED PWM controller has 16 independent
channels that can be configured to generate PWM signals
with different properties.
 All pins that can act as outputs can be used as PWM pins
(GPIOs 34 to 39 can’t generate PWM)
 To set a PWM signal, you need to define these
parameters in the code:
 Signal’s frequency;
 Duty cycle;
 PWM channel;
 GPIO where you want to output the signal.

38 The 6LoWPAN Format


PWM Example
// the number of the LED pin
const int ledPin = 16; // 16 corresponds to GPIO16

// setting PWM properties


const int freq = 5000; //5 KHz
const int ledChannel = 0;
const int resolution = 8;
void setup(){
// configure LED PWM functionalitites
ledcSetup(ledChannel, freq, resolution);

// attach the channel to the GPIO to be controlled


ledcAttachPin(ledPin, ledChannel);
}

39 The 6LoWPAN Format


PWM Example
void loop(){
// increase the LED brightness
for(int dutyCycle = 0; dutyCycle <= 255; dutyCycle++){
// changing the LED brightness with PWM
ledcWrite(ledChannel, dutyCycle);
delay(15);
}

// decrease the LED brightness


for(int dutyCycle = 255; dutyCycle >= 0; dutyCycle--){
// changing the LED brightness with PWM
ledcWrite(ledChannel, dutyCycle);
delay(15);
}
}

40 The 6LoWPAN Format


Getting the Same Signal on Different
GPIOs

41 The 6LoWPAN Format


Getting the Same Signal on Different
GPIOs
// the number of the LED pin
const int ledPin = 16; // 16 corresponds to GPIO16
const int ledPin2 = 17; // 17 corresponds to GPIO17
const int ledPin3 = 5; // 5 corresponds to GPIO5

// setting PWM properties


const int freq = 5000;
const int ledChannel = 0;
const int resolution = 8;

void setup(){
// configure LED PWM functionalitites
ledcSetup(ledChannel, freq, resolution);

// attach the channel to the GPIO to be controlled


ledcAttachPin(ledPin, ledChannel);
ledcAttachPin(ledPin2, ledChannel);
ledcAttachPin(ledPin3, ledChannel);
}

42 The 6LoWPAN Format


Getting the Same Signal on Different
GPIOs
void loop(){
// increase the LED brightness
for(int dutyCycle = 0; dutyCycle <= 255;
dutyCycle++){
// changing the LED brightness with PWM
ledcWrite(ledChannel, dutyCycle);
delay(15);
}

// decrease the LED brightness


for(int dutyCycle = 255; dutyCycle >= 0;
dutyCycle--){
// changing the LED brightness with PWM
ledcWrite(ledChannel, dutyCycle);
delay(15);
}
}
43 The 6LoWPAN Format
I2C
 Connecting an I2C device to an ESP32 is normally as
simple as connecting GND to GND, SDA to SDA, SCL to
SCL and a positive power supply to a peripheral, usually
3.3V (but it depends on the module you’re using).

44 The 6LoWPAN Format


Connecting BME280 sensor using I2C
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

#define I2C_SDA 33
#define I2C_SCL 32

#define SEALEVELPRESSURE_HPA (1013.25)

TwoWire I2CBME = TwoWire(0);


Adafruit_BME280 bme;

unsigned long delayTime;

45 The 6LoWPAN Format


Connecting BME280 sensor using I2C
void setup() {
Serial.begin(115200);
Serial.println(F("BME280 test"));
I2CBME.begin(I2C_SDA, I2C_SCL, 100000);

bool status;

// default settings
// (you can also pass in a Wire library object like &Wire2)
status = bme.begin(0x76, &I2CBME);
if (!status) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}

Serial.println("-- Default Test --");


delayTime = 1000;

Serial.println();
}

46 The 6LoWPAN Format


Connecting BME280 sensor using I2C
void loop() {
printValues();
delay(delayTime);
}

void printValues() {
Serial.print("Temperature = ");
Serial.print(bme.readTemperature());
Serial.println(" *C");

// Convert temperature to Fahrenheit


/*Serial.print("Temperature = ");
Serial.print(1.8 * bme.readTemperature() + 32);
Serial.println(" *F");*/

Serial.print("Pressure = ");
Serial.print(bme.readPressure() / 100.0F);
Serial.println(" hPa");

47 The 6LoWPAN Format


Connecting BME280 sensor using I2C

Serial.print("Approx. Altitude = ");


Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
Serial.println(" m");

Serial.print("Humidity = ");
Serial.print(bme.readHumidity());
Serial.println(" %");

Serial.println();
}

48 The 6LoWPAN Format


SPI

49 The 6LoWPAN Format


Interrupt
 All GPIOs can be configured as interrupts.
 Interrupts are useful for making things happen automatically in
microcontroller programs, and can help solve timing problems.
 With interrupts you don’t need to constantly check the current
value of a pin.
 With interrupts, when a change is detected, an event is triggered (a
function is called).
 attachInterrupt(digitalPinToInterrupt(GPIO), function, mode);
 digitalPinToInterrupt(27)
 Mode:
 LOW: to trigger the interrupt whenever the pin is LOW;
 HIGH: to trigger the interrupt whenever the pin is HIGH;
 CHANGE: to trigger the interrupt whenever the pin changes value – for example
from HIGH to LOW or LOW to HIGH;
 FALLING: for when the pin goes from HIGH to LOW;
 RISING: to trigger when the pin goes from LOW to HIGH.

50 The 6LoWPAN Format


Introducing Timers
 Blocking function
 delay(time in milliseconds)
 Non-blocking function
 millis()
 We will interrupts and timers in the following project:
Detect motion with the ESP32 using a PIR motion sensor
 When motion is detected (an interrupt is triggered), the ESP32
starts a timer and turns an LED on for a predefined number of
seconds.
 When the timer finishes counting down, the LED is
automatically turned off.

51 The 6LoWPAN Format


ESP32 with PIR Motion Sensor

52 The 6LoWPAN Format


ESP32 with PIR Motion Sensor
#define timeSeconds 10

// Set GPIOs for LED and PIR Motion Sensor


const int led = 26;
const int motionSensor = 27;

// Timer: Auxiliary variables


unsigned long now = millis();
unsigned long lastTrigger = 0;
boolean startTimer = false;

// Checks if motion was detected, sets LED


HIGH and starts a timer

53 The 6LoWPAN Format


ESP32 with PIR Motion Sensor
// Checks if motion was detected, sets LED HIGH and
starts a timer
void IRAM_ATTR detectsMovement() {
Serial.println("MOTION DETECTED!!!");
digitalWrite(led, HIGH);
startTimer = true;
lastTrigger = millis();
}

54 The 6LoWPAN Format


ESP32 with PIR Motion Sensor
void setup() {
// Serial port for debugging purposes
Serial.begin(115200);

// PIR Motion Sensor mode INPUT_PULLUP


pinMode(motionSensor, INPUT_PULLUP);
// Set motionSensor pin as interrupt, assign interrupt function and set
RISING mode
attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement,
RISING);

// Set LED to LOW


pinMode(led, OUTPUT);
digitalWrite(led, LOW);
}

55 The 6LoWPAN Format


ESP32 with PIR Motion Sensor
void loop() {
// Current time
now = millis();
// Turn off the LED after the number of seconds defined in the
timeSeconds variable
if(startTimer && (now - lastTrigger > (timeSeconds*1000))) {
Serial.println("Motion stopped...");
digitalWrite(led, LOW);
startTimer = false;
}
}

56 The 6LoWPAN Format


Example: ESP32, DHT + MQTT

57 The 6LoWPAN Format


Code
* Project ESP32, DHT, MQTT and Deepsleep */
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h" // Library for DHT
sensors

#define wifi_ssid "My_APs_ssid" //wifi


ssid
#define wifi_password "my_password" //wifi
password

#define mqtt_server "mqtt_broker_IP" // server


name or IP
#define mqtt_user "username" // username
#define mqtt_password "password" // password

58 The 6LoWPAN Format


Code
#define temperature_topic "topic/temp1" //Topic temperature
#define humidity_topic "topic/humid1" //Topic humidity
#define debug_topic "debug" //Topic for debugging

/* definitions for deepsleep */


#define uS_TO_S_FACTOR 1000000 /* Conversion factor for micro seconds to seconds */
#define TIME_TO_SLEEP 900 /* Time ESP32 will go to sleep for 15 minutes (in seconds)
*/
#define TIME_TO_SLEEP_ERROR 3600 /* Time to sleep in case of error (1 hour) */

bool debug = true; //Display log message if True

#define DHTPIN 14 // DHT Pin


// Uncomment depending on your sensor type:
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT22 // DHT 22 (AM2302)

59 The 6LoWPAN Format


Code
// Create objects
DHT dht(DHTPIN, DHTTYPE);
WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
Serial.begin(115200);
setup_wifi(); //Connect to Wifi network

client.setServer(mqtt_server, 1883); // Configure MQTT connection,


change port if needed.

if (!client.connected()) {
reconnect();
}
dht.begin();

// Read temperature in Celcius


float t = dht.readTemperature();
// Read humidity
float h = dht.readHumidity();
60 The 6LoWPAN Format
Code
// Nothing to send. Warn on MQTT debug_topic and then go to sleep for
longer period.
if ( isnan(t) || isnan(h)) {
Serial.println("[ERROR] Please check the DHT sensor !");
client.publish(debug_topic, "[ERROR] Please check the DHT sensor
!", true); // Publish humidity on mosohomes/humid1
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP *
uS_TO_S_FACTOR); //go to sleep
Serial.println("Setup ESP32 to sleep for every " +
String(TIME_TO_SLEEP) + " Seconds");
Serial.println("Going to sleep now because of ERROR");
esp_deep_sleep_start();
return;
}

61 The 6LoWPAN Format


Code
if ( debug ) {
Serial.print("Temperature : ");
Serial.print(t);
Serial.print(" | Humidity : ");
Serial.println(h);
}
// Publish values to MQTT topics
client.publish(temperature_topic, String(t).c_str(), true); //
Publish temperature on mosohomes/temp1
if ( debug ) {
Serial.println("Temperature sent to MQTT.");
}
delay(100); //some delay is needed for the mqtt server to accept
the message
client.publish(humidity_topic, String(h).c_str(), true); //
Publish humidity on mosohomes/humid1
if ( debug ) {
Serial.println("Humidity sent to MQTT.");
}
62 The 6LoWPAN Format
Code

esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP *
uS_TO_S_FACTOR); //go to sleep
Serial.println("Setup ESP32 to sleep for every
" + String(TIME_TO_SLEEP) + " Seconds");
Serial.println("Going to sleep as normal
now.");
esp_deep_sleep_start();
}

63 The 6LoWPAN Format


Code
//Setup connection to wifi
void setup_wifi() {
delay(20);
Serial.println();
Serial.print("Connecting to ");
Serial.println(wifi_ssid);

WiFi.begin(wifi_ssid, wifi_password);

while (WiFi.status() != WL_CONNECTED) {


delay(100);
Serial.print(".");
}

Serial.println("");
Serial.println("WiFi is OK ");
Serial.print("=> ESP32 new IP address is: ");
Serial.print(WiFi.localIP());
Serial.println("");
}

64 The 6LoWPAN Format


Code
//Reconnect to wifi if connection is lost
void reconnect() {

while (!client.connected()) {
Serial.print("Connecting to MQTT broker ...");
if (client.connect("ESP32Client", mqtt_user, mqtt_password)) {
Serial.println("OK");
} else {
Serial.print("[Error] Not connected: ");
Serial.print(client.state());
Serial.println("Wait 5 seconds before retry.");
delay(5000);
}
}
}

void loop() {
}
65 The 6LoWPAN Format
66 The 6LoWPAN Format

You might also like