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.

Introduction to Surface Mount Technology

Greetings and welcome to today’s lecture. Today, we are going to focus our discussion on the Surface Mount Technology of PCB components mounting. It's our 8th tutorial in the PCB learning series and is going to be a very interesting and interactive class. In Surface-mount technology, SMT components(having small pads) are placed on the surface of the PCB board and their pads are soldered on the same side of the board.

As we discussed in our last lecture on Though-Hole Technology, there are two main methods used to mount components on PCB boards. We studied THT in the last lecture and today, we will focus on  Surface Mount Technology (SMT), we will discuss SMT classifications, types, applications, advantages and disadvantages in detail.

In the beginning, a breadboard was used to hold the components together. This had a major disadvantage because components could pull out as they remain loose in the breadboard, hence giving a hard time to designers, especially in the case of complex circuits. The engineers came out with a solution called the PCB board. Initially, Though-hole technology was used to plug components into the PCB board. Later on, with the invention of SMT components, surface-mount technology came into existence. So, let's have a look at SMT in detail:

Introduction to Surface Mount Technology

  • Surface-mount technology(SMT), initially called planar mounting, is used to mount components on the surface of the PCB board.
  • In Surface-mount technology, SMT components are used, which are quite small in size and have small pads, instead of leads/pins.
  • In SMT, components are placed on the PCB board at their required positions and their pads are soldered with the copper markings on the board.
  • Unlike THT, the component pins in SMT don't cross the PCB layer, they are soldered on the same side of the board.
  • SMT is the most popular method that is being employed in today’s PCB manufacturing process because it can be purely automated hence increasing the number of boards produced and also saving on production time. With this method, the cost of the PCBs was reduced drastically, if you are doing mass production.
  • As the name suggests, the components are mounted on the surface. So, there are no holes for the components mounting as in the THT method.
  • Initially, the process was done manually but today it is done by the use of advanced machinery, thanks to the technological revolution.
  • SMT discovery came in the 1980s when companies were struggling with the high demand for printed circuit boards. Fab houses had started shifting to mass production of the boards and therefore they had to introduce new methods of PCB assembly and mounting to speed up the process.

How to place an SMT PCB order?

There are many online PCB companies available, where we can place orders for PCB with surface mount technology. Let's take the example of JLCPCB Fabrication House, one of the leading PCB manufacturers, which offers top-quality products.
  • First of all, open this JLCPCB SMT Assembly Page.
  • Here you can see, it's quite easy to place the SMT order.
  • First, you need to Upload the PCB Gerber Files, as shown in the below figure:

  • JLCPCB has a remarkable online PCB order tracking system, which keeps you aware of the current situation of your PCB order, shown in the below figure:

  • Once your SMT PCB order gets completed, you will receive it at your doorstep.

SMT Manufacturing Process

  • Using the assembler, solder paste is applied on the parts where the components will be placed. The solder paste placement follows the guidelines from the design.
  • Use the stencil or the solder screen to ensure that the solder has been placed in the exact required positions.
  • Sometimes, stencils and assemblers might not be that accurate and it's the operator's duty to inspect the solder to ensure that it has met the required standards.
  • Depending on the defect, either the assembler corrects the defect or will remove it and reapply afresh.
  • The process of inspection is very important because it will determine the quality of the solder at the end of the process, hence affecting the overall functionality of the board.
  • After inspection, the assembler will place the components accurately following the designs given by the designer. Originally, it was done manually by workers with hand tools. Today, pick-and-place machines have made work quite easy, accurate, and fast.
  • After placement, the components are soldered into pads with the solder gun. Here, the board undergoes a reflow process in which it is passed through the furnace to remelt, liquefy and finally solidify the solder at component joints.
  • Special devices used in the process of SMT are called Surface Mount Devices.

Types of vias

The SMT employs the use of vias in order to connect components with the PCB board. There are three types of vias that are employed throughout the process i.e.

  1. Blind vias.
  2. Through vias.
  3. Buried vias.

Through vias

  • This one connects all the layers of the PCB board by passing through all of them.
  • Mostly Through vias are used for the power pins i.e. ground, Vcc etc.

Blind vias

  • Blind via connects any of the external layers to neighboring two or more layers of the PCB board but won't go through all of them(as that will be Through vias).
  • Blind vias are of several types as listed below:
  1. Controlled depth blind via
  2. Photo defined blind via
  3. Laser drilled
  4. Sequential laminated blind via.

Buried vias

  • Buried via connects any two or more layers of the PCB board but won't touch any of the external layers.
  • As the name suggests, it remains buried inside the external layers of the PCB board.

Machines used in SMT mounting

Here's the list of machines used in the SMT manufacturing process:

PCB Drilling Machine:

  • Even though I said that the SMT components are mounted on the surfaces, so there's no drilling but remember that we discussed vias, which are required to create a connection between layers of the PCB boards.
  • These vias are very tiny holes drilled into the board layers and are done by the drilling machine.

Wave Soldering Machine:

  • This is used for the soldering of components on PCB pads, essential for the mass production of PCB boards.

PCB Brushing Machine:

  • We have discussed the vias drilling, so after the drilling process, we have debris deposited on the PCB boards.
  • This debris is removed by the PCB brushing machine.

Pick-and-Place Machine:

  • Pick-and-Place Machine picks up the components, rotates them in the required direction and places them on the PCB board.

PCB cleaning machine:

  • It does all the necessary cleaning of the board.
  • It also ensures that the board is dry and free from any form of moisture.

Reflow oven:

  • It contains a lot of burners and is used to smooth the soldering process.
  • There are three types of Reflow ovens available:

  1. Vapor Phase Oven.
  2. Infrared Oven.
  3. Convection Oven.

Now, let's have a look at the different types of Surface Mount Methods:

Types of Surface Mount Technology


Type I

    • Only SMD components are found in this type of PCB board.

    Type II

    • Active surface mount devices and DIPs are located on the primary side of the PCB while the surface mount chips are on the secondary side of the board.

    Type III

    • In this type, you will find passive SMCs on the secondary side of the board while the primary side is made of the DIPs only.
    • It contains only discrete mount components and they are all mounted on the bottom side.
    • The discrete components include; transistors, resistors, capacitors etc.

    Applications of the SMT components

    With SMT technology, it has become possible to produce very compact and small-size boards, since machines are used to pick and place the components. Therefore, SMT technology has numerous applications in real-life fields, few are as follows:

    1. Smartphone Evolution: Smartphone boards are quite small in size but complex in design because mobile phones need to be thin and light therefore, this technology has aided a lot in the evolution of the smartphone industry.
    2. Computer and laptop motherboards: It has helped in the production of ultrathin laptops, tablets and computers.
    3. IoT Devices: With SMT technology, IoT has moved to another level since the production of embedded boards become easy and fast.
    4. Involved in the manufacturing of communication and telecommunication equipment i.e. Bluetooth, WiFi, Ethernet devices etc.
    5. Medical devices in aid of health screening.
    6. Finds applications in the transport area i.e. drones, space exploration equipment etc.

    Advantages of the SMT components

    1. They have very low RF interference because they don't have leads.
    2. It takes lower packaging materials and this is due to the advanced manufacturing that is being involved.
    3. If SMT boards are produced in panels(We will cover penalization in upcoming chapters), the process makes it easy to transport in bulk at a reduced cost.
    4. The production cost has been drastically lowered compared to that of the THT product of the equivalent magnitude.
    5. Component failure is very low due to the consistency of the fabrication process involved.
    6. Less expensive process and very economical due to the use of more advanced technologies like PCB Panelization and pick and placing mechanism.

    Disadvantages of the SMT components

    1. It is not the best method to mount high-wattage components because such components dissipate a lot of heat that may end up damaging the PCB board.
    2. This is made up of very tiny components and therefore if there is any damage to the circuit, it is very complex to repair/debug the board as compared to the THT components. This means time-consuming in repairing and also very expensive.
    3. This type of board cannot be used in a place where rough holding is involved.

    So, that was all for today. I hope you have enjoyed today's lecture. In the next lecture, we will have a look at the difference between these two mounting techniques i.e. THT vs SMT. Till then, take care. Have fun !!!

    Sending Data to Cloud with ESP32 and ThingSpeak

    The Internet of Things ( or IoT) is a network of interconnected computing devices such as digital machines, automobiles with built-in sensors, or humans with unique identifiers and the ability to communicate data over a network without human intervention.

    Hello readers, I hope you all are doing great. In this tutorial, we will learn how to send sensor readings from ESP32 to the ThingSpeak cloud. Here we will use the ESP32’s internal sensor like hall-effect sensor and temperature sensor to observe the data and then will share that data cloud.

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

    What is ThingSpeak?

    Fig. 1: ESP32 ThingSpeak

    It is an open data platform for IoT (Internet of Things). 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.

    ThingSpeak is frequently used for internet of things prototyping and proof of concept systems that require analytics.

    Features of ThingSpeak

    • ThingSpeak service enables users to share analyzed data through public channels: Users can view multiple options on their channels via the settings panel. The tab displays sharing options, allowing the user to make their channel private, public or shared with specific users. Professionals can import and export data through their channels as well.
    • ThingSpeak allows professionals to prepare and analyze data for their businesses: Weather forecasters use the MATLAB Analysis app to prepare, analyze, and filter data, such as estimating average humidity or calculating dew point. Users can use the visualization and analysis applications to perform operations on live or historical data by using template codes. To enable modular coding, industry professionals can add new functions to the software. Companies can use ThingSpeak Analysis to read stored data or write new data to their private channels. They can scrape numbers from various web pages thanks to the URL filter.
    • ThingSpeak updates various ThingSpeak channels using MQTT and REST APIs: Professionals in the industry also use the platform to analyze and chart numerical data sent from smart devices and stored on various channels. Business owners can update their feeds, clear, or delete their channels entirely by using REST API calls like POST, GET, DELETE, or PUT. MQTT Publish methods allow users to update their feeds, whereas MQTT Subscribe methods allow them to receive messages.

    Preparing Arduino IDE for ESP32 and ThingSpeak

    • 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.

    Downloading and installing the required Library file:

    • Follow the link attached below to download theThingSpeak Arduino library:

    https://github.com/mathworks/thingspeak-arduino

    • Open the Arduino IDE.
    • Go to Sketch >> Include Library >> Add .ZIP Library and select the downloaded zip file.

    Fig. 2: Adding ThingSpeak Library

    To check whether the library is successfully added or not:

    • Go to Sketch >> Include Library >> Manage Libraries

    Fig. 3

    • Type thingspeak in the search bar.

    Fig. 4: Arduino IDE Library Manager

    • The ThingSpeak library by MathWorks has been successfully downloaded.

    This library comes with multiple example codes. You can use any of the example codes as per your requirements ad also modify the example code.

    Fig. 5: Example Codes

    Getting Started with ThingSpeak

    • 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. 6: Getting Started For Free

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

    Fig. 7: Create New Account

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

    Fig. 8: MathWorks Sign in

    • Create a channel by clicking on the New Channel

    Fig. 9: New Channel

    • Enter the respective details in the channel.
    • As we already mentioned, we will use ESP32’s inbuilt sensors, Hall and temperature sensor to take the readings and then publish them to the ThingSpeak server.
    • So we are using two files, field1 and field2 for temperature and hall readings respectively.
    • You can use/enable more than two fields as per your requirements.

    Fig. 10: Enter the Details in Channel

    • Click o the save button to save the channel details.

    Fig. 11: Save the channel

    • After successfully saving the channel, a new window will open containing the channel details and Channel Stats.

    Fig. 12: Channel Stats

    • In the same window, go to API Keys which contains the Write API keys and Read API keys.
    • Copy the Write API key and paste this in ESP32 Arduino code to send the sensor values to ThingSpeak.
    • You can also customize the chart in Private View. Click on the icon present at the top-right menu of Field Chart (in red box) to edit the chart.
    • Edit the details as per your requirements and click on the save button to save the details.

    Fig. 13: Field Chart Edit

    Arduino Code

    We have already published a tutorial on the ESP32 hall sensor and internal temperature sensor.

    // ------style guard ----

    #ifdef __cplusplus

    extern "C"

    {

    #endif

    uint8_t temprature_sens_read();

    #ifdef __cplusplus

    }

    #endif

    uint8_t temprature_sens_read();

    // ------header files----

    #include <WiFi.h>

    #include "ThingSpeak.h"

    // -----netwrok credentials

    const char* ssid = "SSID"; // your network SSID (name)

    const char* password = "PASSWORD"; // your network password

    WiFiClient client;

    // -----ThingSpeak channel details

    unsigned long myChannelNumber = 1;

    const char * myWriteAPIKey = "API Key";

    // ----- Timer variables

    unsigned long lastTime = 0;

    unsigned long timerDelay = 1000;

    void setup()

    {

    Serial.begin(115200); // Initialize serial

    WiFi.mode(WIFI_STA);

    if(WiFi.status() != WL_CONNECTED)

    {

    Serial.print("Attempting to connect");

    while(WiFi.status() != WL_CONNECTED )

    {

    WiFi.begin(ssid, password);

    delay(1000);

    }

    Serial.println("\nConnected. ");

    }

    ThingSpeak.begin(client); // Initialize ThingSpeak

    }

    void loop()

    {

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

    {

    int hall_value = 0;

    float temperature = 0;

    hall_value = hallRead();

    // Get a new temperature reading

    temperature = ((temprature_sens_read()-32)/1.8 );

    Serial.print("Temperature (ºC): " );

    Serial.print(temperature);

    Serial.println("ºC" );

    Serial.print("Hall value:" );

    Serial.println(hall_value);

    ThingSpeak.setField(1, temperature );

    ThingSpeak.setField(2, hall_value );

     

    // Write to ThingSpeak. There are up to 8 fields in a channel, allowing you to store up to 8 different

    // pieces of information in a channel. Here, we write to field 1.

    int x = ThingSpeak.writeFields(myChannelNumber,

    myWriteAPIKey );

    if(x == 200)

    {

    Serial.println("Channel update successful." );

    }

    else

    {

    Serial.println("Problem updating channel. HTTP error code " + String(x) );

    }

    lastTime = millis();

    }

    }

    Code Description

    • Style guard is used at the beginning to declare some function to be of “C” linkage, instead of “C++” Basically, to allow C++ code to interface with C code.

    Fig. 14: Style Guard

    • Add the required header files.
    • We have already discussed above how to download and add the ThingSpeak library file to Arduino IDE.

    Fig. 15: Libraries

    • Enter the network credentials (SSID and Password).

    Fig. 16

    • A Wi-Fi client is created to connect with ThingSpeak.

    Fig. 17

    • Define timer variables.

    Fig. 18

    • Add the channel number and API (Write) Key. If you have created only one channel then the channel number will be ‘1’.

    Fig. 19

    Setup()

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

    Fig. 20

    • Set ESP32 Wi-Fi module in station mode using mode() function.
    • Enable ESP32’s Wi-Fi module using begin() function which is using SSID and password as arguments.
    • Wait until the ESP32 is not connected with the wifi network.

    Fig. 21

    • Initialize the ThingSpeak server using begin() function that is passing client (globally created) as an argument.

    Fig. 22

    Loop()

      • Inside the loop() function, define an integer type variable to store the hall sensor readings.

    Fig. 23

    • Define another float type variable to store temperature readings.

    Fig. 24

    • Call the hallRead() function to store the hall sensor readings into hall_value

    Fig. 25

    • Temperature_sens_read() function is used to read the temperature of ESP32 core.
    • Temperature observed by the internal temperature sensor is in Fahrenheit
    • o convert observed temperature i.e., in Fahrenheit into Celsius :

    (F-32) *(5/9) = degree Celsius

    Fig. 26

    • Print the temperature in degree Celsius and Hall sensor observations on serial moitor.

    Fig. 27

    • Set the number of fields you have created to the thingSpeak server. We are adding only two fields. You can add up to maximum of 8 fields for different readings.

    Fig. 28

    • writeFields() function is used to write data to the ThingSpeak server. This function is using the channel number and API key as an argument.

    Fig. 29

    • Return the code 200 if the sensor readings are successfully published to ThingSpeak server and print the respective results on the serial monitor.

    Fig. 30

    Testing

    • Connect the ESP32 module with your laptop using USB cable.
    • Select the right development board in Tools >> Boards >> DOIT ESP32 DevKit V1.
    • Compile and upload the code into ESP32 using Arduino IDE.
    • Make sure that you have entered the right Wi-Fi credentials, API key and channel number before uploading the code.
    • Open the ThingSpeak website where you have created a channel and check the sensor readings.
    • A screenshot of the field chart we have created is show below. Where you can see the temperature and hall sensor values on the chart.

    Fig. 31: ThingSpeak Channel Stats

     
    • To see the sensor values on Arduino IDE open the serial monitor with a 115200 baud rate.

    Fig. 32: Results on the Serial Monitor

     

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

    Significant Reasons for Investing in IoT Application Development

    We all have heard of this term by now. IoT or the Internet of Things is an ingenious yet innovative technology that is the support system for uncountable apps in almost all sectors.

    With the ever-increasing demand for higher technology, there has been a rapid growth in the field of IoT. You would require a professional IoT app development company for implementing the correct connected technology solution for your business.

    As we are moving towards and becoming the tech generation, it's exciting to know how IoT Application Development has a huge Market Potential - wondering how it is possible? Let us tell you more.

    Do You Know?

    Let us tell you a fun fact. Worldwide there are about 9 billion Internet of Things (IoT) devices connected in 2020, which is expected to grow up to 25 billion in 2030.

    In addition to this, we will also see a tremendous increase in the earnings & profit that would be generated by IoT and it is capturing all fields and sectors with speed equal to light and would soon become a major life-important technology.

    Still not convinced enough to invest in IoT Application Development? Well, let us help you!

    Why IoT Application Development? 

    Familiar with these above questions? Don't worry; we have got your back!

    The Internet of things has the potential to turn your home into a smart home and make processes automated. It's the world of 5G, and thus both IoT and 5G technologies, when combined, can result in super-advanced technologies and techniques. With each passing day, IoT Application Development services come to life and make more sense than previous days. IoT in the construction industry can boost work productivity and get access to real-time reporting. It can say that it covers almost every aspect!

    Facts to know about the upcoming IoT culture & Investments 

    • Speaking of May 2020, there was an investment of over $5 billion in IoT applications. This entire investment was made by 2,550 Europeans.
    • There has been a trend about smart home appliances. Following this, by the end of next year, i.e., 2023, everyday consumers are expected to spend $150 billion on smart home solutions.

    Key Factors to Capitalize and Put Funds in IoT App Development

    Not only are the ones listed above, but there are many reasons why companies invest in IoT Application development.

    1) Brings in Golden Opportunity for Start-ups:

    To all the Start-up owners, this is for you. IoT applications are the need of the hour because they solve inefficient, slow, and costly processes that many enterprises of different industries were bearing previously. Therefore, many prominent global companies acquire the start-ups for their ideas and promising innovations so that they can integrate them with their existing operation to get better work efficiency performance and increase the turnover while decreasing the cost.

    2) Enhanced work productivity and cost efficiency:

    IoT sensors and devices can automate various routine operations, making it possible to have minimum human participation. It also reduces the amount of time required to complete a task. Hence it makes the processes more productive and cost-efficient.

    3) Employees advantages:

    IoT makes things simple for employees too. It helps them perform complex tasks that might take long hours of effort and work to be completed in minutes. Some of the advantages are:

    • It provides real-time data for any emergencies.
    • It makes it possible for employees to act on any incidents as quickly as possible.
    • Improves work efficiency of employees and makes them less prone to make any mistakes.
    • Enables them to work remotely.

    4) Reduces Risk:

    IoT sensors can save you from significant breakdown risks. IoT sensors predict future equipment failures based on several factors.

    This helps the responsible personnel take care of the faulty spare parts without affecting the whole operation.

    And applying machine learning to collect data helps employees to determine the exact service time of each part of the machine that leads to efficiency in the investment of equipment.

    Process of IoT System development and application:

    • Ideation:  The process starts with your idea of the IoT product. Your vision must be as precise as possible to have a clear picture.
    • Pass it through the Market: Take your idea to your potential customers and get their feedback. See if your IoT product is actually feasible and needed.
    • Choose your Platform: Choose the stack technology on which your IoT product will be based.
    • Select the Hardware: Select the best hardware components that will fit your IoT product.
    • Make it scalable: The software you build for your IoT should be scalable and has the capability to support both on-premise and cloud infrastructure.
    • Speed of your IoT: Your product should be able to process data at high speed, especially if you're building an IoT for commercial purposes.
    • Privacy and Data Security: It is necessary that your IoT product is designed keeping in mind the privacy and data security of your users. Your customers will show trust in you only when they will feel like their information and data are safe with your IoT.
    • Test your final product: Before launching your IoT for the public, run numerous tests and have a pilot launch with limited people access to the app to make sure that there are no bugs.
    • Customer feedback: It is essential for the betterment of your IoT development and application that you get feedback from your customers regarding the app. Provide them with multiple channels to receive feedback,

    Key Takeaways

    Above, we have discussed the reasons to invest in IoT application and development and why big firms have ever-growing interests in IoT investment. IoT products and devices are becoming a vital part of every industry day by day, and soon they will become a necessity.

    Many IT companies offer IoT application development services that help businesses to gain real-time data and insights to analyze their areas of improvement and increase revenue by reducing their costs.

    So, if you are an IT start-up that is looking to revolutionize the industry, then all you need is to innovate an IoT product that solves industries' problems and delivers the results.

    ESP-NOW Protocol with ESP32 and ESP8266

    Hello readers, I hope you all are doing great. In this tutorial, we will learn about the ESP-NOW protocol and how to communicate data between two ESP modules through ESP-NOW protocol and that is too without Wi-Fi connectivity.

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

    What is ESP-NOW Protocol?

    Fig. 1: ESP-NOW Protocol

    ESP–NOW is a connectionless communication protocol that is used for sharing small data packets between two ESP boards. This protocol is developed by Espressif.

    Features of ESP-NOW Protocol:

    • It is a low-power wireless protocol, which makes two or more ESP devices communicate directly with each other without using Wi-Fi.
    • ESP-NOW protocol does not require a handshake for establishing a connection but, they require pairing and once the devices are paired they can exchange data.
    • ESP-NOW offers a persistent connection between ESP nodes. This means, once two ESP nodes are connected with each other (wirelessly) and suddenly one of the ESP devices loses power or restarted, the device will again (automatically) establish a connection with the other node to which it was connected before the power reset.
    • ESP- NOW protocol offers encrypted communication and hence, it is a secure method of wireless communication.
    • To check the success and failure of message delivery a callback function is used to send the information regarding the communication status. Before initializing the ESP-NOW, we need to enable the Wi-Fi for wireless connectivity but it is now required to connect the ESP devices with the internet.

    ESP-NOW Protocol Limitations:

    • This protocol is only supported by ESP devices.
    • Only 10 (maximum) encrypted peers are supported in station mode and a maximum of 6 devices in access point mode.
    • The maximum payload size supported by ESP-NOW protocol is 250 bytes only.

    Although, ESP-NOW protocol can communicate only small data packets ( maximum 250 bytes), but it is a high-speed protocol for wireless communication.

    ESP devices can communicate over ESP-NOW protocol in different network topologies which makes it a very versatile protocol. The communication can be a point to point or point to multipoint (broadcast).

    Different Scenarios in Which ESP Devices Can Communicate

    Peer to peer or one to one communication

    Fig. 2: Point to Point Communication

    In peer-to-peer communication, only two ESP (either ESP32 or ESP8266) devices can connect with each other for data exchange. Each ESP device can act as a master device, a slave device or both master and slave at the same time.

    Broadcast or one to many (master and slave)

    Fig. 3: ESP32 Broadcasting with ESP-NOW protocol

    In broadcast one ESP device (known as a broadcaster) act as a master device and broadcast the data to ESP devices acting as slave devices. Data is shared with all the slave devices simultaneously.

    This communication method is used when users want to control multiple slave devices at a time.

    Many to one. (Gateway)

    Fig. 4: Many to One Communication

    In many to one communication scenarios, there will be a central node or gateway which collects all the data from its nearby connected ESP devices.

    This scenario can be applied when you need to collect sensor data from various sensor nodes to a single collector or central device, which is connected to all the nearby sensors.

    Application of ESP-NOW Protocol

    • ESP-NOW protocol is used when users need to communicate data between two or more ESP devices without using a Wi-Fi router (whether it is ESP32 or ESP8266).
    • This protocol can be used for industrial or residential automation applications. Where we need to transmit small data or instructions like to turn ON and OFF equipment without using Wi-Fi. For example smart lights, sensors, remote control devices etc.

    MAC Address to Identify The Receiver

    MAC address or Media Access Control address is a six-byte hexadecimal address, that is used to track or connect with devices in a network. It provides the user with a secure way to identify senders and receivers in a network and avoid unwanted network access.

    Fig. 5: MAC Address

    Each ESP device has a unique MAC address.

    So, before sharing the data between two or more ESP devices the MAC address of the receiver device should be known to the sender device.

    Implementing ESP-NOW protocol with ESP32 in Arduino IDE

    Both, the ESP32 and ESP8266 modules support the ESP-NOW protocol.

    In this tutorial, we will connect the ESP32 and ESP8266 using the ESP-NOW protocol.

    • We are using Arduino IDE as a compiler and upload 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.

    Fig. 6: ESP-NOW Example Code in Arduino IDE

    Library file Required to implement ESP-NOW Protocol:

    • Download the library from the given link: https://github.com/yoursunny/WifiEspNow
    • In this example, we are using two ESP devices where one is ESP32 and another is ESP8266.
    • We will make ESP32 to act as a Master device and ESp8266 as slave device.

    Sender (ESP32) Source Code

    #include <esp_now.h>

    #include <WiFi.h>

    // REPLACE WITH YOUR RECEIVER MAC Address

    uint8_t broadcastAddress[] = {0xEE, 0xFA, 0xBC, 0xC5, 0xA4, 0xBF};

    typedef struct struct_message {

    char a[32];

    int b;

    float c;

    bool d;

    } struct_message;

    // Create a struct_message called myData

    struct_message myData;

    // callback when data is sent

    void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {

    Serial.print("\r\nLast Packet Send Status:\t");

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

    }

    void setup() {

    // Init Serial Monitor

    Serial.begin(115200);

    // Set device as a Wi-Fi Station

    WiFi.mode(WIFI_STA);

    // Init ESP-NOW

    if (esp_now_init() != ESP_OK) {

    Serial.println("Error initializing ESP-NOW");

    return;

    }

    // get the status of Trasnmitted packet

    esp_now_register_send_cb(OnDataSent);

    // Register peer

    esp_now_peer_info_t peerInfo;

    memcpy(peerInfo.peer_addr, broadcastAddress, 6);

    peerInfo.channel = 0;

    peerInfo.encrypt = false;

    // Add peer

    if (esp_now_add_peer(&peerInfo) != ESP_OK){

    Serial.println("Failed to add peer");

    return;

    }

    }

    void loop()

    { strcpy(myData.a, "THIS IS A CHAR");   // Send message via ESP-NOW esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));   if (result == ESP_OK) { Serial.println("Sent with success"); } else { Serial.println("Error sending the data"); } delay(2000); }

    Code Description

    • The first step is including the required libraries or header files.

    Fig. 7: Library Files

    • Replace the string with the MAC address of the receiver ESP device.

    Fig. 8: MAC Address

    • The next step is creating a structure that contains the type of data you want to share with the receiver node or device. We are using four different data variables which include char, int, float, and bool. You can the data type according to your requirements.

    Fig. 9: Variables

    • Create a variable of struct_message type to store the variable values. We created myData

    Fig.10

    • onDataSent() function is a callback function which will be executed when a message is sent. This function will print a string on serial monitor to show that the message is successfully sent.

    Fig. 11

    Setup()

      • Inside the setup function, the first task is the usual one i.e., initializing the serial monitor for debugging purpose.
      • Set the ESP device in STA mode or in Wi-Fi station mode before initializing ESP-NOW.

    Fig. 12: Serial monitor and Wi-Fi Initialization

    • Next step is, initializing ESP-NOW.

    Fig. 13

    • A callback function is registered which will be called when a message is send (after initializing the ESP-NOW successfully).

    Fig. 14

    • The next thing is pairing with another ESP-NOW device to communicate data.

    Fig. 15: Pairing with the ESP8266 Receiver

    • esp_now_add_peer () function is used to pair with the receiver.
    • This function is passing a parameter called This parameter contains the MAC address of the receiver (ESP8266) to which the sender want to connect and communicate data.
    • If somehow the sender is not able to pair with the receiver ESP device, the result will be printed on the serial monitor.

    Fig. 16

    Loop()

    • In the loop() function, the message will be sent.
    • We have globally declared a structure variable myData.
    • In the loop function values or message that we want to share with the receiver ESP device (ESP8266) is assigned to the variables.

    Fig. 17: Data to Be Shared

    • If the ESP32 (or sender) is successfully connected/paired with the receiver (ESP8266) send the message and once the message is sent, print the result on the Serial monitor.

    Fig. 18

    • Esp_now_send() function is used to send data to receiver (i.e., ESP8266) over ESP-NOW protocol.
    • This function is passing two parameters. First is the broadcastAddress i.e. the MAC address of the receiver and another is the data stored in the variables.

    Fig. 19: Send The Message

    • If there is some error in message sending then print the respective details on the serial monitor.
    • The next message will be sent with a delay of 2 sec (or 2000ms).

    Fig. 20

    ESP8266 (Receiver) Code

    #include <WifiEspNow.h>

    #if defined(ARDUINO_ARCH_ESP8266)

    #include <ESP8266WiFi.h>

    #elif defined(ARDUINO_ARCH_ESP32)

    #include <WiFi.h>

    #endif

    // The recipient MAC address. It must be modified for each device.

    static uint8_t PEER[]{0x02, 0x00, 0x00, 0x45, 0x53, 0x50};

    void printReceivedMessage(const uint8_t mac[WIFIESPNOW_ALEN],

    const uint8_t* buf, size_t count, void* arg)

    {

    Serial.printf("Message from %02X:%02X:%02X:%02X:%02X:%02X\n", mac[0], mac[1], mac[2], mac[3],

    mac[4], mac[5]);

    for (int i = 0; i < static_cast<int>(count); ++i) {

    Serial.print(static_cast<char>(buf[i]));

    }

    Serial.println();

    }

     

    void setup()

    {

    Serial.begin(115200);

    Serial.println();

    WiFi.persistent(false);

    WiFi.mode(WIFI_AP);

    WiFi.disconnect();

    WiFi.softAP("ESPNOW", nullptr, 3);

    WiFi.softAPdisconnect(false);

    Serial.print("MAC address of this node is ");

    Serial.println(WiFi.softAPmacAddress());

    uint8_t mac[6];

    WiFi.softAPmacAddress(mac);

    Serial.println();

    Serial.println("You can paste the following into the program for the other device:");

    Serial.printf("static uint8_t PEER[]{0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X};\n", mac[0],

    mac[1], mac[2], mac[3], mac[4], mac[5]);

    Serial.println();

    bool ok = WifiEspNow.begin();

    if (!ok) {

    Serial.println("WifiEspNow.begin() failed");

    ESP.restart();

    }

    WifiEspNow.onReceive(printReceivedMessage, nullptr);

    ok = WifiEspNow.addPeer(PEER);

    if (!ok) {

    Serial.println("WifiEspNow.addPeer() failed");

    ESP.restart();

    }

    }

    loop()

    {

    char msg[60];

    int len = snprintf(msg, sizeof(msg), "hello ESP-NOW from %s at %lu",

    WiFi.softAPmacAddress().c_str(), millis());

    WifiEspNow.send(PEER, reinterpret_cast<const uint8_t*>(msg), len);

    delay(1000);

    }

    Code Description

    • This code can be used for both ESP8266 as well as ESP32 receivers.
    • The first task is adding the required libraries.
    • h is for enabling wireless connectivity in ESP8266 and WiFi.h is for ESP32 module (if you are using this device).
    • h is to enable the ESP-NOW protocol and its respective function is the ESP device.

    Fig. 21: Header files in Receiver Code

    • printReceivedMessay() function is used to fetch the message details transmitted by ESP32 (sender node), and the MAC address of the transmitter.
    • If you are receiving data from multiple sender nodes then a unique MAC address will be fetched from multiple sender nodes along with the message received.

    Fig. 22

    Setup()

    • Initialize the serial monitor with a 115200 baud rate for debugging purposes.
    • Wi-Fi should be enabled to implement the ESP-NOW protocol and wireless connectivity. It could be either AP or STA mode and does not require to be connected.

    Fig. 23: Serial Monitor Wi-Fi Initialization

    • Print the MAC address of the sender on the serial monitor.

    Fig. 24

    • Initialize the ESP-NOW using begin() function.
    • If somehow the ESP device is unable to initialize the ESP then print the respective details on the serial monitor.

    Fig. 25

    • Once ESP-NOW and Wi-Fi are successfully initialized, the ESP receiver (ESP8266) is ready to receive the data packets from sender.

    Fig. 26

    • Testing (Receiving a message in ESP8266 from ESP32 )
    • Select the ESP8266 development board you are using in Arduino IDE.
    • For that, go to Tools >> Boards and select the right development board.
    • We are using the ESP8266 Generic module as shown below:

    Fig. 27: Selecting The ESP 8266 Development Board

    • Upload the Receiver code in the ESP8266 module.
    • Open the serial monitor with a baud rate of 115200.
    • Press the reset (Rst) button from the ESP8266 development board.
    • MAC address of the receiver will be printed on the serial monitor as shown below:

    Fig. 28: MAC Address of Receiver

    • Copy the MAC address of the receiver and paste into the sender (ESP32) code.
    • Again change the development board from ESP8266 to ESP32.

    Fig. 29: Selecting ESP32 Board in Arduino IDE

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

    Fig. 30: Message Sent

    • If you want to read the data received at ESP8266, remove the ESP32 and power it with a different power source.
    • Connected the ESP8266 with a laptop.
    • Again select the ESP8266 development board on Arduino IDE’s Tools >> Boards
    • Open the serial monitor with a 115200 baud rate.
    • Press the reset (RST) button from the ESP8266 developments board.
    • Results are shown below:

    Fig. 31: Message Received

    This concludes the tutorial. I hope, you found this helpful and I hope to see you soon for the new ESP32 tutorial.

    ESP32 Internal Temperature Sensor

    Hello friends, I hope you all are doing great. Welcome to the 3rd lecture of Section 5(ESP32 Sensors) in the ESP32 Programming Series. We have already discussed the two built-in ESP32 sensors i.e. Hall Effect Sensor and Capacitive Touch Sensor. Today, we are going to discuss the 3rd and final built-in ESP32 sensor i.e. Internal Temperature Sensor.

    ESP32 Internal Temperature Sensor is used to calculate the temperature of the ESP32 core. So, we can't use it to measure the ambient temperature (the temperature of the atmosphere), for that, we need to use embedded temperature sensors i.e. DS18B20, DHT11, BMP280 etc. We will first discuss the basics of this Internal Temperature Sensor and then will design a code to monitor the change in temperature by changing the frequency of the ESP32 CPU.

    Note:

    • Internal Temperature Sensor is not present in all ESP32 variants.
    • So, if ESP32 lacks the sensor, it sends an invalid temperature reading of 53.33oC(equivalent to 128 in decimal).

    Important specs of the ESP32 Temperature Sensor are given in the below table:

    ESP32 Temperature Sensor Features
    Parameter Value
    Converter Types ADC (Analog-to-Digital Converter), DAC (Digital-to-Analog Converter)
    Accurate Temperature Sensing Range -40 °C to 125 °C
    Suitability Good
    Most Accurate Range -10 °C to 80 °C
    Temperature Fluctuation Measurement High resolution
    Potential Performance & Accuracy Issues Voltage fluctuations, Noise, Environmental factors, Nearby heat sources
    Where To Buy?
    No.ComponentsDistributorLink To Buy
    1ESP32AmazonBuy Now

    ESP32 Internal Temperature Sensor

    ESP32’s on-chip temperature sensor cannot be used for monitoring external temperature. It can only be used to monitor the temperature of the core. This temperature sensor is available on some selective ESP32 boards and obsolete on most ESP32 variants. It has a high-temperature sensing range of -40 to 125 °C.

    ESP32 boards are normally used in real-time IoT Projects i.e. home automation, back security etc. Such projects need to run 24/7 to get live updates and may heat up the motherboard. Thus, to get a stable performance in continuous operations, these internal temperature sensors are introduced to monitor the ESP32 Core.

    ESP32 Boards with Built-in Temperature Sensor

    Most of the modern ESP32 variants are equipped with the Internal Temperature Sensor. I have created a list of the ESP32 boards by taking the ESP-IDF documentation that caters to the built-in temperature sensor. Here's the list:

    • ESP32-C2
    • ESP32-C3
    • ESP32-C6
    • ESP32-H2
    • ESP32-S2
    • ESP32-S3

    As you can see, most of the newer versions have a temperature sensor, but some older versions may also have one.

    How does this temperature sensor work?

    ESP32 temperature sensor consists of 2 converters:

    1. 8-bit Sigma-Delta analog-to-digital converter(ADC)
    2. digital-to-analog converter(DAC)

    8-bit Sigma-Delta analog-to-digital converter (ADC)

    Sigma-delta ADCs are widely favored for their exceptional accuracy and remarkable resolution, enabling them to deliver precise measurements. This ADC takes the analog signal from the temperature sensor, converts it to a digital signal and feeds it to the microcontroller for processing.

    Digital-to-analog converter (DAC)

    The DAC is responsible for the accuracy of the temperature measurements. It is embedded within the ESP32 and converts the digital values(converted by the Sigma-Delta ADC) again into analog values to offset any temperature-induced variation. As a result, it ensures accurate readings from the sensor.

    Measuring Errors in Temperature Sensor

    The accuracy of this temperature sensor changes according to the range group of the temperature values. Among different groups, the range of -10 ~ 80 is the most accurate. The reading errors along with their measuring ranges are shown in the below table:

    Measuring Errors in ESP32 Temperature Sensor
    No. Offset Predefined Range (°C) Error (°C) Operating Range (°C)
    1 -2
    50 ~ 125 < 3 Not recommended(Error)
    2
    -1
    20 ~ 100 < 2 Ideal range for best accuracy
    3
    0 -10 ~ 80 < 1 Acceptable range with moderate accuracy
    4
    1
    -30 ~ 50 < 2 Usable range with increased error at extremes
    5
    2
    -40 ~ 20 < 3 Not recommended (error)

    Different factors, including voltage fluctuations, noise, environmental factors, and nearby heat sources, can affect the performance and accuracy of this sensor.

    Formula to convert observed temperature i.e. Fahrenheit to Celsius:

    (F-32) *(5/9) = degree Celsius

    ESP32 Temperature Sensor Applications

    Here are the main applications of the ESP32 built-in temperature sensor:

    Improve Chip Performance

    A designer can easily monitor the internal chip’s temperature through the temperature sensor, identify bottleneck conditions, and conduct performance evaluations under extreme circumstances. So, the sensor helps in optimizing the chip's temperature and, thus, the performance.

    Avoid Overheating

    Electronic components/modules are sensitive, and if they are designed to work for prolonged operation, temperature management is one of the most crucial points to be considered. The built-in temperature sensor is a useful way to measure the operating temperature of the components connected to its peripherals and the whole system. These values are then utilized to set the threshold value so the system can trigger the safety mechanism when a certain heat level is passed. This can be done using the ESP32 code and surely prevent overheating to maintain the performance.

    Energy Monitoring

    The built-in temperature sensor helps to maintain the energy monitoring that, in turn, allows the energy monitoring of the project. The careful observation of the built-in temperature sensor output helps the user understand the relationship between temperature change and energy consumption. Using this approach, designers can target an optimized energy consumption.

    Programming ESP32 to measure Core temperature in Arduino IDE

    • We are using the Arduino IDE as a compiler, we have already installed ESP32 in it, if you haven't, please read out How to Install ESP32 in Arduino IDE.
    #ifdef __cplusplus
    extern "C" {
        #endif
        uint8_t temprature_sens_read();
        #ifdef __cplusplus
    }
    #endif
    uint8_t temprature_sens_read();
    
    void setup()
    {
        Serial.begin(115200);
    }
    
    void loop()
    {
        Serial.print("Temperature: ");
        Serial.print(temprature_sens_read() );
        Serial.print(" F");
        Serial.print("______");
    
        // Convert raw temperature in F to Celsius degrees
        Serial.print((temprature_sens_read() - 32) / 1.8);
        Serial.println(" C");
        delay(1000);
    }

    Code Description

    • Style guard is used at the beginning to declare some function to be of “C” linkage, instead of “C++” Basically, to allow C++ code to interface with C code.
    #ifdef __cplusplus
    extern "C" {
        #endif
        uint8_t temprature_sens_read();
        #ifdef __cplusplus
    }
    #endif
    uint8_t temprature_sens_read();

    Setup() Function

    • Initialize the Serial monitor with a 115200 baud rate for debugging purposes.
    void setup()
    {
        Serial.begin(115200);
    }

    Loop() Function

    • Temperature_sens_read() function is used to read the temperature of the core.
    • Print the observer temperature on the serial monitor.
    void loop()
    {
        Serial.print("Temperature: ");
        Serial.print(temprature_sens_read() );
        Serial.print("______");
    }
    • Convert the temperature from Fahrenheit to degrees Celsius and print on the serial monitor.
    • The result will be printed with a delay of 1 sec.
    // Convert raw temperature in F to Celsius degrees
        Serial.print((temprature_sens_read() - 32) / 1.8);
        Serial.println(" C");
        delay(1000);

    Testing/Results

    • Upload the code into the ESP32 board.
    • Open the serial monitor with a 115200 baud rate.
    • Press the EN button from the ESP32 development board.
    • See the result on the serial monitor as shown below:

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

    Receiving Emails with ESP32 using IMAP Server

    Hello readers, I hope you all are doing great. In our previous tutorial, we learned SMTP server and how to implement an SMTP server for sending emails with ESP32. In the previous tutorial, we also demonstrated some examples like sharing raw text, HTML text, images and text files.

    So, at the transmitter end, we are using the SMTP server.

    But, what about the receiver end?

    At the receiver end, we use another protocol called IMAP (or Internet Message Access Protocol) and POP3 (Post office Protocol V3) for receiving the emails.

    Fig. IMAP and SMTP

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

    What is IMAP Protocol and How does it Work?

    IMAP is an application layer (TCP/IP) protocol that is used at the receiver end to receive emails from SMTP server or mail server. IMAP follows the client/server model.

    Fig. IMAP Protocol

    Features of IMAP protocol:

    • IMAP can operate in three modes:
      1. Online mode
      2. Offline mode
      3. Disconnected mode
    • IMAP uses two ports:
      1. 143 Port – Communication over this port is not secure because this is a non-encrypted IMAP port.
      2. 993 Port – Communication over this port is secure and it is used when the client (IMAP) wants to connect securely through IMAP.
    • Users can access emails from a remote server without deleting the emails from the email server.
    • Setting message flag – The message flag is set to help the user in keeping the track of which message has already been seen.
    • Receivers can create a folder to organize mails in the hierarchy.
    • Users can also download a portion of a message from the mime-multi part in case of large multimedia files.
    • Organizing mail on the server.
    • Check email header – user can check the email header before downloading the mail.

    What is POP3?

    POP3 stands for Post Office Protocol version 3.

    POP3 is another protocol to receive emails. This protocol is used to access the TCP/IP mailbox. The protocol is quite popular due to its offline mail access model.

    The offline access model enables the user to access the mails from the mail server on the local machine, and then delete them from the mail server.

    Why IMAP is Preferred over the POP3?

    • Being an offline access model, POP3 is not suitable for the ideal world. The biggest drawback of the POP3 model is that emails are permanently deleted from the server, and is it not possible to access the mails in different computers.
    • In POP3 user is not allowed to manage the mails on the server whilst in IMAP protocol the user can delete, create or rename the mails on the server.
    • Another drawback of the protocol is data security and safety.
    • So, a new protocol is developed to overcome the drawback of the POP3 protocol. The protocol was named Internet Message Access Protocol or IMAP. Which is an online protocol and mails received via IMAP protocol can be accessed on different computers.

    Though in some applications POP3 protocol is still used, but in most of the email receivers, it is preferred to use IMAP protocol over POP3 protocol.

    Setting parameters for different IMAP service provider

    IMAP (incoming) setting parameter for Gmail

    • IMAP Server address – imap.gmail.com
    • IMAP username – xyz@gmail.com
    • IMAP password – password
    • IMAP port – 993

    IMAP (incoming) setting parameters for Yahoo

    • IMAP Server address – mail.yahoo.com
    • IMAP username – xyz@yahoo.com
    • IMAP password – password
    • IMAP port – 993
    • SSL required – Yes

    Similarly, other email service providers like Outlook and Hotmail, have different setting parameters.

    • Components required to send and receive emails using ESP32 over SMTP server are:
    • Recipient’s email address.
    • Sender’s email address.
    • Content to be shared over SMTP server.
    • ESP mail client library.
    • ESP32 module.

    ESP mail client Library

    To send emails with ESP32 we need to install this ESP Mail Client library. This library, make ESP32 able to send emails over SMTP server.

    Step to install ESP Mail Client Library:

    • To download the ESP Mail Client Library click on the link: https://github.com/mobizt/ESP-Mail-Client
    • Open the Arduino IDE.
    • Go to Sketch >> Include Library >> Add .ZIP Library.
    • Select the downloaded ZIP file.
    • Click on

    Your Arduino IDE is ready to send email using ESP32.

    Create a new Gmail account

    It is recommended to create a new email account for sending emails using ESP32 or ESP8266 modules.

    If you are using your main (personal) email account (for sending emails) with ESP and by mistake, something goes wrong in the ESP code or programming part, your email service provider can ban or disable your main (personal) email account.

    In this tutorial, we are using a Gmail account.

    Follow the link to create a new Gmail account: https://accounts.google.com

    Access to Less Secure apps

    To get access to this new Gmail account, you need to enable Allow less secure apps and this will make you able to send emails. The link is attached below:

    https://myaccount.google.com/lesssecureapps?pli=1

    Fig.

    Arduino IDE Code, for configuring IMAP Protocol in ESP32

    • As we mentioned earlier, we are using Arduino IDE as a compiler and upload into ESP32 module. To know more about Arduino IDE and how to use it, follow our previous tutorial i.e., on the ESP32 programming series.
    • We have already discussed installing the ESP Mail Client Library to make ESP32 able to send emails over the SMTP server.
    • This library includes multiple examples on SMTP like sending text messages, images, HTML code, text files etc. We have attached an image below for your reference.
    • You can use those examples to send emails.

    Fig IMAP and SMTP Example Code

    Note: You can not use the exact code. Hence, you need to make some changes like replacing SSID and password with your network credentials, email address of sender and receiver, setting IMAP and SMTP parameters for respective email service providers etc, needs to be done before uploading the code. We will also describe these things during code description.

    ESP32 IMAP Code

    In this code, we will implement both IMAP and SMTP protocols to receive and transmit emails.

    Although, we are using SMTP in this tutorial, but we have already discussed and demonstrated the implementation on SMTP protocol in our previous tutorial. So, in this tutorial we will not explain the SMTP part.

    Follow our previous tutorial for detailed study of SMTP implementation in ESP32.

    #include <Arduino.h>

    #include <WiFi.h>

    #include <ESP_Mail_Client.h>

    //To use only IMAP functions, you can exclude the SMTP from compilation, see ESP_Mail_FS.h.

    #define WIFI_SSID "public"

    #define WIFI_PASSWORD "ESP32@123"

    //-----------setting IMAP parameters------

    /* The imap host name e.g. imap.gmail.com for GMail or outlook.office365.com for Outlook */

    #define IMAP_HOST "imap.gmail.com"

    #define IMAP_PORT 993

    #define AUTHOR_EMAIL "techeesp697@gmail.com"

    #define AUTHOR_PASSWORD "Tech@ESP123"

    #define RECIPIENT_EMAIL "maneesha607ece@gmail.com"

    //------------setting SMTP credentials----------

    #define SMTP_HOST "smtp.gmail.com"

    #define SMTP_PORT 465

    //------IMAP Rx emails and their status

    /* Callback function to get the Email reading status */

    void imapCallback(IMAP_Status status);

    void printAllMailboxesInfo(IMAPSession &imap);

    void printSelectedMailboxInfo(SelectedFolderInfo sFolder);

    void printMessages(std::vector<IMAP_MSG_Item> &msgItems, bool headerOnly);

    /* Print all attachments info from the message */

    void printAttacements(std::vector<IMAP_Attach_Item> &atts);

    /* The IMAP Session object used for Email reading */

    IMAPSession imap;

    //-------SMTP sending mails and their status----

    /* The SMTP Session object used for Email sending */

    SMTPSession smtp;

    /* Callback function to get the Email sending status */

    void smtpCallback(SMTP_Status status);

     

    void setup()

    {

    Serial.begin(115200);

    #if defined(ARDUINO_ARCH_SAMD)

    while (!Serial)

    ;

    Serial.println();

    Serial.println("**** Custom built WiFiNINA firmware need to be installed.****\nTo install firmware, read the instruction here, https://github.com/mobizt/ESP-Mail-Client#install-custom-built-wifinina-firmware");

    #endif

    Serial.println();

    Serial.print("Connecting to AP");

    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

    while (WiFi.status() != WL_CONNECTED)

    {

    Serial.print(".");

    delay(200);

    }

    Serial.println("");

    Serial.println("WiFi connected.");

    Serial.println("IP address: ");

    Serial.println(WiFi.localIP());

    Serial.println();

    /** Enable the debug via Serial port

    * none debug or 0

    * basic debug or 1

    *

    * Debug port can be changed via ESP_MAIL_DEFAULT_DEBUG_PORT in ESP_Mail_FS.h

    */

    imap.debug(1);

    /* Set the callback function to get the reading results */

    imap.callback(imapCallback);

    ESP_Mail_Session session;

    session.server.host_name = IMAP_HOST;

    session.server.port = IMAP_PORT;

    session.login.email = AUTHOR_EMAIL;

    session.login.password = AUTHOR_PASSWORD;

    /* Setup the configuration for searching or fetching operation and its result */

    IMAP_Config config;

    /* Set seen flag */

    //config.fetch.set_seen = true;

    /* Search criteria */

    config.search.criteria.clear();

    /* Also search the unseen message */

    config.search.unseen_msg = true;

    /* Set the storage to save the downloaded files and attachments */

    config.storage.saved_path = "/email_data";

    config.storage.type = esp_mail_file_storage_type_flash;

     

    config.download.header = true;

    config.download.text = true;

    config.download.html = true;

    config.download.attachment = true;

    config.download.inlineImg = true;

    config.enable.html = true;

    config.enable.text = true;

    /* Set to enable the sort the result by message UID in the ascending order */

    config.enable.recent_sort = true;

    /* Set to report the download progress via the default serial port */

    config.enable.download_status = true;

    config.limit.search = 5;

    config.limit.msg_size = 512;

    config.limit.attachment_size = 1024 * 1024 * 5;

    /* Connect to server with the session and config */

    if (!imap.connect(&session, &config))

    return;

    /* {Optional} */

    printAllMailboxesInfo(imap);

    /* Open or select the mailbox folder to read or search the message */

    if (!imap.selectFolder("INBOX"))

    return;

    /* {Optional} */

    printSelectedMailboxInfo(imap.selectedFolder());

    String uid = String(imap.getUID(imap.selectedFolder().msgCount()));

    config.fetch.uid = uid;

    /* Read or search the Email and close the session */

    //When message was fetched or read, the /Seen flag will not set or message remained in unseen or unread status,

    //as this is the purpose of library (not UI application), user can set the message status as read by set \Seen flag

    //to message, see the Set_Flags.ino example.

    MailClient.readMail(&imap);

    /* Clear all stored data in IMAPSession object */

    imap.empty();

    }

    void loop()

    {

    }

    /* Callback function to get the Email reading status */

    void imapCallback(IMAP_Status status)

    {

    /* Print the current status */

    Serial.println(status.info());

    /* Show the result when reading finished */

    if (status.success())

    {

    /* Print the result */

    /* Get the message list from the message list data */

    IMAP_MSG_List msgList = imap.data();

    printMessages(msgList.msgItems, imap.headerOnly());

    /* Clear all stored data in IMAPSession object */

    imap.empty();

    SMTP_MSG();

    }

    }

    void printAllMailboxesInfo(IMAPSession &imap)

    {

    /* Declare the folder collection class to get the list of mailbox folders */

    FoldersCollection folders;

    /* Get the mailbox folders */

    if (imap.getFolders(folders))

    {

    for (size_t i = 0; i < folders.size(); i++)

    {

    /* Iterate each folder info using the folder info item data */

    FolderInfo folderInfo = folders.info(i);

    ESP_MAIL_PRINTF("%s%s%s", i == 0 ? "\nAvailable folders: " : ", ", folderInfo.name, i == folders.size() - 1 ? "\n" : "");

    }

    }

    }

    void printSelectedMailboxInfo(SelectedFolderInfo sFolder)

    {

    /* Show the mailbox info */

    ESP_MAIL_PRINTF("\nInfo of the selected folder\nTotal Messages: %d\n", sFolder.msgCount());

    ESP_MAIL_PRINTF("Predicted next UID: %d\n", sFolder.nextUID());

    for (size_t i = 0; i < sFolder.flagCount(); i++)

    ESP_MAIL_PRINTF("%s%s%s", i == 0 ? "Flags: " : ", ", sFolder.flag(i).c_str(), i == sFolder.flagCount() - 1 ? "\n" : "");

    }

    void printAttacements(std::vector<IMAP_Attach_Item> &atts)

    {

    ESP_MAIL_PRINTF("Attachment: %d file(s)\n****************************\n", atts.size());

    for (size_t j = 0; j < atts.size(); j++)

    {

    IMAP_Attach_Item att = atts[j];

    /** att.type can be

    * esp_mail_att_type_none or 0

    * esp_mail_att_type_attachment or 1

    * esp_mail_att_type_inline or 2

    */

    ESP_MAIL_PRINTF("%d. Filename: %s, Name: %s, Size: %d, MIME: %s, Type: %s, Creation Date: %s\n", j + 1, att.filename, att.name, att.size, att.mime, att.type == esp_mail_att_type_attachment ? "attachment" : "inline", att.creationDate);

    }

    Serial.println();

    }

    void printMessages(std::vector<IMAP_MSG_Item> &msgItems, bool headerOnly)

    {

    for (size_t i = 0; i < msgItems.size(); i++)

    {

    /* Iterate to get each message data through the message item data */

    IMAP_MSG_Item msg = msgItems[i];

     

    Serial.println("****************************");

    ESP_MAIL_PRINTF("Number: %d\n", msg.msgNo);

    ESP_MAIL_PRINTF("UID: %d\n", msg.UID);

    ESP_MAIL_PRINTF("Messsage-ID: %s\n", msg.ID);

    ESP_MAIL_PRINTF("Flags: %s\n", msg.flags);

    //The attachment may not detect in search because the multipart/mixed

    //was not found in Content-Type header field.

    ESP_MAIL_PRINTF("Attachment: %s\n", msg.hasAttachment ? "yes" : "no");

    if (strlen(msg.acceptLang))

    ESP_MAIL_PRINTF("Accept Language: %s\n", msg.acceptLang);

    if (strlen(msg.contentLang))

    ESP_MAIL_PRINTF("Content Language: %s\n", msg.contentLang);

    if (strlen(msg.from))

    ESP_MAIL_PRINTF("From: %s\n", msg.from);

    if (strlen(msg.sender))

    ESP_MAIL_PRINTF("Sender: %s\n", msg.sender);

    if (strlen(msg.to))

    ESP_MAIL_PRINTF("To: %s\n", msg.to);

    if (strlen(msg.cc))

    ESP_MAIL_PRINTF("CC: %s\n", msg.cc);

    if (strlen(msg.date))

    {

    ESP_MAIL_PRINTF("Date: %s\n", msg.date);

    ESP_MAIL_PRINTF("Timestamp: %d\n", (int)MailClient.Time.getTimestamp(msg.date));

    }

    if (strlen(msg.subject))

    ESP_MAIL_PRINTF("Subject: %s\n", msg.subject);

    if (strlen(msg.reply_to))

    ESP_MAIL_PRINTF("Reply-To: %s\n", msg.reply_to);

    if (strlen(msg.return_path))

    ESP_MAIL_PRINTF("Return-Path: %s\n", msg.return_path);

    if (strlen(msg.in_reply_to))

    ESP_MAIL_PRINTF("In-Reply-To: %s\n", msg.in_reply_to);

    if (strlen(msg.references))

    ESP_MAIL_PRINTF("References: %s\n", msg.references);

    if (strlen(msg.comments))

    ESP_MAIL_PRINTF("Comments: %s\n", msg.comments);

    if (strlen(msg.keywords))

    ESP_MAIL_PRINTF("Keywords: %s\n", msg.keywords);

    /* If the result contains the message info (Fetch mode) */

    if (!headerOnly)

    {

    if (strlen(msg.text.content))

    ESP_MAIL_PRINTF("Text Message: %s\n", msg.text.content);

    if (strlen(msg.text.charSet))

    ESP_MAIL_PRINTF("Text Message Charset: %s\n", msg.text.charSet);

    if (strlen(msg.text.transfer_encoding))

    ESP_MAIL_PRINTF("Text Message Transfer Encoding: %s\n", msg.text.transfer_encoding);

    if (strlen(msg.html.content))

    ESP_MAIL_PRINTF("HTML Message: %s\n", msg.html.content);

    if (strlen(msg.html.charSet))

    ESP_MAIL_PRINTF("HTML Message Charset: %s\n", msg.html.charSet);

    if (strlen(msg.html.transfer_encoding))

    ESP_MAIL_PRINTF("HTML Message Transfer Encoding: %s\n\n", msg.html.transfer_encoding);

    if (msg.rfc822.size() > 0)

    {

    ESP_MAIL_PRINTF("RFC822 Messages: %d message(s)\n****************************\n", msg.rfc822.size());

    printMessages(msg.rfc822, headerOnly);

    }

    }

    Serial.println();

    }

    }

    void SMTP_MSG()

    {

    smtp.debug(1);

    smtp.callback(smtpCallback);

    ESP_Mail_Session session;

    session.server.host_name = SMTP_HOST;

    session.server.port = SMTP_PORT;

    session.login.email = AUTHOR_EMAIL;

    session.login.password = AUTHOR_PASSWORD;

    session.login.user_domain = "";

    /* Declare the message class */

    SMTP_Message message;

    message.sender.name = "The_Engineering_Projects";

    message.sender.email = AUTHOR_EMAIL;

    message.subject = "Auto_Response";

    message.addRecipient("Maneesha", RECIPIENT_EMAIL);

    //Send raw text message

    String textMsg = "Thanks for contacting us. One of our client will contact you soon. www.theengineeringprojects";

    message.text.content = textMsg.c_str();

    message.text.charSet = "us-ascii";

    message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;

    message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;

    message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay;

    /* Connect to server with the session config */

    if (!smtp.connect(&session))

    return;

    /* Start sending Email and close the session */

    if (!MailClient.sendMail(&smtp, &message))

    Serial.println("Error sending Email, " + smtp.errorReason());

    }

    //-----------SMTP Status function-----

    // Callback function to get the Email sending status

    void smtpCallback(SMTP_Status status)

    {

    /* Print the current status */

    Serial.println(status.info());

    /* Print the sending result */

    if (status.success())

    {

    Serial.println("----------------");

    ESP_MAIL_PRINTF("Message sent success: %d\n", status.completedCount());

    ESP_MAIL_PRINTF("Message sent failled: %d\n", status.failedCount());

    Serial.println("----------------\n");

    struct tm dt;

    for (size_t i = 0; i < smtp.sendingResult.size(); i++)

    {

    /* Get the result item */

    SMTP_Result result = smtp.sendingResult.getItem(i);

    time_t ts = (time_t)result.timestamp;

    localtime_r(&ts, &dt);

    ESP_MAIL_PRINTF("Message No: %d\n", i + 1);

    ESP_MAIL_PRINTF("Status: %s\n", result.completed ? "success" : "failed");

    ESP_MAIL_PRINTF("Date/Time: %d/%d/%d %d:%d:%d\n", dt.tm_year + 1900, dt.tm_mon + 1, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec);

    ESP_MAIL_PRINTF("Recipient: %s\n", result.recipients);

    ESP_MAIL_PRINTF("Subject: %s\n", result.subject);

    }

    Serial.println("----------------\n");

    }

    }

    Code Description

    • The first task is adding the required header files or libraries.
    • h is used to enable the Wi-Fi module and hence wireless network connectivity.
    • Another library is h to enable email services for receiving and transmitting mails over IMAP and SMTP protocols respectively.
    • Enter the network credentials in place of SSID and PASSWORD.
    • Enter the IMAP server address and port number of the respective email service provider.
    • In this code, we are using the Gmail service.
    • Enter the SMTP server address and port number of respective email service provider.

    Fig. SMTP server address and port number

    • Enter your (source) email address and password details to receive and transmit emails.
    • Insert another (destination) email address.
    • imapCallback() function is used to fetch the email reading status.
    • Print the list of mailbox folders.
    • Print the information of the selected mail folder.
    • Print all the messages from the message list.
    • Print the attachment contained in the mail.
    • Call the IMAP session object which is used to read emails.
    • SMTPSession object is used for sending emails.
    • This smtpCallback() function is used to get the email sending status.
    • This function also includes printing the results like success and failure of email sent.

    Setup() Code

    • Initialize the serial monitor at a 115200 baud rate for debugging purposes.
    • WiFi.begin() function is used to initialize the Wi-Fi module with Wi-Fi credentials used as arguments.
    • The While loop will continuously run until the ESP32 is connected to the Wi-Fi network.

    Fig

    • If the device is connected to a local Wi-Fi network then print the details on the serial monitor.
    • WiFi.localIP() function is used to fetch the IP address.
    • Print the IP address on the serial monitor using println() function.

    Fig.

    • Imap.debug(1) function is used for debugging through the serial monitor.
    • Where parameter ‘1’ represents basic debug.

    Fig.

    • imap.callback() function is set to get the reading results.

    Fig.

    • Declare the session configuring data.

     

    • Some properties of session configuration and imap_configuration accept the pointer to constant char. You can also change them to a string.
    • Set the session configuration which includes the server address of the IMAP service provider, port, and your email address and password.
    • For searching and fetching operation results set the configuration.
    • Configure the searching criteria for available information.
    • Configuration for searching unseen messages.

    Fig.

    • Set the storage path to save the downloaded files.

    Fig.

    • Configure the flash for storing email files.

    Fig.

    • Set the message (download) header which includes text, HTML message, attachments (to store the attachments you need to enable Serial Peripheral Interface Flash File System or SPIFFS).
    • Follow our previous tutorial i.e., on sending emails with ESP32 over SMTP

    • Enable the results for HTML and text messages which are to be stored in IMAPSession object.
    • The IMAPSession object’s size is limited by config.limit.msg_size.
    • Enable.recent_sort is configured to enable the feature of sorting the messages by UID in ascending order.
    • download_status is configured to indicate the download progress on the serial monitor.
    • limit.search is configured to limit the emails in the search result.
    • The size of the message stored is limited to 512 bytes.
    • The size of attachments and images that can be downloaded is limited to 1024*1024*5bytes.
    • Connect to IMAP server with the set session and configurations.

     

    • Open the selected mail folder to read the received information.
    • Fetch UID from the maximum message number in mailbox and write the UID into a string type variable
    • Read the message once it is fetched.
    • Delete/clear all the data stored in the IMAPSession

    imapCallback()

    • As we mentioned earlier, imapCallback() function is used to fetch the email reading status.
    • The current status is printed on the serial monitor from info() function.
    • If the email is fetched successfully, print the result and message list.
    • After that clear all the data stored in IMAPSession object.
    • SMTP_MSG() function is called when an email is fetched.
    • SMTP_MSG() function initialize the SMTP server to send an email to the destination client. This function contains all the instructions related to sending email which includes debugging, session object, message header, type of data contained in the email (raw text or HTML text), SMTP server settings, connecting to the server.
    • ESP32 will automatically send an email in reply of the mail received from the client device using this SMTP_MSG function.

    Fig.

    Note:- We have already discussed the SMTP server in our previous tutorial that is Sending Emails with ESP32 using SMTP server. So, follow our previous tutorial for a detailed study on SMTP protocol and send an email using ESP32.

    Testing

    • After making the required changes in the given code like Wi-Fi credentials, email service provider’s details, email address of sender and receiver etc. upload the code into the ESP32 module.
    • Make sure you have turned on the access for less secure apps as discussed earlier.
    • Open the serial monitor with a 115200 baud rate.
    • Send an email to the address login in ESP32 from another email.
    • Make sure ESP32 is connected to the internet.
    • When an email is received by ESP32, the respective results are shown below :

    Fig. Email received by ESP32 over IMAP

    • Once the email is fetched completely, SMTP will be initialized and an auto-response email will be sent to the destination email address.

    Fig. Email successfully sent from ESP32 over SMTP

     

    Fig. Response from ESP32

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

    Service Dispatch Software: An Efficient Tool for Delivering Goods and Services 

    The transportation and logistics industry suffered from the impact of the pandemic. The disruptions in supply chains caused massive losses in businesses. Its spillovers extended to those relying on freight and delivery. But as the restrictions started to ease, its recovery followed instantly.

    In 2021, supply chains benefited from the boom in e-commerce as online buyers reached 2.14 billion. Given the massive influx of customers, businesses had to scale up their operations. The challenge now is to improve efficiency and ensure the delivery of goods and services. It has become more challenging for companies to monitor every movement, especially logistics.

    Fortunately, service dispatch software can make things easier and safer. Tracking vehicles and organizing schedules will no longer take so much time. This technology can impose desirable changes in daily processes. With that in mind, we will look at how it guides businesses toward growth.

    Service Dispatch Software in a Nutshell

    Service dispatch software is a technology that plans and schedules routes. It sends the details to the driver's mobile device. Once received, the management can view the progress on the delivery day. This feature allows them to improve efficiency and customer service.

    Through automated technology, 24/7 management of fleets is possible. After automating routing and scheduling processes, coordination of routes and deliveries is easier. It also provides solutions to field workers, technicians, and other service providers. The following are its primary features.

    • Visibility of drive, vehicle, items, and customer information
    • Automatic notification on the arrival date and time to the customers
    • Ability to adjust the schedule due to unexpected problems
    • Access to data analytics to make sound business assessments and decisions.

    For a better result, it has to work hand in hand with route optimization software. Service dispatch software monitors the delivery process through a cloud-based application. Meanwhile, route optimization software finds the best routes for smooth and efficient delivery. Their combined features can improve business processes and customer satisfaction.

    Benefits of Service Dispatch Software

    The number of products and services purchased online keeps growing. That is why transportation and logistics play a vital role in the e-commerce industry. Food and grocery delivery services have their software to monitor drivers. Here are the expected benefits of using service dispatch software.

    Management of the Delivery Process

    Service dispatch software serves as a centralized tracking system for transportation processes. Its features and connection to GPS and mobile apps provide timely updates. It allows the management to track the location and status of the driver and the items. The information gives the company an idea to improve its dispatch system.

    It automates job assignments and notifies drivers about delivery changes. It also has access to traffic and weather conditions. That way, the dispatchers and drivers can estimate how long it will take to reach the drop-off point. In worst-case scenarios, they can adjust and schedule a new dispatch plan.

    Moreover, it reduces or eliminates paperwork like work order management and service reports. It also generates invoices and provides billing assistance and resource management suggestions. It helps companies save more time and focus on improving customer experience.

    Assessment of Driver Safety and Behavior

    Service dispatch software is similar to employee monitoring software. But, it has more detailed info to assess employees. The management can determine whether the drivers follow the driving standards or not. It includes their driving speed, one of the typical causes of road accidents. Also, customers can rate and review their performance.

    Increased Responsiveness

    In a fast-paced environment, responsiveness sets a business apart from its competitors. It is more crucial for those involving field workers and other service providers. With service dispatch software, the management does not have to make follow-ups. The system alone provides all the information they need to track deliveries.

    Its real-time statuses alert the people involved with emergency calls and last-minute requests. That is why it is essential to integrate it with route optimization software. It helps you identify the location and nature of the raised concerns. From there, someone can go to the site, assist the driver, and solve the problem.

    Data for Business Decisions

    The system provides data, which helps businesses present them in charts and dashboards. These make the numerical values easier to interpret and generate recommendations. These figures enable them to assess their performance based on specific parameters. These include customer rating, delivery time, costs incurred. This feature also makes the business scalable and flexible to changing business requirements. It ensures that the services can suffice business needs.

    Customer Experience Improvement

    Service dispatch software can enhance the delivery process, leading to smoother transactions. Management can do job assignments and schedules faster. There is also shorter waiting and delivery time since the system can find the best route. The goods and services arrive at the exact location on time. In turn, customer satisfaction increases, resulting in higher demand.

    The Bottom Line

    Technology is changing, so businesses have to adapt and meet the insatiable demand. In a competitive market landscape, operational efficiency is vital to outdo peers. Service dispatch software improves processes and reduces costs. It helps businesses adapt to the trend and sustain growth.

    Sending Email with ESP32 using SMTP Protocol

    Hello readers, I hope you all are doing great. In this tutorial, we will learn how to send an email using ESP32 module. We will also learn to send text files, images or some sensor readings using the SMTP server using the ESP32 module.

    In IoT (Internet of things), there are various applications where we need to send emails carrying information like sending some sensor readings, altering emails, images, text files and much more.

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

    What is SMTP?

    SMTP or simple mail transfer protocol is an internet standard for sending and receiving electronic mail (or email) where an SMTP server receives emails from the email client.

    SMTP is also used for setting communication between servers.

    Various email providers like Gmail, Hotmail, Yahoo, etc. have unique SMTP addresses and port numbers.

    How does SMTP work?

    SMTP protocol which is also known as a push protocol is used to send emails and IMAP that is Internet Message Access Protocol (or post office protocol or POP) is used to receive emails at the receiver end.

    SMTP protocol operates at the application layer of TCP/IP protocol.

    When a client wants to send emails, a TCP connection will be open for the SMTP server and emails will be sent across the connection.

    SMTP commands:

    • HELO – This command is sent only once per session and is used to identify the qualified domain names and the client to the server.
    • MAIL – used to initiate a message
    • RCPT – Identifies the address
    • DATA – share the data line by line

    SMTP parameters for different email providers

    SMTP parameters for Gmail

    Gmail is the email service provided by Google and Gmail SMTP server is free to access and anyone can access this service, who has a Gmail account.

    • SMTP server: smtp.gmail.com
    • SMTP Port: 465
    • SMTP sender’s address: Gmail address
    • SMTP sender's password: Gmail Password

    SMTP parameters for Yahoo

    • SMTP server: smtp.mail.yahoo.com
    • SMTP Port: 465 (with SSL)
    • Another Port number: 587 (with TLS)
    • SMTP sender’s address: email address
    • SMTP sender’s password: password

    SMTP parameters for Hotmail

    • SMTP server: smtp-mail.outlook.com
    • SMTP port: 587
    • SMTP sender’s address: Hotmail email address
    • SMTP sender’s password: Hotmail password
    • SMTP TLS/SSL required : YES

    SMTP parameters for Outlook

    • SMTP server: smtp-mail.office.com
    • SMTP server port for incoming mail: 993
    • SMTP server port for outgoing mail: 587
    • SMTP sender’s address: Outlook email address
    • SMTP sender’s password: Outlook password
    • SMTP TLS/SSL required : YES

    Sending emails over SMTP using ESP32 in Arduino IDE

    • In this tutorial, we will demonstrate sending raw text messages and HTML messages, images, text files, etc. to the client over the SMTP server.

    Components required to send and receive emails using ESP32 over SMTP server are:

    • Recipient’s email address.
    • Sender’s email address.
    • Content to be shared over SMTP server.
    • ESP mail client library.
    • ESP32 module.

    ESP mail client Library

    To send emails with ESP32 we need to install this ESP Mail Client library. This library, make ESP32 able to send emails over an SMTP server.

    Step to install ESP Mail Client Library:

    • To download the ESP Mail Client Library click on the link given below: https://github.com/mobizt/ESP-Mail-Client
    • Open the Arduino IDE.
    • Go to Sketch >> Include Library >> Add .ZIP Library.
    • Select the downloaded ZIP file. Click on

    Your Arduino IDE is ready to send email using ESP32.

    Create a new Gmail account (Sender)

    It is recommended to create a new email account for sending emails using ESP32 or ESP8266 modules.

    If you are using your main (personal) email account (for sending emails) with ESP and by mistake, something goes wrong in the ESP code or programming part, your email service provider can ban or disable your main (personal) email account.

    In this tutorial, we are using a Gmail account.

    Follow the link to create a new Gmail account: https://accounts.google.com

     

    Access to Less Secure apps

    To get access to this new Gmail account, you need to enable Allow less secure apps and this will make you able to send emails. The link is: https://myaccount.google.com/lesssecureapps?pli=1

    Arduino IDE Code, for sharing raw text and HTML text with ESP32 and SMTP server:
    • As we mentioned earlier, we are using Arduino IDE as a compiler and upload into the ESP32 module. To know more about Arduino IDE and how to use it, follow our previous tutorial Introduction to ESP32 Programming Series.
    • We have already discussed installing the ESP Mail Client Library to make ESP32 able to send emails over the SMTP server.
    • This library includes multiple examples on SMTP like sending text messages, images, HTML code, text files etc. We have attached an image below for your reference.
    • You can use those examples to send emails.

    Fig SMTP example code

    • Note: You can not use the exact code. Hence, you need to make some changes like replacing SSID and password with your network credentials, email address of sender and receiver, SMTP setting parameters for respective email service providers etc, which need to be done before uploading the code. We will also describe these things during code description.

    #include <WiFi.h>

    #include <ESP_Mail_Client.h>

    #define WIFI_SSID "SSID"

    #define WIFI_PASSWORD "PASSWORD"

    #define SMTP_HOST "smtp.gmail.com"

    #define SMTP_PORT 465

    /* The sign in credentials */

    #define AUTHOR_EMAIL "email address"

    #define AUTHOR_PASSWORD "email password"

    /* Recipient's email*/

    #define RECIPIENT_EMAIL "email address_Rx"

    /* The SMTP Session object used for Email sending */

    SMTPSession smtp;

    /* Callback function to get the Email sending status */

    void smtpCallback(SMTP_Status status);

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

    Serial.println();

    Serial.print("Connecting to AP");

    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

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

    Serial.print(".");

    delay(200);

    }

    Serial.println("");

    Serial.println("WiFi connected.");

    Serial.println("IP address: ");

    Serial.println(WiFi.localIP());

    Serial.println();

    /** Enable the debug via Serial port

    none debug or 0 basic debug or 1

    */

    smtp.debug(1);

    /* Set the callback function to get the sending results */

    smtp.callback(smtpCallback);

    /* Declare the session config data */

    ESP_Mail_Session session;

    /* Set the session config */

    session.server.host_name = SMTP_HOST; session.server.port = SMTP_PORT; session.login.email = AUTHOR_EMAIL; session.login.password = AUTHOR_PASSWORD;

    session.login.user_domain = "";

    /* Declare the message class */

    SMTP_Message message; message.sender.name = "ESP32"; message.sender.email = AUTHOR_EMAIL; message.subject = "ESP32 Test Email";

    message.addRecipient("Sara", RECIPIENT_EMAIL);

    /*Send HTML message*/

    String htmlMsg = "<div style=\"color:#2f4468;\"><h1>Hello CLient!</h1><p>- Sent from ESP board</p></div>"; message.html.content = htmlMsg.c_str(); message.html.content = htmlMsg.c_str(); message.text.charSet = "us-ascii";

    message.html.transfer_encoding = Content_Transfer_Encoding::enc_7bit;

    //Send raw text message

    /* String textMsg = "Hello Client! - you have a message from ESP32 board"; message.text.content = textMsg.c_str(); message.text.charSet = "us-ascii";

    message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;*/

    message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;

    message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay;

    /* Set the custom message header */

    //message.addHeader("Message-ID: <abcde.fghij@gmail.com>");

    /* Connect to server with the session config */ if (!smtp.connect(&session))

    return;

    /* Start sending Email and close the session */ if (!MailClient.sendMail(&smtp, &message))

    Serial.println("Error sending Email, " + smtp.errorReason());

    }

    void loop(){

    }

    /* Callback function to get the Email sending status */

    void smtpCallback(SMTP_Status status){

    /* Print the current status */

    Serial.println(status.info());

    /* Print the sending result */ if (status.success()){

    Serial.println("----------------");

    ESP_MAIL_PRINTF("Message sent success: %d\n", status.completedCount());

    ESP_MAIL_PRINTF("Message sent failled: %d\n", status.failedCount());

    Serial.println("----------------\n"); struct tm dt;

    for (size_t i = 0; i < smtp.sendingResult.size(); i++){

    /* Get the result item */

    SMTP_Result result = smtp.sendingResult.getItem(i);

    time_t ts = (time_t)result.timestamp; localtime_r(&ts, &dt);

    ESP_MAIL_PRINTF("Message No: %d\n", i + 1);

    ESP_MAIL_PRINTF("Status: %s\n", result.completed ? "success" : "failed"); ESP_MAIL_PRINTF("Date/Time: %d/%d/%d %d:%d:%d\n", dt.tm_year + 1900,

    dt.tm_mon + 1, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec); ESP_MAIL_PRINTF("Recipient: %s\n", result.recipients); ESP_MAIL_PRINTF("Subject: %s\n", result.subject);

    }

    Serial.println("----------------\n");

    }

    }

    Code Description

    • The first task is adding the required header files or libraries.
    • Wifi.h is used to enable the Wi-Fi module and hence wireless network connectivity.
    • Another library is ESP_Mail_Client.h to enable email service over SMTP (simple mail transfer protocol).
    • Enter the network credentials in place of SSID and PASSWORD.
    • Insert SMTP parameter of the respective email service provider.
    • The parameters used below are for Gmail.
    • Enter the sender’s email address and password details.
    • Insert recipient’s email address.
    • SMTPSession object is used for sending emails.
    • This smtpCallback() function is used to get the email sending status.
    • This function also includes printing the results like success and failure of email sent.

    Setup()

    • Initialize the serial monitor at a 115200 baud rate for debugging purposes.
    • WiFi.begin() function is used to initialize the Wi-Fi module with Wi-Fi credentials used as arguments.
    • The While loop will continuously run until the ESP32 is connected to the Wi-Fi network.

    • If the device is connected to a local Wi-Fi network then print the details on the serial monitor.
    • WiFi.localIP() function is used to fetch the IP address.
    • Print the IP address on the serial monitor using Serial.println() function.

    • Serial.debug() is used to enable the debug via Serial port where ‘0’ and ‘1’ are used as arguments where;
      • - none debug
      • - basic debug
    • Inside ESP_Mail_FS.h header file, ESP_MAIL_DEFAULT_DEBUG_PORT can be used to change the Debug port.
    • Set the smtp.callback() function to get sending results.

    • Next step is setting the message header.
    • Message header will be set inside the setup() function which includes, sender’s name, subject, sender’s email address, receiver’s email address and name.

    Sending raw text message

    Write the message content (raw text) in the textMsg variable which you want to share over email.

    Sending HTML text

    To send HTML text write the respective content in the htmlMsg variable.

    • Connect to server with session configuration using smtp.connect() function.
    • Next thing to do is, send an email to the client for that MailClient.sendMail() function is used and if mail transmission is failed then that will be printed on the serial monitor along with the reason.
    • Loop() function will remain empty.

    Testing

    • Upload the Arduino IDE code in the ESP32 module.
    • Make sure the Wi-Fi network is ON to which your ESP32’s Wi-Fi module is supposed to connect.
    • Open Serial monitor with 115200 baud rate.
    • Also, make sure that you have turned ON the permission for less secure apps.

    Otherwise, you won’t be able to send emails and an error will be printed on the serial monitor.

    • Press the EN button from the ESP32 development board.

    • Check receiver email inbox.

    Arduino IDE code, for sending images and text files using ESP32 and SMTP server:

    In this example code, we will demonstrate how to share text files and images through emails using ESP32 over the SMTP server.

    But, before sharing attachments (text files or images) you need to save those files on the ESP32 filesystem (SPIFFS).

    Uploading files to ESP32 Filesystem (SPIFFS)

    SPIFFS stands for Serial Peripheral Interface Flash File System, which is built into the ESP32 module. This is a lightweight filesystem designed for microcontrollers with flash chips connected via SPI bus, such as the ESP32 flash memory. In this flash memory, we can write, delete, read, and close files.

    • Text files and images will be saved on ESP32 filesystem (SPIFFS) using ESP32 filesystem uploader plugin for Arduino IDE.

    Installing Arduino ESP32 Filesystem Uploader:

    Fig.

    • Restart the Arduino IDE.

    Check if the plugin is successfully uploaded or not:

    • Open Arduino IDE. Select ESP32 development board.
    • Go to
    • Check whether this ESP32 Sketch Data Upload option is available or not. If it is available that means plugin is uploaded successfully and it is ready to upload files.

    Fig.

    Finally, uploading files using SPIFFS or filesystem upload:

    • In Arduino IDE, create a new Arduino sketch.
    • Save the project.
    • Go to Sketch >> Show Sketch Folder. As shown in the image below:

    Fig.

    • Create a new folder named as

    Fig.

    • Inside that data folder add the respective text files or images you want to share over email as shown in the image below:

    Fig.

    • If you are using the example code from ESP mail-client library then the images should be named as png and text files as text_file.text.
    • After saving files inside data folder, open the Arduino IDE then go to Tools >> ESP32 Sketch Data Upload to upload the SPIFFS Image.

    Fig.

    A message “SPIFFS Image Uploaded” will be displayed at the bottom of Arduino IDE, once the SPIFFS image is uploaded successfully.

    Fig.

    Arduino IDE Code

    Code is already available in ESP Mail Client Library. As shown below:

    Fig.

    • You can not use the exact code.
    • Some changes like Wi-Fi credentials, email address of sender and receiver, SMTP setting parameters for respective email service providers etc, need to be done before uploading the code.

    // To use send Email for Gmail to port 465 (SSL), less secure app option should be enabled. https://myaccount.google.com/lesssecureapps?pli=1

    // The file systems for flash and sd memory can be changed in ESP_Mail_FS.h.

    #include <Arduino.h>

    #include <WiFi.h>

    #include <ESP_Mail_Client.h>

    #define WIFI_SSID "SSID"

    #define WIFI_PASSWORD "PASSWORD"

    // server address for Gmail account

    #define SMTP_HOST "smtp.gmail.com"

    /** The smtp port e.g.

    25 or esp_mail_smtp_port_25 465 or esp_mail_smtp_port_465 587 or esp_mail_smtp_port_587

    */

    #define SMTP_PORT 465

    /* The log in credentials */

    #define AUTHOR_EMAIL "Sender's email address"

    #define AUTHOR_PASSWORD "password"

    /* Recipient's email*/

    #define RECIPIENT_EMAIL "receiver's email address"

    /* The SMTP Session object used for Email sending */

    SMTPSession smtp;

    /* Callback function to get the Email sending status */

    void smtpCallback(SMTP_Status status);

    void setup(){

    Serial.begin(115200);

    Serial.println();

    Serial.print("Connecting to AP");

    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

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

    Serial.print(".");

    delay(200);

    }

    Serial.println("");

    Serial.println("WiFi connected.");

    Serial.println("IP address: ");

    Serial.println(WiFi.localIP());

    Serial.println();

    if (!SPIFFS.begin(true)) {

    Serial.println("An error has occurred while mounting SPIFFS");

    }

    else{

    Serial.println("SPIFFS mounted successfully");

    }

    /** Enable the debug via Serial port

    • none debug or 0
    • basic debug or 1

    */

    smtp.debug(1);

    /* Set the callback function to get the sending results */

    smtp.callback(smtpCallback);

    /* Declare the session config data */

    ESP_Mail_Session session;

    /* Set the session config */ session.server.host_name = SMTP_HOST; session.server.port = SMTP_PORT; session.login.email = AUTHOR_EMAIL; session.login.password = AUTHOR_PASSWORD;

    session.login.user_domain = "mydomain.net";

    /* Declare the message class */

    SMTP_Message message;

    /* Enable the chunked data transfer with pipelining for large message if server supported

    */

    message.enable.chunking = true;

    /* Set the message headers */ message.sender.name = "ESP Mail";

    message.sender.email = AUTHOR_EMAIL;

    message.subject = "Test sending Email with attachments and inline images from SD card and Flash";

    message.addRecipient("Sara", RECIPIENT_EMAIL);

    /** Two alternative content versions are sending in this example e.g. plain text and html */

    String htmlMsg = "This message contains attachments: image and text file."; message.html.content = htmlMsg.c_str(); message.html.charSet = "utf-8";

    message.html.transfer_encoding = Content_Transfer_Encoding::enc_qp;

    message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_normal; message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay;

    /* The attachment data item */

    SMTP_Attachment att;

    /** Set the attachment info e.g.

    • file name, MIME type, file path, file storage type,
    • transfer encoding and content encoding

    */

    att.descr.filename = "image.png"; att.descr.mime = "image/png"; //binary data

    att.file.path = "/image.png";

    att.file.storage_type = esp_mail_file_storage_type_flash;

    att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;

    /* Add attachment to the message */

    message.addAttachment(att);

    message.resetAttachItem(att);

    att.descr.filename = "text_file.txt"; att.descr.mime = "text/plain"; att.file.path = "/text_file.txt";

    att.file.storage_type = esp_mail_file_storage_type_flash;

    att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;

    /* Add attachment to the message */

    message.addAttachment(att);

    /* Connect to server with the session config */ if (!smtp.connect(&session))

    return;

    /* Start sending the Email and close the session */ if (!MailClient.sendMail(&smtp, &message, true))

    Serial.println("Error sending Email, " + smtp.errorReason());

    }

    void loop()

    {

    }

    /* Callback function to get the Email sending status */

    void smtpCallback(SMTP_Status status){

    /* Print the current status */

    Serial.println(status.info());

    /* Print the sending result */ if (status.success()){

    Serial.println("----------------");

    ESP_MAIL_PRINTF("Message sent success: %d\n", status.completedCount());

    ESP_MAIL_PRINTF("Message sent failled: %d\n", status.failedCount());

    Serial.println("----------------\n"); struct tm dt;

    for (size_t i = 0; i < smtp.sendingResult.size(); i++){

    /* Get the result item */

    SMTP_Result result = smtp.sendingResult.getItem(i); time_t ts = (time_t)result.timestamp;

    localtime_r(&ts, &dt);

    ESP_MAIL_PRINTF("Message No: %d\n", i + 1);

    ESP_MAIL_PRINTF("Status: %s\n", result.completed ? "success" : "failed"); ESP_MAIL_PRINTF("Date/Time: %d/%d/%d %d:%d:%d\n", dt.tm_year + 1900,

    dt.tm_mon + 1, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec);

    ESP_MAIL_PRINTF("Recipient: %s\n", result.recipients);

    ESP_MAIL_PRINTF("Subject: %s\n", result.subject);

    }

    Serial.println("----------------\n");

    }

    }

    Code Description:

    Most part of the code is similar to the previous one (that is sending raw text and HTML text), including libraries, network credentials, enabling Wi-Fi and the serial monitor, setting the email parameters of the respective email service provided. So we not explaining the complete code but, we will explain the programming part which is different than the previous one.

    Setup()

    • We are initializing the SPIFFS, inside the setup() function to sore files which are to be shared over the SMTP server.
    • begin() function is used to for initializing SPIFFS.

    Fig.

    • If the server supports, enable chunked data transfer with pipelining for large messages.

    Fig.

    • Next, you need to create data attachments.

    Fig.

    • The next thing is sending the image, for that you need to add the attachment details: filename, path, mime type, type of storage, encoding technique.
     

    Fig.

    • After adding the details of the image, add the attachment to the message.

    Fig.

    • To send a text file you also need to add similar details: name of the file, path, storage type, mime type and encoding technique.

    Fig.

    • Add this attachment too to the message.

    Testing

    • Upload the code into the ESP32 board.
    • Make sure you have selected the correct ESP32 development board and COM port.
    • Also, make sure that you have turned on the access for less secure apps for the sender’s email account as discussed earlier. Otherwise, the ESP32 will face an authentication error.
    • Turn ON the Wi-Fi with which your device is supposed to connect with.
    • Once the device is connected with the access point, it will automatically send the attachment to the receiver's email account.

    Fig.

    Fig.

    Fig. Email Received

    This concludes the tutorial; I hope you found this helpful and also hope to see you again with a new tutorial on ESP32.

    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