How to interface raspberry pi with Ultrasonic Sensor

How to interface raspberry pi with Ultrasonic Sensor

This is a video tutorial about how to interface raspberry Pi with ultrasonic sensor. Ultrasonic sensor is used for distance measurement and gives fairly accurate readings as its using ultrasonic sound to find the distance. This is a detailed tutorial including all the explanation about interfacing of sensor, its working, and the algorithm of python program.

The python program is also explained in detail in the video.

To interface raspberry pi with ultrasonic sensor and create a distance meter, you’ll need

  • Raspberry Pi any version
  • Ultrasonic sensor HC-SR04
  • 1k Resistor
  • 1.5k Resistor
  • Breadboard
  • Connecting Wires

Circuit Diagram of Ultrasonic sensor with Raspberry Pi

The interfacing diagram is as shown below

Raspberry pi ultrasonic sensor interfacing circuit

Raspberry pi ultrasonic sensor interfacing circuit

Python Code for Ultrasonic Sensor Interfacing with Raspberry Pi

import RPi.GPIO as GPIO
import time
while True:
    print"distance measurement in progress"
    print"waiting for sensor to settle"
    while GPIO.input(ECHO)==0:
    while GPIO.input(ECHO)==1:

Above code is created in Python 3, however if you’re using python 2 the code will still work for you.

Complete Video tutorial

This is the detailed tutorial of Ultrasonic Sensor Interfacing with Raspberry Pi

Keep experimenting!!!

How to interface relay with raspberry pi to switch AC devices

How to interface relay with raspberry pi to switch AC devices

If you’ve been working on raspberry pi for some time now, you must be thinking about how to make it useful in real world applications, right?

Real world applications, where raspberry pi can turn on / off a device by receiving commands either from internet of via some sensors or via a mobile phone application talking to pi using Bluetooth. The possibilities are literally limitless if we know how to perform this.

In this tutorial, we’re going to see exactly how we can interface a real world device with raspberry pi to perform switching.

Switching Devices with Raspberry Pi

If you’ve experimented on raspberry pi, then you must know that raspberry pi has a GPIO, meaning general purpose input/output port pin.

raspberry pi gpio

As you can see in the above image, the 40-pin GPIO is useful to interface a wide variety of output devices. Raspberry Pi being a digital computer, can generate logic outputs on the GPIO pins. These logic output is called as logic 0 and logic 1. Practically, when writing a program for writing logic 0 on the pin of raspberry pi, an actual 0 volt or GND potential appears on the pin. Similarly, when writing logic 1 on the pin, a +3.3V appears on the pin of Raspberry pi.

By writing a program we can generate logic 0 (gnd) or logic 1 (+3.3v) on any output pin of raspberry pi. But this output voltage is very low to turn on any physical devices. In fact the 3.3V generated on output pin is also current limited so it cannot deliver more than 20 mA current from that pin. It means, we can interface an LED directly to raspberry pi gpio pin, and thats about it. You can’t connect any other output device directly to the pin of raspberry pi, not even a DC motor. So connecting an AC Device needs something different.

Relay as Switching Circuit


As said before, raspberry pi is a digital computer and the output is confined between +3.3v and 0v output levels. Therefore, we need an electronic switching circuit in order to connect any physical device to raspberry pi to perform switching. For the entire discussion of this tutorial, lets assume that we want to connect a Lamp to raspberry pi and make it On / Off. We cannot connect bulb directly to raspberry pi and hence we need a switching circuit. To switch On / Off AC devices, we need a switching circuit like relay.

A relay is an electromagnetic switch which works on DC voltage and can turn on AC as well as DC devices. The internal construction of relay looks like below schematic





As can be seen in above image, a simple relay is having 5 terminals

L1 and L2 are the points of an eletro-magnetic coil which acts as a magnet inside relay. The L1 / L2 can be connected directly to a DC voltage source. Whenever the coil is given with voltage, it acts as an electromagnet.

The terminal Common is a movable terminal and NC (normally closed) and NO (Normally open) are fixed terminals.

Working of Relay

The Common terminal is residing on NC terminal using a sprint tension. This is default condition of relay. If a relay is placed on a table, then the NC and COM terminals are connected to each other. Whenever the coil voltage is applied between L1 and L2, the coil gets magnetized. Due to this magnetism, the common terminal is pulled away from NC and now resides on NO. There by acting against spring tension due to magnetism. As long as relay is energized, the situation remains the same and NO and COM are connected. Whenever the relay is turned off by removal of the coil voltage, then magnetism is finished and common terminal goes back to NC Terminal

See this short gif here

relay switching

relay switching

Now as you can see, if we can properly switch On / Off relay, we can connect any AC device and make it switch along with relay. But the question is how to turn on relay itself. Most relay’s work on 12v or 24v and raspberry pi can’t generate that voltage. There are relays who work on +5v coil voltage also, but they need about 30-50mA current which any microcontroller cannot provide. Therefore we cannot directly connect relay to raspberry pi and hence, we need a switching circuit for relay itself.

Transistorized Switching Circuit for relay

For switching any DC load using raspberry pi or similar microcontroller signal, we can use transistorized switching circuits. More details about transistors can be read here

In order to use transistor for switching relay with raspberry pi, here’s the full circuit here

complete relay switching circuit

complete relay switching circuit

As shown in above circuit. The transistor is used to perform switching of relay coil and the relay terminals are used as switching points for AC Load. Using above circuit, you can connect any AC load to raspberry pi and make the device ON or OFF.’

The Components used here are

  • Q1 = NPN transistor, any normal will do, we’ve used BC548
  • R1 = 330 ohm resistor
  • D1 = simple switching Diode like 4148
  • RL1 = 12v Relay

As seen in above diagram, the Diode D1 is used as a protection device which facilitates the easy turn off of the relay.

The output form raspberry pi pin will go directly to the resistor connected to the base of transistor. Whenever the output is made HIGH, the relay will turn ON, and whenever the output is made LOW, the relay will turn OFF, here’s a program

led1 = 21 #GPIO pin to connect to relay
import RPi.GPIO as GPIO
import time
GPIO.setup(led1, GPIO.OUT)
while True:
    GPIO.output(led1, True)    
    GPIO.output(led1, False)

Relay Module

Currently, instead of making this entire circuit all by yourself, we get a direct relay module in many online stores, it looks like this

relay module

relay module

All we have to do here is give the rated voltage from power supply to this relay module and then connect the signal pin to GPIO of raspberry pi. All the related transistor and switching circuit is already present on this board. While using such relay module, just make sure that the GND of the power supply which gives power to relay module (5v/12v/24v) and the GND of raspberry pi should be made common. Means they should be connected to each other.

A simple demonstration of relay working with a lamp is shown in below video

Let me know in the comments if it was easy to understand or did you faced any difficulty in interfacing with your relay module with Pi



How to setup a Raspberry Pi Video Streaming Server in 5 Minutes

Raspberry Pi Streaming Video Setup

  1. If you do not already have pip installed on your Raspberry Pi, please use this command to install it:
  2. sudo apt-get install python-pip
  3. Install the picamera library by running this command:
  4. pip install picamera
  5. Install the flask Python library by running this command:
  6. sudo pip install flask
  7. Download Miguel’s Flask video streaming project by running this command:
  8. git clone
  9.  In the project folder edit the file.
  10. Comment out this line by adding a “#” to the beginning
  11. #from camera import CameraUn-comment this line
  12. from camera_pi import Camera
  13. Save the file.
  14. Run this command to find out the local IP address of your Raspberry Pi.
  15. ifconfig
  16. You will see many lines of output. You are looking for this one:
  17. inet addr: Bcast: Mask:
  18. The inet addr is your local IP address. In this case,
  19.  Start the Flask server by running this command:
  20. python
  21. You will see this, which means that the server is running on port 5000 and is ready.
  22. * Running on
  23. * Restarting with reloader
  24. Open up a web browser on your favorite device and go to this address, except replace that IP address with the one that your Raspberry Pi is running on.
  25. You should see a live view the video that your Raspberry Pi is capturing.


Communication between Raspberry Pi and PC using MQTT

Communication between Raspberry Pi and PC using MQTT

We know that MQTT can be and is widely used for Internet of Things Applications. But do you know that mqtt can be a good choice of sending data in local networks too? Instead of juggling with TCP or HTTP request and running webserver, mqtt can be a super simple, yet reliable solution for local network data exchange between raspberry pi to raspberry pi or Raspberry pi to computer. You can use mqtt for any small requirement of sending data from one computer to another computer. or you can use mqtt to send data to PC from raspberry pi. You can also use mqtt to send data to raspeberry pi from PC. If you want to know how to setup raspberry pi for the first time, you can read it here

In order to do any of these things, first thing is to understand how mqtt works? and what are the advantages over the conventional client-server communication

How Client-server communication Works?

In a very conventional sense, whenever we talk about 2 computers talking to each other, the general way of communication is Client -> Server Communication.

Lets say when 2 computers wants to talk to each other, unless we’re using a direct TCP communicaiton, we often need server. The typical configuration will look like this

How to use mqtt
Typical Client server configuration

Now in above structure, what usually happens is when client 1 sends some data, the server has to save it. And when client 2 sends a request for that data then server will serve it. Lets take an example of IoT project and client 1 is sending temperature and client 2 wants to have that temperature. The communication goes like this

  1. Client 1 reads temperature and sends it to Server
  2. Server receives it and stores it somehow
  3. Client 2 requests server about data
  4. Server responds with the available data
  5. client 2 gets requested data

How MQTT Works?

Now if the same communication is to be done using mqtt, lets see how it works.

First, in MQTT, there is no need to save the data at the server end. The data saving into any database on server is completely optional. Instead the server immediately sends that data back to the clients who need it by fetching from its own cache. Now how to know which client wants that data? In order to know which client wants which data and which client sends which data, mqtt uses something called topics. A topic is basically a virtual communication ID and is better understood in terms of internet of things. This is one of the reason why mqtt is used most in internet of things.

So talking about IoT, a topic can be a sensor value or a parameter which is being sent by one or more devices and which needs to be received by one or more devices. So topic names can be

  1. Temperature
  2. Humidity
  3. Pressure
  4. Presence sensor
  5. LPG Sensor Value
  6. and so on…

topic can also be the device control action. For example, in IoT you have to turn on cooler or heater or a fan or a motor or anything using a relay. Then topic names can be

  1. Relay 1 or relay 2 or so on
  2. LED
  3. Fan
  4. Motor

basically topic is a means of communication with which the clients will communicate each other.

Now the clients or individual computer in mqtt, can have one of the 2 jobs.

  1. Sending Data
  2. Receiving Data
  3. Doing both

so depending on whether its sending data or receiving data, the client computers are called as

  • Publisher (who sends data)
  • Subscriber (who receives data)

Look at the generalized mqtt block diagram

how mqtt works
how mqtt works

As you can see, the entities are now called as publisher and subscriber. As the storage is completely optional at the server, its now called as broker. The broker is nothing different than server in our previous case. It is a physical entity in your network, like a computer PC or raspberry pi. But saving data ont this computer is optional. The communication between devices happens over a particular topic. Lets assume there is just temperature data which needs to be exchanged. In this case, lets see how mqtt communication happens between 2 computers.

So the subscriber here, at the time of boot up or at the time of running the application code, has to subscribe to the topic it wants to read from the network. Lets assume the topic name here is temp. The publisher is supposed to publish to this topic to broker. And the subscriber has to stay subscribed to this topic from broker. The communication happens like this.

  1. Publisher will read the temperature value and publish over the topic called temp
  2. Broker receives the temperature value over a topic called temp and immediately distributes / sends the value to all the subscribers of the topic temp
  3. All the subscribers of topic temp receives the value.

Its just pure simple and fun to make communication this way. The best part is, the publisher can publish to several topics and subscribe to several topics as well. The same case with subscriber.

How to use mqtt in python

Having understood the theory of how mqtt works, lets give it a quick spin. For this experiment, you’ll need at least 2 computers to have real fun and experience of understanding communication. One of our computer will act as broker and subscriber. One computer will act as publisher.

Installation and Running MQTT python program is a 2 part process.

  1. We need a MQTT server who runs the service, technically, its called mqtt broker — Its Raspberry pi in this experiment.
  2. We need a publisher, who just sends some data to or receives some data from the server, — Its PC in our case can be other RPi or Nodemcu or esp32 or any such thing. In current scene, its the PC

So what we need is an MQTT server (or broker) running on raspberry pi. mosquitto is one such server which can run on Raspberry pi. In this tutorial, we use mosquitto server on raspberry pi.

Now lets see installations to be done

Install Python MQTT Library On raspberry Pi

we need to install both the mqtt server as well as the python client library on raspberry pi so that we can not only receive data, but also be able to interpret it using python code. In short to receive the data in python codes.

so on raspberry pi, first install the mqtt server with below command. Make sure you type these commands in terminal of your raspberry pi computer.

sudo apt-get install -y mosquitto mosquitto-clients

this command will install the mosquitto MQTT broker and client libraries on raspberry pi and will run it automatically in the background. The broker is now installed on the raspberry pi. Now lets run the mqtt broker so that its operational. This can be done by

sudo systemctl enable mosquitto

Above line will run the broker on raspberry pi.

Next, we need to run the subscriber code on raspberry pi as well. This code will read the values published by the publisher. In this case, we’re making use of broker itself as a subscriber as well. To access the mqtt functionalities through python program, we need to install the mqtt python libraries on raspberry pi. Mosquitto here is the software which will act as broker meaning it will act as the receiver of data or sender too in some cases. To read the received data in python program, we need python mqtt library. To install python MQTT library, run below command on termianl of raspberry pi. The most popular mqtt library for python is paho-mqtt library which can be installed with this command

sudo pip install paho-mqtt

Above line will install the paho-mqtt python library with which we can write a code to read the data coming from a sender like PC or microcontroller.

If you’ve both python2 and python3 installed on your raspberry pi, which you obviously would have; then its better to explicitly specify that you want to install libraries for python3 with this command

sudo pip3 install paho-mqtt

Above command will install paho mqtt libraries for python3

MQTT Python Code

Now the Code, below python code is useful to receive data on raspberry pi mqtt broker on specified port address. As discussed before, MQTT needs a topic like temp to receive data, this is also called as channel, so whatever topic you’re specifying here, should be the same one used on the sending device (publisher). Look at the code below, this is a python code for raspeberry pi to receive mqtt data.

import paho.mqtt.client as mqtt #import library
MQTT_SERVER = "localhost" #specify the broker address, it can be IP of raspberry pi or simply localhost
MQTT_PATH = "test_channel" #this is the name of topic, like temp
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))
    # more callbacks, etc
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()# use this line if you don't want to write any further code. It blocks the code forever to check for data
#client.loop_start()  #use this line if you want to write any more code here

Install MQTT python libraries On PC

After installing everything required on Raspberry Pi, we’ve to install the things needed on PC

We only need the python mqtt libraries on PC for sending data to mqtt broker running on raspberry pi. It can be installed by running below command in command prompt of windows. Make sure you run the command prompt by right clicking and clicking on “Run as Administrator”

pip3 install paho-mqtt

make sure, you open the command prompt as “Administrator” otherwise it may cause issues in installation.

Now use below simple python code to send data to the test channel created in raspberry pi mqtt server. You need to specify the raspberry pi IP address as the mqtt server address in the below code. Run below code on PC

import paho.mqtt.publish as publish
MQTT_PATH = "test_channel"
import time
while True:
    publish.single(MQTT_PATH, "Hello World!", hostname=MQTT_SERVER) #send data continuously every 3 seconds

And that is about it. whatever data instead of “hello world” you send, it’ll be sent and published to the mqtt broker. Now this is a very simple and crude sample and as you learn more, you can experiment more about it.

Interesting thing is, MQTT is a preferred way to send data from any kind of IoT Device to major cloud service providers like microsoft azure and aws.

Keep Experimenting!!!

Send email using Raspberry pi python program

Send email using Raspberry pi python program

In this post, am sharing you some useful code for sending email through python. In this program, we will use the python’s smtplib library to send emails using raspberry pi

here we discuss 2 types of mail sending codes, one is simple email sending and other is sending email with attachments

The below codes are tested to work on python 3.6 and onward versions of Python

Simple e-mail and email with attachment

import smtplib

server = smtplib.SMTP('',587)



msg = 'test msg'



Send email using raspberry pi with subject

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
fromaddr = "YOUR ADDRESS"

msg = MIMEMultipart()

msg['From'] = fromaddr

msg['To'] = toaddr

msg['Subject'] = "SUBJECT OF THE MAIL"


msg.attach(MIMEText(body, 'plain'))

server = smtplib.SMTP('', 587)


server.login(fromaddr, "YOUR PASSWORD")

text = msg.as_string()

server.sendmail(fromaddr, toaddr, text)


Send email with Attachment using raspberry pi

import smtplib

from email.MIMEMultipart import MIMEMultipart

from email.MIMEText import MIMEText

from email.MIMEBase import MIMEBase

from email import encoders

fromaddr = "YOUR EMAIL"


msg = MIMEMultipart()

msg['From'] = fromaddr

msg['To'] = toaddr

msg['Subject'] = "SUBJECT OF THE EMAIL"


msg.attach(MIMEText(body, 'plain'))


attachment = open("PATH OF THE FILE", "rb")

part = MIMEBase('application', 'octet-stream')



part.add_header('Content-Disposition', "attachment; filename= %s" % filename)


server = smtplib.SMTP('', 587)


server.login(fromaddr, "YOUR PASSWORD")

text = msg.as_string()

server.sendmail(fromaddr, toaddr, text)

What is the difference between raspberry pi  3 vs raspberry pi 4

What is the difference between raspberry pi 3 vs raspberry pi 4

So the new raspberry pi version 4 is out now, it’s quite speculating among the developers around the world about how it’ll be working and what are the new features. Most of the technical people might have been enjoying the talks about the differences between raspberry pi 3 and raspberry pi 4. So let’s see what the differences between these 2 computers are and what they mean for us. In this post, we’ll see the differences from a user’s perspective about what he’ll be better able to do and not just the specifications. So let’s see

Better Computer

Raspberry pi 4 has an advanced System on Chip (SOC) Broadcom BCM2711 at its heart which is a Quad core processor based on ARM Cortex-A72 architecture. It’s a 64-bit SoC clocked at 1.5GHz. Ultimately, a better processor stands for better performance as a whole as computer. Compared to previous version of raspberry pi, RPi 4 will perform much faster since its clocked higher than the older version. This gives an overall better performance as a standalone computer

Faster Execution

Coupled with a choice of 1GB / 2GB / 4GB RAM and a faster processor, raspberry pi 4 will result in faster execution of existing applications. There will be a significant performance difference in opening built in applications like the browse and office application for simple text typing applications. Raspberry pi 3 was having only 1 GB of RAM and no choice of going forward. Obviously, for most designers and developers around the world, the choice would be to go with 4GB RAM Version

Faster Networking

Raspberry pi 4 has got dual wifi setup having 2.4 GHz and 5.0 GHz IEEE 802.11ac wireless LAN. Meaning you can have faster data transferes with wifi and the standard Ethernet port has also been upgraded to Gigabit Ethernet. Overall in networking, it’ll provide with more options if not much faster than the previous version if you’re using wifi. If you have a gigabit Ethernet connection, then the Ethernet connection will give you upper boost in terms of network support. It has also got latest Bluetooth 5.0 BLE support using which you can connect multiple Bluetooth devices to raspberry pi at the same time

More Displays 4k Video

With 2 micro-hdmi ports, we can connect 2 display monitors at the same time to raspberry pi. And both of them supports 4k video. With openGL ES 3.0 Graphics, the video output from raspberry pi will definitely stunning and pleasing to the eyes of viewer and user. However the micro-hdmi setup will incur additional costs with respect to buying the micro hdmi to regular sized hdmi connectors.

More Power Options

With powerful CPU and more RAM offcourse the raspberry pi will consume more power than any earlier versions of raspberry pi. And hence the power requirements for the raspberry pi are also upped. Now we need a minimum 3 Ampere type C USB power supply for raspberry pi. Additionally a never before power facility is also given through the GPIO +5V pin. However anyway, the raspberry pi needs a minimum 4 Ampere of current. And the official website says that you can use +5v, 2.5 Ampere supply with it, but only if you’re not going to use anything over USB. So better be equipped with a higher rated Type C power supply

Apart from all these major changes, almost everything else remains the same this includes

  1. 40 pin GPIO
  2. Display port
  3. Camera Port
  4. MicroSD card support
  5. Raspbian official operating system

Having said all this, the Raspberry pi is still the same beloved computer used for Daily computing with more power and a power house for the embedded applications. Keep experimenting!!!