Hello everyone,
I'm working on a motor control project for my mechatronics engineering course, and I've run into a challenge that I hope you can help me solve.
The goal is to control a motor to rotate toward a desired position and then return to its initial position (0). The important thing is that the home position is saved in some way so that in the event of a power outage or other unwanted interruption, we can recover and return the motor to this home position.
I have written a code base (see below) that uses an encoder to track the motor position, but I am having difficulty implementing an effective way to save and retrieve the motor position using EEPROM. Especially to ensure that the position is kept up to date without overwrite the EEPROM too much.
Here is the code I've been working on:
// Defines the pin for encoder B
const int pinEncoderB = 3; // Make sure the pin supports interrupts
// Defines the pins for motor control
const int pinMotorControl1 = 7; // PWM pin to control speed or direction
const int pinMotorControl2 = 8; // PWM to control speed or direction
const int pinEnableMotor = 6; //Enable pin for motor driver
long encoderValue = 0;
long desiredPosition = 177; // Degrees with an error of +2 due to the error
void setup() {
pinMode(pinEncoderB, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(pinEncoderB), readEncoder, CHANGE);
pinMode(pinMotorControl1, OUTPUT);
pinMode(pinMotorControl2, OUTPUT);
pinMode(pinEnableMotor, OUTPUT);
Serial.begin(9600);
}
void loop() {
long positionError = desiredPosition - encoderValue;
if (encoderValue < desiredPosition) {
//Moves the motor forward
analogWrite(pinEnableMotor,100); //Enable motor
digitalWrite(pinMotorControl1, HIGH);
digitalWrite(pinMotorControl2, LOW);
} else {
// Stops the engine
digitalWrite(pinEnableMotor, LOW);
}
Serial.println(encoderValue);
}
void readEncoder() {
// Increase the encoder value with each change
encoderValue++;
}
This are my questions:
- How can I modify my code to correctly implement the EEPROM save functionality and retrieve motor position effectively and safely?
- Is there a better strategy to handle unwanted interruptions, such as power outages, by ensuring that the motor returns to its initial position upon restart?
Any suggestions, code examples, or references to relevant documentation would be greatly appreciated.
Thank you in advance for your help!