I am trying to write a program to increase and decrease the rpm of a stepper motor using two pushbuttons. The button counter seems to work, but the stepper motor's speed is not changing. i am wondering if it is a problem with the loop function.
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <ezButton.h>
#include <AccelStepper.h>
// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);
ezButton inc (6);
ezButton dec (10);
int cnt =0;
int incPrev, decPrev, speedPrev, val1, val2;
// Define stepper motor connections and steps per revolution:
const int dirPin = 2;
const int stepPin = 3;
AccelStepper myStepper(1, stepPin, dirPin);
//#define stepsPerRevolution 10
long speed;
void setup()
{
//lcd
lcd.begin(16,2);
lcd.backlight();
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
myStepper.setMaxSpeed(10000);
Serial.begin(9600);
}
void loop()
{
updatecnt();
inc.loop();
dec.loop();
digitalWrite(dirPin, HIGH);
Serial.print(speed);
myStepper.setSpeed(200*cnt);
myStepper.runSpeed();
}
void updatecnt ()
{
if((inc.isPressed()) && (cnt < 10)) //&& (inc != incPrev ))
{
cnt++;
}
else if((dec.isPressed()) && (cnt > 0)) // && (dec != decPrev))
{
cnt--;
}
lcd.clear();
lcd.print("RPM = ");
lcd.print(cnt);
}
you never set the value of the variable speed so it will always be 0. You are also clearing and re-printing your LCD every time through loop() which is an expensive task. Only do it if one of the buttons has been pressed. You can also increase your serial baud rate beyond the 1980s standard
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <ezButton.h>
#include <AccelStepper.h>
// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);
ezButton inc (6);
ezButton dec (10);
int cnt = 0;
int incPrev, decPrev, speedPrev, val1, val2;
// Define stepper motor connections and steps per revolution:
const int dirPin = 2;
const int stepPin = 3;
AccelStepper myStepper(1, stepPin, dirPin);
//#define stepsPerRevolution 10
long speed;
void setup()
{
//lcd
lcd.begin(16, 2);
lcd.backlight();
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
myStepper.setMaxSpeed(10000);
Serial.begin(115200);
delay(2000);
digitalWrite(dirPin, HIGH);
}
void loop()
{
inc.loop();
dec.loop();
updatecnt();
myStepper.runSpeed();
}
void updatecnt ()
{
bool update = false; // no need to update speed
if (inc.isPressed() && cnt < 10) {
cnt++;
update = true;
}
else if (dec.isPressed() && cnt > 0) {
cnt--;
update = true;
}
if ( update == true ) {
long speed = 200 * cnt;
Serial.print("New speed = ");
Serial.println(speed);
myStepper.setSpeed(speed);
lcd.clear();
lcd.print("RPM = ");
lcd.print(cnt);
}