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
}
}