Send SMS With Raspberry Pi Pico W

by mahmoodmustafashilleh in Circuits > Raspberry Pi

1293 Views, 4 Favorites, 0 Comments

Send SMS With Raspberry Pi Pico W

Untitled design (1).jpg
Canva-free-thumbnail.png

Easily send SMS text messages with the Raspberry Pi Pico W for free using Twilio. Sending text messages to your users can be essential to an IoT application. With low cost and the capability to connect to the Internet with a few lines of code, the Raspberry Pi Pico W is many people's choice for IoT development, especially when it comes to DIY projects. In this tutorial, I quickly show how to get this setup!

There is no library in MicroPython that allows you to send SMS easily, and there is not enough onboard storage to pip install the Python package for Twilio, or just about any Python package for that matter, so we need to get more creative and use their API because we can connect to the internet with the Pico W! Using some simple requests to their API we can begin sending SMS without the need for any 3rd party Python package.

-----

Before we delve into the topic, we invite you to support our ongoing efforts and explore our various platforms dedicated to enhancing your IoT projects:

  • Subscribe to our YouTube Channel: Stay updated with our latest tutorials and project insights by subscribing to our channel at YouTube - Shilleh.
  • Support Us: Your support is invaluable. Consider buying me a coffee at Buy Me A Coffee to help us continue creating quality content.
  • Hire Expert IoT Services: For personalized assistance with your IoT projects, hire me on UpWork.

Explore our Stores for Premium Products:

  • ShillehTek Store: Access exclusive discounts on Arduino, Raspberry Pi sensors, and pre-soldered components at our ShillehTek Website.

Shop on Amazon:

Supplies

  • Raspberry Pi Pico W
  • Usb to Micro-USB Wire

Setup Twilio Account

Create your Twilio account here: https://www.twilio.com/

Step through the account creation process to get your account token and phone number. This can be found in your Twilio console.

You are left with a good amount of free credit to start sending messages. You do not need a credit card to do this which is nice.


Run Code Snippet With Twilio Information

Connect your Raspberry Pi Pico W to your computer using the Micro-USB cable.

I am assuming MicroPython is your coding environment of choice for the Raspberry Pi Pico W, if it is not, I highly recommend it given that it is the most popular coding language for the device.

Using MicroPython on your Pico W, and call the following function:


import time
import network
import urequests


def send_sms(ssid, password, recipient, sender,
message, auth_token, account_sid):
"""
Description: This is a function to send a recipient a message
with a Twilio phone number.

Parameters:

ssid[str]: The name of your internet connection
password[str]: Password for your internet connection
recipient[str]: Phone number of recipient
sender[str]: Phone number for twilio account
message[str]: Message to recipient
auth_token[str]: Token from twilio profile
account_sid[str]: Sid from twilio profile
"""

# Just making our internet connection
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)


# Wait for connect or fail
max_wait = 10
while max_wait > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
max_wait -= 1
print('waiting for connection...')
time.sleep(1)
# Handle connection error
if wlan.status() != 3:
raise RuntimeError('network connection failed')
else:
print('connected')
status = wlan.ifconfig()
#print('ip = ' + status[0])

headers = {'Content-Type': 'application/x-www-form-urlencoded'}
data = "To=" + recipient + "&From=" + sender + "&Body=" + message
print("Attempting to send SMS")
r = urequests.post("https://api.twilio.com/2010-04-01/Accounts/" +
account_sid + "/Messages.json",
data=data,
auth=(account_sid,auth_token),
headers=headers)
if r.status_code >= 300 or r.status_code < 200:
print("There was an error with your request to send a message. \n" +
"Response Status: " + str(r.status_code))
else:
print("Success")
print(r.status_code)
r.close()


The code is relatively self-explanatory in the doc-string for the function. You need to pass in your internet connection parameters, and also the relative information from your Twilio account (keep that information hidden from the public). Also, you need to add the sender's phone number and the message you want to send. If you input all of the information correctly you should see a text message pop up, I recommend trying to send it to your phone.

One important thing to note is that the headers are only accepted as an x-www-urlencoded rather than JSON. Twilio will not accept JSON payloads I believe. At least I could not get that to work. Either way, you should not have to worry about it here, just something to note.

Hope this tutorial went well for you. Please subscribe to my Youtube Channel if you think this was great.

https://www.youtube.com/channel/UCD13UWk3lJtjka7BoA0KZ5w