Here is an update,
I wanted to use a normal encoder (KY-40) for centering. But it is not precise and sometimes jumps and won't center properly.
So, I changed my mind, I am going to use a PS2 mouse as an encoder, which is very precise.
The mouse will be mounted on steering shaft to record shaft position. Accordingly Arduino will control DC motor to center the shaft.
I have tested the PS2 mouse with L298N and 12V DC Motor. It does move motor as intended.
I would like to add PID control to this system. Can someone help me with the PID loop?
Here's the code
#include "PS2Mouse.h"
#define in1 8 //output pin - when this pin is high motor rotates in CW direction
#define in2 9 //output pin - when this pin is high motor rotates in CCW direction
#define enA 10 //PWM signal to enable motor rotation
int counter = 5000;
int motorSpeed = 0;
int counter1 = 0;
PS2Mouse mouse(6,5);
void setup()
{
Serial.begin(9600);
// Set motor pins as outputs
pinMode (in1,OUTPUT);
pinMode (in2,OUTPUT);
pinMode (enA,OUTPUT);
}
void loop(){
uint8_t stat;
int x,y;
mouse.getPosition(stat,x,y);
if (x>0)
{
counter = counter + x;
}
else if (x<0)
{
counter = counter + x;
}
Serial.println(counter);
if (counter > 5050) // if steering is moved, mouse should detect the movement, thus we know motor needs to start tuning to bring steering back to center
{
digitalWrite(in1, HIGH); // move motor in CW direction
digitalWrite(in2, LOW);
motorSpeed = map(counter, 5050, 8000, 0, 255);
}
else if (counter < 4950)
{
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH); // move motor in CCW direction
counter1 = counter1 - 10000 ;
counter1 = counter1 * -1;
motorSpeed = map(counter1, 5050, 8000, 0, 255);
}
else
{
motorSpeed = 0; // stop motor
}
if (motorSpeed > 255) motorSpeed = 255;
analogWrite (enA, motorSpeed);
}