Tutorial Esp32
Tutorial Esp32
pinMode(GPIO, OUTPUT);
digitalWrite(GPIO, STATE);
pinMode(GPIO, INPUT);
digitalRead(GPIO);
All ESP32 GPIOs can be used as inputs, except GPIOs 6 to
11 (connected to the integrated SPI flash).
CIRCUIT CONNECTION.
SOURCE CODE.
// set pin numbers
const int buttonPin = 4; // the number of the pushbutton pin
const int ledPin = 5; // the number of the LED pin
void setup() {
Serial.begin(115200);
// initialize the pushbutton pin as an input
pinMode(buttonPin, INPUT);
// initialize the LED pin as an output
pinMode(ledPin, OUTPUT);
}
void loop() {
// read the state of the pushbutton value
buttonState = digitalRead(buttonPin);
Serial.println(buttonState);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH
if (buttonState == HIGH) {
// turn LED on
digitalWrite(ledPin, HIGH);
} else {
// turn LED off
digitalWrite(ledPin, LOW);
}
}
ledcAttachPin(GPIO, channel)
This function accepts two arguments. The first is the GPIO
that will output the signal, and the second is the channel
that will generate the signal.
ledcWrite(channel, dutycycle)
CIRCUIT CONNECTION.
SOURCE CODE.
#define POTENTIOMETER_PIN 36 // ESP32 pin GPIO36 (ADC0) connected to
Potentiometer pin
#define LED_PIN 21 // ESP32 pin GPIO21 connected to LED's pin
BLUETOOTH
#if !defined(CONFIG_BT_ENABLED) || !
defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make
menuconfig` to and enable it
#endif
Then, create an instance
of BluetoothSerial called SerialBT:
BluetoothSerial SerialBT;
setup()
loop()
if (Serial.available()) {
SerialBT.write(Serial.read());
}
if (SerialBT.available()) {
Serial.write(SerialBT.read());
}
It will be easier to understand exactly how this sketch
works in the demonstration.
CIRCUIT CONNECTION.
SOURCE CODE.
#include <BluetoothSerial.h>
BluetoothSerial SerialBT;
const int ledPin = 2; // Define the GPIO pin connected to the LED
void setup() {
SerialBT.begin("ESP32_LED_Control"); // Name for the Bluetooth module
pinMode(ledPin, OUTPUT);
}
void loop() {
if (SerialBT.available()) {
char command = SerialBT.read();
if (command == '1') {
digitalWrite(ledPin, HIGH); // Turn the LED on
} else if (command == '0') {
digitalWrite(ledPin, LOW); // Turn the LED off
}
}
}
ESP32: Send Messages to
WhatsApp
CallMeBot WhatsApp API
To send messages to your WhatsApp account with the
ESP32, we’ll use a free API service called CallMeBot service.
You can learn more about CallMeBot at the following link:
https://www.callmebot.com/
CallMeBot API
To send a message using the CallMeBot API you need to
make a POST request to the following URL (but using your
information):
https://api.callmebot.com/whatsapp.php?
phone=[phone_number]&text=[message]&apikey=[your_apikey]
[phone_number]: phone number associated with
your WhatsApp account in international format;
[message]: the message to be sent, should be URL
encoded.
[your_apikey]: the API key you received during the
activation process in the previous section.
For the official documentation, you can check the following
link: https://www.callmebot.com/blog/free-api-whatsapp-
messages/
SOURCE CODE.
This code are using for notify the detection of digital sensor
on ESP32. The whatsapp massage will appear “Motion
Detection”.
#include <WiFi.h>
#include <HTTPClient.h>
#include <UrlEncode.h> // Install library UrlEncode by Masayuki
const char* ssid = "HUAWEI nova 11 Pro"; // connect your wifi hostpot mobile
phone
const char* password = "faris1992"; // password wifi
// Free resources
http.end();
}
void setup() {
Serial.begin(115200);
pinMode(sensor_pin, INPUT);
pinMode(led_pin, OUTPUT);
digitalWrite (led_pin, LOW);
void loop() {
int state = digitalRead(sensor_pin);
if (state == HIGH) { // if motion detected
digitalWrite(led_pin, HIGH); // turn LED ON
sendMessage("Motion Detected!"); //send message
delay(5000);
}
else {
digitalWrite(led_pin, LOW); // turn LED OFF if we have no motion
}
Application:
Now you will get the token id, copy this ID and paste in Notepad.
Now search IDBot in search and open it and click on start.
The bot will return the ID after you click on start as shown below.
Let’s Interface the LED to
ESP32
https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot
Extract the library and add it to the libraries folder path of Arduino IDE.
For information about how to add a custom library to the Arduino IDE and use examples
from it, refer Adding Library To Arduino IDE in the Basics section.
Now install another library which is Arduinojson library for the above example. We need to
install the Arduinojson library using the Arduino Library Manager.
Before uploading the code make sure you have added your SSID, Password, Token
ID, and Chat ID as follows.
const char* ssid = "ADD_YOUR_SSID";
const char* password = "ADD_YOUR_PASS";
#define BOTtoken " XXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
#define CHAT_ID " XXXXXXXXXX"
CIRCUIT CONNECTION
SOURCE CODE
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);
if (text == "/start") {
String welcome = "Welcome, " + from_name + ".\n";
welcome += "Use the following commands to control the LED.\n\n";
welcome += "/led_on to turn ON LED\n";
welcome += "/led_off to turn OFF LED\n";
welcome += "/state to request current LED state \n";
bot.sendMessage(chat_id, welcome, "");
}
if (text == "/led_on") {
bot.sendMessage(chat_id, "The LED is turned ON", "");
ledState = HIGH;
digitalWrite(ledPin, ledState);
}
if (text == "/led_off") {
bot.sendMessage(chat_id, "The LED is turned OFF", "");
ledState = LOW;
digitalWrite(ledPin, ledState);
}
if (text == "/state") {
if (digitalRead(ledPin)){
bot.sendMessage(chat_id, "LED is ON", "");
}
else{
bot.sendMessage(chat_id, "LED is OFF", "");
}
}
}
}
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);
void loop() {
if (millis() > lastTimeBotRan + botRequestDelay) {
int NewMessages = bot.getUpdates(bot.last_message_received + 1);
while(NewMessages) {
Serial.println("Response Received!");
NewMessagesHandle(NewMessages);
NewMessages = bot.getUpdates(bot.last_message_received + 1);
}
lastTimeBotRan = millis();
}
}
NODE RED
Running on Windows
Install Node.j
Download the latest LTS version of Node.js from the official Node.js home page.
It will offer you the best version for your system.
Run the downloaded MSI file. Installing Node.js requires local administrator
rights; if you are not a local administrator, you will be prompted for an
administrator password on install. Accept the defaults when installing. After
installation completes, close any open command prompts and re-open to
ensure new environment variables are picked up.
This page gives specific instructions on setting up Node-RED in a Microsoft
Windows environment. The instructions are specific to Windows 10. They may
also work for Windows 7 and Windows Server from 2008R2, but it is advisable
not to use them due to lack of current support.
Note : Some of the following instructions mention the "command prompt". Where this is used, it
refers to either the Windows cmd or PowerShell terminal shells. It is recommended to use
PowerShell on all newer versions of Windows as this gives you access to commands and folder
names that are closer to those of Linux/Mac.
Quick Start
1. Install Node.js
Download the latest LTS version of Node.js from the official Node.js home page.
It will offer you the best version for your system.
Run the downloaded MSI file. Installing Node.js requires local administrator
rights; if you are not a local administrator, you will be prompted for an
administrator password on install. Accept the defaults when installing. After
installation completes, close any open command prompts and re-open to
ensure new environment variables are picked up.
Once installed, open a command prompt and run the following command to
ensure Node.js and npm are installed correctly.
v18.15.0
9.5.0
2. Install Node-RED
3. Run Node-RED
Running on Windows
Once installed, the simple way to run Node-RED is to use the node-red command in
a command prompt: If you have installed Node-RED as a global npm package,
you can use the node-red command:
C:>node-red
THEORY:
Node-RED is a programming tool for wiring together hardware devices, APIs and
online services in new and interesting ways.
HTTP being used on request-response is not the best option for transferring
data fast and efficiently. On the other hand, we have MQTT which is lightweight,
fast and best for sending data over different IoT devices.
Before starting Node-RED flow creation process, let us know the name of the
components and its uses
as Figure 1.
The components of
Node-RED are:
● Node library
● Visual Editor
● Current Flow
● Help/Info
● Deploy
● Debug
● node-red
Name: My Home
Icon: dashboard
Note:
For Icon symbol you should use a name accordingly to the icon’s names
in this link: https://klarsys.github.io/angular-material-icons
TASK PART A:
Modify the dashboard layout to become like illustrated in Figure below:
PART B: Create Node-RED flow
2. Arrange and connect all nodes to become like illustrated in Fig.5 below:
3. Change properties of “mqtt in”, “mqtt out”, “gauge” and “switch” as shown
in Fig.6 (a) - (d) below:
MQTT IN Properties:
Server: 178.128.127.202:1883
Topic: espXX/DHT22
Figure 6 (a): MQTT in node
Note: for topic’s name, change “XX” to your board number such as 01,02,..
and so on
GAUGE Properties:
Group: [Garden]Humidity
Value format: {{msg.payload.humidity}}
Figure 6 (c): GAUGE node
SWITCH Properties:
Group:[My Home] Room 1
On Payload:{ "value" : "on"}
Off Payload: {"value" : "off"}
Figure 6 (d): SWITCH node
4. Your Node-RED application is ready. Click the Deploy button on the top
right corner.
5. Click on the “TAB Button” and observe the dashboard, then write down
your observation in Practical Work Assessment Form.
1. Open MQTT Box and create a new MQTT Client with following setting:
● MQTT Client Name: Node Red Localhost (you can change to any
name)
● Protocol: mqtt/tcp
● Host: 178.128.127.202:1883
Topic: espXX/DHT22
payload: {"humidity":69.7}
TASK PART C:
a. Open the MQTT Box and Node-RED side by side as shown in Figure below
and click at a switch then observe data received at MQTT Box. Then write
down your observation in Practical Work Assessment Form.
b. Open the MQTT Box and Node-RED side by side as shown in Figure below
and click at a “Publish” button at MQTT Box then observe changing at
Gauge Meter at Node-RED. Then write down your observation in Practical
Work Assessment Form.
PART D: MQTT - Node-RED Application using ESP32
2. Once the circuit ready, open Arduino IDE software and rewrite the code
shown in Appendix 1. You may download this code from
https://github.com/kingdiaw/LAB_IBC/blob/main/PW5_partD/PW5_partD.i
no. Change:
ssid
password
broker
unique_id
topic_subscribe
topic_publish
3. Upload the sketch. Before clicking the upload button, go to Tools →
Board, and select the board you’re using. Make sure that Board Node
MCU-32S and select ESP32’s COM port.
4. Press the upload button and wait for the “Done uploading.” message.
TASK:
2. At node-RED, add another (2) TWO switch node that will publish data with
following JSON format:
Table 1
#include <WiFi.h>
#include "DHTesp.h" //DHTesp by beegee_tokyo Version 1.17.0
#include <ArduinoJson.h> //ArduinoJson by Benoit Blanchon Version 6.13.0
#include <MQTT.h> //MQTT by Joel Gaehwiler Version 2.4.7
//MQTT setting
const char* broker ="xxx.xxx.xxx.xxx"; //Server PTSS
const char* unique_id = "espXX";
String topic_subscribe = "espXX/room/control";
String topic_publish = "espXX/DHT22";
MQTTClient mqtt(1024);
//DHT Pin
const byte dhtPin = 25;
DHTesp dht;
// LED Pin
const byte ledPin = 2;
const byte led1 = 22;
//Global Variable
unsigned long ledTick=0;
unsigned long sysTick=0;
float temperature=0.0,humidity=0.0;
const unsigned int TIME_INTERVAL = 15000; //15 Sec
WiFi.begin(ssid, password);
Serial.println(value);
void loop() {
//MQTT Running
mqtt.loop();
if(!mqtt.connected()){
setup_mqtt();
}
StaticJsonDocument<200>data;
data["temperature"]=temperature;
data["humidity"]=humidity;
serializeJson(data,Serial);
Serial.println();
serializeJsonPretty(data,Serial);
Serial.println();
String payload;
serializeJson(data,payload);
mqtt.publish(topic_publish,payload);
}