DC MOTOR RPM Hall Sensor Encoder







Arduino Sketch


#include "SPI.h"
#include "TFT_22_ILI9225.h"

#define TFT_RST 8
#define TFT_RS  9
#define TFT_CS  10  // SS
#define TFT_SDI 11  // MOSI
#define TFT_CLK 13  // SCK
#define TFT_LED 3   // 0 if wired to +5V directly

#define TFT_BRIGHTNESS 200 // Initial brightness of TFT backlight (optional)

TFT_22_ILI9225 tft = TFT_22_ILI9225(TFT_RST, TFT_RS, TFT_CS, TFT_LED, TFT_BRIGHTNESS);

//Arduino PWM Speed Control:
int E1 = 5;  // MOTOR_1
int M1 = 4;  // MOTOR_1
int E2 = 6;  // MOTOR_2                    
int M2 = 7;  // MOTOR_2  

#define PULSES_PER_TURN 2096 / 4

//The sample code for driving one way motor encoder
const byte encoder0pinA = 2;//A pin -> the interrupt pin 0
const byte encoder0pinB = 1;//B pin -> the digital pin 4
byte encoder0PinALast;

boolean Direction;//the rotation direction 

// The pin the encoder is connected


volatile long pulseCount = 0;

unsigned long previousMillis = 0;
unsigned long currentMillis = 0;
int rpm = 0;
int motorPwm = 200;

void setup() {
  
  tft.begin();
  Serial.begin(57600);//Initialize the serial port
  EncoderInit();//Initialize the module

  pinMode(M1, OUTPUT);   
  pinMode(M2, OUTPUT);

  digitalWrite(M1,LOW);   
  analogWrite(E1, motorPwm);

  tft.setFont(Terminal12x16);
  tft.drawText(20, 30, "Maker Tutor", COLOR_WHITE); 
   
  tft.drawText(0, 60,"PWM="+ String( motorPwm) + " /RPM", COLOR_WHITE); 
}

void loop()
{
   currentMillis = millis();
  if (( currentMillis - previousMillis > 1000 ))  
    { 
         previousMillis = currentMillis;
          cli();//noInterupts
         rpm = (float)(pulseCount * 60 / PULSES_PER_TURN );
         pulseCount = 0;
        

         tft.drawText(20, 80, String(rpm), COLOR_RED); 
         sei();//Interupts
    }
    
}
void EncoderInit()
{
  
  pinMode(encoder0pinB,INPUT);  
  attachInterrupt(0, wheelSpeed, CHANGE);
}
void wheelSpeed()
{
  
  pulseCount++;
  
}

ความคิดเห็น