Sending SMS Alerts with ESP32 using Twilio

Sending SMS using ESP32

SMS is widely used as a part of communication, whether official or personal. SMS technology is fast, convenient, cost-effective, and environmentally friendly. SMS communication can be used by getting paid service from Telecom Service Providers. To build an SMS-sending project, a GPRS module, a SIM card, and a microcontroller such as the ESP32 are necessary components. These components work together to establish a connection with the Telecom Service Providers, enabling the transmission of SMS

But what if I told you that we can able to do it by only using microcontrollers and Twilio cloud API Service?

Yes, using IoT-capable microcontroller boards and IoT Cloud Services makes it very easy to deploy such a Mechanism.

In this project, we are going to send SMS using the ESP32 board. The ESP32's built-in Wi-Fi connectivity enables it to communicate with the internet to Access Twilio cloud API for sending SMS. This project has various benefits for various applications, such as delivering notifications, alarms, and alerts. 

In the previous project, we have already learned how to send an email alert using ESP32

Introduction to Twilio

Twilio is a cloud communication platform that provides a set of APIs for the integration of SMS, voice calls, video messages, WhatsApp, email, and authentication. While there is a cost associated with owning this API, but a free trial is also available. IoT development microcontroller boards can access the internet and utilize the Twilio web service to send SMS messages to registered numbers.

Twilio is a cloud platform service that allows programmatically sending SMS for a wide range of projects. It provides an API that seamlessly integrates with mobile apps and software. Also, libraries and modules are available to integrate the API with microcontrollers and embedded platforms.

Components Required

For this project, we need very few requirements including Software and Hardware

  1. ESP32 Microcontroller Module
  2. Twilio Account
  3. Arduino IDE

Configuring Twilio Trial Account

Since Twilio is not a free service, it is a paid one but the trial account is free for use. We are going to create a trial account for testing the SMS API feature offered by the platform.

Let’s see some of the basic steps involved in creating the account:

  • Go to the Twilio to start creating a trial Account. Enter the required basic details necessary for opening the account.

configuring twilio trial account

  • Please verify your email account by clicking on the verification link sent to the provided email address. Additionally, verify your mobile number by confirming the OTP (One-Time Password) sent to your mobile number.
  • Once you complete the verification process, Twilio will redirect you to a page where you can fill in personalized setting details. After submitting this information, you will be directed to the main Twilio console page.

Twilio console page

Adding Caller IDs

Adding caller IDs to Twilio means we are permitting Twilio to Send Messages to the given Caller IDs. Every Caller ID must be verified first to send the messages using Twilio Cloud API in a free trial Account.

  • Go to the Phone Numbers section, expand it, and click on Verified Caller IDs. Here you will see your verified number is already listed.
  • If you wish to add another caller ID, simply click on the "Add a new Caller ID" button located at the top right corner. Fill in the required details and verify the additional number to successfully add it as another Caller ID.

Adding Caller IDs

Purchasing a Twilio Number

An active number of a country is needed to send an SMS to Caller IDs. Twilio offers different active Phone numbers from different countries but these are not for free. You have to pay some bucks for using an Active Number. But don’t worry we can use it for free for our testing purposes.

We are using a free trial account on Twilio, we get some amount credited to our account for free. We can use the same money to purchase an active number.

  • Now Go to the Phone Numbers section then Manage > Buy a number.
  • Select any desired country and especially don’t forget to select capabilities as SMS, because it will filter out the numbers which are active for Sending Messages.

Purchasing Twilio Number

  • Upon clicking on the "Buy" button, a prompt will appear displaying the number and requesting acceptance of the Terms & Conditions. If you notice any red marks, that indicates additional document requirements for using the SMS services on that particular number. In such cases, it is advisable not to purchase that number solely for testing purposes.

review twilio phone number

  • Finally, after searching for different countries, successfully found a number that offers SMS capabilities without any registration requirements or restrictions.

twilio phone number

  • Now head over to Phone Numbers > Active Numbers. You will see the number listed there which you have just brought.

twilio active phone number

Creating a Messaging Service

Till now we have added caller ID and brought a Twilio Number to send SMS. Now will see how to set up the programmable messaging service.

  • Go to the Messaging section then Services. Click on Create Messaging Service.

message services on twilio

  • Give a name to your messaging Service then click Create Messaging Service.

messaging service setup

  • To add a sender, click “Add Senders” and select the sender type as "Phone number". Afterward, click on "Continue" to proceed.

messaging sender information

  • Select the Phone Number that you purchased earlier. This Twilio Number will work as a sender number. Click on ‘Add Phone Numbers’.

add phone number twilio

  • Finally, Inside the services you can see your recently created Messaging Service.

Sending Test Messages

Now, let’s see how can we initiate Message send.

  • Head over to Messaging > Try it out > Send an SMS. Then there you notice that your Caller ID number is already written whereas choose Messaging Service in the “From” Section.
  • Then select a messaging service that you have previously created.
  • Give the proper message body as per your choice. Then click on Send Message.

Sending Test Messages on Twilio

You can see the real SMSs we are receiving.

twilio test sms

Programming ESP32 using Arduino IDE

Programming the ESP32 for accessing the Twilio account is a relatively straightforward task. First, we must include the Twilio built-in library in our code. By connecting the ESP32 to the internet through its WiFi capabilities, we can access the Twilio cloud API. The program allows customization of the message content and enables us to specify the recipient's mobile number to whom we want to send the message.

We are using Arduino IDE to Program our ESP32, it has inbuilt WIFI and other necessary Libraries.

Twilio ESP32 Client Library

Installing the Twilio ESP32 library is necessary to use the Twilio programmable messaging service by accessing the Twilio cloud API. So, let’s see how to install it in Arduino IDE.

  • Go to the library manager of your Arduino by Sketch> include libraries> manage libraries.
  • Search for “Twilio esp32 client” and you will find the first library named “twilio-esp32-client” by Adam Demuri.
  • Install it and that’s how easy Library Installation is.

Twilio ESP32 Client Library

Program explanation to send SMS with ESP 32

We have included all the basic necessary libraries to connect to Twilio cloud API. We have also included some variables and objects to store data for further programming.

#include "twilio.hpp"
// Set these - but DON'T push them to GitHub!
static const char *ssid = "Semicon Media 2.4";
static const char *password = "cdfiP29to665";
// Values from Twilio (find them on the dashboard)
static const char *account_sid = "AC8476551d242d0bd512f453c48fe8accf";
static const char *auth_token = "91fae1f82af10dad0c7918461bhg97bb";
// Phone number should start with "+<countrycode>"
static const char *from_number = "+1343_____19";
// You choose!
// Phone number should start with "+<countrycode>"
static const char *to_number = "+9170______24";
static const char *message = "Sent from my ESP32";
Twilio *twilio;

In the Above lines of code, we used the pointers SSID & Password to store the character value of WIFI Network credentials through which our IoT board connects to the Internet.

Accessing API keys

For accessing the Twilio cloud API programmable messaging service, we need to get the correct API keys to securely connect to our Twilio account. API keys including Account SID and Auth Token should be taken by login into Twilio Account. Account SID & Auth Token need to be replaced with your credentials inside the code for successful sending Messages.

  • Login to your Twilio Account. Head over to the top right corner then Account > API keys & token.
  • There you can see the required details of your API keys.

Twilio API keys and token

Also, we have defined pointers to store the sender and receiver numbers. You need to replace the sender number with the number that you have purchased on your Twilio account. And the receiver’s mobile number should be the number Added to the list of verified caller IDs if you are using a Free trial Twilio Account. The pointer message stores the characters of your messages, you can directly put your message inside double quotes.

Finally, we initialize an object of the class of the library Twilio.

void setup() {
  Serial.begin(115200);
  Serial.print("Connecting to WiFi network..");
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED){ 
    Serial.print("..");
    delay(500);
  }
  Serial.println("Connected!");

Inside Setup() function, we initialize the serial port on baud rate 115200. Then we start to command WiFi.begin() to initialize the WIFI to connect to a network by providing the correct SSID and password.

Then we monitor the connection by command WL_CONNECTED and, we print periods to the serial monitor as a progress indicator by a delay of 500 milliseconds. Finally, the Connected will print on the serial monitor after a successful connection.

  twilio = new Twilio(account_sid, auth_token);
  delay(1000);

The following above Lines initiate a new Twilio instance with parameters passing as Account SID and Auth Token.

  String response;
  bool success = twilio->send_message(to_number, from_number, message, response);
  if (success)
    {Serial.println("Sent message successfully!");}
  else
    {Serial.println(response);}
}

To send an SMS using the Twilio API, you can call the send_message() function, providing the recipient number, sender number, message content, and a variable to store the response. This function handles the HTTP request in the background, sending all the required parameters to the Twilio API to successfully send the SMS.

The function returns True if the message successfully sends else it will print the response getting from HTTP.

void loop() {
}

Since sending SMSs is not free due that we put our code in Setup() which sends only one SMS when the board starts and makes the loop empty.

Working Explanation of Sending an SMS with ESP32

Now, you have to simply load the sketch inside the Arduino IDE. Fill in the required necessary details inside the code like correctly providing API keys and WiFi network credentials to connect it to the internet. Also, don’t forget to replace the sender and recipient mobile numbers.

Further working steps:

  • Open the code sketch in Arduino IDE, and connect the ESP32 module via a micro-USB cable.
  • Select the board as ESP32 Dev Module (only work if you installed ESP32 board manager already)
  • Select a COM port

selecting com port for esp32

  • Upload the code by following the steps already discussed above and give it a try. Open the serial monitor set the correct baud rate and wait until it shows Connected.
  • On the serial monitor, you will get a successful message if it is successfully done

ESP32 Sent SMS

  • Finally, to ensure that the recipient successfully receives the SMS, you can check the recipient's mobile number for the presence of the SMS.

received test sms from esp32

Hope you liked and enjoyed the project and learned something useful from it. If you have any questions, you can leave them in the comment section below.

Code

#include "twilio.hpp"

// Set these - but DON'T push them to GitHub!

static const char *ssid = "Semicon Media 2.4";

static const char *password = "cdfiP29to665";

// Values from Twilio (find them on the dashboard)

static const char *account_sid = " AC8476551d242d0bd512f453c48fe8accf ";

static const char *auth_token = "91fae1f82af10dad0c7918461bhg97bb";

// Phone number should start with "+<countrycode>"

static const char *from_number = "+1343_____19";

// You choose!

// Phone number should start with "+<countrycode>"

static const char *to_number = "+9170______24";

static const char *message = "Sent from my ESP32";

Twilio *twilio;

void setup() {

  Serial.begin(115200);

  Serial.print("Connecting to WiFi network..");

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED)

  { Serial.print("..");

    delay(500);

  }

  Serial.println("Connected!");

  twilio = new Twilio(account_sid, auth_token);

  delay(1000);

  String response;

  bool success = twilio->send_message(to_number, from_number, message, response);

  if (success)

    {Serial.println("Sent message successfully!");}

  else

    {Serial.println(response);}

}

void loop() {

}

109 Comments

A powerful share, I simply given this onto a colleague who was doing just a little evaluation on this. And he in actual fact purchased me breakfast as a result of I found it for him.. smile. So let me reword that: Thnx for the treat! However yeah Thnkx for spending the time to discuss this, I feel strongly about it and love studying more on this topic. If doable, as you turn into expertise, would you mind updating your weblog with extra details? It's extremely useful for me. Massive thumb up for this blog post!

I have to express my affection for your generosity in support of folks who need help with that subject matter. Your personal dedication to passing the solution around has been unbelievably informative and has consistently enabled those much like me to achieve their desired goals. Your helpful suggestions can mean a whole lot a person like me and still more to my colleagues. Thanks a ton; from all of us.

My spouse and i got really joyous when Edward could deal with his investigation using the precious recommendations he got from your very own web page. It is now and again perplexing to just continually be giving away procedures that men and women may have been trying to sell. So we acknowledge we've got the website owner to appreciate for this. All of the explanations you have made, the straightforward blog navigation, the friendships you can give support to create - it's got everything exceptional, and it's making our son in addition to the family know that the situation is brilliant, which is really vital. Thanks for everything!

There are actually a variety of particulars like that to take into consideration. That is a nice point to convey up. I provide the ideas above as general inspiration however clearly there are questions like the one you bring up the place the most important factor might be working in sincere good faith. I don?t know if best practices have emerged round things like that, but I'm positive that your job is clearly recognized as a good game. Each girls and boys really feel the impression of only a second抯 pleasure, for the rest of their lives.

Hi there! I just wanted to ask if you ever have any issues with hackers?
My last blog (wordpress) was hacked and I ended up losing several
weeks of hard work due to no back up. Do you have any methods to prevent hackers?

Heya are using Wordpress for your blog platform?
I'm new to the blog world but I'm trying to get started and create my own. Do you need any html coding knowledge
to make your own blog? Any help would be really appreciated!

Thanks a lot for providing individuals with a very marvellous possiblity to read from this website. It's usually so cool and as well , packed with a great time for me and my office acquaintances to search the blog the equivalent of three times per week to read the newest issues you will have. Of course, we are always impressed for the fabulous things you serve. Selected 3 tips in this article are rather the most suitable I've had.

I wanted to write down a brief comment to say thanks to you for some of the remarkable points you are giving out here. My extended internet research has finally been recognized with high-quality information to share with my neighbours. I 'd point out that most of us readers are truly endowed to dwell in a useful network with so many lovely individuals with helpful tactics. I feel really happy to have discovered your entire webpages and look forward to really more thrilling times reading here. Thanks a lot again for a lot of things.

I wanted to compose a quick comment to thank you for all the remarkable hints you are showing here. My time-consuming internet research has finally been recognized with wonderful concept to talk about with my classmates and friends. I would say that most of us website visitors are quite fortunate to live in a perfect site with so many brilliant individuals with beneficial tips. I feel very privileged to have seen your weblog and look forward to really more exciting moments reading here. Thanks a lot once more for a lot of things.

I definitely wanted to construct a comment in order to say thanks to you for all the remarkable guides you are giving out on this site. My extended internet lookup has now been compensated with reasonable concept to share with my friends. I 'd mention that many of us readers are very much fortunate to live in a fine site with very many outstanding professionals with valuable things. I feel pretty privileged to have used the webpage and look forward to tons of more entertaining moments reading here. Thanks a lot once more for everything.

hello!,I love your writing very much! percentage we be in contact
extra approximately your article on AOL? I need an expert on this area to unravel my problem.

Maybe that is you! Looking ahead to see you.

I want to express my admiration for your kindness in support of men and women who actually need help with your subject. Your special commitment to getting the message all around has been surprisingly practical and have specifically allowed professionals like me to realize their goals. Your new important useful information denotes a whole lot a person like me and even further to my colleagues. Thank you; from each one of us.

Good post. I study something more difficult on different blogs everyday. It should always be stimulating to read content from different writers and observe a bit of one thing from their store. I抎 choose to make use of some with the content on my weblog whether or not you don抰 mind. Natually I抣l provide you with a hyperlink in your web blog. Thanks for sharing.

I'm curious to find out what blog platform you happen to be working with?
I'm experiencing some minor security issues
with my latest website and I would like to find something more safeguarded.

Do you have any suggestions?

Hello there, I discovered your web site by way of Google
while searching for a comparable matter, your web site came up,
it looks good. I've bookmarked it in my google bookmarks.

Hi there, just turned into aware of your blog via Google, and located that it is really informative.
I am going to watch out for brussels. I will appreciate should you proceed this in future.
Lots of people can be benefited from your writing.
Cheers!

Good post. I learn something more challenging on completely different blogs everyday. It will at all times be stimulating to read content material from different writers and practice a bit something from their store. I抎 prefer to use some with the content material on my blog whether you don抰 mind. Natually I抣l offer you a hyperlink on your net blog. Thanks for sharing.

Hey! Do you know if they make any plugins to help with
SEO? I'm trying to get my blog to rank for some targeted keywords but I'm not seeing
very good results. If you know of any please share.
Appreciate it!

Thank you a lot for giving everyone an extremely splendid chance to read articles and blog posts from this site. It's always so cool and stuffed with fun for me and my office peers to visit your blog at least three times in 7 days to see the new guides you have got. Not to mention, I'm so actually satisfied with all the mind-blowing thoughts served by you. Selected 2 areas in this posting are undoubtedly the most effective I've had.

Hello there! I could have sworn I've visited this web
site before but after going through many of the
articles I realized it's new to me. Nonetheless, I'm
definitely pleased I found it and I'll be bookmarking it and
checking back often!

Can I just say what a reduction to find somebody who truly knows what theyre talking about on the internet. You definitely know the way to bring an issue to mild and make it important. More people have to read this and perceive this side of the story. I cant consider youre no more common because you undoubtedly have the gift.

Wow, marvelous weblog structure! How lengthy have you been running a blog for?
you made running a blog look easy. The whole glance of
your web site is excellent, as smartly as the content
material!

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.