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.

Sensor

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:

  1. Location: it is known where a device is within the network.
  2. Parallelism: allows many devices to work at the same time.
  3. Modularity: allows separating data. For example, one sensor measures, another processes, and another sends data.
  4. 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).

Sensor

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.

Sensor

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

Sensor

2. Open ARDUINO IDE

3.Modify, change, or select the type of board that is being used. In my case, a XIAO ESP32C6.

Sensor

4. Test that the code can be uploaded to the board to confirm that everything is correctly connected.

Sensor

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.

Sensor Sensor

7. Afterwards, you will be able to observe that there is a client or that this page has been visited.

Sensor

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.

Sensor

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:

Regarding the libraries, the following are used:

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