Firstly we will be Connecting motors to ESC’s and will then Calibrate –

Connecting Motors to ESC – 

  • As we know, in quadcopter, 2 motors rotate in CW direction and 2 motors rotate in CCW direction.
  • Refer the image below to connect ESC to Motor.


  • Arrange the Motors in the given way.

Calibrating ESC’s – 

Electronic speed controllers are responsible for spinning the motors at the speed requested by the autopilot. Most ESCs need to be calibrated so that they know the minimum and maximum pwm values that the flight controller will send. This page provides instructions for calibrating ESCs

About ESC Calibration

ESC calibration will vary based on what brand of ESC you are using, so always refer to the documentation for the brand of ESC you are using for specific information (such as tones). “All at once” calibration works well for most ESCs, so it is good idea to attempt it first and if that fails try the “Manual ESC-by-ESC” method.

** Warning **
Before calibrating ESCs, please ensure that your copter has NO PROPS on it and that the APM is NOT CONNECTED to your computer via USB and the Lipo battery is disconnected

Method 1 – Manual ESC-by-ESC Calibration

  1. Plug one of your ESC three-wire cables into the throttle channel of the RC receiver. (This is usually channel 3.)
  2. Turn on the transmitter and set throttle stick to maximum (full up).
  3. Connect the LiPo battery
  4. You will hear a musical tone then one or two beeps.
  5. After the two beeps, lower the throttle stick to full down.
  6. You will then hear a number of beeps (one for each battery cell you’re using) and finally a single long beep indicating the end points have been set and the ESC is calibrated.
  7. Disconnect battery. Repeat these steps for all ESCs.
  8. After calibration, recheck that motors should work in coordination with throttle stick i.e as soon as throttle stick is moved from its minimum position, motor should start rotating.
  9. Make sure that all ESC’s are calibrated and are working properly.

Method 2 – All at once ESC calibration –

  • Turn on your transmitter and put the throttle stick at maximum.

  • Connect the Lipo battery. The autopilot’s red, blue and yellow LEDs will light up in a cyclical pattern. This means the it’s ready to go into ESC calibration mode the next time you plug it in.

  • With the transmitter throttle stick still high, disconnect and reconnect the battery.

  • For PX4 or Pixhawk, press and hold the safety button until it displays solid red.
  • The autopilot is now in ESC calibration mode. (On an APM you may notice the red and blue LEDs blinking alternatively on and off like a police car).
  • Wait for your ESCs to emit the musical tone, the regular number of beeps indicating your battery’s cell count (i.e. 3 for 3S, 4 for 4S) and then an additional two beeps to indicate that the maximum throttle has been captured.
  • Pull the transmitter’s throttle stick down to its minimum position.


  • The ESCs should then emit a long tone indicating that the minimum throttle has been captured and the calibration is complete.
  • If the long tone indicating successful calibration was heard, the ESCs are “live” now and if you raise the throttle a bit they should spin. Test that the motors spin by raising the throttle a bit and then lowering it again.
  • Set the throttle to minimum and disconnect the battery to exit ESC-calibration mode.

Arming the Copter – 

  • Make sure that Transmitter and reciever are connected.
  • For Arming, hold the throttle to Extreme minimum and Yaw to Extreme left. That is the left joystick should be held for 4-5  seconds in exreme bottom right corner.
  • Now hold in this position for 4-5 seconds to Arm.
  • Blue and Red LED will blink in APM confirming the Arming.
  • If After arming, setup is left idle for 12-15 seconds, it again get Disarmed.


  • Ensure your transmitter’s flight mode switch is set to “Stabilize Mode”.
  • Arm your Quadcopter.
  • Give a small amount of throttle. All motors should spin at about same speed and they should start at the same time. If the motors do not all start at the same time and spin at the same speed, the ESC’s are still not properly calibrated.
  • Disarm your copter.

For more on Calibration, you can take a look at this video –

Connecting things together and Flying !!

In this tutorial, we will be looking on final connections to be made to make your quadcopter flying ready.


Step 1 – Solder the Input Power Cable and ESC’s power cable

  • First of all start by soldering the esc’s and the battery connector to the bottom plate.
  • The frame we are using have a power distribution in built. Hence just need to solder the Power Cable (Where battery will be connected) and the ESC’s power input pins.
  • Solder it perfectly. Make sure that +ve (red wire) and -ve (black wire) are soldered at proper place.

Step 2 – Making Connections and Assemble the Quad (Upper, Lower Frame and 4 legs)

  • Setup the frame. Make sure that the screws are tightened correctly.

  • Now mount the motors on the arms and make all connections.
  • Mount the Motors in the Configuration as given below.

  • Make the ESC’s connections with APM as shown.We are making Quad X.

  • Connect all the components correctly.

  • Tie everything using Zip Tie Cables so that nothing should come on the way of propeller.
  • Stick the APM and Reciever on the frame using Double Sided tape.

Step 3 – Making Sure that Everything is working fine –

  • The frame is assembled and connections are done.
  • Make sure that propellers aren’t fitted yet.
  • Connect the battery and Arm the Quadcoter.
  • Give some Throttle. See that all the motors start at same time.
  • Take the Quad in your hand and Bend it. You should feel the effect of change in speed of rotation of motor.
  • If you bend it to the left, the 2 left motors should Speed up while the 2 right motors should speed down so that it will make quad stable.
  • Repeat the same at all Directions and make sure that everything is fine.
  • Now you can put on the propellers and fly your Quad in Open Ground (Fly it in open space only as no one should get hurt if anything goes wrong)

Step 4 – Flying Directions –

  • Here are some flying directions which everyone should know before flying.

  • Always incresase the Throttle very slowly.
  • To practice well, you can also virtually simulate using your Transmitter and laptop. It will be the best way to practice flying.


In this tutorial, we will be using –

  1. APM 2.8 flight controller – see here
  2. FlySky FS-i6 2.4G 6CH PPM RC Transmitter With FS-iA6B Receiver – see here
  3. Q450 Quadcopter Frame – PCB Version Frame Kit with Integrated PCB – see here
  4. 2212 920KV Brushless DC Motor for DJI – see here
  5. Orange HD Propellers – see here
  6. DYS 30A Brushless Speed Controller ESC – see here
  7. Orange 3000mAh 3S 40C/80C Lithium polymer battery Pack (LiPo) – see here

Step 1 – Installing Mission Planner and Connecting with APM

  • MissionPlanner is an open source application (for windows only) designed to act as a virtual ground control station for your copter, plane or rover devices. The utility enables you to configure the various settings of your autonomous device and ensure its peak performance
    You can download  Mission Planner from : OR  you click here to download directly
  • It can be used to Program APM and Pixhawk Flight controllers.
  • Now connect Your APM flight controller to PC using USB to MicroUSB cable, a Green led will light up and Red led will start blinking
  • PC willl detect the Board as “Arduino Mega” and will automatically install the required drivers.
  • Open Mission Planner software and select proper COM port on the top right corner and select the baud rate at 115200.
  • Don’t select on connect yet on the top right corner.

  • Now go to “INITIAL SETUP” tab and click on “Install Firmware” and then select the type of Mutirotor setup. Here we will be selecting Quadrotor setup. Proceed furthur by giving furthur permisions and the firmware updation will start.

  • It will take 2-3 minutes to boot the Firmware to the APM board ( Make Sure your PC is connected to internet as it will be downloading some required files ).
  • After completion, click on the CONNECT on top right corner of the window to connect the APM board to PC.
  • Now it will show the Device as “Quadrotor”

Step 2 – Calibrating Compass and Accelerometer

  • Now again go to the Initial Setup tab and click on Mandatory Hardware.

  • Firstly, select on frame type, and select the X type of frame for your Quadcopter.

  • Now go to the Accel Calibration Section and click on Calibrate Accel.

  • Follow the instructions as shown on screen and perform the same to calibrate the Accelerometer.
  • After finishing the accelerometer calibration, you can head for compass calibration.
  • APM 2.8 have built in compass, hence no need for external compass.
  • Just head on to Live Calibration and Start rotating your APM 3600

  • Click on finish, when done
  • You can also view it graphically by going to flight data tab on top right corner.
  • Move the APM while it is connected to Mission Planner. You will see the change in position of flight and corresponding values also.


Step 3 – Connecting and Calibrating Radio Control

  • For this, we will have to connect Reciever to the Flight Controller
  • The Pin Configuration of Input side of APM (Which is to be connected to APM) and configuration of Reciever FS-iA6 is as shown.
  • APM 2.5, 2.6, 2.8 all have similar configuiration. Here the outermost pin is Ground, Middle pin is for Positive supply and the innermost pin is Singnal Pin.
  • Ideal way to connect various channels with reciever is also shown.

  • Below is the PinOut for the Reciever FS-iA6. First channel is for ROLL/AILERON, Second is for  PITCH/ELEVATOR, Third is for THROTTLE, Fourth is for YAW/RUDDER and fifth and sixth are Mode selection switch.
  • Here also, outer one is Negative switch, middle one is  Positive switch and the left one or innermost one is signal pin.
  • Channel wise setup is similar in other 6 Channel Recievers also.

  • Now Connecting receiver with the transmitter. Here we will be connecting APM with Reciever.
  • Take reference from below image for connection.

  • Now since the Connection is done, a red light will glow up in the Receiver. Make sure, that the Reciever is binded with Transmitter. If it isn’t binded, you can view this video to how to bind – 
  • Now go to the Radio Calibration section in the Mandatory Hardware part.

  • You will see different bars for different parameters. Now if you change the position of any stick on the transmitter’s joystick, the bar for corresponding parameter will change.
  • Click on the calibrate radio button and vary all the parameters between its extreme ends. Move joystick in all direction upto extreme ends and also change the position of knobs to extreme.
  • You will now notice that Red extreme lines will be captured by the Mission Planner for the corresponding channels. Now since the extremes will be captured by software, click on the “click when done button” to save the same.

Now the calibration is done, and your APM is now programmed to fly. Now you need to do Connections of APM with ESC’s, which will then be connected to Motors.


Hope that you should have gone through the initial raspberry pi setup as given in our previous tutorials : – )
Raspberry Pi 3 B+ have a total of 40 GPIO pins

Above image properly mentions pin configuration of the Raspberry Pi 3 B+, now explaining it briefly –

  1. Voltage Pins – Two 5V ( pin 2 and 4 ) pins and two 3V3 ( pin 1 and 17 ) pins are present on the board, as well as a number of ground pins i.e 0V ( pin 6,9,14,20,25,30,34 and 39 ) which are unconfigurable. The remaining pins are all general purpose 3V3 pins, meaning outputs are set to 3V3 and inputs are 3V3-tolerant.
  2. Outputs – A GPIO pin designated as an output pin can be set to high (3V3) or low (0V).
  3. Inputs – A GPIO pin designated as an input pin can be read as high (3V3) or low (0V). This is made easier with the use of internal pull-up or pull-down resistors. Pins GPIO2 and GPIO3 have fixed pull-up resistors, but for other pins this can be configured in software.
  4. More – As well as simple input and output devices, the GPIO pins can be used with a variety of alternative functions, some are available on all pins, others on specific pins.
    1. PWM (pulse-width modulation)
      • Software PWM available on all pins
      • Hardware PWM available on GPIO12, GPIO13, GPIO18, GPIO19
    2. SPI
      • SPI0: MOSI (GPIO10); MISO (GPIO9); SCLK (GPIO11); CE0 (GPIO8), CE1 (GPIO7)
      • SPI1: MOSI (GPIO20); MISO (GPIO19); SCLK (GPIO21); CE0 (GPIO18); CE1 (GPIO17); CE2 (GPIO16)
    3. I2C
      • Data: (GPIO2); Clock (GPIO3)
      • EEPROM Data: (GPIO0); EEPROM Clock (GPIO1)
    4. Serial (UART)
      • TX (GPIO14); RX (GPIO15)

You can also visit : for more detailed Information

Blinking LED using GPIO pin –

Step 1 – Connections

Here we will be using GPIO 21 or pin no. 40 to make the LED blink. Ground ( 0V) at pin 39 will be used to provide ground with a resistance ( 270,330,1k ohm )  in series to LED. Make connection by referring the Diagram below –

Step 2 – Writing Python code on Python 3(IDLE)

  • Open Python 3 (IDLE) in your Raspberry Pi

  • Now Create a new file. And add the code import RPi.GPIO as GPIO # Importing GPIO library
import time
LedPin = 40 # Defining pin40 as LedPin

def setup():
 GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
 GPIO.setup(LedPin, GPIO.OUT) # Set LedPin's mode is output
 GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to turn on led
def blink():
 while True:
  GPIO.output(LedPin, GPIO.HIGH) # led on
  time.sleep(1) # keeping it in previous state for 1 sec
  GPIO.output(LedPin, GPIO.LOW) # led off
  time.sleep(1) # keeping it in previous state for 1 sec

def destroy():
 GPIO.output(LedPin, GPIO.LOW) # led off
 GPIO.cleanup() # Release resource

if __name__ == '__main__': # Program start from here
   except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
&nbsp; &nbsp;destroy()<code></code>

Save the code as

  • Now open the terminal and type sudo python , such command is used to run any python file via terminal
  • You can press “Ctrl+C” to stop the program.



Hi, Welcome to your first Graphical User Interface(GUI) tutorial with Tkinter in Python to control GPIO’s of Raspberry Pi. In this tutorial, you will learn how to create a simple GUI using Tkinter.

Before getting started let us explain you some terms –

What Is A Graphical User Interface (GUI) ?

GUI is a graphical desktop app that helps you to interact with the computers. Here we will be creating GUI in Raspberry Pi which will be used to interact with its GPIO.

All the apps that we run on a computer are a type of GPIO.

  • GUI apps like Sudoku, Chess, Solitaire, etc.., are games that you can play.
  • GUI apps like Chrome, Firefox, Safari, etc.., are used to surf the Internet.

What Is Tkinter ?

Tkinter is an inbuilt Python module used to create simple GUI apps. It is the most commonly used module for GUI apps in the Python. You don’t need to worry about installation of the Tkinter module as it comes with Python default.


Step 1 – Making connections

  • Make connections as shown in the diagram below.

  • Here we will control Output for pins GPIO26 (Pin 37) and GPIO20 (Pin38) and will connect anode of the LED’s to them.
  • Pin no. 39 is used to provide ground.

Step 2 – Entering Code 

  • Open the python IDLE in Raspberry Pi and create a new Python file and enter the following code.
#This code has been written by
#visit for more information

from Tkinter import * #importing Tkinter Library
import tkFont
import RPi.GPIO as GPIO #importing GPIO library

GPIO.setmode(GPIO.BOARD) #setting up the GPIO pins
GPIO.setup(37, GPIO.OUT) #setting pin37 as output pin
GPIO.output(37, GPIO.LOW) #setting pin37 as LOW initially
GPIO.setup(38, GPIO.OUT) #setting pin38 as output pin
GPIO.output(38, GPIO.LOW) #setting pin38 as LOW initially

win = Tk() #setting up window from Tk() naming win

myFont = tkFont.Font(family = 'Helvetica', size = 36, weight = 'bold') #setting up font naming myfont

def led1ON(): #defining function led1ON
print("LED1 button pressed") #to be printed on terminal
if GPIO.input(37) :
GPIO.output(37,GPIO.LOW) #setting pin37 to low
led1Button["text"] = "LED 1 ON" #text for led1Button

GPIO.output(37,GPIO.HIGH) #setting pin37 to high
led1Button["text"] = "LED 1 OFF" #text for led1Button

def led2ON():
print("LED2 button pressed")
if GPIO.input(38) :
GPIO.output(38,GPIO.LOW) #setting pin38 to low
led2Button["text"] = "LED 2 ON" #text for led2Button
GPIO.output(38,GPIO.HIGH) #setting pin38 to high
led2Button["text"] = "LED 2 OFF" #text for led2Button

def exitProgram():
print("Exit Button pressed")
GPIO.cleanup() #Quitting program

win.title("My GUI") #title for window
win.geometry('800x300') #Dimensions of the window

exitButton = Button(win, text = "Exit", font = myFont, command = exitProgram, height =2 , width = 6) #setting button naming exitbutton 
exitButton.pack(side = BOTTOM) #button position for exitbutton #commanding to button to exitProgram

led1Button = Button(win, text = "LED 1 ON", font = myFont, command = led1ON, height = 2, width =8 ) #setting button naming led1Button, y=50) #button position for led1Button #commanding to button to led1ON function

led2Button = Button(win, text = "LED 2 ON", font = myFont, command = led2ON, height = 2, width =8 ) #setting button naming led2Button, y=50) #button position for led2Button #commanding to button to led2ON function

mainloop() #commanding mainloop for starting main loop



  • Working of each command mentioned in the corresponding comment.
  • Now save the program. We are saving it as gui_project python file.
  • Now open terminal and type command sudo python and press Enter.

  • Now the window naming My GUI will open up as shown.

  • Now you can control the pins with this graphical user interface. If you have touch display, you can also use it by touch.
  • Now you can yourself explore the world of GUI from Tkinter. For more help on tkinter visit :


In this tutorial we will be Designing a Graphical panel through which we will be able to control all the 21 GPIO’s of Raspberry Pi as an Input or Output Pin.

Credits for the program – scotty3785, Original code link – click here

Step 1 – Programming the Raspberry Pi

  • Open the python IDLE in Raspberry Pi and create a new Python file and enter the following code.
#This code has been published by 
#visit for more information

import sys

  from Tkinter import *
  from tkinter import *

import RPi.GPIO as pi
import math
#import tkSimpleDialog

class LED(Frame):
"""A Tkinter LED Widget.
a = LED(root,10)
current_state = a.get()"""

   def __init__(self,master,size=10,**kw):
      self.size = size
      self.state = LED.OFF_STATE
      self.c = Canvas(self,width=self['width'],height=self['height'])
      self.led = self._drawcircle((self.size/2)+1,(self.size/2)+1,(self.size-1)/2)
   def _drawcircle(self,x,y,rad):
       """Draws the circle initially"""
       return self.c.create_oval(x-rad,y-rad,x+rad,y+rad,width=rad/5,fill=color,outline='black')
   def _change_color(self):
       """Updates the LED colour"""
       if self.state == LED.ON_STATE:
       self.c.itemconfig(self.led, fill=color)
   def set(self,state):
       """Set the state of the LED to be True or False"""
       self.state = state
   def get(self):
       """Returns the current state of the LED"""
       return self.state

## Future Functionality
##class gpioEdit(tkSimpleDialog.Dialog):
## """Dialog to be expanded to support advanced gpio features like
## - Pull Up / Pull Down Resistor Config
## - Debounce"""
## def __init__(self, master,gpio):
## top = = Toplevel(master)
## if gpio.isInput():
## title = "Edit Input: %s" %(str(
## else:
## title = "Edit Output: %s" %(str(
## l = Label(top,text=title)
## b = Button(top, text="Submit", command=self.submit)
## l.grid(row=0)
## b.grid(row=1)
## def submit(self):
## print("Submitted")

class GPIO(Frame):
   """Each GPIO class draws a Tkinter frame containing:
   - A Label to show the GPIO Port Name
   - A data direction spin box to select pin as input or output
   - A checkbox to set an output pin on or off
   - An LED widget to show the pin's current state
   - A Label to indicate the GPIOs current function"""
   gpio_modes = ("Passive","Input","Output")

   def __init__(self,parent,pin=0,name=None,**kw): = pin
      if name == None: = "GPIO %02d" % (
         ##Future capability
         ##self.bind('<Double-Button-1>', lambda e, s=self: self._configurePin(e.y))
         self.parent = parent
         self.state = False
         self.cmdState = IntVar()
         self.Label = Label(self,
         self.mode_sel = Spinbox(self,values=self.gpio_modes,wrap=True,command=self.setMode)
         self.set_state = Checkbutton(self,text="High/Low",variable=self.cmdState,command=self.toggleCmdState)
         self.led = LED(self,20)
         self.current_mode = StringVar()

         function = self.getPinFunctionName()
         if function not in ['Input','Output']:
            self.mode_sel['state'] = DISABLED

## def _configurePin(self, y):
## """Future capability to setup pull up/down"""
## new = gpioEdit(self.parent,self)

    def isInput(self):
       """Returns True if the current pin is an input"""
       return (self.mode_sel.get() == "Input")

    def setMode(self):
        """Sets the GPIO port to be either an input or output
       Depending on the value in the spinbox"""
       if (self.mode_sel.get() == "Input"):
       elif (self.mode_sel.get() == "Passive"):

    def getPinFunctionName(self):
        pin =
        functions = {pi.IN:'Input',
        return functions[pi.gpio_function(pin)]

## Future Functionality
## def setPullUp(self,pullup):
## """Defines the GPIO as having a pull up resistor so the input
## state is inverted when read
## setPullUp(True) - Pin is pulled up
## setPullUP(False) - Pin is not pulled up"""
## self.pullup = pullup

   def toggleCmdState(self):
      """Reads the current state of the checkbox, updates LED widget
      and sets the gpio port state."""
      self.state = self.cmdState.get()

   def updatePin(self):
      """Sets the GPIO port state to the current state"""

   def updateLED(self):
      """Refreshes the LED widget depending on the current state"""

   def updateInput(self):
      """Updates the current state if the pin is an input and sets the LED"""
      if self.isInput():
         state = pi.input(
         self.state = state

class App(Frame):
   def __init__(self,parent=None, **kw):
      self.parent = parent
      self.ports = []
     ## Get the RPI Hardware dependant list of GPIO
     gpio = self.getRPIVersionGPIO()
     for num,(p,r,c) in enumerate(gpio):

   def onClose(self):
       """This is used to run the Rpi.GPIO cleanup() method to return pins to be an input
       and then destory the app and its parent."""
       except RuntimeWarning as e:

    def readStates(self):
        """Cycles through the assigned ports and updates them based on the GPIO input"""
        for port in self.ports:

    def update(self):
        """Runs every 100ms to update the state of the GPIO inputs"""
        self._timer = self.after(100,self.update)
   def getRPIVersionGPIO(self):
       """Returns the GPIO hardware config for different Pi versions
       Currently supports layout 1 and 3"""
       gpio1 = ((0,0,0),
       gpio2 = ((2,0,0),
       gpio3 = ((2,0,0),
   if pi.RPI_REVISION == 3:
      gpio = gpio3
      self.parent.title('Raspberry Pi GPIO - A+/B+/2B+')
   elif pi.RPI_REVISION == 2:
        #Change this when I know the pins on RPi GPIO Version 2
        gpio = gpio2
        self.parent.title('Raspberry Pi GPIO - A/B Rev2')
   elif pi.RPI_REVISION == 1:
        self.parent.title('Raspberry Pi GPIO - A/B')
        gpio = gpio1
        self.parent.title('Raspberry Pi GPIO - Unknown Version')
        ##Assume same config as A+/B+/2B+
        gpio = gpio3
        return gpio

def main():
    root = Tk()
    root.title("Raspberry Pi GPIO")
    a = App(root)
    """When the window is closed, run the onClose function."""

if __name__ == '__main__':
  • Now save the program. We are saving it as python file.

Step 2 – Running the program and Understanding the GUI panel

  • Now open terminal and type command sudo python to run the program.
  • A panel window will open up like this –

  • From here you can set the status of any GPIO pin from the Corresponding drop down menu as Passive, Input or Output.
  • If you have selected Output, then you will have to mark or unmark the corresponding High/Low box to make the Pin Low or High
  • If you have selected Input, then the low Input will show the the Red colour and if input is high, it will show  Green Colour.

Now you can Explore the more of a GUI with Tkinter.

For more on tkinter you can visit –

In this tutorial we will be Using Ultrasonic Sensor (SR-04) with Raspberry Pi –

Step 1 – Connections

  • Here we will be using GPIO24 as Trigger pin and GPIO25 as Echo pin.
  • For this, connections will be as shown –

  • We have to connect echo pin in a Voltage Divider, made by 330Ω and 470Ω as Shown.

Step 2 – Working on Code –

  • Create a new file in IDLE and write the code as given
  • The Code for the Following will be –
#This code is Written by
import RPi.GPIO as GPIO
import time


#set GPIO Pins

#set GPIO direction (IN / OUT)

def distance():
&nbsp;&nbsp;&nbsp;&nbsp;# set Trigger to HIGH
&nbsp;&nbsp;&nbsp;&nbsp;GPIO.output(GPIO_TRIGGER, True)

&nbsp;&nbsp;&nbsp;&nbsp;# set Trigger after 0.01ms to LOW
&nbsp;&nbsp;&nbsp;&nbsp;GPIO.output(GPIO_TRIGGER, False)

&nbsp;&nbsp;&nbsp;&nbsp;StartTime = time.time()
&nbsp;&nbsp;&nbsp;&nbsp;StopTime = time.time()

&nbsp;&nbsp;&nbsp;&nbsp;# save StartTime
&nbsp;&nbsp;&nbsp;&nbsp;while GPIO.input(GPIO_ECHO) == 0:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;StartTime = time.time()

&nbsp;&nbsp;&nbsp;&nbsp;# save time of arrival
&nbsp;&nbsp;&nbsp;&nbsp;while GPIO.input(GPIO_ECHO) == 1:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;StopTime = time.time()

&nbsp;&nbsp;&nbsp;&nbsp;# time difference between start and arrival
&nbsp;&nbsp;&nbsp;&nbsp;TimeElapsed = StopTime - StartTime
&nbsp;&nbsp;&nbsp;&nbsp;# multiply with the sonic speed (34300 cm/s)
&nbsp;&nbsp;&nbsp;&nbsp;# and divide by 2, because there and back
&nbsp;&nbsp;&nbsp;&nbsp;distance = (TimeElapsed * 34300) / 2

&nbsp;&nbsp;&nbsp;&nbsp;return distance

if __name__ == '__main__':
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;while True:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dist = distance()
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print ("Measured Distance = %.1f cm" % dist)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# Reset by pressing CTRL + C
&nbsp;&nbsp;&nbsp;&nbsp;except KeyboardInterrupt:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print("Measurement stopped by User")
  • Now save this as python file as
  • Open terminal and type command sudo python and press Enter.
  • Now you will get Realtime reading by Ultrasonic Sensor on the terminal.

  • You can press Ctrl+C any time to stop the program.

Hope that you would have liked it. For any Querry, you can leave a comment below : – )




In this tutorial, we will get to learn about installing any official OS for any model of Raspberry Pi-

The officially available OS for Raspberry Pi as on Official Website

  • Ubuntu MATE
  • Snappy Ubuntu Core
  • Windows 10 IoT Core
  • OSMC ( Open Source Media Centre )
  • LibreELEC ( Just enough OS for KODI )
  • PiNet

In this, we will be installing LibreELEC in our Raspberry Pi

Hardware Required

Raspberry Pi Board ( any ), Class 10 MicroSD Card with its adapter to insert it in Laptop ( 16 GB ), Power supply to power the Rapberry Pi, Display with HDMI support, HDMI to HDMI cable, USB mouse and Keyboard.

There are 2 methods to Install the LibreELEC on SD Card –                                                                                                                                                                          – First, using the LibreELEC Installation media                                                                                                                                                                                          – Second, using the Image file and writing it on Disk using Win32 disk Imager. This can be used for any OS. Click here to jump to Method 2

Make sure the SD card is formatted

Downloading the Image for Required OS –

Visit the Official Download page of raspberry pi and choose the OS to be Downloaded –

Metho 1

Step 1 – Downloading the Required Installation Media 

  • For tutorial purpose, we will now continue with the installation of LibreELEC OS. Steps involved for the installation of other OS’s are also the same



  • Click on the required OS and it will redirect you to the official developer page of the LibreELEC. Now click on the downloads section of the website or directly click here or visit the link :
  • There you will get to download the installation media required to boot the SD card with the LibreELEC OS. For windows, click on windows link and for Linux and MacOS, click on the respected links given. We will be using windows –

  • Setup file “LibreELEC.USB-SD.Creator.Win32.exe” will be downloaded. Now install  and run the file as an administrator
  • Now Installation media will open like this –

Step 2 – Downloading and Burning Image file for the OS on SD Card

  • Now Select the appropriate file and Download it in Required folder

  • Make sure that the SD card is formatted
  • After download, select the SD card port and click on the write button. It will take few minutes depending upon your system to write OS on your SD Card.
  • After finishing, eject the SD card and insert it in your Raspberry Pi and boot it up.


Step 1 – Downloading the Image for the appropriate board

  • Download the compressed image file with extention .gz name “LibreELEC-RPi2.arm-9.0.0.img”.

  • After downoading extract .img from .gz file using WnZip
  • The extracted file will be a Disk Image file named “LibreELEC-RPi2.arm-9.0.0” having size of about 549 MB

Step 2 – Burning the Image file on SD card

  • Download the Win32 Disk Imager software ( for Windows only ) from here or click on the link : . This is used to write any image file to USB stick or SD card.
  • After download install the Win32 disk Imager software and open it.

Click on the folder icon and select the image file and the also select the drive on which it is to be written and click on write as shown below

  • A dialogue box will aper to confirm you. Click on Ok and proceed.
  • Writing will be completed in few mintes depending upon your system. Now safely eject your SD card and Inser it into the Pi. Power it on and boot it up.

Method 2 is the most basic and easiest method to write any OS to SD card. You just need Disk image file of the OS and Win32 Disk Imager to write it on SD card. Yes, it’s really simple as it seems.

Hope that you would have liked it. For any Querry, you can leave a comment below : – )


Meeting the Raspberry Pi

Hope that you should have purchased the Raspberry Pi 3 B+ starter kit. Now let’s introduce you with the Raspberry Pi

  • USB ports — These are used to connect a mouse and keyboard. You can also connect other components, such as a USB drive.
  • SD card slot — You can slot the SD card in here. This is where the operating system software and your files are stored.
  • Ethernet port — This is used to connect the Raspberry Pi to a network with a cable. The Raspberry Pi can also connect to a network via wireless LAN.
  • Audio jack — You can connect headphones or speakers here.
  • HDMI port — This is where you connect the monitor (or projector) that you are using to display the output from the Raspberry Pi. If your monitor has speakers, you can also use them to hear the sound.
  • Micro USB power connector — This is where you connect a power supply. You should always do this last after you have connected all your other components.
  • GPIO ports — These allow you to connect electronic components such as LEDs and buttons to the Raspberry Pi. The picture given below is the detailed GPIO pin representation of the Pi –


 Formatting the SD card

 Installing Raspbian with NOOBS

  •  Downloading NOOBS
    →  Using NOOBS is the easiest way to install Raspbian on your SD card. To get hold of a copy of                   NOOBS:



→ You should see a box with a link to the NOOBS files. Click on the link ( As Shown Below )


  →  The simplest option is to download the zip archive of the files

 Formatting the SD Card

If the SD card on which you wish to install Raspbian currently has any of your personal or Important      data, you should get the backup of at any other place as it will be erased after format.

  • Visit the SD Association’s website and download SD Formatter 4.0 for Windows or Mac.
  • Follow the instructions to install the software.
  • Insert your SD card into the computer or laptop’s SD card reader and make a note of the drive letter allocated to it, e.g. F:/
  • In SD Formatter, select the drive letter for your SD card, and format it.

Extracting NOOBS from Zip Archive

Next, you will need to extract the files from the NOOBS zip archive you downloaded from the Raspberry Pi website.

  • Go to your Downloads folder and find the zip file you downloaded.
  • Extract the files and keep the resulting Explorer/Finder window open.

Copying the Files

  • Now open another Explorer/Finder window and navigate to the SD card. It’s best to position the two windows side by side.
  • Select all the files from the NOOBS folder and drag them onto the SD card.

  • Now eject the SD card safely

Booting from NOOBS

  • Once the files have been copied over, insert the micro SD Card into your Raspberry Pi, and plug the Pi into a power source.
  • You will be offered a choice when the installer has loaded. You should check the box for Raspbian, and then click Install.


  • Click Yes at the warning dialog, and then sit back and relax. It will take a while, but Raspbian will install.


  • When Raspbian has been installed, click OK and your Raspberry Pi will restart and Raspbian will then boot up.

Connect your Raspberry Pi

Let’s connect up your Raspberry Pi and get it running.

  • Check whether your Raspberry Pi already has an SD card in the slot at the underside, and if not, insert an SD card with Raspbian installed (via NOOBS).
  • Find the USB connector for your mouse, and connect the mouse to one of the USB port on the Raspberry Pi (it doesn’t matter which one).
  • Connect the keyboard in the same way.
  • Look at the HDMI port on the Raspberry Pi — notice that it has a large flat side on top.

Now make sure your monitor is plugged into a wall socket and turned on

  • Connect the monitor cable to the Pi’s HDMI port — use an adapter if necessary.
  • Plug the power supply into a socket and connect it to the micro USB power port.


You should see a red light on the Raspberry Pi and raspberries on the monitor. 

The Pi will boot up into a graphical desktop as shown.


Finish the Setup

When you start your Raspberry Pi for the first time, the Welcome to Raspberry Pi application will pop up and guide you through the initial setup.

Follow the steps – Set your Country and your time zone. Then set a new password for youe raspberry pi.

You are now Done with the set up of Raspberry Pi. Now with Raspberry Pi SKY is the limit !!!!!!

Hope that you would have liked it. For any Querry, you can leave a comment below : – )

  • Hey there, in this tutorial we will be learning about how to use laptop as Display for Raspberry Pi. Laptop’s keyboard and pointer will also work with it, hence will no longer need Dedicated display, mouse, and keyboard. We will be using SSH protocol and VNC server to Interface with raspberry pi.
  • But don’t be excited, you will need a dedicated HDMI display, mouse and keyboard for initial process.
  • Before starting the tutorial, we hope that Raspbian is installed in your Pi’s SD card and has been booted already.

( If you haven’t installed Raspbian on Pi, please refer our tutorial – )

Buy our Raspberry Pi Starter Kit –

Buy our Raspberry Pi Advanced Started Kit –

Step 1 – Creating a blank SSH file in SD Card (Windows)

  • For this, eject the SD card from the Pi and insert it into the laptop using SD Card holder. In SD card we have to load a blank SSH file.
  • For this open command prompt on your laptop in which SD card is inserted and give the command “echo>I:\ssh” where I is the drive letter allotted to the SD card drive.



  • And press Enter. A blank file named ssh will be created in SD card like shown-


  • Now eject the SD card safely from the Device.

Step 2 – Enabling SSH in Raspberry Pi

  • Plug in your Pi, connect a HDMI Display, Mouse and Keyboard.

  • Open the terminal of your Raspberry Pi and write command “sudo raspi-config” and press Enter.



  • A Raspberry Pi configuration menu will open. Now use arrow keys to change between the options and press Enter on 5th option, i.e Interfacing option



  • Now, move to the 2nd option, i.e SSH and press Enter



  • A window will open to ask you to enable the SSH Server. Select YES using side arrow keys and press Enter
  • A pop-up will appear showing that SSH server is Enabled.

Step 3 – Enabling VNC Server in Raspberry Pi

  • Repeat the same steps given in Step 2. But now enter into the 3rd Option, i.e VNC in Interfacing Options menu.
  • A window will open to ask you to enable the VNC Server. Select YES using side arrow keys and press Enter



A pop-up will appear showing that VNC server is Enabled.

Now both SSH and VNC server are enabled. Now reboot the raspberry pi.

Step 4 – Downloading the required Softwares in Laptop

You will need to Download 3 softwares in your Laptop. All softwares with their download links are given below ( Please make sure that you are downloading the suitable version of the software depending on your system ) –

  1. Angry IP Scanner. Click here to download or visit this link :
  2. PuTTY. Click here to download or visit this link :
  3. VNC viewer. Click here to download or visit this link :

Download and install all the softwares in your system and then proceed to furthur steps.

Step 5 – Connecting  Raspberry Pi to Laptop

If Pi is connected to laptop with LAN cable directly then follow given steps

  • Open Network and Sharing center of Laptop ( Your laptop will not recognize the raspberry pi connected via ethernet port unless changing some settings  ) and click on the WiFi network you are connected.

  • Click on the properties and then click on the Sharing tab


  • Now click on the sharing tab



  • Check on the Box and allow other users to connect to your pc’s internet connection and in Drop down menu select Local Area connection. Click on OK after finishing.


Step 6 – Knowing IP address of  Raspberry Pi 

⇒ If External display is already connected, you can open terminal in pi and type command “sudo ifconfig” and press enter. Network details of raspberry pi will be shown

  • The IP address of the ethernet port will be shown at the place as Marked in above picture. Here it is Make note of YOUR IP address for further use. After this, you can directly jump to Next step.

 If you don’t have a display now, don’t worry. Let the Raspberry Pi be connected to the laptop via Ethernet Cable and follow steps as given

  • Open the Network and sharing centre and Now click on the Local Area Connection by Unidentified Network


  • Click on the Properties tab and then Double Click on the option of ( Internet Protocal Version 4 )



  • A Window with IPv4 properties will open. Note the IP address written in the first box and close that Window.



  • IP address will be in the range of that only ( In my case, it showing i.e IP address will be in Range of to )
  • Now Open the software Angry IP scanner and enter the Range of IP address in which you want to scan for IP ( Note : You just have to vary the last 3 digits of the IP address from 1 to 255, remaining first 9 digits will remain same. In my case 192.168.137 will remain same as it was shown in IPv4 properties )
  • After entering the proper IP range, click on the start button to scan for any alive host in that IP range



  • Software will start searching for the hosts alive in that IP range.
  • After scanning is done, search for search for host name “” and note carefully the IP address associated with it.



  • Here the IP adress is –

– Note the IP address of the RaspberryPi

Step 7 –  Connecting to Raspberry Pi using SSH with PuTTY

Open the PuTTY Software. A PuTTY Configuration window will open up.

  • Enter the IP address of Raspberry Pi at the given space.
  • Below that, make sure that SSH option is selected.
  • And then without changing any settings click on open button.



  • A PuTTY security alert window will open. Click on “Yes” to proceed.

Congratulations! Now we have established a connection between Pi and Laptop

  • A window asking for login credentials for RaspberryPi will open, You have to Enter username first, then press enter and then password for logging in to Raspberry Pi. ( By Default Username is “pi” and password is “raspberry )



  • Congratulations! Now you have entered inside the terminal of raspberry pi.
  • Now to view the Pi’s screen, type a command “vncserver”. It will turn on the vnc server of raspberry pi.
  • Also, note the VNC Desktop address i.e generated after turning on the vnc server
  • Here it is –



Step 8 –  Viewing Raspberry Pi using VNC viewer

  • Open VNC viewer in your laptop and enter the VNC address in the top bar and press enter. ( VNC address was generated in the last step )


                                  *Don’t forget to put :1,:2,:3 ( as shown in PuTTY ) as mentioned in VNC address

  • An Identity Check window will appear. Click on contine to move further.
  • In next step, it will ask for authentication
  • Enter the Username and password of Raspberry Pi for login and press on Enter.
  • This is how Rasberry Pi screen will appear.



Congratulations, you have successfully displayed the Raspberry Pi’s screen on your laptop. You can use Laptop’s Display, Touchpad and Keyboard as Output and Input devices for pi.

Hope that you would have liked it. For any Querry, you can leave a comment below : – )


In this document, we will guide you on How to Install Ubuntu MATE 16.04.2 LTS and ROS Kinetic on Raspberry Pi.



Step1: Download the image for Ubuntu MATE

Official Download Link for Ubuntu MATE for Raspberry Pi
It comes packaged as an XZ archive so use 7 Zip to extract the IMG file.


Step2: Download and Install Win32 Disk Imager
Installing an OS onto a Raspberry Pi requires you to use another computer to write the image file onto a micro SD card. You must have a way to mount a micro SD card onto the computer using either an inbuilt or external USB reader.

  • Insert your micro SD card and launch Win32 Disk Imager.
  • Select your extracted Ubuntu Mate IMG file and change the Device to the drive letter of your micro SD Card.
  • Click Write to begin the process.

  • It will take about 10 minutes to write the image


Step 3: Eject the device safely in Windows, insert it into the Raspberry Pi 3 and power it on.
  • Connect Raspberry Pi to Monitor or TV using HDMI cable.
  • Select English as the Language and click Continue.

  • Select “I don’t want to connect to a wi-fi network right now” and click Continue.

  • Select an appropriate location on the map to set the timezone and system locale and click Continue

  • Select an appropriate keyboard layout and click Continue.

  • Enter an appropriate Name, Username and Computer name and then a password. Select “Log in automatically” and click Continue.

  • The installer will now proceed to configure the system.

  • When configuration is complete you will see the splash screen below.

  • Go to the System Menu in the top left corner and select Preferences – Internet and Network – Network Connections.

  • Select “Wired connection 1” under Ethernet and click the Edit button. Click on the “IPv4 Settings” tab at the top.

  • Click on the Method drop-down list and select Manual.

  • Enter an appropriate IP Address, a Netmask in CIDR notation and the Gateway address. Enter your networks DNS server address. Click Save. Click Close to finish.



How to install ROS Kinetic on Raspberry Pi 3 (Ubuntu Mate)


The ROS framework is compatible with a short list of Linux distributions. Neither the hardware side is not better. There are just few hardware architectures compatible with ROS. Raspberry Pi is one of the development boards compatible in terms of hardware with ROS.

So, I thought to install ROS Kinetic on the Raspberry Pi 3 running Ubuntu Mate. But only a certain version of Ubuntu Mate is compatible with ROS and Raspberry Pi 3, it is about the Ubuntu MATE for Raspberry Pi 3. This is an OS version released last year and include support for the WiFi and Bluetooth modules integrated into the Pi 3.

The OS version used by me on Raspberry Pi 3 is Ubuntu MATE 16.04.2.

The ROS version that I have installed is Kinetic Kame. Kinetic was released early last year and is compatible with Ubuntu Mate 16.04. I chose this version for two reasons:

  1. it will be officially supported for the next five years;
  2. it is the most complete version after Indigo;

The first step in installing ROS on Raspberry Pi 3 is called Mate. Ubuntu Mate. The operating system is simple to install. I followed the steps on the download page, and within minutes I managed to have a Pi 3 running Ubuntu Mate.

What you find below are the steps to install ROS Kinetic on the Raspberry Pi 3.


Step1 : Go to System -> Administration -> Software & Updates


Step2 : Check the checkboxes to repositories to allow “restricted,” “universe,” and “multiverse.”

Software and Updates



Step3 : Setup your sources. List
sudo sh -c ‘echo “deb $(lsb_release -sc) main” > /etc/apt/sources.list.d/ros-latest.list’


Step4 : Setup your keys
wget -O – | sudo apt-key add –


Step5 : To be sure that your Ubuntu Mate package index is up to date, type the following command
sudo apt-get update


Step6 : Install ros-kinetic-desktop-full
sudo apt-get install ros-kinetic-desktop-full


Step7 : Initialize rosdep
sudo rosdep init
rosdep update


Step8 : Setting up the ROS environment variables
echo “source /opt/ros/kinetic/setup.bash” >> ~/.bashrc
source ~/.bashrc


Step9 : Create and initialize the catkin workspace

mkdir -p ~/catkin_workspace/srccd catkin_workspace/src


cd ~/catkin_workspace/



Step10 : Add the catkin_workspace to your ROS environment

source ~/catkin_workspace/devel/setup.bash

echo “source ~/catkin_workspace/devel/setup.bash” >> ~/.bashrc


Step11 : Check the ROS environment variables
export | grep ROS


The setup looks like in the picture 

Check the ROS installation
  1. Open a new terminal and type: roscore
  2. Open a new terminal and type: rosrun turtlesim turtlesim_node


Testing Rplidar


  • ### Create a ROS Workspace

mkdir -p ~/catkin_ws/src
cd ~/catkin_ws/src

  • ### Clone the ROS node for the Lidar in the catkin workspace src dir

git clone

  • ### Build with catkin

cd ~/catkin_ws/catkin_make

  • ### Set environment when the build is complete

source devel/setup.bash

  • ### Launch demo with rviz

Check the authority of rplidar’s serial-port :

ls -l /dev |grep ttyUSB

Add the authority of write: (such as /dev/ttyUSB0)

sudo chmod 666 /dev/ttyUSB0

Start a rplidar node and view the scan result in rviz.

$ roslaunch rplidar_ros view_rplidar.launch    #for rplidar A1/A2

Start a rplidar node and run rplidar client process to print the raw scan result




Rviz will pop-up and show a background grid. The “view” from the laser scanner will be marked in red. The laser scanner is positioned at the center of the grid, it has a range of roughly 15cm to 6 meters, so you’ll be able to see everything around it on its scanning plane within that range.

A rotary encoder is a device that you can rotate infinitely. Simple ones like this one have no real state like a pot does, so when you start up, you won’t be able to simply read from the encoder where it is turned to. But because you can keep turning it it has no beginning, middle or end anyways. However, if you keep track of that rotation in code, you can use it as a knob input you can turn up or down as much as you would like.

Most simple encoders like this only make use of 4 pins, one of those is ground and other Vcc. Those other two pins change state and are always either high or low, so they can only have a total of 4 combinations. 00, 01, 10, and 11. This is known as 2 bit gray code. So when you turn it, the arduino can say… Well you were at 01, and now you are at 00 so you move this way. Or you were at 01, but now you are at 10 so you must have moved the other way. You can see that this encoder has 5 pins, the other 2 are just a simple switch that is engaged when you press down. (see the second illustration on the right)

It sounds super simple, and it kinda is, but what we can do is every time a value changes we can check what direction it moved. Then if we increment a value every time it turned one way, and deincrement it when we move one step the other, we can keep track of how much it has moved since we started. So if you want a knob that can turn up to 11, this is your guy. (there is a double pun in there I promise)

So, the really funky thing about a rotary encoder is for it to work, we need to know every time those values change. This can be hard because if the arduino is in the middle of doing something, like delay(1000) or what have you, we will miss the change. So we need a way to say to the arduino “I don’t care what you are doing, or when you are doing it, if you see any of these two pins change state, you drop everything and attend to them”. To do this we need something called interrupts.

Interrupts Are Magic

Interrupt pins are special pins that can stop your arduino and force it to do something else before it moves on. Because they are special pins you only get a few of them on your arduino, but these pins can watch for any CHANGE (high to low / low to high), FALLING (high to low) or RISING (low to high). You can attach interrupt functions to these pins, so if a change happens, it will drop everything and run that function. It gets funky as it breaks the basic linear nature of the arduino loop, but can become the most powerful thing when you get the hang of it.

Any global variables that are used inside these functions have a special name. They are called volatile variables, and for good reason. Their values can change at any time. So if you use a volatile twice in your loop, it may not be the same value the second time if it was change during an interrupt function.


To keep track of the rotary encoder we are going to do something that will look really weird, so bear with me. The encoder has 2 digital pins that are either HIGH (1) or LOW (0) right? If we treat the pins as binary, we read them as 00, 01, 10, or 11. The sequence the encoder outputs while spinning clockwise is 00, 01, 11, 10 repeat. So if you have a reading of 01, the next reading can either be 00 or 11 depending on the direction the knob is turned. So by adding the previous encoded value to the beginning of the current encoded value we get 1 of 8 possible numbers (0001, 0010, 0100, 0111, 1000, 1011, 1110 & 1101) 1101, 0100, 0010 & 1011 all mean cockwise movement. 1110, 0111, 0001 & 1000 are all counter-clockwise.

So now we can say this: (sum is last reading + current reading)

if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue ++; //clockwise movement
if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue --; //counter-clockwise movement

If we wanted to treat the binary as decimal numbers we could even shorten that to this:

if(sum == 13 || sum == 4 || sum == 2 || sum == 11) encoderValue ++;
if(sum == 14 || sum == 7 || sum == 1 || sum == 8 ) encoderValue --;

Arduino Code

//these pins can not be changed 2/3 are special pins
int encoderPin1 = 2;
int encoderPin2 = 3;

volatile int lastEncoded = 0;
volatile long encoderValue = 0;

long lastencoderValue = 0;

int lastMSB = 0;
int lastLSB = 0;

void setup() {
  Serial.begin (9600);

  pinMode(encoderPin1, INPUT); 
  pinMode(encoderPin2, INPUT);

  digitalWrite(encoderPin1, HIGH); //turn pullup resistor on
  digitalWrite(encoderPin2, HIGH); //turn pullup resistor on

  //call updateEncoder() when any high/low changed seen
  //on interrupt 0 (pin 2), or interrupt 1 (pin 3) 
  attachInterrupt(0, updateEncoder, CHANGE); 
  attachInterrupt(1, updateEncoder, CHANGE);


void loop(){ 
  //Do stuff here

  delay(1000); //just here to slow down the output, and show it will work  even during a delay

void updateEncoder(){
  int MSB = digitalRead(encoderPin1); //MSB = most significant bit
  int LSB = digitalRead(encoderPin2); //LSB = least significant bit

  int encoded = (MSB << 1) |LSB; //converting the 2 pin value to single number
  int sum  = (lastEncoded << 2) | encoded; //adding it to the previous encoded value

  if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue ++;
  if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue --;

  lastEncoded = encoded; //store this value for next time


1.0 Introduction

A typical rotary incremental encoder consists of a light-emitting diode (LED), a disk, and a light detector on the opposite side of the disk (see next figure). The disk, which is mounted on the rotating shaft, has patterns of opaque and transparent sectors coded into the disk. As the disk rotates, the opaque segments block the light and, where the glass is clear, light is allowed to pass. This generates square-wave pulses, which can then be interpreted into position or motion. These pulses can be read by microcontroller as part of a PID feedback control system to determine translation to distance, rotational velocity, and/or angle of a moving robot or robot part. For instance, if you have a wheel rotating, and you want to measure the time it takes to rotate exactly 40 degrees, or if you want to know when you have traveled X distance, you can use an rotary encoder. The encoder will be fixed on your robot, and the mechanical part (the encoder wheel) will rotate with the wheel. Since the output of an encoder is a square wave, you can then count the pulses if you hook up this signal to a digital counter or microcontroller. Knowing the distance/angle between each pulse, and the time from start to finish, you can easily determine position or angle or velocity or whatever. Encoders are necessary for making robot arms, and very useful for acceleration control of heavier robots. They are also commonly used in robot for maze navigation.


Rotary Incremental Encoder Basic working model

Rotary Encoders usually offer 100 to 6,000 segments per revolution. This means the encoder can provide 3.6 deg of resolution for 100 segments and 0.06 deg of resolution for 6,000 segments. Linear encoders work under the same principle as rotary encoders except that instead of a rotating disk, there is a stationary opaque strip with transparent slits along its surface, and the LED-detector assembly is attached to the moving body.

2.0 Quadrature Encoder

An encoder with one set of pulses is sometime not sufficient because it cannot indicate the direction of rotation. Using two code tracks with sectors positioned 90 degree out of phase (see next figure); the two output channels of the quadrature encoder indicate both position and direction of rotation. For example, if A leads B, the disk is rotating in a clockwise direction. If B leads A, the disk is rotating in a counter-clockwise direction. Therefore, by monitoring both the number of pulses and the relative phase of signals A and B, the microcontroller can track both the position and direction of rotation. In addition, some quadrature encoders include a third output channel – called a zero or reference signal – which supplies a single pulse per revolution. This single pulse can be used for precise determination of a reference position. This signal is called the Z-Terminal or the index in most of encoder. A typical, ideal quadrature signal looks like this:


Quadrature Encoder Output

With incremental encoders, you can measure only changes in position (from which you can determine velocity and acceleration), but it is not possible to determine the absolute position of an object. Another type of encoder, called an absolute encoder, is capable of determining the absolute position of an object. Its function is similar to position feedback using variable resistor (analog output), the only differences are that it can be rotated in 360 degree and digital output. This type of encoder has alternating opaque and transparent segments like the incremental encoder, but the absolute encoder uses multiple groups of segments that form concentric circles on the encoder wheel like a bull’s-eye on a target or dartboard. The concentric circles start in the middle of the encoder wheel and, as the rings go out toward the outside of the ring, each of them has doubled the number of segments than the previous inner ring.

To make encoder measurements, you need a basic electronic component called a counter. Based on its several inputs, a basic counter emits a value that represents the number of edges (low to high or high to low transitions in the waveform) counted. Most of the Microchip PICs have this peripheral; normally Timer 0 or Timer 1 is used as external input counter. External interrupt pins (INT) can also be used for counting the pulse; the rising edge (low to high) or falling edge (high to low) is configurable. Once the edges are counted, the next thing you need to take care is how those values are converted to position, further to speed and etc. The process by which edge counts are converted to position depends on the type of encoding used. There are three basic types of encoding, X1, X2, and X4.

2.1 1X Encoding

You will be able to see the signals shown in the next figure if we are scanning from left to right ; and reverse the direction or scan from right to left on previous figure. This is a quadrature cycle and the resulting increments and decrements for X1 encoding. When channel A leads channel B, the increment occurs on the rising edge of channel A. When channel B leads channel A, the decrement occurs on the falling edge of channel A.


1X Encoding

2.2 2X Encoding

A shortcoming of the previous method is that the count frequency is the same as the frequency of channel A. Thus, an encoder is said to have a resolution of 500 pulses per revolution (ppr) does exactly that. We can do better by using both edges of Channel A. This is not too hard to arrange in hardware but this uses up valuable board space. The equality test described just now works just as well if we are detecting falling edges. Thus we can use the same routine for both rising and falling edges and detect twice as many transitions. With 2X decoding our 500 ppr encoder can generate 1000 pulses per revolution.


2X Encoding

2.3 4X Encoding

It is possible to do even better if we examine the edges of both channel A and channel B. There are four edges for each phase of channel A and it is possible to get 2000 pulses per revolution from our 500 ppr encoder.


4X Encoding

When I cut out the middle part of this signals which shown in the next figure, we can see clearly that the two bit encoder field (A, B) is Gray Code Encoded. Only one of the two bits changes for any given state transition.


4X Encoding State Transition

Furthermore, we can tell whether the wheel is turning clockwise or counter-clockwise based on the state transitions, which are mutually exclusive for the two directions, as shown in the table below.


4X Encoding State Transition Table

Most engineers will be more comfortable with the table above representing a state transition diagram, as shown in figure below.


4X Encoding State Transition Diagram

If you have a microcontroller with the ability to generate interrupt form external source, it is pretty simple to get the count we want. But at least it must has two external interrupt pins for 4X encoding, let’s say we use PIC18F4520 (3 external interrupt pins). Channel A is connected to the INT1/RB1 pin and channel B is connected to the INT0/RB0 pin. The sense of the interrupt is changed after each interrupt so that the routine responds alternately to rising and falling edges. On each interrupt, after determining the current state, we can get the direction by checking back the previous state and Count Value will be increased or decreased. Listing below is the example interrupt routine for PIC18F4520 and the sequence is based on the previous state transition diagram.


4X Encoding Interrupt Routine Listing

Angle of rotation (degree) = (CountValue/XN) x 360 where N = number of pulses generated by the encoder per shaft revolution, X is the encoding type. Let’s say Rotary Encoder B-106-23983 (available from is used, N=500ppr and we use 4X encoding, so our angle of rotation (degree) = CountValue x 0.18. This encoder outputs capable to produce up to 100 kHz pulse, it is good enough for a normal mobile robot. Your microcontroller speed might limit the maximum angular speed of your encoder due to the time for serving interrupt routine. Some of the 8-bit Microchip PIC has Quadrature Encoder Interface (QEI) feature with noise filters like PIC18F2331, PIC18F2431, PIC18F4331 and PIC18F4431. With this model of microcontroller, configure some of the related registers is sufficient; position and velocity of your encoder can be obtained directly without serving the interrupt routine. Hope this article helps in using rotary encoder. If you have any feedback, please discuss in our technical forum:

* If you like to have faster response from author regarding your inquiry/comments/feedback, please do post in our technical forum as we seldom check the comment section in tutorial site.