Hi
I'd like to build a robot car and I'd like to control its position with PID, because when I tell it for example go forward 100 steps, then it goes 105 steps. And I'd like to prevent this overshooting with PID.
I made a simple code, but it's not the best because I control the speed of the motor and when the analog value goes under 120 then the motor stops, simply there is no enough volts.
I would like to know that, can I make a PID that controls my motors with constant analog value(around 150), and the PID's output would be the steps. What should I change? Sorry for my stupidity, I'm a newbie.
Here is my code:
#include <Arduino.h>
#include <analogWrite.h>
#include <PIDController.h>
PIDController pos_pid;
//motor control
const int A_mspeed = 32;
const int B_mspeed = 13;
const int in1 = 33;
const int in2 = 25;
const int in3 = 26;
const int in4 = 27;
double speed = 0;
int motor_value = 255;
//encoder pins
const int encoderA = 18;
const int encoderB = 19;
volatile long int A_encodercnt = 0;
volatile long int B_encodercnt = 0;
//increase the encoder's value
ICACHE_RAM_ATTR void encoderA_IR(){
A_encodercnt++;
Serial.print("A: ");
Serial.println(A_encodercnt);
}
/*
ICACHE_RAM_ATTR void encoderB_IR(){
B_encodercnt++;
Serial.print("B: ");
Serial.println(B_encodercnt);
}
*/
void MotorClockwise(int power){
if(power > 50){
analogWrite(A_mspeed, power);
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
}else{
analogWrite(A_mspeed, 0);
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
}
}
void MotorCounterClockwise(int power){
if(power > 50){
analogWrite(A_mspeed, power);
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
}else{
analogWrite(A_mspeed, 0);
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
}
}
void setup() {
Serial.begin(115200);
//motor pins
pinMode(A_mspeed,OUTPUT);
pinMode(B_mspeed,OUTPUT);
pinMode(in1,OUTPUT);
pinMode(in2,OUTPUT);
pinMode(in3,OUTPUT);
pinMode(in4,OUTPUT);
//detect rising edge
//attachInterrupt(digitalPinToInterrupt(encoderB), encoderB_IR, RISING);
attachInterrupt(digitalPinToInterrupt(encoderA), encoderA_IR, RISING);
pos_pid.begin();
pos_pid.tune(20, 0, 200);
pos_pid.limit(-255, 255);
pos_pid.setpoint(20);
}
void loop() {
motor_value = pos_pid.compute(A_encodercnt);
if(motor_value > 0){
MotorCounterClockwise(motor_value);
}else{
MotorClockwise(abs(motor_value));
}
Serial.println(A_encodercnt);
Serial.println(motor_value);
delay(2);
}