Using NEMA 23 stepper motor with R60 and 20x4 LCD but while changing the speed of motor and display the same. I tried with Timer interrupt one for LCD display and one for Motor running code but not able to fix it. Below I am pasting my code. Can somebody provide their guidance to fix this issue?
#include <AccelStepper.h>
#include <LiquidCrystal.h>
// Initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
#define stepPin 10
#define dirPin 11
// Define the pins for the switches
const int increaseSpeedPin = 15;
const int decreaseSpeedPin = 16;
// Define the stepper motor and the pins it will use
AccelStepper stepper(AccelStepper::DRIVER, stepPin, dirPin); // Pin 2 for STEP, Pin 3 for DIRECTION
// Variables to store the current speed
int speed = 800;
int last_speed = 0;
const int maxSpeed = 6000; // Adjust this value as needed
unsigned long currentMillis = 0;
unsigned long lastDebounceTimeSpeedUp = 0;
unsigned long lastDebounceTimeSpeedDown = 0;
const unsigned long debounceDelay = 150; // Debounce delay in milliseconds
const unsigned long displayDelay = 150; // Debounce delay in milliseconds
void setup() {
// Set up the LCD's number of columns and rows:
lcd.begin(20, 4);
lcd.print("Motor Speed: ");
lcd.print(speed);
// Set up the pins for the switches
pinMode(increaseSpeedPin, INPUT_PULLUP);
pinMode(decreaseSpeedPin, INPUT_PULLUP);
// Set the maximum speed and acceleration
stepper.setMaxSpeed(maxSpeed);
stepper.setAcceleration(500); // Adjust this value as needed
noInterrupts(); // Disable all interrupts
// Enable pin change interrupt for PCINT12 (PC4), PCINT10 (PC2), and PCINT9 (PC1)
PCICR |= (1 << PCIE1); // Enable pin change interrupt for PCINT[14:8]
PCMSK1 |= (1 << PCINT12) | (1 << PCINT10) | (1 << PCINT9); // Enable interrupts for PCINT12, PCINT10, and PCINT9
interrupts(); // Enable all interrupts
stepper.setSpeed(speed);
}
void loop() {
// Run the stepper motor at the set speed
stepper.runSpeed();
// Check if the increase speed button is pressed
if(speed != last_speed) {
lcd_disp();
}
}
void lcd_disp() {
currentMillis = millis(); // Get the current time
if (digitalRead(increaseSpeedPin) == LOW && (currentMillis - lastDebounceTimeSpeedUp) > displayDelay) {
lastDebounceTimeSpeedUp = currentMillis;
lcd.setCursor(13, 0);
lcd.print(" "); // Clear previous value
lcd.setCursor(13, 0);
lcd.print(speed);
last_speed = speed;
}
}
ISR(PCINT1_vect) {
currentMillis = millis(); // Get the current time
if (digitalRead(increaseSpeedPin) == LOW && (currentMillis - lastDebounceTimeSpeedUp) > debounceDelay) {
lastDebounceTimeSpeedUp = currentMillis;
speed += 25;
stepper.setSpeed(speed);
} else if(digitalRead(decreaseSpeedPin) == LOW && (currentMillis - lastDebounceTimeSpeedDown) > debounceDelay) {
lastDebounceTimeSpeedDown = currentMillis;
speed -= 25;
stepper.setSpeed(speed);
}
}