NETWORKING AND COMMUNICATIONS
Individual assignments
- Design, build, and connect wired or wireless node(s) with network or bus addresses and local input &/or output device(s)
For this week, work was focused on communications and information exchange between devices. Knowing this, for this week it was decided to work with WiFi networks. Due to my major, I never had the opportunity to program or use microcontrollers that could be capable of using WiFi. Likewise, I decided to use this type of communication because I want to create a page where data collection and visualization can be observed. In the same way, I would love to integrate a system where I could control my robot remotely. Therefore, I consider that working with WiFi is my ideal option.
What is networking?
That is, networks. It is a connection process given through wiring systems or wireless technologies. The goal is the transfer of information from a point or node in the network. There are no intermediaries, because it is a direct path between connection points. A very simple example of its application is the use of a cellphone connected to WiFi to access the internet.
How Networking and Communications work
The connection between devices has different applications or functions, all depending on what is intended to be done. Among them, the following can be found:
- Location: it is known where a device is within the network.
- Parallelism: allows many devices to work at the same time.
- Modularity: allows separating data. For example, one sensor measures, another processes, and another sends data.
- Interference: allows avoiding signals from mixing or colliding.
For these to work, they need a device that generates the data, then this is converted into signals (electrical, radio, light), they travel through a medium, and another device receives and decodes the information. This is a general idea of how network communications work.
Types of communication
There are several types of communication (also that can be chosen for this week).
Wired
It refers to a type of communication with cables. The most typical is the serial type.
- Asynchronous (without clock): UART/USART type. There are no clock signals, instead they use an agreed speed. Usually, you can see this type of communication in Arduino when you set the speed of data collection in the Serial Monitor.
- Synchronous (with clock): There are several types. I2C type uses 2 cables (SDA referring to data and SCL with respect to the clock), this type of communication is a bit more complex and needs deeper study of the topic; On the other hand, there is SPI, which is much faster than I2C, it uses MOSI (data out), MISO (data in), SCK (clock), and CS (selection).
Wireless
That is, communications without cables. They are usually found in technologies such as: Wi-Fi (internet), Bluetooth, LoRa, etc.
This type of communication uses physical media to share information. It can be through wiring, using voltage or optical fiber. But it can also be wireless, such as radio frequency (in the case of Wi-Fi), light, sound.
What did I do in my week 11?
As I had already explained, during this week I worked with Wi-Fi HTTP. The way it works is by connecting the microcontroller being used to Wi-Fi and converting it into an HTTP web server. I relied on this page, which has very valuable information about networking.
First, I designed a board in Altium using the XIAO ESP32C6 microcontroller. In this way, I relied on what was seen in week 6 and week 8. Afterwards, I did the following process.
1.Connection of the board to the computer
2. Open ARDUINO IDE
3.Modify, change, or select the type of board that is being used. In my case, a XIAO ESP32C6.
4. Test that the code can be uploaded to the board to confirm that everything is correctly connected.
5. Perform programming code
#include <WiFi.h>
const char* ssid = "Piso 03";
const char* password = "123456789";
WiFiServer server(80);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("Conectando al WiFi...");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConectado!");
Serial.print("IP: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop() {
WiFiClient client = server.available();
if (client) {
Serial.println("Nuevo cliente");
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();
//Creación de página
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
client.println("<!DOCTYPE html>");
client.println("<html>");
client.println("<h1>Hola desde mi XIAO ESP32C6</h1>");
client.println("</html>");
client.println();
client.stop();
}
}
6. Once the program is uploaded to the microcontroller and it is tested that it works correctly, the IP given by the Serial Monitor was copied and pasted into a web browser. In this way, you can observe the created page.
7. Afterwards, you will be able to observe that there is a client or that this page has been visited.
8. Finally, I modified some settings so that the page had a better presentation.
#include <WiFi.h> //Library that allows connecting my board to WiFi
//WiFi credentials are set here:
const char* ssid = "Piso 03"; //network name
const char* password = "123456789"; //network password
WiFiServer server(80); //Creates a web server on the standard port (HTTP), hence 80
//Sensor pin definitions
const int trigPin = D2; //sends pulse
const int echoPin = D1; //receives the bounce
bool sensorActive = false; //Allows knowing if the sensor is active or not
void setup() {
Serial.begin(115200); //Allows viewing messages in the serial monitor
//Configures the pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
//WiFi connection - starts connection
WiFi.begin(ssid, password);
//Waits until connected and prints dots while waiting
Serial.println("Connecting...");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
//Prints or shows the IP in the Serial Monitor to access from browser
Serial.println("\nConnected!");
Serial.println(WiFi.localIP());
//Starts web server
server.begin();
}
//Function that allows measuring distance with the sensor
float measureDistance() {
//Generates a pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
//Measures the time it takes for the sound to return
long duration = pulseIn(echoPin, HIGH);
//Calculates the distance
float distance = duration * 0.034 / 2;
//Returns the distance in cm
return distance;
}
void loop() {
//Detect if someone connects to the browser
WiFiClient client = server.available();
//If there is a connection, read what the browser requested
if (client) {
String request = client.readStringUntil('\r');
//Clears extra data
client.flush();
// If the button is pressed
if (request.indexOf("/toggle") != -1) {
//Change from OFF to ON or vice versa
sensorActive = !sensorActive;
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/plain");
client.println();
client.println(sensorActive ? "ON" : "OFF");
client.stop();
return;
}
// Browser requests sensor data
if (request.indexOf("/data") != -1) {
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/plain");
client.println();
//If active, measure distance or send
if (sensorActive) {
float distance = measureDistance();
client.println(distance);
} else {
client.println("OFF");
}
client.stop();
return;
}
// Web page
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
//Write HTML within the code without errors
client.println(R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
font-family: Arial;
text-align: center;
background: #0f172a;
color: white;
}
h1 {
margin-top: 50px;
}
button {
padding: 15px 30px;
font-size: 18px;
border: none;
border-radius: 10px;
background-color: #38bdf8;
color: black;
cursor: pointer;
}
button:hover {
background-color: #0ea5e9;
}
#distance {
font-size: 40px;
margin-top: 30px;
}
</style>
</head>
<body>
<h1>WELCOME TO SENSOR TESTING</h1>
<button onclick="toggleSensor()">Activate/Deactivate</button>
<div id="distance">Sensor off</div>
<script>
function toggleSensor() {
fetch('/toggle')
.then(r => r.text())
.then(d => {
console.log("Status:", d);
});
}
function update() {
fetch('/data')
.then(r => r.text())
.then(d => {
if(d === "OFF"){
document.getElementById('distance').innerHTML = "Sensor off";
} else {
document.getElementById('distance').innerHTML = d + " cm";
}
});
}
setInterval(update, 1000);
</script>
</body>
</html>
)rawliteral");
client.stop();
}
}
9. This ended up being my final result.
Results
This code allows me to display in real time the data collected by my sensor. In this way, you can visualize the measured distances, as well as have control over turning the sensor on and off.
How does the programming work?
Based on the first code that was made, the logic it follows is:
- Board turns on.
- Connects to Wi-Fi.
- Outputs IP.
- The IP is copied and pasted into the browser.
- Send HTML.
- The page is displayed.
Regarding the libraries, the following are used:
Allows connection to the internet.
#include <WiFi.h>
Defines the network name and password.
const char* ssid = "Piso 03";
const char* password = "123456789";
Allows creating a web server. 80 is used because it is an HTTP port and it is the one used by browsers.
WiFiServer server(80);
Attempts to communicate or connect to Wi-Fi
WiFi.begin(ssid, password);
Waits for connection
while (WiFi.status() != WL_CONNECTED)
Prints the IP
Serial.println(WiFi.localIP());
Allows knowing if there are clients or not.
WiFiClient client = server.available();
Clears leftover data
client.flush();
This code establishes that it is a web page.
client.println("Content-type:text/html");
Finally, this code writes the normal web page.
client.println("<!DOCTYPE html>");
client.println("<html>");
client.println("<h1>Hola desde mi XIAO ESP32C6</h1>");
client.println("</html>");
This allows ending the communication.
client.stop();
Conclusions
It is important to understand connections and how they work so that communication between devices can be established to control systems remotely, view data in real time, exchange information, and automation. During this week, it was achieved that the XIAO ESP32C6 board acted as a server capable of interacting with a user through a web page.
If you want to access to my work from this week, please click here to download!
Finally, for the group assignment for this week, you can find the information here