tutorials

My Blog

Latest blog
In previous tutorials we learnt "How to use a pushbutton with Arduino" and "How to control DC motor with Arduino". In this article we will see how to control Servo Motors. Servo motors are very useful in many projects, mostly robotic. Before we can control one we have to know what a Servo motor is and how it works.

Introduction To Servo Motor:

There are many types of servo motors in the market in a variety of form factors. But all work in a similar fashion. Unlike a DC motor which rotates 360° a Servo motor just travels 180° and has a gear system which increases the torque.



servo

In above image you can see the internals of a standard hobby servo. It consists of 3 important parts, the motor, control circuit and drive gears. All of these are enclosed in a case. The circuit is a closed loop motor controller with a feed back potentiometer. The potentiometer sends feedback to the circuit which tells the current position of the servo shaft.

Pinouts:

servo

As you can see in the image Servo has 3 pins. Signal, Vcc and Gnd, these pins can be recognized based on the colour of the wire. Usually Orange/Yellow is the signal wire, Red is Vcc and Black is Gnd.

Now that you are familiar with pins of servo we can move on to see how we can control a servo using Arduino. Before that here are some things you will need:

Requirement:

Now that you have gathered all the required components, we can move forward to control the servo.


Controlling Servo Using Arduino:

To control servo we need PWM signals, PWM stands for Pulse Width Modulation. In PWM a digital pin is used to generate a square wave. It is a signal created by high and low pulses with an equal interval of time. The duration of on time / High signal is called as Pulse Width and controlling the duration can create different frequencies.


Arduino PWM
Arduino has 6 PWM pins (3,5,6,9,10 & 11). As arduino is a 8-bit controller its PWM is 0-255, 0 being lowest and 255 being highest. When the output is 255 the pin is at 5v constant, for 127 it is 2.5v and so on.

To control the Servo we will use this feature of the arduino. So lets start with something simple.

  1. Simple Servo Control With Arduino:




First connect the servo to arduino as shown in the figure. The Vcc is connected to 5v, Gnd is connected to Gnd and Signal pin is connected to pin 9. The servo is powered directly from arduino but if you are planning to use more than one servo, I suggest using an external power supply. For more information of power requirements of your servo check it's data sheet. 

Now refer the code bellow:

#include<Servo.h> //import the servo library

Servo myServo; //set servo variable as myServo


void setup()
{
   myServo.attach(9); //connect servo signal to pin 9
}

void loop()

{
   for(int i=0; i <= 180; i++) //goes 0 to 180 real quick ;p
   {
      myServo.write(i); //writes the value to turn servo 
      delay(50); //50ms delay
   }
   
   for(int i=0; i>= 0; i--) //goes form 180 to 0 
   {
      myServo.write(i); //writes the value to turn servo
      delay(50); //50ms delay
   }
}

Upload this code to uno. You will notice the servo sweeps from end to end. 



This code is best for checking if a servo is working. But for most projects we need a precise way to control servo angle. For that we will use a potentiometer.

2. Controlling Servo Using Potentiometer:

servo motor

In this circuit the servo connections are similar to previous one. Here we have added a 10k ohm potentiometer (variable resistor). The central terminal of pot is connected to A0 pin, other two pins are connected to 5v and Gnd. The pot will be used to generate analog values which we will map to the servo. Thus the change in resistance of the potentiometer will help us control the movement of servo precisely.

Lets take a look at the code:

#include<Servo.h>

Servo myServo;
int potPin = 0; //Set a variable named potPin as A0

void setup()
{
  myServo.attach(9);
}

void loop()
{
  int val = analogRead(potPin); // read the pot value,save it in val
  val = map(val, 0, 1023, 0, 180); //scale the pot readings to 0-180
  myServo.write(val); //set the servo position according to val
  delay(50); //50ms delay
}

Upload the code to arduino and you should see the servo move to a specific position. It depends on the position of potentiometer. Now turning the pot will move the servo head.


The above method combined with other projects can be used for many applications like RC toys, robots and much more. We will see some projects related to it in future. 

That's all for this tutorial. If you have any doubts or questions, feel free to ask in the comment. If you like my tutorials do follow for more. 

See you in next tutorial, until then keep experimenting... ;)
Are you a beginner and want to get into robotics? then you must have many questions in mind like "How to make the robot move?" or "which tools to use to make the robot move?". If you are anything like me then you probably have disassembled tons of toys to figure that out. Most common thing you find in these toys are DC motors. 

In this tutorial we will see, how to control a DC Motor, it's speed and direction using arduino and L293D motor driver IC.

So without wasting any more time, lets get right into it.


Requirements:

For this project we will need,
So every thing in the list might look familiar except "L293D". Let me explain about this IC in a simple and short term. L293D is a motor drive IC which can be used to control 2 DC motors or 1 Stepper motor. It has 2 H-bridges which helps control the speed and direction of  motors. 

l293d ic

We cannot connect a motor directly to arduino as it will fry the board instantly. So we use a motor driver like L293D or L298N. You can find motor driver modules and shields online which help control multiple motors but for this tutorial we will stick with minimum for learning the basics. 

In the above image you can see the pin outs of the IC. Each side controls one motor. For this tutorial we will control one motor using arduino.

 Pin No
 Function
 Name
1
Enable pin for Motor 1
Enable 1,2
2
Input 1 for Motor 1
Input 1
3
Output 1 for Motor 1
Output 1
4
Ground 
Ground
5
Ground 
Ground
6
Output 2 for Motor 1
Output 2
7
Input 2 for Motor 1
Input 2
8
 Power the Motors
 Vcc 2
9
Enable pin for Motor 2
Enable 3,4
10
Input 1 for Motor 1
Input 3
11
Output 1 for Motor 1
Output 3
12
Ground 
Ground
13
Ground 
Ground
14
Output 2 for Motor 1
Output 4
15
Input2 for Motor 1
Input 4
16
Power the IC
Vcc 1


Connections:


motordriver

Here we have connected the input pins of IC to arduino:
  • IN1 to Pin 8
  • IN2 to Pin 9
  • Enable1 to Pin 5 (PWM)
Pin 4,5,12,13 of IC are connected to GND of Arduino and battery. If you don't do this, the motor will not work.



Connect Pin 8 and 16 of the IC to +ve terminal of 9v battery. This will power our motor and the IC itself. 



That's all we need to do. now we can write code to control the motor.

Coding:

#define ENA1 5 //Sets pin 5 of arduino as Enable1
#define IN1 8 // Sets pin 8 of arduino as Input 1
#define IN2 9 // Sets pin 9 of arduino as Input 2

 void setup()
{
//Set all pins as output
   pinMode(ENA1, OUTPUT);
   pinMode(IN1, OUTPUT);
   pinMode(IN2, OUTPUT);
}

 void loop()
{
   analogWrite(ENA1, 255); //Sets speed of motor using PWM
   digitalWrite(IN1, HIGH); //Input 1 is turned on
   digitalWrite(IN2, LOW); //Input 2 is turned off
   delay(3*1000); //Runs for 3 seconds

   analogWrite(ENA1, 255);
   digitalWrite(IN1, LOW); //Both inputs are turned off
   digitalWrite(IN2, LOW);
   delay(2*1000); // Waits for 2 seconds

   analogWrite(ENA1, 255);
   digitalWrite(IN1, LOW); // Input 1 is off
   digitalWrite(IN2, HIGH); // Input 2 is on
   delay(3*1000); //Runs for 3 seconds

   analogWrite(ENA1, 255);
   digitalWrite(IN1, LOW);
   digitalWrite(IN2, LOW);
   delay(2*1000);
}

Let's brake down the code to make it easy to understand.

First we define pins that we will be using.

#define ENA1 5
#define IN1 8
#define IN2 9
 

Here the ENA1 pin is connected to pin 5 of arduino as it is a PWM enabled pin. This will help us control the speed of our motor.
Next there are pins 8 and 9 connected to pin IN1 and IN2 respectively. These pins will make the motor start, stop and change direction depending on which pin is HIGH/LOW. 

void setup()
{
   pinMode(ENA1, OUTPUT);
   pinMode(IN1, OUTPUT);
   pinMode(IN2, OUTPUT);
}


In the setup we set the purpose of the declared pins, in this case all pins are set as output. 

Now comes the loop function. The code in this part runs in a loop.

  analogWrite(ENA1, 255);
 digitalWrite(IN1, HIGH);
 digitalWrite(IN2, LOW);
 delay(3*1000); 


Here notice the function analogWrite(ENA1, 255) we are using the PWM feature of pin 5. The PWM value can be anything between 0-255, where 0 will turn off the motor and 255 will spin the motor at full speed. Varying the value between 1-254 will give different speeds.
Next two functions are digitalWrite, these these sets a pin either HIGH or LOW. As in the above example, the IN1 is HIGH and IN2 is LOW, this will make the motor turn in one direction. Right or Left depending on the way you connected the terminals.

Swapping the HIGH and LOW will change the direction of rotation, and making both LOW/HIGH Will make the motor stop.


Now that you have an idea of the code, it's time to upload the code. So connect your arduino to PC and upload the code.

Testing:

Now that the code is uploaded, power the motors and IC with 9v as shown in the circuit in previous step. You will see that the motor spins in one direction for 3 seconds then stops for 2 seconds and spins in other direction.



Here you can see the code in action. Now you can edit the code and change the values in analogWrite. Make it anything between 0-255 and see the results. Similarly you can control one more motor with L293D.

That's all for this tutorial. Now you know how to control DC motors using Arduino. There are other better methods like using Motor drive modules and shields but that's a topic for another tutorial. Till then keep experimenting. 

Feel free to ask any doubts or leave any suggestions. If you liked the tutorial, follow for more. It's totally free!

arduino pushbutton


In last tutorial I shared a quick introduction to Arduino Uno. We also learnt how to program the microcontroller to blink a LED. In this article I will show you how to use a Pushbutton to control the LED. It will be very useful for future projects. So without wasting any more time, lets begin.


Requirement:


Once you have everything we need, we can connect it all and make a circuit. But before that, lets first see how a push button works.

How A Push Button Works:

To understand the working refer to the diagram. Usually push buttons have 4 pins marked as 1,2,3 & 4. The pins in vertical line are connected together. The circuit is completed when button is pressed and pins 1,3 and 2,4 are shorted. 
Pushbutton


Circuit:

The circuit is simple. Just connect the LED to pin no. 10. Make sure to use a 220ohm resistor or you might damage the LED. The button is not so hard either. Just connect one terminal of the button to pin no. 2 and ground via 220ohm resistor. Connect the other terminal to 3.3v. Refer the diagram below for better understanding.

pushbutton switch


The circuit when assembled on a breadboard should look like following: 


Coding:

Now that we have made a circuit, we can write a code to use it. The first code is very simple.

#define LED 10 //Declared pin 10 as LED
#define btn 2  //Declared pin 2 as btn
int btn_state = 0;  //Declared a variable btn_state and set it as 0

void setup()
{
   pinMode(LED, OUTPUT);  //Sets pin 10 (LED) as OUTPUT
   pinMode(btn, INPUT);  //Sets pin 2 (btn) as INPUT
 }

 void loop()
 {
    btn_state = digitalRead(btn); //Reads the input of pin 2 and save it in btn_state
    if(btn_state == HIGH)  //If the button is pressed
    {
        digitalWrite(LED, HIGH); //Turn on the LED
     }
     else
     {
        digitalWrite(LED, LOW); //Else turn off LED
      }
   }

This first code is simple, when the button is pressed LED turns on and remains on until  the button is pressed. You can see how it works in the GIF bellow.


This works very well but sometimes we need a different arrangement. Lets say we want to toggle LED on and off using the same switch. For that we will have to make some changes to the code. 

To use the pushbutton as a toggle switch we need to remember the switch state. For saving the state we will use flags. 

Flags are variables that save the state of a pin (High/low or integers).
Lets take a look at the code:


#define LED 10 //Declared pin 10 as LED
#define btn 2 //Declared pin 2 as btn

int btn_state = 0; //Declared variable to store state (Low by default)

int flag = 0; //Declared variable flag to store switch state


void setup() 

{
  pinMode(LED, OUTPUT); //Set LED as output
  pinMode(btn, INPUT); //Set btn as input
  digitalWrite(LED, LOW); //Sets LED LOW by default
}

void loop() 

{
  btn_state = digitalRead(btn); //Store btn state (HIGH/LOW)in variable

  if(btn_state == HIGH)//If btn is pressed

  {
    if(flag == 0) //Check if flag is 0
    {
      digitalWrite(LED, HIGH); //Turn LED on
      flag = 1; //Set flag to 1
    }
    else if(flag == 1) //If flag is 1
    {
      digitalWrite(LED, LOW); //Turn LED off
      flag = 0; //Set flag to 0
    }
  }
}

After uploading the above code, you will notice that the LED is off by default. Now press the button once and the LED should turn on. It will remain on until the button is pressed again. 



Now you will notice some error. The circuit is not working as it is supposed to. The button press is registered multiple times or isn't registered at all. This is because of button bouncing.

What Is Switch Bouncing?

Switch bouncing is a real world problem that we mostly ignore in theory. It is a common problem which at times can be very annoying. In switches a metal plate is pressed down to short contacts of the terminals. In theory when a button is pressed the contact should be made and switch should be closed. But what happens is when we press the button, before fully closing the metal plate bounces between the terminals in microseconds. This is not noticeable to humans but this rapid vibration generates a quick pulse of on/off in the microcontroller giving error in the results.

To over come this problem we need to add a debouncing method in out code. In next code we will add a simple debouncing feature which will eliminate the errors and give us a cleaner result.

Refer to the code below:
#define LED 10
#define btn 2 

int btn_state = 0; 
int flag = 0; 

long lastDebounceTime = 0; // the last time the output pin was toggled 
long debounceDelay = 200; // the debounce time 

void setup() 

   pinMode(LED, OUTPUT); 
   pinMode(btn, INPUT); 
   digitalWrite(LED, LOW); 


void loop() 

   btn_state = digitalRead(btn); 
   
   //Filters out the noise by setting a time buffer
   if ( (millis() - lastDebounceTime) > debounceDelay) 
   { 
     if(btn_state == HIGH) 
     { 
       if(flag == 0) 
       { 
          digitalWrite(LED, HIGH); 
          flag = 1; 
          lastDebounceTime = millis(); //Sets current time
        } 
       else if(flag == 1) 
       { 
         digitalWrite(LED, LOW); 
         flag = 0; 
         lastDebounceTime = millis(); //Sets current time
        } 
      } 
    } 
}

In above code we have used a simple debounce method, to explain in simple terms what we do is use a delay (200ms) after the first contact of the plate. So when a button is pressed and first contact is made the code sets a 200ms timer until which all other contacts are ignored thus filtering out all noise.



After uploading the code you will notice a better result. The LED turns on and off with every button press. This debounce code can be used in any project where you have used push buttons or switches to eliminate errors.

That's all for this tutorial, hope you like it and understand the concepts. Now you can experiment with multiple LEDs and Buttons to get better at coding. 

If you like my tutorials and want more, feel free to leave a comment and follow for more updates. 

Contact Us

Contact With Us

Followers

Translate

Get in touch with us.

  • +91 7276861817
  • projecthub.in@protonmail.com