Using DC Motors In The Arduino Uno

Introduction
 
In my previous article I had explained about working water flow sensor using Arduino Uno. In this article I'll show you ho to work with DC Motors in the Arduino Uno.
 
Requirements
  • Arduino 
  • 6v DC Motor
  • PN2222 Transistor
  • Diode
  • 270 ohm Resistor
  • led
  • Bread Board
Connection
 
  
 
Led Connection
  • Anode pin to the digital pin 13
  • Cathode pin to the Gnd 
DC Motor
 
DC Motor that converts the direct current electrical power to the mechanical power 
 
PN2222 Transistor
 
It is used for low power amplifying and switching application

 
 
 
 
Programming
  1. int motor=3;  
  2. int led=13;  
  3.   
  4. void setup()  
  5. {  
  6.   pinMode(led,OUTPUT);  
  7.   pinMode(motor,OUTPUT);  
  8.   Serial.begin(9600);  
  9.   if(! Serial);  
  10.   Serial.println("Speed up to 0 to 255");  
  11. }  
  12. void loop()  
  13. {  
  14.   if(Serial.available())  
  15.   {  
  16.     int speed=Serial.parseInt();  
  17.     if(speed >=0 && speed <=255)  
  18.     {  
  19.       digitalWrite(led,HIGH);  
  20.     }   
  21.     else {  
  22.       digitalWrite(led,LOW);  
  23.     }  
  24.       analogWrite(motor,speed);  
  25.     }  
  26.   }  
Explanation
 
Declare the variable as motor and led in int data type then move to the setup() function. In the setup function set the pinMode to the led and the motor led and motor as OUTPUT and set the BaudRate (9600); if (! Serial), then print the value in the serial monitor.
 
After that move to loop() function. Firstly, we want to check the Serial is available are not if it is means  declare the speed variable and intialize Serial.parseInt(). The Serial.parseInt() is used to read the numbers entered as text in serial monitor and convert it to int data type and set the conditions. 
  1. if(speed >=0 && speed <=255)    
  2. {    
  3.     digitalWrite(led,HIGH);  //led ON  
  4. }     
  5. else 
  6. {    
  7.     digitalWrite(led,LOW);    //led OFF
  8. }                                                                                                                                      

Ream more articles on Arduino:

Up Next
    Ebook Download
    View all
    Learn
    View all