Servo Motor Control with ESP32 WebServer

Hello readers, we hope you all are doing great. In this tutorial, we are going to demonstrate how to interface and control a servo motor using an ESP32 board. After that, we will demonstrate how to create a webserver to control the servo motor’s shaft position with the ESP32 board.

Servo Motors are among the most important actuators in robotics, with applications ranging from RC planes to automated door locks.

Where To Buy?
No.ComponentsDistributorLink To Buy
1ESP32AmazonBuy Now

Hardware components required

  • A servo motor
  • ESP32 development board
  • Connecting wires
  • Breadboard

Servo Motor

There are several specific types of electric motor applications in which the motor must rotate only at a specific angle. For such applications, we need a special type of motor with such a special arrangement that causes the motor to rotate at a specific angle for a given electric signal (input). The servo motor comes into effect for this purpose.

A servo motor is a linear or rotary actuator that enables accurate control of linear or angular position, acceleration, and velocity. It is made up of a motor and a sensor for position feedback. It also necessitates a fairly sophisticated controller, which is frequently a dedicated module designed specifically for use with servo motors.

Fig. Servo Motor

The primary reason to use a servo motor is that it offers angular precision, which means that it will only rotate as far as we want it to before stopping and waiting for the next signal to take action. The servo motor, unlike a standard electric motor, begins to turn as soon as we apply input power to it and continues to rotate until we turn off the power. We cannot restrict the rotational progress of an electric motor, but we can control its speed and turn it on and off. Small servo motors are included in numerous beginner Arduino launcher kits since they are simple to use in small electronic projects and applications.

Interfacing Servo Motor with ESP32

 

Fig. Interfacing Servo motor with ESP32

When compared to an Arduino, interfacing a servo motor to the ESP32 is extremely difficult because it does not support analogWrite(). However, it employs a variety of frequencies and timers, allowing all digital pins to be used as PWM pins and to send signals much faster than any Arduino.

Connections:

Servo motor consists of three wires;

Table 1 ESP32 and servo motor interfacing

Controlling servo motor

A servo motor is controlled by sending a PWM or pulse width modulated signal. A servo motor can only turn for a total of 180-degree movement (90 degrees in either direction).

The PWM signal sent to the motor specifies the position of the shaft, and the rotor will turn to the desired position depending on the duration of the pulse sent through the control wire.

Arduino IDE programming

We are using Arduino IDE to compile and upload code into the ESP32 module. To know more about Arduino IDE and how to use it, follow our previous tutorial i.e., on the ESP32 programming series.

  • Installing Required Libraries
  • Download the library from the given link:

https://github.com/RoboticsBrno/ServoESP32

  • Open the Arduino IDE.
  • Go to Sketch >> Include Library >> Add .ZIP library.
  • Select the zip file you have downloaded from the above link.

Fig. Adding Library file

Arduino IDE Code

  • We are using the example code that comes with the library file we have downloaded for the above link.
  • To access the example code, go to Files >> Examples >> Servo ESP32 and select the required example code.
  • In this tutorial, we are using a simple servo example code.

#include <Servo.h>

static const int servoPin = 4;

Servo servo1;

void setup()

{

Serial.begin( 115200 );

servo1.attach( servoPin);

}

void loop() {

for(int posDegrees = 0;

posDegrees <= 180;

posDegrees++)

{

servo1.write( posDegrees );

Serial.println( posDegrees );

delay( 20);

}

for(int posDegrees = 180;

posDegrees >= 0;

posDegrees--)

{

servo1.write( posDegrees);

Serial.println( posDegrees);

delay(20);

}

}

Code Description

    • The first task is adding the required library files or header files.

Fig. header file

  • Define the GPIO pin which you are going to use for controlling the servo motor.

Fig. Defining Variables

  • Create an object Servo, which is called

Setup()

  • Inside the setup() function, the first task is to initialize the serial monitor with a 115200 baud rate for debugging purposes.
  • Attach the GPIO pin you have assigned to the variable servoPin (in the global declaration) to the servo object.

Fig. setup function

Loop()

  • As we mentioned earlier, a servo motor can only rotate between 0 to 180 degrees. So in this code, we are changing the position of the servo motor from 0 degree to 180 degrees and then back to 0 degree from 180 degrees.
  • We have defined a variable postDegree to store the position or angle of the servo motor.
  • We are using the for() loop, which will change the position of servo motor from 0 to 180 degrees.

Fig.

  • Another for() loop is used to change the position back to 0 degrees from 180 degrees.

Testing

  • Select the right development board from Tools >> Boards >> DOIT ESP32 DevKit V1 in Arduino IDE.
  • Compile and upload the code into ESP32 using Arduino IDE.
  • Open the serial monitor with a 115200 baud rate as defined in the Arduino code.
  • Press the EN button from the ESP32 development board.
  • Now you should see the servo motor’s shaft rotating as per the instructions provided.
  • You can observe the variation on shaft’s angle on the serial monitor as well, as shown below:

Fig. Serial monitor output

Fig. ESP32 and servo motor

Creating a web server to control servo motor with ESP32

Let’s create a web server to control the position of the servo motor. We will create a web page containing a slider to control the angle/position of the servo motor’s shaft.

We have also created a tutorial on creating a simple web server with ESP32.

Arduino IDE Code

#include <WiFi.h>

#include <Servo.h>

Servo servo1; // create servo object to control a servo

// twelve servo objects can be created on most boards

// GPIO the servo is attached to

static const int servoPin = 13;

// Replace with your network credentials

const char* ssid = "SSID";

const char* password = "PASSWORD";

// Set web server port number to 80

WiFiServer server(80);

// Variable to store the HTTP request

String header;

String valueString = String(5);

int angle_x = 0;

int angle_y = 0;

// Current time

unsigned long currentTime = millis();

// Previous time

unsigned long previousTime = 0;

// Define timeout time in milliseconds (example: 2000ms = 2s)

const long timeoutTime = 2000;

void setup() {

Serial.begin(115200);

servo1.attach(servoPin); // attaches the servo on the servoPin to the servo object

// Connect to Wi-Fi network with SSID and password

Serial.print("Connecting to ");

Serial.println(ssid);

WiFi.begin(ssid, password);

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

delay(500);

Serial.print(".");

}

// Print local IP address and start web server

Serial.println("");

Serial.println("WiFi connected.");

Serial.println("IP address: ");

Serial.println(WiFi.localIP());

server.begin();

}

 

void loop(){

WiFiClient client = server.available(); // Listen for incoming clients

if (client) { // If a new client connects,

currentTime = millis();

previousTime = currentTime;

Serial.println("New Client."); // print a message out in the serial port

String currentLine = ""; // make a String to hold incoming data from the client

while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected

currentTime = millis();

if (client.available()) { // if there's bytes to read from the client,

char c = client.read(); // read a byte, then

Serial.write(c); // print it out the serial monitor

header += c;

if (c == '\n') { // if the byte is a newline character

// if the current line is blank, you got two newline characters in a row.

// that's the end of the client HTTP request, so send a response:

if (currentLine.length() == 0) {

// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)

// and a content-type so the client knows what's coming, then a blank line:

client.println("HTTP/1.1 200 OK");

client.println("Content-type:text/html");

client.println("Connection: close");

client.println();

// Display the HTML web page

 

client.println("<!DOCTYPE html><html>");

client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");

client.println("<link rel=\"icon\" href=\"data:,\">");

// CSS to style the slider

// Feel free to change the background-color and font-size attributes to fit your preferences

client.println("<style>body { text-align: justify; font-family: \"Trebuchet MS\", Arial; margin-left:auto; margin-right:auto;}");

client.println(".slider { width: 600px; }</style>");

client.println("<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>");

// Styling Web Page

client.println("</head><body><h1>Control Servo via ESP32</h1>");

client.println("<p>Angle: <span id=\"servoPos\"></span></p>");

client.println("<input type=\"range\" min=\"0\" max=\"180\" class=\"slider\" id=\"servoSlider\" onchange=\"servo(this.value)\" value=\""+valueString+"\"/>");

client.println("<script>var slider = document.getElementById(\"servoSlider\");");

client.println("var servoP = document.getElementById(\"servoPos\"); servoP.innerHTML = slider.value;");

client.println("slider.oninput = function() { slider.value = this.value; servoP.innerHTML = this.value; }");

client.println("$.ajaxSetup({timeout:2000}); function servo(pos) { ");

client.println("$.get(\"/?value=\" + pos + \"&\"); {Connection: close};}</script>");

client.println("</body></html>");

//GET /?value=180& HTTP/1.1

if(header.indexOf("GET /?value=")>=0) {

angle_x = header.indexOf('=');

angle_y = header.indexOf('&');

valueString = header.substring(angle_x+1, angle_y);

//Rotate the servo

servo1.write(valueString.toInt());

Serial.println(valueString);

}

// The HTTP response ends with another blank line

client.println();

// Break out of the while loop

break;

} else { // if you got a newline, then clear currentLine

currentLine = "";

}

} else if ( c != '\r' ) { // if you got anything else but a carriage return character,

currentLine += c; // add it to the end of the currentLine

}

}

}

// Clear the header variable

header = "";

// Close the connection

client.stop();

Serial.println("Client disconnected.");

Serial.println(" ");

}

}

Code Description

  • Replace SSID and PASSWORD with your network credentials.

Fig. Variables to store Network credentials

  • As we are creating a web server, we need to assign a port to it and normally we use port 80 for a local webserver.
  • So, in the below code, we have assigned port 80 to the web server and then initialized a few variables:

Fig.

  • header variable is used to store the HTTP requests.
  • Variables angle_x and angle_y are used to store the position/angle of servo motor’s shaft.

Fig.

  • Variables to store timer values for a delay of 2sec or 2000ms.

Fig.

Setup()

  • Inside the setup() function, servoPin is being attached to the servo1 object.

Fig.

  • Wi-Fi.begin() is used to initialize the ESP32’s wi-fi module.
  • IP address of the device will be fetched once ESP32 is successfully connected to the wi-fi network.
  • begin() function is used to initialize the webserver mode in ESP32.

Loop()

  • After the webserver has been initialized successfully, the ESP32 server will be continuously waiting for the client connection.

Fig

  • Once the connection is established between the access point and the client device, the access point will wait for the data input.
  • A string type variable called currentLine has been defined to hold the incoming data from the client.
  • If there is a byte to be read from the client, then it will be stored inside the char type variable

HTML to display a web page

  • The ESP32 will respond to your browser with HTML (hypertext markup language) code that will be used to construct the web page.
  • HTTP header always starts with a response code e.g.: HTTP/1.1 200 ok
  • An HTML page will be created on the client’s browser, from where the client device can control the position of the servo motor.

Fig.

  • The next line, which signals that we are transmitting HTML, should always be the first thing we send.
  • Make the web page responsive in any web browser.
 

Fig.

  • The next task is styling the webpage and the slider.
  • The maximum and minimum angles are 180 and 0 degrees respectively.
  • valueString variable is containing the current angle/position of the slider, fetched from the HTTP request.

Fig.

  • Close the web connection and clear the header that was used to store the HTTP request header.
  • Print information about the closed web connection on the serial monitor.

Fig. Close the connection

Testing

  • Enter the Wi-Fi or network credentials in the code.
  • Compile and upload the code into ESP32 using Arduino IDE.
  • Make sure you have selected the right development board and com port before uploading the code.
  • Open the serial monitor with a 115200 baud rate as defined in the Arduino code.
  • Press the EN button from the ESP32 development board.

Fig. Serial Monitor

  • Copy the IP address from the serial monitor.
  • Open the web browser.
  • Paste the IP address. A webpage to control the position/angle of servo motor will be displayed, as shown below:

Fig. Web Page

This concludes the tutorial. I hope you found this of some help and also to see you soon with a new tutorial on ESP32.

Capacitance Measurement using Arduino

Hello geeks, welcome to our new project. In this project, we are going to make a very useful and interesting electronics tool that we as engineers or tinkers need in everyday life. We use the capacitor in most of our projects for various purposes such as filters or power supplies. Most of the time, we do not have a provision to measure the capacitor value in our digital multimeter. So, this time we came up with the solution. Hence, we will make our own capacitance measurement tool using Arduino.

Rather than investing in new electronic equipment, we will use an Arduino board and some basic components to measure the capacitance. To make this project, we should have some working knowledge about the capacitor. Here, we will not discuss the in-depth working of capacitors, but we will talk briefly so that it would be easy to understand the working principle of our project.

The capacitor is an electronic component that basically stores the energy when applied to an electric field. It has two parallel terminals connected by two parallel conducting plates separated by a dielectric material. Dielectric materials are electrical insulators(resist to pass the current) that can be polarised by applying an electric field. When we connect a battery with the capacitor then due to potential difference, the electric field is created between two oppositely charged plates of the capacitor and this way the capacitor stores the energy.

Where To Buy?
No.ComponentsDistributorLink To Buy
1CapacitorAmazonBuy Now
2ResistorAmazonBuy Now
3LCD 16x2AmazonBuy Now
4Arduino UnoAmazonBuy Now

Software to install

To make this project, we will need some software to install. As we will make our project in the simulation, so for that we will install Proteus simulation software and for coding, we will use the Arduino IDE.

A brief about Proteus, it is a tool used for simulation and design of electronic circuits. Here we can design different types of electronic circuits and run the simulation. Although Proteus has a very big database for electronic components, still we need to install some libraries which we will use in this project.

  • Arduino UNO - We have to install the library for Arduino UNO.
  • LCD module - We have to install a library for the LCD module.

You can download this whole project for example Proteus Simulation and Arduino Code, by tapping the below button:

Capacitance Measurement using Arduino

Project overview

In this project, we will use the following components-

  • Arduino UNO - We will use this as the main controller for this project. It will calculate the capacitance of the capacitor.
  • 16x2 LCD Module - We will use this to show the result of measured capacitance and some user-related messages.
  • Resistors and Capacitors - We will be using some resistors to make the RC circuit which is required for measuring the capacitance.

Now let's talk about the working of this project. The capacitance of any capacitor is the amount of charge that is stored in that capacitor and its unit is Faraday (F). To measure the capacitance, we will use some basic properties of the capacitor.

So when we connect a power supply with a resistor across the terminals of a capacitor, it will take a certain amount of time to fully charge. And when we connect any discharging resistor as a load across it, then it will take a certain amount of time to fully discharge. And this charging and discharging time will be proportional to the capacitance of the capacitor and the charging resistor in the RC circuit.

We will use the time constant formula for the calculation of capacitance. The time constant of any capacitor is known as the time taken by the capacitor to charge 63 percent of applied voltage or the time taken by the capacitor to discharge to 33 percent of stored voltage.

Here,

T (Tau) = Time constant(Seconds)

R = Resistance (Ohms)

C= Capacitance (Farads)

Using the above principle, we will charge the capacitor using a resistor to reach the charge of the capacitor to 63 percent of applied voltage and we will measure the time taken by the capacitor to reach that point. As we know the resistor’s value and time constant, using these two, we can calculate the capacitance:

Components required

  • Arduino UNO
  • 16x2 LCD module
  • 10 kOhms Resistor
  • 220 Ohms Resistor
  • An unknown capacitor(Enter range here )

Components details

1. Arduino UNO

  • Arduino UNO is an open-source development board that will be used to measure capacitance.
  • It comes with 14 digital I/O pins and 6 analog I/O pins.
  • It has 1 UART, 1 SPI, and 1 I2C hardware which are multiplexed with GPIO pins.
  • Digital pins can be used for input and output for digital data. In this project, we have used digital pins for charging the capacitor.
  • Analog pins have 10 bits of ADC (Analog to Digital convertor) resolution ranging values from 0 - 1023.
  • Analog pins can be used for input and output purposes. In this project, we have used analog pins as input for measuring the discharge and charge voltage.

Note-Whenever uploading the code on the Arduino UNO, disconnect any wire which is connected to Rx(D0) and Tx(D1) pins, otherwise, it will give an error while uploading the code.

2. LCD Module

  • LCD stands for Liquid Crystal Display, and its display is made using liquid crystal technology.
  • For more knowledge of how LCD works, prefer this link Working of LCD display.
  • We have used a 16x2 LCD display in this project.
  • The LCD module works in two different data modes: 8-bit or 4-bit mode.
  • We have used 4-bit mode which means we can send 4-bit data in a single cycle to the LCD module.
  • We have used an LCD module to display the user-related information such as capacitance value and the welcome message.

3. Resistors and Capacitors

  • Resistors, as the name suggests, is an electronic component that controls the flow of current in a circuit.
  • Current flowing in any circuit is inversely proportional to resistance.
  • They are used mostly in every type of electronic circuit for current limiting, voltage divider, and in some noise filters.
  • There are various types of resistors available depending upon the current rating, manufacturing materials, and use case.
  • Although we are making this project in simulation, if you want to make this project using the real components for that we will use the carbon composition through-hole resistors.
  • Capacitors are electronic components that have the ability to store energy.
  • When we connect any battery across the terminals of capacitors then it will start charging.
  • We can store a large amount of charge for a very short period of time in capacitors.

Circuit diagram and Working

Now, we have a list of all the required components. Let's start connecting them.

  • Make sure, we have the correct version of Proteus and have installed all the required libraries which we will be using in this project.
  • Now let’s start creating the new project in the Proteus.
  • Import the listed components to the workspace of Proteus.
  • Now we have imported all the components to the workspace.
  • First, connect the charging resistor of 10K ohms with the digital pin 8 of Arduino UNO and then connect the discharging resistor of 220 ohms with the digital pin 9 of the Arduino UNO.
  • We will use the D8 pin for charging the capacitor and the D9 pin for discharging the capacitor.
  • Now connect the capacitor which we want to measure in between these two resistors and connect another terminal of the capacitor with the ground.
  • Connect an analog pin of Arduino UNO with the discharging resistor terminal and that analog pin will be A0 on Arduino UNO.
  • After that, we are finished with our RC circuit.
  • Let’s connect the LCD module with the Arduino UNO, as we are using the LCD module in 4 bits mode so we need to connect only four data pins with Arduino UNO.
  • Connect D4 pin to D7 pins of the LCD module with D2 to D5 pins of the Arduino UNO.
  • While connecting them, keep in mind that they must be connected in the same order.
  • Connect the RS pin with the D6 and Enable pin with the D7 pin of Arduino UNO.
  • Connect the RW pin with the ground which enables the write mode in the LCD module.
  • Connect the 5v power supply with Vdd and Gnd pins of the LCD module.
  • Now we have connected all the components.
  • Before moving to the coding part, reverify your connections once.

While working on the real components, make sure you have connected the backlight of the LCD module and set the contrast properly otherwise nothing will be visible on the LCD module.

Arduino code of Capacitance measurement-

Downloading and including libraries

  • This project will need the library for the LCD module.
  • Before going to write, we must download and include all the required libraries.
  • We can download the library for the LCD module using this link LCD module library.
  • To include the library, go to the Sketch >> Include Library >> Manage Libraries… Using this, we can add libraries directly by searching the window.
  • Or if you have downloaded the library using the link then you will have a zip file for the library. In this case, follow this path: Sketch >> Include Library >> Add .Zip Library
  • After downloading the library, we are all set to start our code.
  • First, include the LCD library header at the start, make an object for the same, and declare all the pins which are used for the LCD module.

Variable declaration

  • Now we will declare all the variables and pins which we are going to use in this project.
  • Declare the charging pin, discharging pin, and an analog pin for measuring the charging voltage as 8,9 and A0 respectively.
  • Declare variables to store the start time, stop time, and a variable to store the duration.
  • Declare a function “measure()” which will read the analog values.
  • After the declaration, we will define a function “measure()”.
  • We have defined this at the end of the code.
  • This function will read the analog values from the pin and return the values for the same.
  • Here, we have declared and defined the function separately but we can define the function without declaring it, but it is not a good practice to do so and sometimes that will cause errors in the code also.

Void setup()

  • After declaring all the required variables, we will start writing the “void setup()” function.
  • This is a built-in function in the structure of the Arduino sketch.
  • We can write any code without this function. As per the structure of the Arduino sketch, this function must be in the code.
  • In this function, we will write the pin mode and initialization of other peripherals which will be required in the code.
  • This function will only run once when the code starts.
  • So in this function, we will first begin the LCD module and print the instructions to use.
  • Then set the pin mode of pins and the initial state of the pins.

Void loop()

  • This is also a built function of Arduino sketch.
  • As per the structure of the Arduino sketch, we can not delete this function from the code even though we don’t have anything to write in this.
  • This function executes after the “void setup()” function.
  • In this function, we will write our main code which we want to run continuously.
  • As the name suggests this will run in a loop.
  • Initially, when there is no capacitor connected then the analog value will be in the maximum range and that is 1010 to 1030.
  • So now, we will display the message that ‘place a capacitor’ and code will be in a while loop until we connect any capacitor to the circuit.
  • Now when we connect any capacitor, the above condition will be unsatisfied, then code will enter in a next infinite while and there we will write the process of charging and discharging of capacitor and time constant.
  • First, we will discharge the whole capacitor, for that we will run a while loop, and using the measure() function, we will measure the currently stored voltage in the capacitor.
  • And when the stored voltage reaches below or equal to the threshold, we will change the pin mode of pins to start charging the capacitor again and store the start time of charging.
  • Using the measure() function, monitor the charging voltage in the capacitor and when the stored charge reaches 63 percent which is 648 of 1023 then we will stop the charging and store the stop charging time also.
  • And display the charging percent on the LCD module.
  • Now calculate the total time taken by the capacitor to reach the 63 percent of charge and that will be the time constant of the capacitor.
  • Using the time constant formula, we can calculate the capacitance of the capacitor as we know the charging resistor connected to the capacitor.
  • As we know the charging resistor value is 10k ohms, using that when we divide the time taken by the resistor value, then we will get the capacitance.
  • And the calculated result will be displayed on the LCD module for 3 seconds, after that code will enter in an infinite while loop.
  • Now we have to reset the device to measure any new capacitor value.
  • Here, our coding part will be completed, it is time to test our code with the circuit and now we will move to the next section.

Results and Working

  • As we are going to test our project in the Proteus simulation, we have to include the hex file of our code in the Arduino UNO module.
  • The first step is to generate the hex file of the code.
  • Click on the Arduino UNO module in the Proteus then browse to the location of the generated hex file.
  • After adding the code, we are ready to run the simulation and click on the Play button to start the simulation.
  • First of all when the code starts, on the LCD module, we will show the range of capacitance that can be measured using this device and the message to place the capacitor if it is not placed already.
  • When the capacitor is placed, then the discharging process will start to eliminate any pre-stored charge in the capacitor, thus we will get the more accurate value.
  • After 100 percent discharge, the charging process will start and it will go to 63 percent of the stored charge.
  • Thereafter, the code will calculate the capacitance using the time constant formula, and the result will be displayed on the LCD module with the message to reset the device to measure again.
  • After the compilation of the simulation, click on the stop button to stop the running code.

I hope we have covered all the points related to this project such as circuit diagrams, codes, and working simulation. And I think this will be a very useful project for your daily tinker life. Please let us know if you face any difficulties while making this project in the comment section below.

We will be happy to hear if you will make this project used in your projects.

Thanks for reading this article. All the best and see you in the next project.

Accessing ESP32 Dual Core

We are familiar with multiple features of the ESP32 module. Like Wi-Fi capabilities, classic Bluetooth, Bluetooth low energy (BLE), inbuilt sensors etc.

Hello readers, I hope you all are doing great. We have already mentioned in our previous tutorials that, ESP32 is also featured with a Dual-Core Processor. Which provides better performance and efficiency.

In this tutorial, we will learn how to use ESP32’s dual cores. ESP32 has two (32-bit each) Tensilica Xtensa LX6 microprocessors namely, core0 and core1 which makes it a powerful dual-core microcontroller and hence stands apart from its predecessors.

When we compile and upload a code using Arduino IDE, we do not have to worry about which core executes the code. It just runs.

Fig. 1 ESP32 dual-core processor

Features of Dual-Core processor

  • Power Efficiency: A single-core processor can rapidly hit 100% of its workload. On the other hand, a dual-core processor allows the efficient allocation of resources with a multitasking environment.
  • Increased Performance to Multithread Programs: Aside from being able to run multiple programs at the same time, dual-core processors can also collaborate to make a single program faster and more efficient. Multithreading allows programmers to send different instructions from the same program into two processing paths. On a single processor with hyper-threading, the program is still limited to the single core's maximum processing speed. However, on a dual-core, this effectively doubles the speed available to that program.
  • Two programs running simultaneously: Two cores allow two programs to run at the same time. The many complex calculations that a computer must perform to create the average browsing experience are difficult to quantify; however, single-core processors only create the illusion of multitasking through technologies such as hyper-threading.
Where To Buy?
No.ComponentsDistributorLink To Buy
1ESP32AmazonBuy Now

FreeRTOS in ESP32

A FreeRTOS (real-time operating system) firmware is already available in the ESP32 module. FreeRTOS is helpful in improving the system performance and managing the resources of the module. FreeRTOS allows users to handle several tasks like measuring sensor readings, making a network request, controlling motor speed etc. all of them run simultaneously and independently.

FreeRTOS offers multiple APIs for different applications. Those APIs can be used to create tasks and make them run on different cores. You need to create tasks to assign a particular part of code to a specific core. You can also prioritize that on which core the code will run. Priority value starts with level_0.

Accessing ESP32’s both cores using Ardui1no IDE

Whenever we run a code on Arduino IDE, it runs on core_1 by default.

  • How to check on which core the code is running?

There is a function you can use to check on which core the code is running on.

xPortGetCoreID()

Run the following code in Arduino IDE:

void setup()

{

Serial.begin(115200);

Serial.print( " setup() is running on: Core_" );

Serial.println( xPortGetCoreID() );

delay(1000);

}

void loop()

{

Serial.print( " loop() is running on: Core_" );

Serial.println( xPortGetCoreID() );

delay(1000);

}

  • Open the serial monitor with a 115200 baud rate.
  • Press the EN button from the ESP32 development board.

Fig. 2 Serial Monitor

From the results on the serial monitor, you can see that both setup() function and loop() function are running on core_1.

Steps to be followed to create a task are:

  • Create a task handle to keep a track of the task created. For example, a task handle named task is created below:

Fig. 3

  • Inside setup() function, create a task assigned to a specific core. xTaskCreatedPinnedToCore() function is used to create a task assigned to a specific core.

This function takes seven arguments:

  1. Name of the function to implement the task
  2. Name of the task
  3. Stack size assigned to the task in words (where 1 word = 2 Bytes)
  4. Task Input parameter
  5. Priority of the task
  6. Task handler
  7. Core where the task should run

Fig. 4

  • Create a function that contains the code for the task you have been created.

For example, we have created a function named task_code(). Inside the task_code() function a for(;;) loop is used which will create an infinite loop. All the instructions to be given for a particular core to perform a particular task like led blinking, sensor readings etc. will be written inside this for(;;) loop.

Fig. 5

  • How to delete the created task, during the code execution?

You can use the function vTaskDelete() during the code execution to delete a task. This function takes the task handle (task) as an argument.

  • Code for creating and assigning the separate task to each core

In this code we will use two LEDs to be processed by different core.

TaskHandle_t task1;

TaskHandle_t task2;

// Assign GPIOs pins to LEDs

const int led1 = LED_BUILTIN;

const int led2 = 25;

void setup() {

Serial.begin(115200 );

pinMode( led1, OUTPUT );

pinMode( led2, OUTPUT );

//create a task that will be executed in the Task1code() function, with priority 1 and executed on core 0

xTaskCreatePinnedToCore(task_1code, // Task function.

"Task1", // name of task.

10000, // Stack size of task

NULL, // parameter of the task

1, // priority of the task

&task1, // Task handle to keep track of created task

1); // pin task to core 1

delay(1000);

//create a task that will be executed in the Task2code() function, with priority 1 and executed on core 1

xTaskCreatePinnedToCore(task_2code, //Task function.

"task2", //name of task.

10000, //Stack size of task

NULL, //parameter of the task

1, //priority of the task

&task2, //Task handle to keep track of created task

0); //pin task to core 0

delay(1000);

}

//task_1code: blinks an LED every 1000 ms

void task_1code( void * pvParameters ){

Serial.print( "task1 running on: core " );

Serial.println( xPortGetCoreID() );

for(;;)

{

digitalWrite( led1, HIGH);

delay(1000);

digitalWrite(led1, LOW);

delay(1000);

}

}

//task_2code: blinks an LED every 500 ms

void task_2code( void * pvParameters )

{

Serial.print( "task2 running on: core " );

Serial.println(xPortGetCoreID() );

for(;;){

digitalWrite(led2, HIGH );

delay(500);

digitalWrite(led2, LOW );

delay(500);

}

}

void loop()

{

Serial.print( " loop() is running on: Core " );

Serial.println( xPortGetCoreID() );

delay(1000);

}

Code Description

  • We have created two task handle to keep track of two different tasks created for each core. Task1 is for core_1 and task2 is for core_0.
  • Although we do not need to create a new task and a task handle for core_1 because the void loop() function be default run on core_1 but for better understanding we are creating a different task for each core.

Fig. 6

  • Allocate GPIOs to the LEDs. Led1 is the inbuilt one that is connected with GPIO2 (internally) and another one is led2 to be connected with GPIO 25.

Fig. 7

Setup()

  • Initialize the serial monitor with a 115200 baud rate for debugging purposes.
  • Set the mode of LEDs as OUTPUT.

Fig. 8 setup() function

  • Create a task (task1) using xTaskCreatePinnedToCore() This task will take seven parameters which include; the task function namely task_1code(), name of the task, stack size of the task, priority level, task handle (if created), core to which you want to assign the task.

Fig. 9

  • Create a similar task for another core. We will create a different function for this task namely task_2code() and will pass task_2 as a task handle and the core selected is

Fig. 10

  • The next step is to create functions to execute the above task for each core.
  • task_1code() function is passed as a parameter in
  • xPortGetCoreID() function is used to fetch the core number on which the current function is running on.
  • This function will make the inbuilt LED (GPIO2) or led1 blink with a delay of 1 second or 1000msec.
  • This for(;;) loop will make led1 blink continuously which is similar to the instructions executed inside loop() function.
  • print() function is used to print the results on the serial monitor for debugging purposes.

Fig. 11

  • task_2code() function is called for task2.
  • This code will be executed in core0.
  • Led2 (GPIO25) will blink continuously with a delay of 0.5sec.

Fig. 12

  • Inside the loop function we called the xPortGetCoreID() function to get the core number which is responsible to execute the instructions written inside loop() function

Fig. 13 loop function

Testing

Components required:

  • ESP32 development board
  • Breadboard
  • 2*Jumper wires
  • 1*LED
  • 1*resistor(330 ohms)

Steps for testing:

  • Connect the LED with ESP32 as shown below:

Fig. 14 connecting LED with ESP32

  • Upload the code into the ESP32 development board.
  • Open the serial monitor with a 115200 baud rate.
  • Press the EN from the ESP32 development board.
  • Results observed from the serial monitor are shown below:

Fig. 15 Results on the serial monitor

  • On the serial monitor, we can see that task1 functions are processed by core 1 and task2 is processed by core 0.
  • We have already mentioned that core1 is the default processing core so instructions inside the loop() function are processed by core1.

This concludes the tutorial. We hope you found this helpful and also hope to see you soon with a new tutorial on ESP32.

Sending Sensor Readings to Google Sheet Through IFTTT using ESP32

Hello readers, I hope you all are doing great. In our previous tutorial, we learnt how to make HTTP POST from ESP32 to the IFTTT server.

In this tutorial, we will learn about another application of the ESP32 module in the field of IoT (Internet of Things). We can publish multiple sensor readings from ESP32 to Google sheets via the IFTTT web service.

IFTTT is used as a third-party web service to integrate Google sheets with ESP32.

Fig. 1

Where To Buy?
No.ComponentsDistributorLink To Buy
1ESP32AmazonBuy Now

Creating an IFTTT Account for Integrating ESP32 with Google Sheets

We are going to create an applet (on the IFTTT server) that is responsible to integrate the Webhooks and Google Sheets services.

While operating with the IFTTT server there are some services/utilities that we are going to deal with like Applets and Webhooks. Before getting started with the project, let’s first introduce you to those terms:

Applet

An Applet is a small application or a utility program, which is used for one or a few simple functions. It connects two or more devices or apps together. An applet provides integration between two devices or services to enable some functionality that those devices or services cannot do alone or on their own. An applet consists of actions and triggers.

Fig. 2

Webhooks

  • Webhooks are hypertext transfer protocol (HTTP) callbacks that are defined by the user. They are data and executable commands sent from one app to another over HTTP rather than through the computer's command line. Essentially, it is a method for apps to send automated messages or information to other apps.
  • When an event occurs on the "trigger" application, the app serializes the data and sends it to a webhook URL from the "action" application (the app that processes the data from the "trigger" application). After that, the active application can send a callback message.

Getting Started with IFTTT:

  1. Enter the following link in the web browser: https://ifttt.com
  2. Login with your Gmail or Facebook accounts for free.
  3. Click on Create icon (top left menu) to create an

Fig. 3: Creating an Applet

  1. Click on the ”if This” icon.

Fig. 4: “If This”

  1. Select a service. Search for the Webhooks service and select the respective icon.

Fig. 5: Search and Select Webhooks

  1. Click on the Receive a web request option to select a trigger option. The trigger will fire every time the maker service receives a web request to notify it of an event.

Fig. 6: Receive a Web Request

  1. Assign a name to the trigger event and click on Create trigger We have assigned ESP32_GoogleSheets.

Fig. 7: Create Trigger

  1. Next, click on the “Then That”

Fig. 8:  Then That

  1. To select the service, search for the Google Sheets service and click on the respective icon.

Fig. 9:  Google Sheets

 
  1. The next step is selecting an action, click on Add row to the spreadsheet

Fig. 10: Select an Action

  1. Click on the connect button to connect with the Google Sheet service, if you haven’t connected to it yet.

Fig. 11: Connect to Google Sheets Service

  1. A new window will pop up, where you need to log in with your Gmail account.
  2. Enter your Gmail account address and password.
  3. Click on Allow icon, (as shown below) to allow the IFTTT web service to access files from your Google drive. So that IFTTT can create new folders or update details in the existing Google drive folders with new sensor readings.

Fig. 12: Allow IFTTT Service to Access Files of your Google Drive

  1. Finally, complete the action field by assigning the name to the spreadsheet and path the folder in Google drive. Leave the Formatted row as it is (default).
  2. A folder named IFTTT will be created by default if you leave the above fields empty.

Fig. 13: Complete Action Fields

  1. Click on the finish

Fig. 14: Applet Successfully Created

Testing the Applet

Before interfacing the IFTTT service (applet) with ESP32, let us test the applet whether it is created successfully or not.

  1. Open the following link: https://ifttt.com/maker_webhooks
  2. Click on the Documentation

Fig. 15

  • A new window will open containing your key (API).
  • Enter the details in To trigger an Event and click on Test it.

Fig. 16: Test your Applet

  • Open your Google drive.
  • You should see a folder (named IFTTT ) in your Google drive.
  • Open the folder to see the values received from the IFTTT server.

Fig. 17:  IFTTT Folder in Google Drive

 

Components Required:

  • ESP32 development board.
  • USB cable to connect to ESP32 development board with the computer.

No external components are required as we are using the ESP32’s inbuilt sensors to take the readings.

 

Arduino IDE code

Let’s have an overview of the project before writing the Arduino code:

  • To access the internet, the ESP connects to the local Wi-Fi network.
  • Then, the Hall sensor will take the readings;
  • Your ESP32 will communicate with the IFTTT Webhooks service that publishes the readings to a spreadsheet on Google Sheets that is saved in your Google Drive’s folder.
  • After publishing the readings, the ESP goes into deep sleep mode for 15 minutes;
  • After 15 minutes the ESP wakes up;
  • After waking up, the ESP connects to Wi-Fi, and the process repeats.
  • We are using Arduino IDE to compile and upload into the ESP32 module. To know more about Arduino IDE and how to use it, follow our previous tutorial i.e., on ESP32 programming series.

#include <WiFi.h>

// Replace with your SSID and Password

const char* ssid = "SSID";

const char* password = "Password";

// Replace with your unique IFTTT URL resource

const char* serverName = "https://maker.ifttt.com/trigger/replace_this_with_eventName/with/key/replace_this_with_your_unique_key ";

// Maker Webhooks IFTTT

const char* server="maker.ifttt.com";

//----Timer for sleep

uint64_t uS_TO_S_FACTOR = 1000000; // Conversion factor for micro seconds to seconds

uint64_t TIME_TO_SLEEP = 900; //sleep for 15 minutes

 

void setup()

{

Serial.begin(115200);

delay(100);

Serial.print("Connecting to: ");

Serial.print(ssid);

WiFi.begin(ssid, password);

int timeout = 10 * 4; // 10 seconds

while( WiFi.status() != WL_CONNECTED && ( timeout-- > 0) )

{

delay(200);

Serial.print(".");

}

Serial.println(" ");

if(WiFi.status() != WL_CONNECTED )

{

Serial.println(" Failed to connect, going back to sleep ");

}

Serial.print("WiFi connected in: ");

Serial.print(millis());

Serial.print(", IP address: ");

Serial.println(WiFi.localIP());

makeIFTTTRequest();

// enable timer deep sleep

esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);

Serial.println("Going to sleep now");

esp_deep_sleep_start(); // start deep sleep for 900 seconds (15 minutes)

}

 

void loop()

{

// sleeping so wont get here

}

void makeIFTTTRequest()

{

Serial.print("Connecting to ");

Serial.print(server);

WiFiClient client;

int retries = 5;

while(!!!client.connect(server, 80) && (retries-- > 0))

{

Serial.print(".");

}

Serial.println();

if(!!!client.connected())

{

Serial.println(" Failed to connect... ");

}

Serial.print(" Request server: ");

Serial.println( serverName );

// Hall sensor values

String jsonObject = String("{\"value1\":\"") +

hallRead() +

"\",\"value2\":\"" + hallRead()

+ "\",\"value3\":\"" +

hallRead() + "\"}";

client.println(String("POST ") + serverName + " HTTP/1.1");

client.println(String("Host: ") + server);

client.println("Connection: close\r\nContent-Type: application/json");

client.print("Content-Length: ");

client.println(jsonObject.length());

client.println();

client.println(jsonObject);

int timeout = 5 * 10; // 5 seconds

while(!!!client.available() && (timeout-- > 0)){

delay(100);

}

if(!!!client.available()) {

Serial.println("No response...");

}

while(client.available()){

Serial.write(client.read());

}

Serial.println("\nclosing connection");

client.stop();

}

Code Description

  • Add the required header files.
  • WiFi.h header file is used to enable the Wi-Fi module and its respective functions.

Fig. 18:  Library Files

  • Enter the network credentials, SSID and Password.

Fig. 19:  Network Credentials

  • Add the IFTT domain name, the event name (you have created) and the API key. The event name we have created is ESP32_test.

Fig. 20

  • IFTTT Server URL.

Fig. 21

  • Time_To_Sleep variable is used to set a timer (sleep time) of 15 minutes (900 sec). ESP32 processor will wake up from sleep mode after every 15 minutes to take the sensor readings and publish them to Google Sheets.
  • uS_To_S_Factor is used to store the conversion value for converting the timer unit from microseconds to seconds.

Note: The ESP32 sleep time should not be very short. A very short sleep time can result in the exceeded limit of requests imposed by the IFTTT service.

Fig. 22: Timer

 

Setup()

    • Initialize the Serial monitor with a 115200 baud rate for debugging purposes.

Fig. 23:  Serial Monitor

  • Enable ESP32’s Wi-Fi module using begin() function which is using SSID and password as arguments.
  • Wait until the ESP32 is not connected to the Wi-Fi network.
  • Fetch the IP address using WiFi.localIP() function.

Fig. 24:  Wi-Fi

  • makeIFTTTRequest() function is used to connect ESP32 with the client server.

Fig. 25

  • esp_sleep_enable_timer_wakeup() function is used to enable the timer for sleep mode.
  • The duration of sleep mode is passed as an argument inside the timer function.
  • Esp_deep_sleep_start() function is used to start the sleep mode.

Fig. 26

  • The below code represents the process happening inside the makeIFTTTRequest()

Fig. 27

  • ESP32 connects to IFTTT serve and then communicates with the server (IFTTT) through port 80.
  • ESP32 tries 5 times to connect to the server and if it couldn’t then it will enter the sleep mode.

Fig. 28

  • jsonObject variable is used to store the sensor data to be shared to the Google Sheets via the IFTTT server.
  • We are using ESP32’s inbuilt Hall sensor to take the readings.
  • This variable will take three sensor values and ESP32 will communicate the readings to Google Sheets.

Fig. 29

  • Connection with the server will be closed once the data is shared successfully and ESP32 will enter to sleep mode form next 15 minutes.

Fig. 30

Testing

  • Select the right development board in Tools >> Boards >> DOIT ESP32 DevKit V1 in Arduino IDE.
  • Compile and upload the code into ESP32 using Arduino IDE.
  • Make sure that you have entered the right Wi-Fi credentials, API key and event name before uploading the code.
  • Open the serial monitor with a 115200 baud rate as defined in the Arduino code.
  • Press the EN button from the ESP32 development board.
  • Go to your Google drive.
  • You should see a folder (named IFTTT ) in your Google drive.
  • Another folder will be there inside the IFTTT folder (named as ESP32_hall sensor readings, in our case)
  • Open the folder to see the values received from the IFTTT server.
  • The spreadsheet will be updated after every 15 minutes. If you press the EN button before completing the sleep duration(15 minutes), the spreadsheet will be updated automatically with new sensor data, as shown below:

Fig. 31: Hall Sensor Readings on Google Sheets

Fig. 32: Serial Monitor

This concludes the tutorial. I hope you found this of some help and also to see you soon with the new tutorial on ESP32.

Key Steps To Improve Health And Safety In Industrial Workplaces

Industrial workplace health and safety are essential for avoiding work-related accidents, injuries, and fatalities. In fact, as many as 13,455,000 workers across manufacturing industries in the US are at risk for fatal and nonfatal injuries, the CDC reveals. Not only does improving workplace health and safety protect workers, but it also prevents lost work days and lost revenue. The National Safety Council found work injuries cost businesses a total of $161.5 billion annually, equating to $1,100 per worker.

Improve employee training

New workers are three times more likely to sustain an injury in their first month than workers with a year's experience on the job. By improving employee training and tailoring programs to the demands of each individual role, you can better minimize the risk of accident and injury (a lab employee, for instance, requires vastly different training to an industrial line worker). In fact, OSHA advises implementing different plans for five key areas in order to form a comprehensive health and safety approach: hazard assessment; hazard mitigation; hazard prevention; electrical safety; and safety training. Additionally, it’s important to provide refresher training sessions on a regular basis. Never make health and safety training a one-time occurrence. By reiterating health and safety information and advice throughout the year, you can ensure workers maintain awareness of best practices.

Implement a health and safety management system

A health and safety management system is essential for identifying and resolving workplace hazards and protecting workers, as well as improving overall operational performance. In fact, it can reduce total costs arising from occupational injuries by at least 20-40%. To devise your system, OSHA recommends first identifying any health and safety issues, including, risks and hazards, management system deficiencies, and opportunities for improvement, and then prioritizing those issues. You can then determine the goals of your health and safety management system in order to maximize workplace safety and minimize risks. If an employee does sustain an injury while on the job, it’s important they inform themselves of their legal rights. Filing a lawsuit for personal injury damages can help injured employees secure financial compensation to cover the cost of medical bills and lose income, Aaron Allison Law explains.

Incentivize compliance

By incentivizing compliance, you have a better chance of ensuring your employees adhere to health and safety standards. Industrial workplaces often involve high-risk activities dealing with heavy machinery, electrical tools, and toxic chemicals on a daily basis. As such, employees can easily become too comfortable and lax, which results in potential injury or death. Incentivizing compliance could, for example, involve rewarding employees or managers when they achieve pre-set health and safety goals. Similarly, examples of non-compliance with rules and guidelines should also be corrected.

Health and safety should be a priority in all industrial workplaces. By improving employee training, implementing a health and safety management system, and incentivizing compliance, you can keep your workplace as safe as possible for employees.

ESP32 HTTP Post with ThingSpeak and IFTTT

ESP32 is a powerful chip for Internet of Things applications. This tutorial is also based on another ESP32 application in the field of IoT.

Hello readers, I hope you all are doing great. In the previous tutorial, we learned how to send sensor readings from ESP32 to the cloud (ThingSpeak webserver).

In this tutorial, we will learn to send HTTP POST requests from the ESP32 board to ThingSpeak and IFTTT APIs.

Where To Buy?
No.ComponentsDistributorLink To Buy
1ESP32AmazonBuy Now

What is HTTP?

Fig. 1 Hypertext Transfer Protocol

HTTP stands for hypertext transfer control and it is a protocol for transferring data between a web client and a web server. Hyper text transfer protocol was invented alongside HTML (Hypertext markup language) to create the first interactive, text-based web browser: the original www or World Wide Web.

Server and client communication process over HTTP:

  • The ESP32 (client) sends an HTTP request to a server ( for example ThingSpeak or IFTTT.com)
  • The server responds to the ESP32 ( client ).
  • Finally, the response contains request status information as well as the requested content.

HTTP POST Request

Fig. 2 HTTP POST Request

Hypertext transfer protocol uses particular request methods to execute various tasks. Two mostly used HTTP request methods are: HTTP GET request and HTTP POST request.

HTTP GET request is generated to request data from a specific resource and the HTTP POST request method is used to send data from the client device to the server to create or update resources.

In this tutorial, we will demonstrate only the HTTP POST method with ThingSpeak and IFTTT web services.

Features of the HTTP POST request:

  • Unlimited data length: Data is submitted through the body of HTTP so there is no limit/restriction on data length.
  • Secure: Data does not get saved on the web browser hence, this method of data communication is secure.
  • Allows different data types.
  • Data privacy.

What is IFTTT?

IFTT stands for If This Then That. It is a free web service for making different services like email, weather services, Twitter etc to connect.

IFTTT means if a service is triggered, other IFTTT services will take action.

 

Fig. 3 IFTTT

IFTTT and ESP32

IFTTT acts as a bridge between ESP32 and other web services. Some of the tasks the ESP32 board can perform with the IFTTT API service are:

  • Sending Emails and SMSs
  • Controlling ESP32 with Google Assistant
  • Communicating data or information with smartphones.
  • Scheduling events for ESP32.

IFTTT comprises Applets and Applets further contains two IFTTT services namely trigger and action.

You can use the applets created by a company or can also create your own applet. To use the IFTTT applet with ESP32, we need to create an applet by ourselves. Such applet will contain Webhooks service to interact directly with ESP32 and other services that you want to use like email, Twitter service etc.

There are cases while using ESP32 with the IFTTT: either ESP32 will trigger the IFTTT to do some task or the IFTTT triggers ESP32 to do some task.

Steps to trigger IFTTT via ESP32

  • Create an IFTTT account
  • Create an Applet to connect Webhooks to the desired service.
  • Sending HTTP POST request from ESP32 board to IFTTT
  1. Creating an IFTTT account:

Enter the following link in the web browser: https://ifttt.com

  1. Login with your Gmail or Facebook accounts for free.
  2. Click on Create icon (top left menu) to create an Applet.
 

Fig. 4 Creating an Applet

 
  1. Click on the ”if This” icon.

Fig. 5 ” If This”

 
  • Select a service. Search for the Webhooks service and select the respective icon.

Fig. 6 Search and Select Webhooks

 
  • Click on the Receive a web request option to select a trigger option. The trigger will fire every time the maker service receives a web request to notify it to an event.

Fig. 7 Receive a Web Request

 
  • Assign a name to the trigger event and click on Create trigger We have assigned ESP32_test.
 

Fig. 8 Create Trigger

  • Next, click on the “Then That”

Fig. 9 Then that

  • Select a service. We are selecting an Email service.

Fig. 10 Selecting a Service

  • Next, define what will happen whenever the event is triggered (the event that we have created earlier) and click on the Finish

Fig. 11

  • Testing the Applet
  1. Open the following link: https://ifttt.com/maker_webhooks
  2. Click on the Documentation A new window will open containing your key (API).
  3. Enter the details in To trigger an Event and click on Test it.
 

Fig. 12 To Trigger an Event

Fig. 13 Event Successfully Triggered

 
  • Open the email account, you have used while creating an IFTTT account.
  • You should receive an email from IFTTT.

Arduino Code

#include <WiFi.h>

#include <HTTPClient.h>

//---------Netwrok Credentials

const char* ssid = "SSID";

const char* password = "Password";

const char* serverName = "http://maker.ifttt.com/trigger/ESP32_test/with/key/Enter you API key";

unsigned long lastTime = 0;

unsigned long timerDelay = 15000;

void setup()

{

Serial.begin(115200);

WiFi.begin(ssid, password);

Serial.println("Connecting");

while(WiFi.status() != WL_CONNECTED)

{

delay(500);

Serial.print(".");

}

Serial.println("");

Serial.print("Connected to WiFi network with IP Address: ");

Serial.println(WiFi.localIP());

// Random seed is a number used to initialize a pseudorandom number generator

randomSeed(hallRead());

}

Void Loop()

//Send an HTTP POST request after every 15 seconds

if ((millis() - lastTime) > timerDelay)

{

//Check WiFi connection status

if(WiFi.status()== WL_CONNECTED)

{

WiFiClient client;

HTTPClient http;

// Your Domain name with URL path or IP address with path

http.begin(client, serverName);

// Specify content-type header

http.addHeader("Content-Type", "application/x-www-form-urlencoded");

// Data to send with HTTP POST

String httpRequestData = "value1=" + String(random(25)) + "&value2=" + String(random(25))+ "&value3=" + String(random(25));

// Send HTTP POST request

int httpResponseCode = http.POST(httpRequestData);

/*

// If you need an HTTP request with a content type: application/json, use the following:

http.addHeader("Content-Type", "application/json");

// JSON data to send with HTTP POST

String httpRequestData = "{\"value1\":\"" + String(random(40)) + "\",\"value2\":\"" + String(random(40)) + "\",\"value3\":\"" + String(random(40)) + "\"}";

// Send HTTP POST request

int httpResponseCode = http.POST(httpRequestData);

*/

Serial.print("HTTP Response code: ");

Serial.println(httpResponseCode);

Serial.println("successfully conected to host");

// Free resources

http.end();

}

else

{

Serial.println("WiFi Disconnected");

}

lastTime = millis();

}

}

Code Description

  • Add the required header files.
  • WiFi.h header file is used to enable the Wi-Fi module and its respective functions.
  • HTTPClient.h header file is used to let the server and client pass information with HTTP response or request.

Fig. Libraries

  • Enter the network credentials, SSID and Password.

Fig. Network Credentials

  • Add the IFTT domain name, the event name (you have created) and the API key. The event name we have created is ESP32_test.

Fig.

Setup()

  • Initialize the Serial monitor with a 115200 baud rate for debugging purposes.

Fig.

  • Enable ESP32’s Wi-Fi module using begin() function which is using SSID and password as arguments.
  • Wait until the ESP32 is not connected to the Wi-Fi network.
  • Fetch the IP address using WiFi.localIP() function.

Fig.

  • randomSeed() function is used to generated a pseudorandom number. We are using Hall sensor to take hall readings and share them to IFTTT server (host).

Fig.

Loop()

  • If the ESP32 board is successfully connected to the Wi-Fi network, HTTP POST requests will be generated automatically after every 15 seconds.
  • Some random values (hall readings) will be sent through value1, value1, value3

Fig

  • Send HTTP POST request.
  • Print the HTTP POST response with the response code.
  • Response code 200 is for successful communication and 402 code will be printed if some error is detected during HTTP post request.

Fig.

  • Following lines are used when you want to make a request with some JSON

Fig.

  • End the HTTP request.

Fig.

Testing

  • Select the right development board in Tools >> Boards >> DOIT ESP32 DevKit V1 in Arduino IDE.
  • Compile and upload the code into ESP32 using Arduino IDE.
  • Make sure that you have entered the right Wi-Fi credentials, API key and event name before uploading the code.
  • Open the serial monitor with a 115200 baud rate as defined in the Arduino code.
  • Press the EN button from the ESP32 development board.
  • On the serial monitor, we can check whether ESP32 is successfully connected to the network or not and whether the HTTP POST request is generated successfully or not.

Fig. 14 Serial Monitor

  • Open your IFTTT account and click on My
  • Next, click on View Activity.

Fig. 15 View Activity

  • A screenshot of the latest activity is shown below:

Fig. 16 Received data.

 
  • Check your registered email. You should receive an email from IFTTT.

Fig. 17 Email Received from IFTTT Server

 

Making an HTTP POST Request (JSON data) from ESP32 to ThingSpeak with Arduino IDE

We have already posted an article on sending sensor readings from ESP32 to ThingSpeak. In this article, we will learn how to send HTTP POST requests from ESP32 to send JSON data to the ThigSpeak server.

ThingSpeak is a web service operated by MathWorks where we can send sensor readings/data to the cloud. We can also visualize and act on the data (calculate the data) posted by the devices to ThingSpeak. The data can be stored in either private or public channels.

Steps to be followed to access ThingSpeak API:

  • First, you need to create a MathWorks Account.
  • To create an account or log in to ThingSpeak (operated by MathWorks) server follow the link: https://thingspeak.com/
  • Click on Get Started for free.

Fig. 18 Getting Started for Free

  • Enter your details to create a MathWorks account as shown below:

Fig. 19 Create New Account

  • If you have already created a MathWorks account, then click on Sign in.

Fig. 20 MathWorks Sign in

  • Create a channel by clicking on the New Channel

Fig. 21 New Channel

  • Enter the respective details in the channel.

Fig. 22 Create a New Channel

 

Arduino Code

//-----------Libraries

#include <WiFi.h>

#include <HTTPClient.h>

//-----------Network Credentials

const char* ssid = "replace with your network SSID";

const char* password = "replace with netwrok password";

// Domain Name with full URL Path for HTTP POST Request

const char* serverName = "http://api.thingspeak.com/update";

// Service API Key

String apiKey = "Write API Key";

unsigned long lastTime = 0;

unsigned long timerDelay = 5000; //to add delay of 5sec

void setup()

{

Serial.begin(115200);

WiFi.begin(ssid, password); //initialize ESP32 wifi module

Serial.println("Connecting");

while(WiFi.status() != WL_CONNECTED)

{

delay(500);

Serial.print(".");

}

Serial.println("");

Serial.print("Connected to WiFi network with IP Address: ");

Serial.println(WiFi.localIP());

Serial.println("Timer set to 10 seconds (timerDelay variable), it will take 10 seconds before publishing the first reading.");

// Random seed is a number used to initialize a pseudorandom number generator

randomSeed(analogRead(25));

}

void loop()

{

//Send an HTTP POST request after every 5 seconds

if ((millis() - lastTime) > timerDelay)

{

//Check the WiFi connection status

if(WiFi.status()== WL_CONNECTED)

{

WiFiClient client;

HTTPClient http;

http.begin( client, serverName );

http.addHeader("Content-Type", "application/json");

String httpRequestData = "{\"api_key\":\"" + apiKey +

"\",\"field1\":\"" +

String(random(30)) + "\"}";

int httpResponseCode = http.POST(httpRequestData);

Serial.print("HTTP Response code: ");

Serial.println(httpResponseCode);

// Free resources

http.end();

}

else {

Serial.println("WiFi Disconnected");

}

lastTime = millis();

}

}

Code Description

  • Add the server address and API (Write) Key.

Fig.

Setup()

  • Inside setup() function, initialize the serial monitor with a 115200 baud rate for debugging purposes. Also initialize the Wi-Fi module using WiFi.begin() function.
  • randomSeed() function is used to generate pseudorandom numbers.
  • Inside the randomSeed() function, the data you want to share will be passed as an argument.
  • The data could be a sensor reading or some analog values.

Loop()

    • Inside the loop function, once the ESP32 board is successfully connected with Wi-Fi, ESP32 will make an HTTP POST request for JSON data.
    • The request will be made after every 5 seconds.
    • In this code, we will share JSON data.

Fig.

  • Print the HTTP POST response with the response code.
  • Response code 200 is for successful communication and 402 code will be printed if some error is detected during HTTP post request.

Fig.

Testing

  • Select the right development board in Tools >> Boards >> DOIT ESP32 DevKit V1 in Arduino IDE.
  • Compile and upload the code into ESP32 using Arduino IDE.
  • Make sure that you have entered the right Wi-Fi credentials, and write the API key before uploading the code.
  • Open the serial monitor with a 115200 baud rate to check whether ESP32 is connected to Wi-Fi or not.
  • Open the ThingSpeak account and check the Channel Stats.

Fig. : data (JSON) Chart on ThingSpeak

 

This concludes the tutorial. I hope you found this of some help and also to see you soon with the new tutorial on ESP32.

Hyperconverged Infrastructure Market in 2022 and Beyond

Hyperconverged infrastructure becomes the go-to option for enterprise-level companies and startups looking to scale fast. While server virtualization is a mature technology, HCI continues to be one of the hottest trends in the IT industry right now. HCI offers businesses improved reliability, reduced deployment time, lower maintenance costs, and easy scalability. If you are thinking about purchasing a hyperconverged infrastructure solution, take a look at what your competition is doing. If other companies in your market are adopting HCI, maybe it's time you should, too. Let's take a look at the current state of the industry and the global HCI market growth.

The State of the Industry

HCI is a great way to reduce operating costs and simplify IT by using a single virtual environment to combine, compute, storage and networking. This virtual-box solution is flexible and affordable enough, allowing even smaller companies and startups to purchase HCI architecture to connect and interact with their remote workers, branch offices, and IoT applications.

According to researchers, the global HCI market will continue to grow at a steady pace during the next five years. Increasing customer demand and rapid adoption of SaaS and other cloud-based solutions due to the changes in daily operations of most businesses caused by the Covid-19 pandemic has brought HCI into the spotlight. More and more vendors are offering hyperconverged solutions, both for cloud and on-premise infrastructures.

More Software Offerings

According to experts, the HCI market was valued at an impressive $7.34 billion in 2020. It's predicted to surpass the $10 billion mark by 2025. Backup and recovery solutions and performance-enhancing environments remain the main drivers of market growth. Other niches where HCI solutions are popular include VM farms, desktop virtualization software, and database management.

  • The tech is moving beyond the large data centers which were its early adopters.
  • IT vendors have simplified control of HCI solutions, making them available for the general market.
  • The ability to scale horizontally by adding new virtual nodes is intuitively easy to understand even for non-tech-savvy entrepreneurs.
  • It leads to increased adoption of HCI by companies from different sectors of the economy, including retail and logistics.

Server providers and other IT vendors are divided on the issue of HCI. While some of them seem to have exited the HCI market completely, others, including even a few hardware vendors, have doubled their efforts, focusing on selling software-only products.

HCI and Edge: A Perfect Fit

Hyperconverged infrastructure fits seamlessly with Edge computing. Even smaller companies have to rely on Edge if they have branch offices or operate in remote locations. Industries like retail and banking use Edge as their default option. Since HCI removes the need for separate storage and networking devices, combining Edge with HCI creates natural synergy. Connecting thin clients and VDI workstations to the company's data center running on HCI improves the systems' reliability and makes it harder to breach from the outside. From the business point of view, partnering with a single HCI vendor instead of several hardware providers leads to cost reduction and better control and maintenance. HCI solutions consume less power and take up less space than their standard hardware counterparts.

Adoption of high-speed mobile networks like 5G will lead to further growth of Edge data centers using HCI. Enterprise data centers will either switch to this new business model or will provide HCI solutions alongside their traditional IT silos. In short, the HCI will continue to co-evolve alongside Edge, expanding from the niche of serving remote office environments to other businesses that look to cut costs, reduce storage capacity and benefit from centralized management of resources that HCI offers.

Hybrid Cloud Solutions Running on HCI

When it comes to IT infrastructure, the hybrid cloud has become the default option for most companies. Hyperconverged infrastructure can serve as the backbone of the hybrid- and multi-cloud platforms. Since HCI runs on widely-used x86 infrastructure and doesn't require tweaking and overhauling, cloud service providers switch from traditional storage/compute/network silos to hyperconverged alternatives.

Major players like Dell and Amazon are rapidly moving into the HCI niche. The new Dell Technologies Cloud runs on the VxRail platform, which is one of the HCI market leaders. AWS now offers Nutanix's hyperconverged infrastructure available as a service. Microsoft has come up with Azure Stack HCI, a powerful solution for hybrid clouds.

Hyperconverged infrastructure can become a promising alternative to popular public clouds like AWS or Microsoft Azure. The biggest selling points of HCI are its ability to scale, reduced costs, better performance, and control.

The Fastest-growing HCI Application

As mentioned previously, backup and data recovery remain the main market driver for HCI adoption. Due to the increasing number of cyberattacks, infrastructure security becomes one of the primary concerns for most companies. HCI allows to backup data on the fly, creating healthy redundancy. It's a cheaper solution since it doesn't require third-party solutions for data backup and disaster recovery. It also brings down costs associated with storage requirements, making hyperconverged infrastructure the most affordable and attractive option for backup and disaster recovery on the market right now.

Conclusion

Hyperconverged infrastructure will see increased adoption both by enterprise-level companies and data centers. It has found its natural synergy with Edge computing. The need for increased security will accelerate HCI adoption in the niche of backup and disaster recovery. The popularity of hybrid cloud solutions will also increase the number of companies using HCI for their IT needs.

Introduction to MATLAB Command Window

Hello friends! I hope you all had a great start to the new year.

In our first lecture, we had looked at the MATLAB prompt and also learned how to enter a few basic commands that use math operations. This also allowed us to use the MATLAB prompt as an advanced calculator. Today we will look at the various MATLAB keywords, and a few more basic commands and MATLAB functions, that will help us keep the prompt window organized and help in mathematical calculations. We are also going to get familiar with MATLAB’s interface and the various windows. We will also write our first user-defined MATLAB functions.

MATLAB keywords and functions

Like any programming language, MATLAB has its own set of keywords that are the basic building blocks of MATLAB. These 20 building blocks can be called by simply typing ‘iskeyword’ in the MATLAB prompt.

The list of 21 MATLAB keywords obtained as a result of running this command is as follows:

  • 'break'
  • 'case'
  • 'catch'
  • 'classdef'
  • 'continue'
  • 'else'
  • 'elseif'
  • 'end'
  • 'for'
  • 'function'
  • 'global'
  • 'if'
  • 'otherwise'
  • 'parfor'
  • 'persistent'
  • 'return'
  • 'spmd'
  • 'switch'
  • 'try'
  • 'while'

To test if the word while is a MATLAB keyword, we run the command

iskeyword(‘while’)

The output ‘1’ is saying that the result is ‘True’, and therefore, ‘while’ is indeed a keyword.

‘logical’ in the output refers to the fact that this output is a datatype of the type ‘logical’. Other data types include ‘uint8’, ‘char’ and so on and we will study these in more detail in the next lecture.

Apart from the basic arithmetic functions, MATLAB also supports relational operators, represented by symbols and the corresponding functions which look as follows:

Here, we create a variable ‘a’ which stores the value 1. The various comparison operators inside MATLAB used here, will give an output ‘1’ or ‘0’ which will mean ‘True’ or ‘False’ with respect to a particular statement.

Apart from these basic building blocks, MATLAB engineers have made available, a huge library of functions for various advanced purposes, that have been written using the basic MATLAB keywords only.

We had seen previously that the double arrowed (‘>>’) MATLAB prompt is always willing to accept command inputs from the user. Notice the ‘’ to the left of the MATLAB prompt, with a downward facing arrow. Clicking this downward facing arrow allows us to access the various in-built MATLAB functions including the functions from the various installed toolboxes. You can access the entire list of in-built MATLAB functions, including the trigonometric functions or the exponents, logarithms, etc.

Here are a few commands that we recommend you to try that make use of these functions:

A = [1,2,3,4];

B = sin(A);

X = 1:0.1:10;

Y = linspace(1,10,100);

clc

clear all

quit

Notice that while creating a matrix of numbers, we always use the square braces ‘[]’ as in the first line, whereas, the input to a function is always given with round brace ‘()’ as in the second line.

We can also create an ordered matrix of numbers separated by a fixed difference by using the syntax start:increment:end, as in the third command.

Alternatively, if we need to have exactly 100 equally separated numbers between a start and and end value, we can use the ‘linspace’ command.

Finally, whatever results have been output by the MATLAB response in the command window can be erased by using the ‘clc’ command which stands for ‘clear console’, and all the previously stored MATLAB variables can be erased with the ‘clear all’ command.

To exit MATLAB directly from the prompt, you can use the ‘quit’ command.

In the next section, let us get ourselves familiarized with the MATLAB environment.

The MATLAB Interface Environment

A typical MATLAB work environment looks as follows. We will discuss the various windows in detail:

When you open MATLAB on your desktop, the following top menu is visible. Clicking on ‘new’ allows us to enter the editor window and write our own programs.

You can also run code section by section by using the ‘%%’ command. For beginners, I’d say that this feature is really really useful when you’re trying to optimize parameters.

Menu Bar and the Tool Bar

On the top, we have the menu bar and the toolbar. This is followed by the address of the current directory that the user is working in.

By clicking on ‘New’ option, the user can choose to generate a new script, or a new live script, details of which we will see in the next section.

Current Folder

Under the Current Folder window, you will see all the files that exist in your current directory. If you select any particular file, you can also see it details in the bottom panel as shown below.

Editor Window

The Editor Window will appear when you open a MATLAB file with the extension ‘.m’ from the current folder by double clicking it, or when you select the ‘New Script’ option from the toolbar. You can even define variables like you do in your linear algebra class.

The code in the editor can also be split into various sections using the ‘%%’ command. Remember that a single ‘%’ symbol is used to create a comment in the Editor Window.

Workspace Window

Remember that the semicolon ‘;’ serves to suppress the output. Whenever you create new variables, the workspace will start showing all these variables. As we can see, the variables named ‘a’, ‘b’, ‘c’, and ‘x’, ‘y’, ‘z’. For each variable, we have a particular size, and a type of variable, which is represented by the ‘Class’. Here, the ‘Class’ is double for simple numbers.

You can directly right click and save any variable, directly from this workspace, and it will be saved in the ‘.mat’ format in the current folder.

Live Editor Window

If however, you open a ‘.mlx’ file from the current folder, or select the option to create a ‘New Live Script’ from the toolbar, the Live Editor window wil open instead.

With the Live Script, you can get started with the symbolic manipulation, or write text into the MATLAB file as well. Live scripts can also do symbolic algebraic calculation in MATLAB.

For example, in the figure below, we define symbol x with the command

syms x

We click ‘Run’ from the toolbar to execute this file.

The Live Editor also allows us to toggle between the text and the code, right from the toolbar. After that, the various code sections can be run using the ‘Run’ option from the toolbar and the rendered output can be seen within the Live Editor.

Command History

Finally, there is the command history window, which will store all the previous commands that were entered on any previous date in your MATLAB environment.

Figure window

Whenever you generate a plot, the figure window will appear which is an interactive window with it’s own toolbar, to interact with the plots.

We use the following commands to generate a plot, and you can try it too:

X = 1:0.1:2*pi;

Y = sin(X)

plot(X,Y)

The magnifier tools help us to zoom into and out of the plot while the ‘=’ tool helps us to find the x and y value of the plot at any particular point.

Also notice that now, the size of the ‘X’ and ‘Y’ variables is different, because we actually generated a matrix instead of assigning a single number to the variable.

Creating a New User-Defined Function

By selecting New Function from the toolbar, you can also create a new user-defined function and save it as an m-file. The name of this m-file is supposed to be the same as the name of the function. The following template gets opened when you select the option to create a new user-defined function:

The syntax function is used to make MATLAB know that what we are writing is a function filee. Again notice that the inputs to the function, inputArg1 and inputArg2, are inside the round braces. The multiple outputs are surrounded by square braces because these can be a matrix. We will create a sample function SumAndDiff using this template, that will output the sum and difference of any two numbers. The function file SumAndDiff.m looks as follows:

Once this function is saved in the current folder, it can be recognized by a current MATLAB script or the MATLAB command window and used.

Exercises:

  1. Create a list of numbers from 0 to 1024, with an increment of 2.
  2. Find the exponents of 2 from 0th to 1024th exponent using results of the previous exercise.
  3. What is the length of this matrix?
  4. Plot the output, and change the y axis scale from linear to log, using the following command after using the plot function: set(gca, ‘yscale’, ‘log’)
  5. Let us go ahead now and import an image into MATLAB to show you what the image looks like in the form of matrices. You need to have the image processing toolbox installed in order for the image functions to work.

Run the following command in the MATLAB prompt:

I = imread(‘ngc6543a.jpg’);

This calls the image titled ‘ngc6543a.jpg’ which is stored inside MATLAB itself for example purposes. Notice the size of this image variable I in the workspace. You will interestingly find this to be a 3D matrix. Also note the class of this variable.

In the next tutorial, we will deep dive into the MATLAB data types, the format of printing these data types and write our first loops inside MATLAB.

What is the difference between BIM and CAD Software for Architects?

Are you a new architect or aspiring to become an architect? If the answer is "yes," you will need to have the best programs to make a mark in this industry. Well, the two most important categories of software in architecture are building information modeling (BIM) and computer-aided design (CAD). Which one should you use? Keep treading as we dig deeper into each category and highlight key examples for you to consider.

What is CAD?

CAD, shortening for computer-aided design, is the use of computers to help create, modify, and optimize building design. CAD programs are developed to help people design and document their models using advanced computer technology. CAD files are particularly useful where multiple parts are required to fit precisely in a larger assembly.

Architects using CAD can effectively create both 3D models and 2D drawings for the parts of their products. The fast development of 3D CAD programs has rapidly transformed the building design and manufacturing industries because architects can create more complex products faster than before.

CAD Advantages 

The main advantages of using CAD include:

  • It makes it pretty easy for starters to get into the world of 2D and 3D.
  • You are able to create extremely complex models that were otherwise not possible with standard programs.
  • Spotting errors and correcting them in building design is easy and fast. You do not need to go to scratch to correct such errors.
  • Most CAD programs automatically create documentation for architects. This is very useful, especially when working on complex projects.

The main challenge of using CAD programs is that they simplify the work of architects so much. Although this is a good thing because you can complete projects faster, there is a risk of making some people complacent because everything has been done. See: you only need to fetch different parts from the library.

Good examples of CAD programs include AutoCAD, ArchiCAD, SketchUp, and AutoCAD Civil 3D. Most architects usually start with CAD programs before moving on to BIM.

What is BIM?

BIM is a new system where architects, engineers, and contractors collaborate by using the same database when creating new designs. This means that the entire team can easily visualize the whole building project way ahead of breaking the ground. It is considered a sort of natural evolution of CAD. So, how exactly does BIM work?

BIM provides the digital presentation of the actual facility that an architect is working on. It allows you to bring all the designs that you have, including different CAD models, so that you can work on them further or make rapid changes. When applied well, BIM can help the entire project team to visualize all parts easily, review them, and identify errors way before the task commences.

BIM Advantages

BIM has become so important in architecture, and it is now considered one of the most advanced technologies. Here are the main advantages:

  • BIM is better at making more complete presentations of architectural designs.
  • It pools all your docs into one database so that the entire team can easily access the latest changes.
  • BIM allows you to provide a lot more to your building design clients compared to what you would do with CAD.
  • Resource tracking with BIM is pretty easy.

The main challenge about BIM is that it is a relatively new method, and a lot of architects are yet to adopt it. This means that you might find working with some architects challenging because they are not used to BIM.

Common BIM building design software you might want to consider are Autodesk BIM 360, Revit, and Autodesk Civil 3D.

The building design and architectural niches are evolving fast, and you should not be left behind in using them. The good thing is that these advanced applications are making it a lot easier to create better models faster and note errors early. Since most architects are still in CAD programs, it is important to ensure you are also good in it even as you build skills in BIM. Remember that whether you prefer CAD or BIM, you will only be able to create top-rated designs by working with the best programs.

Introduction to MATLAB

Hello Friends! I hope you all are doing great welcoming 2022. With the start of the New Year, we would like to bring to you a new tutorial series. This tutorial series is on a programming language, plotting software, a data processing tool, a simulation software, a very advanced calculator and much more, all wrapped into one package called MATLAB.

We would welcome all the scientists, engineers, hobbyists and students to this tutorial series. MATLAB is a great tool used by scientists and engineers for scientific computing and numerical simulations all over the world. It is also an academic software used by PhDs, Masters students and even advanced researchers.

MATLAB (or "MATrix LABoratory") is a programming language and numerical computing environment built by Mathworks and it’s first version was released in 1984. To this day, we keep getting yearly updates. MATLAB allows matrix data manipulations, plotting of symbolic functions as well as data, implementation of robust algorithms in very short development time, creation of graphical user interfaces for software development, and interfacing with programs written in almost any other language.

If you’re associated with a university, your university could provide you with a license.

You can even online now! You can simply access it on…

You can quickly access MATLAB at https://matlab.mathworks.com/ Here’s a small trick. You can sign up with any email and select the one month free trial to get quickly started with MATLAB online.

And in case you can’t have a license, there’s also Octave, which is a different programming language but very similar in all the fundamental aspects to MATLAB. Especially for the purposes of these tutorials, Octave will help you get started quickly and you can access it on: https://octave-online.net/#

Typical uses of MATLAB include:

  1. Math and numerical computation from the MATLAB prompt
  2. Developing algorithms and scripts using the MATLAB editor
  3. Modeling and simulation using Simulink, and toolboxes
  4. Data Visualisation and generating graphics
  5. Application development, with interactive Graphical User Interface
  6. Symbolic manipulation using MuPad

MATLAB is an interpreted high-level language. This means any command input into the MATLAB interpreter is compiled line by line, and output is given. This is useful for using MATLAB as a calculator as we will see in the next section.

Using MATLAB as an Advanced Calculator/ Beginner Commands

By default, the MATLAB Prompt will be visible to you. The two angled brackets ‘>>’ refer to the MATLAB Command Prompt. Think of this as the most basic calculator. In fact, whenever you look at this, think of it as a Djinn asking for an input from you.

Anything that you give it and press enter is known as a command. Whatever it outputs is known as the response. Whatever question you ask Matlab, it will be willing to respond quickly.

For example, in the figure below, I simply write the command ‘2+2’ and press enter, to get the answer ‘4’ as a response.

You can even define variables like you do in your algebraic geometry class.

Notice that the semicolon ‘;’ that we see there is simply an indicator of when a statement ends like many other programming languages. Although this is not a necessary input in MATLAB, unlike many other languages which will simply give you an error if you forget this semicolon. Another function this serves is to suppress the output.

In MATLAB, you don’t need to ask for the answer or the result to be printed and it will continue to print by itself as part of the response. However, if you don’t want to see the output, you can suppress it.

You can also look at the value stored in a variable by simply writing the variable name and pressing ‘enter’.

We can even create a matrix of numbers as shown in the image below. This can be a 1D matrix, or a 2D matrix. Notice the use of square brackets, commas and semicolons in order to create the matrix of numbers.

You can even create matrices of numbers which are 3D numbers or even higher dimensions. When we will learn about images, we’ll see how an image is just a collection of numbers, and simple manipulation of those matrices will help us in manipulation of images.

Saving Programs in MATLAB

You can write and save your own commands in the form of an ‘m-file’, which goes by the extension ‘.m’. You can write programs in the ‘Editor window’ inside the MATLAB which can be accessed by selecting the ‘New Script’ button in the top panel. This window allows you to write, edit, create, save and access files from the current directory of MATLAB. You can, however, use any text editor to carry out these tasks. On most systems, MATLAB provides its own built-in editor. From within MATLAB, terminal commands can be typed at the MATLAB prompt following the exclamation character (!). The exclamation character prompts MATLAB to return the control temporarily to the local operating system, which executes the command following the character. After the editing is completed, the control is returned to MATLAB. For example, on UNIX systems, typing the following commands at the MATLAB prompt (and hitting the return key at the end) invokes the vi editor on the

Emacs editor.

!vi myprogram.m % or

!emacs myprogram.m

Note that the ‘%’ symbol is used for commenting in MATLAB. Any command that is preceded by this simple will be ignored by the interpreter and not be executed.

In the figure above, we have saved our very first program titled ‘Program1.m’ using the editor window in MATLAB.

Since MATLAB is for scientists and engineers primarily, it directly understands a lot of mathematical numbers natively, such as pi, e, j (imaginary number) etc.

You can quickly go to the MATLAB or the Octave terminal to test this out. Just type pi, or e and press enter to see what you get.

Introduction to Simulink

MATLAB is also a great simulation software. For more sophisticated applications, MATLAB also offers SIMULINK which is an inbuilt simulation software and provides a block diagram environment for multidomain simulation and Model-Based Design. Simulink provides a graphical editor, customizable block libraries, and solvers for modelling and simulating dynamic systems.

A very simple example of the Simulink block diagram model can be understood by the following model which simply adds or subtracts two or more numbers.

The block diagram looks as follows:

The model example for this can be opened using the following command.

openExample('simulink/SumBlockReordersInputsExample')

You can start playing with this model at once, on your MATLAB Desktop. And in fact you will find many more such examples of modelling and simulation programs that you can already start playing with online, in the set of MATLAB examples and also on the forum.

The MATLAB Community and Forum

MATLAB provides a whole community known as MATLAB-Central where MATLAB enthusiasts can ask questions and a lot of enthusiasts are willing to answer these forum questions.

There is also also, ‘file-exchange’ which is part of MATLAB-Central where people post their programs, functions and simulations for anyone to use for free.

MATLAB provides on-line help for all of its built­ in functions and programming language constructs. The commands lookfor, help, helpwin, and helpdesk provide on-line help directly from the MATLAB prompt.

Introduction to MATLAB Toolboxes

There are also several optional "toolboxes" available from the developers of MATLAB. These toolboxes are collections of functions written for special appli­cations such as symbolic computation, image processing, statistics, control system design, and neural networks. The list of toolboxes keeps growing with time. There are now more than 50 such toolboxes. The real benefit of using MATLAB is that there are teams of engineers and scientists from different fields working on each of these toolboxes and these will help you quickly get started into any field, after understanding the basics of the language. A lot of functions that are frequently performed in any particular research field, will be at the tips of your fingers in the form of ready-to-use functions. This will help you gain essential intuitions about all the different fields you may be interested in learning, getting started on, and quickly becoming a pro in. That’s the unique power MATLAB users wield.

Over the coming tutorials, we will look at the wonders that can be performed with MATLAB.

MATLAB can also interface with devices, whether they are GPIB, RS232, USB, or over a Wi-Fi, including your personal devices. It can help you manipulate images, sound and what not! You can also do 3d manipulation of animated models in MATLAB, and that’s very easy to do. We will go over this as well. We will also look one level below these 3d models and see how these themselves are also just numbers and coordinates in the end.

I absolutely enjoy MATLAB, and there’s a simple reason I’m presenting this tutorial series to you. Because I believe you should enjoy it too!

This will not only let you see ‘The Matrix’, which is the way computers perceive the real world around us, it will also change the way you yourself look at the world around you, and maybe you eventually start asking the holy question yourself… “Are we all living in a simulation?”

Exercises

Exercise: While you can get started on your own with the forum, and functions and simulations freely available, in order to procedurally be able to follow our tutorial and be able to build everything on your own from the scratch, we will strongly recommend you to follow our exercise modules.

In today’s module, we will ask you to perform very basic arithmetic tasks that will give you an intuitive feel of how to use the MATLAB prompt as an advanced calculator and make the best use of it.

For this we recommend finishing the following tasks:

  1. Use the following arithmetic operations to carry out complex calculations between any two numbers. The arithmetic operations are: Addition (+), subtraction (-), multiplication (*), division (/), and power(^).
  2. Also try to use basic math functions that are built-in for MATLAB such as, exp, log, sin, cos, tan, etc. Here are a few examples of commans you can run

sin(pi/2) exp(4)

log(10)/log(3)

  1. Also, define a few variables. Not only number variables, but also matrix variables as shown in the example below.

a=1; b= 2; c = 3; A= [1,2,3,4]; B= [5,6,7,8];

Notice that the case-sensitivity does matter for the name of the variables.

Pro Tip: You can also perform the arithmetic operations of addition, subtraction, multiplication, division and power, element-wise between any two matrices. While addition and subtraction work element-wise by default, you can perform element-wise multiplication, division, and power by using the arithmetic operations as ‘.*’, ‘./’ and ‘.^’

In the next tutorial, we will deep dive on the data types of MATLAB, keywords, what functions mean, and also write our very first function in MATLAB. If you are familiar with loops, that may come easy, because we will also write our very first loop that will help us perform repeated tasks with a relatively small number of commands.

Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir