Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

Using Twilio Sync with MQTT on an ESP8266

In this guide, we'll show you how to use the lightweight messaging protocol MQTT with Twilio Sync for IoT, an Espressif ESP8266, and the Arduino IDE. We'll show how to use the Twilio Device Manager and set up a Device Fleet as well as how to connect your ESP8266 to Sync and make API calls to control an LED.

Yes, that's right, blinky lights! Sound good? Let's dive in...

Sync for IoT is currently in Developer Preview, which means access is by invite only. If you'd like to try what you see in these docs, sign up for the developer preview and the team at Twilio will get you onboarded as soon as possible.

Sign Into - or Register For - a Twilio Account

Create a new Twilio account (sign up for a free Twilio trial here), or sign into your existing Twilio account.

Once you are logged in, navigate to Twilio Device Manager.

Deploy a Fleet of ESP8266 Things

In Sync parlance, a Device Fleet is a collection of devices, keys, certificates, and configurations. You can have more than one fleet, but fleets themselves are isolated - a sometimes necessary feature when you need to keep collections of things from inadvertantly interacting with each other.

A default Fleet is already provisioned for you automatically, get started by navigating to it in the Device Management console:

Locating the default Ffleet in the Twilio Console

Optionally, you can also provision a new fleet using the API.

        Using the API to create a Device Fleet in Ma.

        Create a Device Fleet

        Using the API to create a Device Fleet in Ma.

        Once you are familiar with how Fleets work, we're ready to proceed with a Deployment.

        Configure the New Fleet's Deployment

        As soon as your fleet is set up, Twilio will automatically configure a default Deployment. You'll see that the 'Default Deployment' field in your Fleet is now populated, as in the following picture:

        A default deployment is automatically provisioned for each new Device Fleet.

        Click through to the new deployment by clicking the link labeled 'Configure the Deployment'.

        Every deployment is configured with a default Service Instance.

        As you can see in the above screenshot, Twilio also has automatically linked your deployment with a default Sync Service Instance. Instances are similar to databases in a manner; all of the data from the 'conversation' you'll have with the ESP8266 (or any other device in the Deployment we just created) will be stored in this one Sync instance.

        You can also configure a new Deployment through the API, as shown in this snippet.


              Once you've got a handle on the Deployment (and a pointer to the instance), you're ready to create your first Device and a Key for its authentication.

              Create an ESP8266 Device and a Device Key

              In the Device Manager, a Device refers to a particular piece of hardware. When that hardware connects, Twilio determines which Device it matches based on the credential it provides, either a certificate or a key. We'll set up a Key for our ESP8266, since they're easier to use with the resource constraints of the ESP.

              When inside your Fleet, click the 'Devices' link on the left sidebar. Enter a Friendly name or Unique name if you'd like, then hit the 'Create' button.

              Create a New ESP8266 Device in Deployed Devices

              You can also provision an new Device using the API, as illustrated in this code snippet.


                    Next, when in your Device configuration, click the 'Keys' link in the left sidebar followed by the red 'Create a Key' button to create a new Device Key.

                    Create New Device Key Button

                    Assign a new friendly name to the Device Key; the Device SID should automatically be populated (but can always be recovered in the console by navigating back into the Deployment to your Device). Save both the Key and the Secret once your key is created - you cannot recover the secret once it is shown!

                    Create a Device Key in Sync Deployed Devices

                    Note that you can also create and delete Device Keys using the API. This code sample shows you how to do this programmatically.


                          In the C++ Arduino code, 'KEY' will take the value of sync_key, while 'SECRET' will take sync_password.

                          Create a Sync Document

                          A Document is a simple type of Sync object which is perfect for sharing state in a small application such as this. Note that you have to create a Document before you connect your ESP8266 to Sync; the document's name will become the MQTT topic to which the ESP8266 will subscribe.


                                While creating it, also initialize 'led' to 'OFF'; we'll use that in the code to... keep the LED off when your ESP first connects.

                                Prerequisites to Use an ESP8266 with Sync

                                Grab our code for the ESP8266 here.

                                For this quickstart's development, we used a NodeMCU ESP8266 development board with the Arduino IDE. Any other suitable ESP8266 with a LED defined as LED_BUILTIN would work (as would moving outside of the Arduino ecosystem) but is beyond the scope of this guide.

                                In the Arduino IDE, install two libraries:

                                • ArduinoJSON (by Benoit Blanchon - GitHub)
                                • PubSubClient (by Nick O'Leary - GitHub)

                                In recent versions of the IDE the Library Manager can be reached by a menu path similar to 'Sketch' -> 'Include Library' -> 'Library Manager'. Both libraries can be installed an managed through the Arduino IDE.

                                Edit the Code for Your WiFi Network and For Sync

                                You'll need to make edits to the C++ sketch in order to get it to work on your network and with your deployment, device, and keys. First, ensure your ESP8266 can connect to a friendly Wireless Network by changing:

                                • ssid
                                • password

                                Next, you will need to change two variables and an optional two more to connect to your deployment.

                                      Modify SSID and WiFi password for a friendly network, and add your Sync for IoT credentials.

                                      Edit your WiFi and Sync Credentials

                                      Modify SSID and WiFi password for a friendly network, and add your Sync for IoT credentials.

                                      Matching the instructions above, change:

                                      • sync_key
                                      • sync_password

                                      The next two may not have to change; if you didn't name your Sync Document 'BoardLED' you will have to change it here though.

                                      • sync_document
                                      • sync_device_name

                                      Upload the Code and Blink the ESP8266 LED

                                      Once all the variables are set, you're ready to rock. Upload the code to the board and open the Arduino Serial Monitor ('Tools' -> 'Serial Monitor'). If all goes well, you should see a happy message log similar to the following:

                                      WiFi connected!  IP address:
                                      Attempting to connect to Twilio Sync...
                                      Connected!  Subscribing to sync/docs/BoardLED
                                      Message arrived on topic {"led":"OFF"}
                                      LED turned off!

                                      But there's one more step... blinking that LED! Modify the above Document with the Update command, now setting 'led' to 'ON'.


                                            You should see two updates - one from Sync informing you the update went through, and another on the device - both lighting the LED and sending a message over serial.

                                            ESP8266 Connected to Sync over MQTT

                                            Updating Sync from the ESP8266

                                            We've also included some commented out lines which show how to send information back to Sync from the ESP8266. Remove the comment here to send a msg back to Sync!

                                                  Remove the commented lines to send data back through Sync on a timer.

                                                  Optionally Send Data Back to Sync

                                                  Remove the commented lines to send data back through Sync on a timer.

                                                  Note that we're sending back valid JSON, in string form. Snce you also have it installed, you can also generate JSON through the ArduinoJSON library.

                                                  A Fully Synced Internet of Things!

                                                  And with that, you've got blinking lights on the ESP8266 all driven through a Sync Document over MQTT! With your new infrastructure, you can scale up to many devices or go deep on a single one - Twilio's Sync for IoT is ready for whatever you throw at it.

                                                  We can't wait to see where you take it - let us know what you've built by sending us pictures on Twitter!

                                                  Rate this page:

                                                  Need some help?

                                                  We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.