Codearrduinohead
Codearrduinohead
h>
void setup() {
// Set pin modes
pinMode(enablePin, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(pulPin, OUTPUT);
pinMode(lmswPin1, INPUT_PULLUP); // Use internal pull-up resistor for limit
switch pin 1
pinMode(lmswPin2, INPUT_PULLUP); // Use internal pull-up resistor for limit
switch pin 2
Serial.begin(115200);
Timer1.initialize(10000);
Timer1.attachInterrupt(stepMotor);
rotateMotor(true);
}
String previousCocheck = "off";
void loop() {
Serial.println(cocheckCopy);
previousCocheck = cocheckCopy;
}
if (cocheckCopy == "on" && Serial.available() > 0) {
String command = Serial.readStringUntil('\n');
Serial.println("ACK");
if (command == "a") {
rotateMotor(true);
} else if (command == "b") {
rotateMotor(false);
} else if (command == "c" || command == "None") {
// Stop the motor
isRunning = false;
Timer1.stop(); // Stop the timer interrupt
}
delay(10);
}
void stepMotor() {
// Check the limit switch state
bool currentLmswState1 = digitalRead(lmswPin1);
if (currentLmswState1 == LOW && previousLmswState1 == HIGH) {
handleLimitSwitch(true);
cocheck = "on";
}
previousLmswState1 = currentLmswState1;
bool currentLmswState2 = digitalRead(lmswPin2);
if (currentLmswState2 == LOW && previousLmswState2 == HIGH) {
handleLimitSwitch(false);
cocheck = "on";
}
previousLmswState2 = currentLmswState2;
if (isRunning || limitSwitchPressed) {
// Check limit switch state
if (limitSwitchPressed) {
// Set direction pin based on limit switch direction
digitalWrite(dirPin, limitSwitchDirection ? HIGH : LOW);
}
// Generate a pulse
digitalWrite(pulPin, HIGH);
delayMicroseconds(5);
digitalWrite(pulPin, LOW);
delayMicroseconds(5);
if (--stepsToSend <= 0) {
// Stop the motor after sending the required steps
isRunning = false;
limitSwitchPressed = false; // Reset limit switch flag
Timer1.stop();
cocheck = "on";
}
}
}