I'm trying to control the speed of RMCS 2292 DC motor which has an attached encoder.
#include <PID_v1.h>
#define encoder0PinA 2
#define motor 7 //motor PWM pin
volatile unsigned int encoder0Pos = 0;
volatile unsigned int user_input = 0;
volatile unsigned int rpm;
int reqrpm;
double Setpoint, Input, Output;
double Kp=2, Ki=5, Kd=1;
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);
const int sampleRate = 1;
void setup() {
pinMode(encoder0PinA, INPUT);
digitalWrite(encoder0PinA, HIGH); // turn on pull-up resistor
pinMode(motor,OUTPUT);
attachInterrupt(digitalPinToInterrupt(2), doEncoder, RISING); // encoder pin on interrupt 0 - pin 2
Serial.begin (9600);
Serial.println("start"); // a personal quirk
Input = map(rpm, 0, 30, 0, 255);
//turn the PID on
myPID.SetMode(AUTOMATIC);
myPID.SetSampleTime(sampleRate);
reqrpm = 15;
Setpoint = map(reqrpm, 0, 30, 0, 255);
}
void loop() {
encoder0Pos = 0;
delay(1000);
float rpm = encoder0Pos*0.0005291*60;
Input = map(rpm, 0, 30, 0, 255);
myPID.Compute();
analogWrite(motor, Output);
Serial.println(rpm);
}
void doEncoder() {
encoder0Pos++;
}
The problem is that it doesn't run continuously. Whatever the delay time is given, it runs and stops for that amount of time. I want it to run continuously. When I try to run it without the PID implemented, it runs continuously. What should I do? Oh, I am using a motor driver to control the speed.