DAY-01

On the Wednesday of thirteenth week, Mr. Neil sir conducted our thirteenth global session. He took the random generator in first 90 minutes. He gave us overall explaination about week-13 which includes Networking and Communications.
In this assignment, I have made documentation on-
Group Assignment
1. Send a message between two projects.
Individual Assignment
1. Design, build, and connect wired or wireless node(s) with network or bus addresses and local input &/or output device(s).

Basics of Networking and Communication:-
Networking and communication in electrical engineering and electronics form the backbone of modern information exchange. These systems interconnect devices, such as computers, printers, and sensors, enabling them to share resources and data efficiently. Networks can be categorized into local area networks (LANs), which connect devices within a confined area like a building, and wide area networks (WANs), which cover larger geographical areas. Mobile networks facilitate connectivity for devices on the move.
Communication within networks occurs through various media, including cables (like Ethernet) and wireless technologies (such as Wi-Fi and cellular networks). Key hardware components, such as routers, switches, and access points, manage data traffic and ensure devices can communicate smoothly.
Central to networking are communication protocols, which are standardized sets of rules that dictate how data is transmitted and received. Protocols like TCP/IP (Transmission Control Protocol/Internet Protocol) ensure reliable and organized data exchange across the Internet and other networks. These protocols cover aspects like data formatting, error handling, and synchronization, allowing different devices and systems to communicate seamlessly.
Overall, networking and communication systems are essential for enabling the interconnected world we live in, supporting everything from personal computing to large-scale industrial operations and global Internet connectivity.
There are two types of communication methods - Serial and Parallel


DAY-02

Group Assignment
Click here to read more about group assignment.
Individual Assignment
In the individual assignment, I documented on Design, build, and connect wired or wireless node(s) with network or bus addresses and local input &/or output device(s). So, here I learned two way communication between two XIAO-ESP32-C3 microcontroller using serial communication.
Here, I refer the YouTube Video for two communication between the microcontrollers. There are two nodes, one XIAO-ESP32-C3 microcontroller is Transmitter to transmit the signals and another is Receiver to receive the signal. Following are the steps -


Transmitter Node -
Firstly, I uploaded the code of Transmitter node in the one XIAO-ESP32-C3 using Arduino IDE.
Code -
#include < esp_now.h>
#include < WiFi.h>
const int pushDown = 10;
int oldSwitchState = 0;
int lightsOn = 0;

// REPLACE WITH YOUR RECEIVER MAC Address
uint8_t broadcastAddress[] = {0x64, 0xE8, 0x33, 0x80, 0x95, 0x78};
/*struct __attribute__((packed)) dataPacket {
int state ;
};*/
int state ;
esp_now_peer_info_t peerInfo;

// callback when data is sent - I CAN CHANGE THIS FUNCTION BELOW
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
Serial.print("\r\nLast Packet Send Status:\t");

Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}

void setup() {
pinMode(pushDown,INPUT);
// Init Serial Monitor
Serial.begin(115200);

// Set device as a Wi-Fi Station
WiFi.mode(WIFI_STA);

// Init ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
//pinMode(pushDown, INPUT);
}

// Once ESPNow is successfully Init, we will register for Send CB to
// get the status of Trasnmitted packet
esp_now_register_send_cb(OnDataSent);

// Register peer
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;

// Add peer
if (esp_now_add_peer(&peerInfo) != ESP_OK){
Serial.println("Failed to add peer");
return;
}
}

void loop() {

// dataPacket packet;

//packet.state = digitalRead(pushDown);
//Serial.println(lightsOn);
state = digitalRead(pushDown); // read the pushButton State
if (state != oldSwitchState) // catch change
{
oldSwitchState = state;
if (state == HIGH)
{
// toggle
lightsOn = !lightsOn;
}
}
Serial.println(lightsOn);

esp_now_send(broadcastAddress, (uint8_t *) &lightsOn, sizeof(lightsOn));

delay(30);
}


Code Explaination with Connections -
In this setup, a push button is connected to a Xiao ESP32-C3 microcontroller for two-way communication using ESP-NOW. The push button has one pin connected to the D10 pin of the Xiao ESP32-C3 microcontroller, and this connection is grounded through a pull-up resistor to ensure the pin reads a stable state. The other pin of the push button is connected to the 3V3 pin to provide the necessary voltage. The code initializes the serial monitor for debugging and sets the device as a Wi-Fi station. It initializes ESP-NOW and registers a callback function `OnDataSent` to check the status of the data sent. It also registers the receiver's MAC address and adds the peer information required for ESP-NOW communication.
In the main loop, the code reads the state of the push button connected to D10. If the state of the push button changes, it toggles the value of the `lightsOn` variable, which indicates whether the LED should be on or off. This state is then sent to the receiver microcontroller using ESP-NOW. The `esp_now_send` function sends the current state of the `lightsOn` variable to the specified MAC address of the receiver. The loop includes a small delay to debounce the button press and ensure reliable state detection. This setup allows the push button to control an LED or other components connected to the receiver microcontroller, enabling a simple form of remote control through Wi-Fi communication.


Receiver Node -
Now, I uploaded the code of Receiver node in the another XIAO-ESP32-C3 using Arduino IDE.
Code -
#include < esp_now.h>
#include < WiFi.h>
const int lightME = 10;

int lightsOn;

// Callback function that will be executed when data is received
void OnDataRecv(const uint8_t *mac_addr, const uint8_t *incomingData, int len) {
memcpy(&lightsOn, incomingData, sizeof(lightsOn));
Serial.print("button: ");
Serial.println(lightsOn);
digitalWrite(lightME, lightsOn);
}

void setup() {
// Initialize Serial Monitor
Serial.begin(115200);
pinMode(lightME, OUTPUT);

// Set device as a Wi-Fi Station
WiFi.mode(WIFI_STA);

// Init ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}

// Register for receive callback function
esp_now_register_recv_cb(OnDataRecv);
}

void loop() {
// Nothing to do here
}


Code Explaination with Connections -
In this setup, an LED is connected to the Xiao ESP32-C3 microcontroller to receive data via ESP-NOW and control the LED's state based on the received data. The cathode (negative leg) of the LED is connected to the ground (GND) pin, while the anode (positive leg) is connected to the D10 pin through a resistor, which limits the current to protect the LED. The code begins by including the necessary `esp_now.h` and `WiFi.h` libraries for ESP-NOW and Wi-Fi communication. The `lightME` constant is defined to specify the pin connected to the LED.
In the `setup` function, the serial monitor is initialized for debugging purposes, and the D10 pin is configured as an output to control the LED. The ESP32 is set to Wi-Fi station mode using `WiFi.mode(WIFI_STA)`. The ESP-NOW protocol is initialized, and if it fails, an error message is printed to the serial monitor. Upon successful initialization, a callback function `OnDataRecv` is registered to handle incoming data. This callback function copies the received data into the `lightsOn` variable, prints the button state to the serial monitor, and sets the LED's state accordingly using `digitalWrite`. The `loop` function remains empty as all the action happens in the callback function, triggered by incoming data. This setup allows the Xiao ESP32-C3 to receive data from another ESP-NOW device and control the LED based on the received information.


Finally, here I got the output that one Xiao ESP32-C3 microcontroller with a push button sends the button state via ESP-NOW to another Xiao ESP32-C3 microcontroller, which then controls an LED based on the received state. When the button is pressed, the state is sent wirelessly, and the receiving microcontroller toggles the LED on or off accordingly, providing remote control of the LED through wireless communication.

In this setup, the ESP-NOW protocol is used to facilitate wireless communication between two Xiao ESP32-C3 microcontrollers. ESP-NOW is a low-power, connectionless Wi-Fi protocol developed by Espressif that enables devices to communicate directly with each other without needing a traditional Wi-Fi network. It supports low-latency, peer-to-peer communication, making it ideal for applications requiring fast and efficient data exchange. The protocol allows devices to send short, encrypted packets to multiple peers simultaneously. In this specific setup, one microcontroller is configured with a push button and sends the button's state via ESP-NOW to the other microcontroller. The receiving microcontroller then controls an LED based on the received state, toggling it on or off accordingly. This direct communication is achieved by setting the devices to Wi-Fi Station mode, allowing them to exchange data quickly and efficiently without the need for an access point or router.

Now, I have used ESP32 to turn On/Off of in-built LED from Webpage by generating the IP address of it.


Firstly, open the Arduinno IDE for the programming. Go to sketch > include library > manage libraries.


Now, add the wifimanager library by tzapu.


Select the version as per your convinience.


Now, go to file > Examples > Wifimanager > Basic to add default code file.


Open default code file.



Comment down the unnecessary program.


Now, Select the board from tools tab.


Now, again go to examples > wifi > simplewifiserver.


Open default code file.


Enter the Hotspot name and password which is conneccted with the laptop.



Make changes in the code as per the required output.


Now, go to the serial monitor to check the output.


Here, I got the generated IP addreess of my webpage.


Just by clicking on "here", I opeerated the LED On/Off.


Here is the final output. Here, firstly I used ESP32 micrcontroller to control the in-built LED from webpage through generated IP address. Now, I used XIAO-ESP32-C3 microcontroller to read the input values of MQ135 Gas sensor through webpage. Following are the steps-


Firstly, I uploaded the code in the XIAO-ESP32-C3 board that I already made in the assignment of Input Devices. Here, I inserted ssid and password of my mobile wifi which is already connected with the laptop.




After uploading the code in the microcontroller using Arduino IDE, here I got the IP address of the webpage.


Then, I inserted generated IP address in the search bar of Chrome to open the webpage.


Here, I got the output that shows the realtime values of input sensed by MQ135 Gas sensor.

Code:-
#include < WiFi.h>
#include < WebServer.h>

// Include MQ135 library if needed

/*Put your SSID & Password*/
const char* ssid = "Nothing phone 1"; // Enter SSID here
const char* password = "129129129"; // Enter Password here

WebServer server(80);

// MQ135 Sensor
const int sensorPin = A0; // Analog input pin connected to MQ-135 sensor

void setup() {
Serial.begin(115200);
delay(100);

// Initialize Wi-Fi
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected!");
Serial.print("Got IP: ");
Serial.println(WiFi.localIP());

server.on("/", handle_OnConnect);
server.onNotFound(handle_NotFound);

server.begin();
Serial.println("HTTP server started");
}

void loop() {
server.handleClient();
}

void handle_OnConnect() {
float airQuality = analogRead(sensorPin); // Read analog value from MQ-135 sensor
server.send(200, "text/html", SendHTML(airQuality));
}

void handle_NotFound() {
server.send(404, "text/plain", "Not found");
}

String SendHTML(float airQuality) {
String ptr = "< !DOCTYPE html>\n< html>\n";
ptr += "< head>\n";
ptr += "< meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">\n";
ptr += "< title>XIAO-ESP32-C3 Webserver< /title>\n";
ptr += "< style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}\n";
ptr += "body{margin-top: 50px;} h1 {color: #444444;margin: 50px auto 30px;}\n";
ptr += "p {font-size: 24px;color: #444444;margin-bottom: 10px;}\n";
ptr += "< /style>\n";
ptr += "< /head>\n";
ptr += "< body>\n";
ptr += "< div id=\"webpage\">\n";
ptr += "< h1>XIAO-ESP32-C3 Webserver< /h1>\n";

ptr += "< p>Air Quality: ";
ptr += airQuality;
ptr += "< /p>\n";

ptr += "< /div>\n";
ptr += "< /body>\n";
ptr += "< /html>\n";

return ptr;
}


Code Explaination:-

This code sets up a simple web server on a XIAO-ESP32-C3 microcontroller to display air quality readings from an MQ-135 gas sensor. It includes the necessary libraries for Wi-Fi and web server functionalities. I have defined the Wi-Fi credentials and created an instance of the WebServer class to handle requests. Specifically, I inserted the SSID and password of the Wi-Fi network to which the XIAO-ESP32-C3 will connect in the code. In the setup() function, I initialize the serial communication for debugging and connect the XIAO-ESP32-C3 to the specified Wi-Fi network. Once connected, I register two routes: the root URL ("/"), which triggers the handle_OnConnect function, and a handler for 404 errors (handle_NotFound). The loop() function continuously listens for incoming client requests using server.handleClient(). The handle_OnConnect() function reads the air quality value from the MQ-135 sensor and sends an HTML response containing this value. If a client requests a URL that does not exist, the handle_NotFound() function sends a 404 error message. The SendHTML(float airQuality) function generates an HTML string that displays the air quality reading, which is then sent to the client.
The protocol used in this code is HTTP (Hypertext Transfer Protocol). HTTP is a protocol used for transmitting hypertext requests and information on the internet. In this setup, the XIAO-ESP32-C3 microcontroller acts as a web server, listening for incoming HTTP requests on port 80. When a client, such as a web browser, sends an HTTP request to the microcontroller, the web server processes the request and sends back an HTTP response. This response includes HTML content that displays the air quality reading from the MQ-135 sensor. The use of HTTP allows any device with a web browser to access the air quality data by simply connecting to the XIAO-ESP32-C3's IP address.

Output:-


Siddhi Bodhe Fab Academy😁