Monday, December 15, 2014

Arduino DC Motor Control 2

DC Motor control using Arduino
After controlling a dc motor speed and direction using arduino uno board at this link Arduino DC Motor Control 1 I am going to remove the potentiometer and add two push buttons to control the speed up and down.
In the arduino uno board there are two external interrupts: int0 on digital pin 2 and int1 on digital pin 3. We will use int0 to speed up the motor and int1 to reduce the speed of our motor. I added an led to show that the speed is at maximum value (at pin 12).
The code of the interrupt is as:
  attachInterrupt(0, speed_up, FALLING);
  attachInterrupt(1, speed_down, FALLING);

 When the interrupt at pin 2 occurs a function called speed_up will be called and the 
 speed of our motor will be raised. When the interrupt at pin 3 occurs a function called
 speed_down will be called and the speed is going to go down.
 The circuit is shown below: 


arduino dc motor speed control arduino code

Arduino DC motor control code:
#include <PWM.h>
int32_t frequency = 20000; //pwm frequency in Hz
  int s = 0;
   void setup(){
  pinMode(0, OUTPUT);
  pinMode(1, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(4, INPUT_PULLUP);
  pinMode(5, INPUT_PULLUP);
  pinMode(6, INPUT_PULLUP);
  attachInterrupt(0, speed_up, FALLING);
  attachInterrupt(1, speed_down, FALLING);
   InitTimersSafe();
  bool success = SetPinFrequencySafe(9, frequency);
  }
 int fwd(){
   while(1){
   digitalWrite(0,HIGH);
   digitalWrite(1,LOW);
   if (digitalRead(6)==0) break;}}
  
 int pwd(){
   while(1){
   digitalWrite(0,LOW);
   digitalWrite(1,HIGH);
   if (digitalRead(6)==0) break;}}
   
  void loop()
 {
  digitalWrite(0,LOW);
  digitalWrite(1,LOW);
  digitalWrite (12,LOW);
  digitalWrite(13, LOW);
  pwmWrite(9,s);
  if (digitalRead(4)==0) {digitalWrite(13, HIGH);fwd();}
  if (digitalRead(5)==0) {digitalWrite(13, HIGH);pwd();}
 }
 void speed_up(){
   s = s + 5;
   if (s >255){
    s = 255;
    digitalWrite (12,HIGH);}
    else digitalWrite (12,LOW);
 pwmWrite(9,s);
  }
 void speed_down(){
   s = s - 5;
   if (s <5) s = 0;
   pwmWrite(9,s);
   digitalWrite (12,LOW);
  }

Arduino DC motor control video:
Last this video has some explanations.