Maker Pro
Raspberry Pi

Send Text Messages With a Raspberry Pi and Nexmo

September 03, 2018 by Muhammad Aqib
Share
banner

Learn how to use a Raspberry Pi, a motion sensor, and Nexmo to send and receive text messages to your phone! 

Hardware

Software

1 Nexmo

In this article, we are going to send an SMS to our number on event detection, using the HC-SR501 motion sensor. Whenever the motion sensor detects a person, the Nexmo sends a message to the phone number that we enter in the code. You can quickly adapt this tutorial to build a security system in your home or even track when your dog goes out the door.

We can use Nexmo to send and receive SMS (text messages) and voice calls. Nexmo has a library for Python, which we can use in our codes to send and receive SMS. Nexmo gives the API key and an API secret code to every user so they can use it in their codes.

Required Hardware

  • Raspberry Pi
  • HC-SR501 motion sensor

Signing up for Nexmo and Getting Started

First, head to the Nexmo website and click sign up.

Sign up takes you to a page where you need to enter some information. When you submit that information, a code is sent to the number you entered. You will have to type the code back for confirmation.

After signing up, Nexmo takes you to the getting started page. Here, you will see the API key and API secret, note these as you will need it in the code.

If you want to send the message to multiple numbers, navigate to the test numbers section, as shown in the figure below.

Add the number there, and it will send a code to this number. You will need to write the code back for confirmation.

Installing the Nexmo Python Library

To use Nexmo for sending the message from your Raspberry Pi, we need to install the Nexmo library that we're using in our Python code. To install it, type the below code in the terminal:

pip install nexmo

Circuit Diagram

The hardware part is very easy for this project. Make the connection as described in the table below:

The connections in schematic format.

Code Explanation

First of all, we need to import the required libraries into our code. We import the Nexmo library so we can send messages using Nexmo through event detection. Then, we use the GPIO library to read the output of the motion sensor and the time library to add delay in our code.

import nexmo  # Importing the nexmo library
import RPi.GPIO as GPIO
from time import sleep

Next, we initialize GPIO 17 for the motion. This pin reads the motion sensor. When the motion sensor detects a body, we will see HIGH on the motion sensor and when the motion sensor doesn’t detect a body, we will see LOW.

sensor_pin = 17		# Initialized GPIO 17 for motion sensor
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(sensor_pin, GPIO.IN)         # Declared GPIO 17 as input pin

We need to connect to Nexmo using the API key and API secret that we received when we signed up for a Nexmo account.

client = nexmo.Client(key='86af8054', secret='wVFo9rKpcYbVg')

Next, we create a function that we call whenever the motion sensor sends us a HIGH state. The sensor sends a message and if it’s successful, it sends us a response that it was successful. Otherwise, it shows an error message.

Note: If you are a trial user, you can only send the message to the tested numbers and you can only send them between 10 A.M to 10 P.M.

def send_sms():
    # Sending the message
    response = client.send_message({'from' : 'Nexmo', 'to' : receiver, 'text' : message})
    # Getting the response message
    response = response['messages'][0]
    
    # Checking whether we are successful or we got a error
    if response['status'] == '0':
        print 'send message', response['message-id']
    else:
        print 'Error:' , response['error']

Read the output state of the motion sensor and if it reads as HIGH, use the send_sms function and give a delay of 5 seconds.

try:
        # Reading the motion sensor pin state
        pin_state = GPIO.input(sensor_pin)
        if pin_state==0:                 #When output from motion sensor is LOW
            print "Body Not Detected",pin_state
            sleep(0.1)
            
        elif pin_state==1:               #When output from motion sensor is HIGH
            print "Body Detected",pin_state
            send_sms()
            sleep(5)

That’s it! Copy and paste the full project code (provided below) in a new text file in the Raspberry Pi and save it using the extension “.py”. You can then run this code by going into the terminal, navigating to the file location and using:

python <filename.py>

Replace the filename.py with your file name and voila! Try triggering the motion sensor and see whether you get a message after a couple of seconds on the phone number that you entered in the code. If it doesn’t work, try removing the code for the motion sensor detection and see if you can send a message from your code. Again, keep in mind that if you are a trial user then you can only use this service between 10 am and 10 pm.

Automatic Text Message Video Demo

Check out the video below to see the project take shape and to watch a completed demo!

Full Project Code

import nexmo  # Importing the nexmo library
import RPi.GPIO as GPIO
from time import sleep

sensor_pin = 17		# Initialized GPIO 17 for motion sensor
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(sensor_pin, GPIO.IN)         # Declared GPIO 17 as input pin

# Connecting to the nexmo using API key and API secret
client = nexmo.Client(key='86af8054', secret='wVFo9rKpcYbVg')

receiver = 'Enter number' # The number at which you want to send to
message = '''Body detected '''

# Function to send message
def send_sms():
    # Sending the message
    response = client.send_message({'from' : 'Nexmo', 'to' : receiver, 'text' : message})
    # Getting the response message
    response = response['messages'][0]
    
    # Checking whether we are successful or we got a error
    if response['status'] == '0':
        print 'send message', response['message-id']
    else:
        print 'Error:' , response['error']

while True:
    try:
        # Reading the motion sensor pin state
        pin_state = GPIO.input(sensor_pin)
        if pin_state==0:                 #When output from motion sensor is LOW
            print "Body Not Detected",pin_state
            sleep(0.1)
            
        elif pin_state==1:               #When output from motion sensor is HIGH
            print "Body Detected",pin_state
            send_sms()
            sleep(5)
    except KeyboardInterrupt:
        GPIO.cleaup()

Author

Avatar
Muhammad Aqib

For custom projects, hire me at https://www.freelancer.pk/u/Muhammadaqibdutt

Related Content

Comments


You May Also Like