Heyy guys, I am using Flysky module to rotate a motor, I am using N20 encoder and LN298N motor Diver. The output I have set is RPM, No of turns, etc.
I want that when I turn the joystick up the motor should rotate and when I leave the joystick or pull it back to the initial position, the motor should rotate the same no of turns in the opposite direction as it has turned while moving the joystick up. This is my code, let me know what changes I should do.
#define ENCODEROUTPUT 1800
const int HALLSEN_A = 3; // Hall sensor A connected to pin 3 (external interrupt)
int in1 = 2;
int in2 = 11;
int enable1 = 5; // pin with ~ symbol
int channel_2 = 6; // pin with ~ symbol
//The sample code for driving one way motor encoder
volatile long encoderValue = 0;
long initialEncoderValue = 0;
int interval = 1000;
long previousMillis = 0;
long currentMillis = 0;
int rpm = 0;
boolean measureRpm = false;
int motorPwm = 0;
void setup() {
pinMode(channel_2, INPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(enable1, OUTPUT);
Serial.begin(57600);//Initialize the serial port
EncoderInit();//Initialize the module
encoderValue = 0;
previousMillis = millis();
}
void loop() {
int pwm = 0;
int value = pulseIn(channel_2, HIGH, 25000);
Serial.println(value);
if (value == 0)
{
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
analogWrite(enable1, 0);
}
else if (value > 1530)
{
pwm = map(value, 1530, 2000, 0, 255);
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
analogWrite(enable1, pwm);
}
else
{
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
analogWrite(enable1, 0);
}
// Update RPM value on every second
currentMillis = millis();
if (currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
// Calculate the number of turns from the initial position
float turns = (float)(encoderValue - initialEncoderValue) / ENCODEROUTPUT;
// Only update display when there have readings
if (turns > 0) {
Serial.print("Number of turns: ");
Serial.print(turns);
}
// Revolutions per minute (RPM) =
// (total encoder pulse in 1s / motor encoder output) x 60s
rpm = (float)(encoderValue * 60 / ENCODEROUTPUT);
// Only update display when there have readings
if ( rpm > 0)
{
Serial.print(encoderValue);
Serial.print(" pulse / ");
Serial.print(ENCODEROUTPUT);
Serial.print(" pulse per rotation x 60 seconds = ");
Serial.print(rpm);
Serial.println(" RPM");
}
encoderValue = 0;
}
}
void EncoderInit()
{
// Attach interrupt at hall sensor A on each rising signal
attachInterrupt(digitalPinToInterrupt(HALLSEN_A), updateEncoder, RISING);
}
void updateEncoder()
{
// Add encoderValue by 1, each time it detects rising signal
// from hall sensor A
encoderValue++;
}

