Inputting more than 360 degrees for an encoder

For the encoder target position can i input more than 360 degrees so the motor will
turn more than 360 degrees?
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"
#include <RCSwitch.h>

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
const int encoderPinA = 2;
const int encoderPinB = 3;
volatile int encoderPos = 0;
int encoderPosTarget = 0;
bool direction = true;
const int rfReceiverPin = 11; // RF Receiver connected to pin 11
RCSwitch mySwitch = RCSwitch(); // Create an instance of RCSwitch

void setup() {
Serial.begin(9600);
AFMS.begin();
pinMode(encoderPinA, INPUT_PULLUP);
pinMode(encoderPinB, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(encoderPinA), encoder_ISR, CHANGE);
mySwitch.enableReceive(rfReceiverPin); // Enable the receiver on pin 11
}

void loop() {
if (mySwitch.available()) {
unsigned long receivedValue = mySwitch.getReceivedValue();
handleKeyFobPress(receivedValue);
mySwitch.resetAvailable();
}
}

void encoder_ISR() {
if (digitalRead(encoderPinA) == digitalRead(encoderPinB)) {
encoderPos++;
} else {
encoderPos--;
}
}

void rotateToPosition(int targetPosition) {
if (encoderPos < targetPosition) {
direction = true;
myMotor->run(FORWARD);
myMotor->setSpeed(255); // Adjust speed as needed (0 to 255)
} else {
direction = false;
myMotor->run(BACKWARD);
myMotor->setSpeed(255); // Adjust speed as needed (0 to 255)
}

while (encoderPos != targetPosition) {
if (direction && encoderPos >= targetPosition) {
myMotor->run(RELEASE);
break;
}
if (!direction && encoderPos <= targetPosition) {
myMotor->run(RELEASE);
break;
}
}
}

void handleKeyFobPress(unsigned long receivedValue) {
if (receivedValue == /* code for your specific key fob press */) {
if (direction) {
encoderPosTarget = 180; // Rotate to 180 degrees for example
} else {
encoderPosTarget = 0; // Rotate back to 0 degrees
}
rotateToPosition(encoderPosTarget);
direction = !direction; // Toggle direction flag
}
}

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'

Use code tags (the < CODE/ > icon above the compose window) to make it easier to read and copy for examination

https://forum.arduino.cc/t/how-to-get-the-best-out-of-this-forum

Please post a link to the datasheet.

Input where, when?

Yes.

Please edit your post to add code tags.

Encoder positions are counted in encoder steps, which are rarely degrees.

Did you copy this code from somewhere? The comments would be valid ONLY if the encoder were an absolute angle shaft encoder, with 360 steps per revolution.

encoderPosTarget = 180; // Rotate to 180 degrees for example
} else {
encoderPosTarget = 0; // Rotate back to 0 degrees
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.