sagar saini
Published © GPL3+

BO Motor With Encoder Gives Precise Movement

To precisely control the BO motor or to make any low cost project using PID we can consider this types of encoder integration with motors.

BeginnerFull instructions provided1.5 hours365
BO Motor With Encoder Gives Precise Movement

Things used in this project

Hardware components

Arduino Nano R3
Arduino Nano R3
×1
DFRobot BO motor
×1

Software apps and online services

Arduino IDE
Arduino IDE
EasyEDA
JLCPCB EasyEDA

Hand tools and fabrication machines

Soldering iron (generic)
Soldering iron (generic)
Solder Wire, Lead Free
Solder Wire, Lead Free

Story

Read more

Schematics

Reference Schematics of encoder

Code

Velocity code

Arduino
//The sample code for driving one way motor encoder
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_RESET 1
Adafruit_SSD1306 display(128, 64, &Wire, OLED_RESET);
const byte encoder0pinA = 2; //A pin -> the interrupt pin 0
const byte encoder0pinB = 3; //B pin -> the digital pin 3
byte encoder0PinALast;       //Store the previous state of pin

int duration;     //the number of the pulses
boolean Direction;//the rotation direction


void setup()
{
  Serial.begin(9600);//Initialize the serial port
  EncoderInit();     //Initialize function for encoder
  Wire.begin();
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.clearDisplay();
}

void loop()
{
  Serial.print("Pulse:");
  Serial.println(duration);
 
  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  display.print("Pulse:");
  display.display();

  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(50,30);
  display.print(duration/2);
  display.display();
  duration=0;
  delay(300);
  
}

void EncoderInit()
{
  Direction = true;   //default -> Forward
  pinMode(encoder0pinB,INPUT);
  attachInterrupt(0, wheelSpeed, CHANGE); // digitalPinToInterrupt(interruptPin) instead of 0
// syntax of interrupt will be = interrupt pin, function to be executed, Condition of Function HIGH, LOW, CHNAGE, RISING AND FALLING
}

void wheelSpeed()
{
  int Nstate = digitalRead(encoder0pinA);
  if((encoder0PinALast == LOW) && Nstate==HIGH)
  {
    int val = digitalRead(encoder0pinB);
    if(val == LOW && Direction)
    {
      Direction = false; //Reverse
    }
    else if(val == HIGH && !Direction)
    {
      Direction = true;  //Forward
    }
  }
  encoder0PinALast = Nstate;

  if(!Direction)  duration++;
  else  duration--;
}

Credits

sagar saini

sagar saini

73 projects • 69 followers
I am Sagar Saini an electronic hardware enthusiast

Comments