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.

    How to use Counters in Ladder Logic Programming?

    Hello friends! We hope you are very well! Today we are here for complementing our knowledge with one of the most important topics in PLC programming and practice its implementation in PLC ladder logic programming. Our topic today is about counters which help us to know the production size at any time, the repetition of specific tasks and events. Many real-life situation problems need counter like garage capacity should be tracked by using counters to report how many cars are inside and if there is room for incoming cars or it's full. Another critical problem is to count the repetitive tasks and events in manufacturing. Furthermore, counting products and pieces for taking an action like performing maintenance, stop operation, turn over to next production stage... et cetera.

    Counter in conventional control

    Counters are used in conventional or relay logic control. they mainly receive pulses and count these pulses and when it reaches a preset value the output coil of the counter is energized. They mostly include an LCD showing the counting as shown in figure 1.

    Figure 1: Omron counter [1]

    The main idea of most counters is counting input pulses by using logic circuits i.e. flip-flop and determining the output based on which an output relay is energized. There are two main types of the counter as regards structure: synchronous counters when all flip-flops and asynchronous counters when each flip-flop is connected to its separate clock. In addition, counters can be classified based on functionality into UP, DOWN, and UP-DOWN counters. If you are not familiar with logic circuit components like flip-flops so do not worry as it's not our concern here. We just want to let you know how physical counters in the traditional controller are complicated and take a lot of space as we need hundreds of flip-flops and other circuit components to have a counter which counts for a limited number. Figure 2 shows the logic circuit of the counter that can count from 0 to 9. It utilizes 4 flip-flops as shown. The type of this counter is an asynchronous counter as each flip-flop takes its clock from the output of the previous flip-flop. Furthermore, table 1 lists the truth table of the counter. It shows how the counter determines the count based on the output Q0, Q1, Q3, and Q4. For example, when all outputs are zeroes, that means the counter reads zero. When Q0 is high, Q1 is low, Q2 is low, and Q3 is high, that means the counter reads 9. But in PLC, it's the easier story, it’s software counters with flexible functionality and usability as well as we will see in the next section. So let's enjoy learning and practicing counters in ladder logic programming.

    Figure 2: Asynchronous 0-9 counter

    Table 1: the truth table of 0-9 counter

    Pulse to be counted Q3 Q2 Q1 Q0
    0 0 0 0 0
    1 0 0 0 1
    2 0 0 1 0
    3 0 0 1 1
    4 0 1 0 0
    5 0 1 0 1
    6 0 1 1 0
    7 0 1 1 1
    8 1 0 0 0
    9 1 0 0 1
     

    Counter in PLC

    Simply, Counter in plc is an instruction to count up or down to preset value and energize an output at reaching that preset value. There are three types of counters in PLC which are:

    Count up type

    In this counter, each time a trigger input signal has been received at (CU), the counter counts up until reaching the preset value (PV) to energize output as shown in figure 3. The counter has three inputs: the trigger command, the reload command, and the preset value to set to what number the maximum counter is going to count up. Furthermore, it has two outputs: the counter output which is turned to true when the counter reaches the PV values, and the current value (CV) which tells the current value at any time to whom the counter reaches.

    Figure 3: The counter Up instruction block [2]

    Count down type

    In this counter, each time a trigger input signal has been received at (CD), the counter counts down until it reaches zero at then the counter output is energized. As shown in figure 4, the counter has three inputs: the trigger command for counting down (CD), the reload command to reload to the PV value, and the preset value to set to what number the initial value from whom the counter starts the count down. Furthermore, it has two outputs: the counter output which is turned to true when the counter reaches the PV values, and the current value (CV) which tells the current value at any time to whom the counter reaches.

    Figure 4: The counter down instruction block[2]

    Up-Down counters

    In this counter, the two functions of the count up and count down can be combined in one block. each rising edge of a trigger input signal has been received at (CD), the counter counts down. And each time it receives a command trigger signal at (CU), it counts up and so on till it reaches the PV values. At then the counter output is energized. As shown in figure 5, the counter has five inputs: the trigger command for counting down (CD), the trigger command for count up (CU), the reload command to reload to the PV value, the reset command to reset to zero, and the preset value to set to what number the initial value from whom the counter starts counting up or down. Furthermore, it has three outputs: the counter down output (QD) which is turned to true when the counter reaches zero, the counter up output (QU) which goes to true when the counter reaches the PV value, and the current value (CV) which tells the current value at any time to whom the counter reaches.

    Figure 5: The counter Up-down instruction block[2]

    Ladder program examples for counters

    Now after we have introduced to counters in PLC as regard to their types, functionalities, inputs, and outputs, let’s get to have the fun of practicing our lab work for counters with our simulator.

    Count up example

    Figure 6 shows the ladder simple program example for a counter of type Up counter. In this example, the counter counts the input objects by a sensor that triggers the counter to increment. The ladder program is shown on the left side window while the simulator window appears on the right part. You can notice on the simulator window, we track all inputs and outputs as well. In the beginning, the current value (CV) is zero and the preset value is set to 10 meaning the counter will energize its output when it counts up to 10. Let’s press the input trigger and see what is going on. My friends, try to think before you go forward to see the simulator output as I am ganging will be the same as what you imagine!

    Figure 6: Ladder example of a counter UP type

    As you imagine exactly, figure 7 shows the counter is incrementing each time the input trigger signal is rising. Until it reach to or above 10 which is the PV value at then the counter output turns on as shown in figure 8.

    Figure 7: The counter incrementing with triggering signal input

    Figure 8: the counter output turns ON by reaching to or above the PV value

    On the other hand, the reset signal can be used for resetting the counter to the zero to start over counting as shown in Figure 9.

    Figure 9: the counter CV reset to zero by hitting the reset.

    Count down example

    This counter is used to count down from the PV value to zero. Figure 10 shows a very simple ladder program for the count down the program on the left part and its simulation appears on the right as well. The simulation windows show the PV value is set to 10 and the current value (CV) is initially starting from the PV value. Therefore, it starts with a value of 10. So let’s try to hit the input CD signal and see what the simulator shows.

     

    Figure 10: Ladder example of count down counter

    Figure 11 shows the counter is decrementing the CV by hitting the input CD. And continue decrementing until reaching zero. So what is going to happen then? Think!

    Figure 11: the counter is decrementing by hitting the input CD

    Exactly! And well though, as figure 12 shows, once the counter reaches zero, the output changes to true.

    Figure 11: the counter output set to TRUE when reaching zero

    Again, the reset button can be utilized to reset the counter to its initial state as shown in figure 12. You can notice that the CV reset to 10 which is the initial value and equal to the preset value (PV).

    Figure 12: Reset button reinitiate the counter to the PV value

    Count up-down example

    Now we are going to combine all features in the UP and down counters in one counter which is called the UP-Down counter. Figure 13 shows a simple ladder example for that counter. The ladder code is shown on the left and the simulator window is on the right. The simulation window shows all inputs and outputs of the UP-DOWN counter.

    Figure 13: A ladder example of UP-Down counter

    Testing the up-down counter ladder program

    We have two functions to test with this type of counter which is up counting and down counting. Figure 14 shows the initial state of the ladder program, it shows we start testing when the current value (CV) shows 2. So what do you expect when hitting the count up and the count down? Thinking and validate with the simulator results below.

    Figure 14: initial state at the running of the up-down example

    By hitting the count-up function, the counter acts like a UP counter and the current value is incremented as in figure 15.

    Figure 15: count up function incremented the CV

    On the other hand, by hitting the count down function, the counter acts as a down counter and the current value is decremented as in figure 16. And by pressing reset, the counter CV value will be reset to zero, while it reloaded to the PV value by pressing the load counter button. In addition, the output QU will be energized when the counter reaches or is higher than the PV value which is 10 in this example while the output QD will be true when the counter reaches zero. To sum up, this up-down counter can act as both types of counters UP and Down. I know someone is going to ask why we have such a counter when we already have one of each counter type? Well! That’s a really good question. And the answer is that, yes we can implement any problem relating to performing counting by using these two counters. However, some problems need to perform both functions UP and Down counting at the same time. For example, the Garage problem has cars getting in and out all the time and when cars get in we need to count up the cars and when cars get out we need to count down to report the number of cars in the garage at any time. So in such a problem, having one counter do the whole job is better than having two punters for reducing the conflictions and increasing the flexibility of calculations.

    Figure 16: count down function decremented the CV

    Next topic

    I would like to thank you so much for following up with us up to this point of learning and practice. Despite briefly introducing the logic gates, we will elaborate in the next station on the logic gates and their functions and usage in ladder logic programming. So you be ready for more learning and practice the ladder logic and logic gates in deep detail.

    How to Use Timers in Ladder Logic Programming?

    Hello friends! I hope you are doing very well, today we have a very crucial topic which is “timers”. Yes! Exactly like what comes to your mind. For running equipment i.e. motor at a specific time and/or for some amount of time we need timers. Timers are used even before PLC in classic or relay logic conventional control. However, there is a big difference between capabilities and limitations between using physical timers in classic or old fashion relay logic and using software timers in PLC. By completing this article you will be able to know what are timers and their types and applications. In addition, we are going to show off how to use timers in ladder logic programming with examples.

    What are timers used for in industrial applications?

    Well! This is a very good question to start and its answer can be taken as a motive to learn timers comprehensively. Timers are used to turn on actuators i.e. motors for a specific amount of time or turn off them after a specific amount of time. They are used for scheduling tasks on and off based on the process sequences.

    How do timers work?

    There are many types of timers based on the functions. However, all timers are working in the same principle that they are preset to a specific amount of time. Then when their coils are energized, the timers’ contacts are changing over to the opposite of their initial states i.e. from ON to OFF or from OFF to ON based on the delay time and the timer type. Therefore, we can imagine the main components of timers are the coil and contacts as shown in figure 1 [1]. It shows a relay timer for Telemecanique type showing the setting for the time delays, coil, and the contacts.

    Figure 1: physical relay timer

    Advantages of Timers in PLC over relay timers

    The relay timers are limited in time setting i.e. for 24 hours and a specific amount of physical NO and NC contacts. While timers in PLC are logical software components with the unlimited setting of time which makes them very flexible with logic requirements. In addition, using physical relay timers costs us more space and wiring. While we can use soft timers in ladder logic with no limitations. Types of timers as we are going to describe in detail later, are limited to basic functions in the relay timers while all types of timers can be implemented in PLC using ladder logic programming.

    Timers types

    All timers have a coil and contacts and the latter will be changed over their states by energizing their coil based on the preset time and the type of timer. In the following subsection the most common timer types are introduced:

    ON-DELAY timer

    This type of timer is used to postpone the start of running. Figure 2 depicts the timing diagram of the On-Delay timer. As shown in this timer delayed the output from the input by the preset delay time. The figure shows that, after the input gets started, the time counts up until the preset amount of time elapsed, then the output starts as long as the input is ON. However, in the second pulse of the input, we can notice the output was not started because there was no chance to reach the amount of delay time that is preset in designing the timer.

    Figure 2: The timing diagram of the On delay timer [2]

    OFF-DELAY timer

    In this type of timer, we aim at delaying the shutdown of the output. Figure 3 depicts the timing diagram of the OFF delay timer in which, the output starts at the time input starts and the output lasts after a specific time delay after the input gets off. You can notice that, in the second pulse of the input, the output did not shut down after the second pulse of the input due to the incoming of another input pulse before the delay time reached the preset value.

    Figure 3: The timing diagram of the Off delay timer [2]

    Pulse timer

    This timer type energizes the output in each rising edge of the input for a fixed amount of time. Figure 4 shows the timing diagram of a pulse-type timer. It shows the output comes active each time it finds a rising edge of the input and keeps active for a fixed amount of time which is preset for the timer.

    Figure 4: Timing diagram of, the pulse timer [2]

     

    Accumulative timer

    In an on-delay timer, if the input does not stay on for the preset time delay period there would not be a chance for the output to be energized. So there should be another modified timer to accumulate the period each time the input is ON and activate the output when reaching the preset value. This timer is called an accumulative timer and its timing diagram is depicted in figure 5. In this example, assume the preset values of 12 s, the first input pulse shown in blue resumes for 4 seconds and it goes on for another 8 seconds. The time is accumulated from the first and the second pulse until reached the preset value which is 12 seconds. The output gets ON as long as the preset time has reached and the input is ON.

    Figure 5: on-delay accumulative timer

    Timers in PLC and ladder logic program

    Timers of different types can be used in PLC with great flexibility. Now let’s learn and practice timers with our simulator. But before we get to start we just need to introduce ourselves to the timer blocks in the ladder logic program.

    Generate ON delay timer instruction

    Figure 6 shows the instruction for generating an ON Delay timer. As you can see the instruction has two inputs and two outputs. The first input “IN” is the input contact of type Boolean. This input contact triggers the timer and initiates it to start counting the time. The second operand is the “PT” by which we set the required time delay. Moving to the outputs, the first output is “Q” this is the main output of the timer and it turns to true when the timer reaches the preset time delay. The second output is the “ET” which reports the time elapsed so far since the timer started to count time. The “PT” and “ET” are of time data type format and can be in milliseconds, seconds, minutes, hours, days et cetera.

    Figure 6: Generate ON delay instruction

    ON-Delay timer example ladder program

    Figure 7 shows a very simple example program that uses an ON Delay timer for delaying the running of a motor. The ladder code is shown on the right part of figure 7. It shows that one input contact connected to address “I0.0” and its tag named “trigger_timer” is connected to the timer input. And the preset value is set to be one minute “T#1m” which means one minute. Notice the format is very simple. You type T denoting the time format and then “#” followed by the amount of time and at last the unit of time which could be “MS” for milliseconds, “S” for seconds, “m” for minutes, “d” for days … et cetera. Moving to the outputs, the timer output “Q” is connected to the motor meaning that the motor will be running after the timer counts complete one minute. The other output is “ET” which tells the time elapsed so far since the timer set to start counting time. Let’s go to the simulator window on the left side. We added all inputs and outputs to control the inputs and show the output as well. You can notice that, by setting the input “trigger_timer” to true, the timer starts counting the time as you can read in the “ET” variable that shows the time spent so far “T#29S_335MS” meaning 29 seconds and 335 milliseconds have been elapsed since input set to true. Since the PT time is not reached, the output is still false as shown in blue color.

    Figure 7: ON-Delay timer sample program with a simulator

    Figure 8 shows the moment when the timer reached the PT value which is one minute in our example. You can notice on the left window, the ET value becomes one minute which is equal to the PT value. Therefore, the timer output turned to true and the motor is switched on consequently. To sum up, this example shows how the output has become ON after one minute delay of the input.

    Figure 8: ON-Delay timer energized the output after one minute delay

    OFF delay timer example ladder program

    After we have shown how we can delay the start of a motor by using the On Delay timer. Here we are going to show how to delay the shutdown. Figure 9 shows an example of a very simple ladder program that uses an OFF delay timer to delay the shutdown of an output. As you can see on the left the input is ON and the output starts running with the input at the same time. Let's try to set the input OFF as in figure 10, you can notice the output is still ON and the time counter is incrementing until it reaches the PT value which is set to one minute in our example. Figure 11 reports the moment at which the time counter reached the PT value which is one minute. At that moment the output or the motor is shut down. In a conclusion, the Off delay timer is our tool to delay the shutdown of output or terminate a process.

    Figure 9: OFF delay timer example

    Figure 10: The input is off while input is still run

    Figure 11: the output shutdown delayed one minute

    Pulse timer example

    In this example, we are going to start and stop the motor in a pulsative operation mode thanks to the pulse timer type. That means the input to the timer will start the output to run for a specific amount of time that is present in the PT value regardless of receiving any other input pulses. In figure 12, the pulse timer example is shown. The very simple ladder logic program is displayed on the left window and the simulation is shown on the left window. You can notice that, once the timer received a high state of the input, it energized the output and started counting the time. However, when the input went OFF the output keep running ON for the designated while represented in PT value which is one minute for this example as shown in figure 13. Let’s test the condition of having another input signal as shown in figure 14. When the input goes again high which the last pulse does not complete, the output continues running and the timer does not reset its timing count. However, when the pulse time is reached as in figure 15, the output is shut down and the timer now is ready to start another pulse by noticing a rising edge of the input.

    Figure 12: pulse timer example

    Figure 13: the output continue running for its pulse period

    Figure 14: another pulse does not reset the timer until complete one pulse period

    Figure 15: output shutdown after completing pulse period

    Accumulative timer ladder example

    In this ladder example, we are going to show you how to continue accumulating the time until reaching the PS value at which the timer energizes its output as shown in figure 16. The example shows a very simple ladder code that has two inputs connected in parallel to OR logic. So any of these two inputs will trigger the counter to count up the time. On the left window, all inputs and outputs including timer operand and outputs are listed in simulating table to show the values while the program is executing.

    Figure 16: an accumulative timer ladder example program

    Let us start triggering the timer by one of the inputs as shown in figure 17. As you can notice the timer starts counting the time as shown in the ET value on the left window showing the simulation. What if we set the inputs OFF? In the ON Delay timer, the time will be reset. But in this timer, it does not and instead, it waits for another input signal to accumulatively increment the time till reaching the PT value as shown in figure 18. Let’s verify the concept by setting one of the inputs ON as shown in figure 19, the timer accumulates the timing counter until it reached the PT value which is set to one minute in this example. At that moment the output is energized as shown in figure 20. And finally, figure 21 shows how the timer is reset by switching on a reset button. One good practical example for using this type of timer is the maintenance schedule. For example, we can schedule the maintenance to be conducted after one year or after a specific amount of time or number of operating hours. So the timer will keep accumulating the time of operation regardless of the downtime and raise a flag to notify it is the time for performing maintenance.

    Figure 17: starting the timer by enabling one of the inputs

    Figure 18: setting the inputs off does not reset the timer

    Figure 19: timer accumulates the time

    Figure 20: the output goes ON after reaching the PT value

    Figure 21: timer reset its timing count

    What next

    I would like to thank you so much for following up with our tutorial that far. So far you are familiar with timers types and how to utilize the suitable one for your task based on the logic you want to perform. Next tutorial we are going to go through counters showing their types and functionalities and for what reasons we need counters how we can use them appropriately.

    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