#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include <AccelStepper.h>
#include <Wire.h>
#define I2C_ADDR 0x27
#define LCD_COLUMNS 16
#define LCD_LINES 2
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
const int dirPin = 23;
const int stepPin = 25;
const byte dout_pin = 20;
const byte sck_pin = 21;
int motorSpeed = 0;
long number = 0;
unsigned long currentTime = 0;
int interval= 1000; //1000 mS
int setpoint = 0;
const uint8_t ROWS = 4;
const uint8_t COLS = 4;
char keys[ROWS][COLS] = {
{ '1', '2', '3', 'A' },
{ '4', '5', '6', 'B' },
{ '7', '8', '9', 'C' },
{ '*', '0', '#', 'D' }
};
uint8_t colPins[COLS] = { 7, 6, 5, 4 }; // Pins connected to C1, C2, C3, C4
uint8_t rowPins[ROWS] = { 11, 10, 9, 8 }; // Pins connected to R1, R2, R3, R4
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
String keystr = ""; // holds valid ky press
String endstr =""; // holds terminating char#
AccelStepper myStepper(AccelStepper::DRIVER, stepPin, dirPin); //define object as myStepper
void setup() {
Serial.begin(115200);
pinMode(dirPin, OUTPUT);
pinMode(stepPin, OUTPUT);
pinMode(dout_pin, INPUT);
pinMode(sck_pin, INPUT);
// set stepper acceleration and max speed
myStepper.setAcceleration(500);
myStepper.setMaxSpeed(1000);
lcd.init();
lcd.begin(16,2);
lcd.backlight();
lcd.clear();
// Print something
lcd.setCursor(0, 0);
lcd.print("motor speed");
lcd.setCursor(0, 1);
lcd.print("control");
delay (4000);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("setpoint: ");
lcd.setCursor(0,1);
lcd.print("RPM: ");
int myNum = 0; // set intial setpoint to 0 rpm
display(myNum);
}
void loop() {
int setpoint = readkeypad();// get sepoint value from readkeypad function
// set the motor speed:
motorSpeed = setpoint;
if (setpoint>1000){
motorSpeed = 0;
}
myStepper.setSpeed(motorSpeed);
myStepper.runSpeed();
// update LCD display every 1 sec
if (millis()> currentTime +interval)
{ currentTime = millis();
int myNum = setpoint;
display(myNum);// update LCD display
}
}
// ........functions.......
//keypad routine
int readkeypad(){
char key = keypad.getKey();//gets a char if key pressed
if (key){
endstr = (char)key; // assigns the char to endstr
}
if(endstr == "#") { //checks for null char '#'
long number = keystr.toInt(); // if yes,then convert string keystr into an integer
endstr = "";// set the strings to null
keystr = "";
return number;
}
if (isDigit(key)){//checks to see if char is a digit
keystr += (char) key; //if it is, add it to the string keystr
return;
}
}
// display setpoint and motorSpeed on LCD
void display(int num) {
lcd.setCursor(10,0);
lcd.print(num);
lcd.print(" ");
lcd.setCursor(5,1);
lcd.print(motorSpeed);
lcd.print(" ");
return;
}