I cannot figure out what I am doing wrong here... I am trying to control a hard drive motor by setting a speed from a keypad and then having a PID take an input speed and run the motor at that speed. I want the (I2C)LCD to show the input speed and the speed that is read by a little photodiode/LM393 chip thing.
I am days deep into this code and just cant get it. I am a total newb so it might be some simple thing that I dont understand properly.
Care to look it over and tell me whats wrong? Everything compiles fine, I am just dumb.
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include <PID_v1.h>
#include <Servo.h>
#define MAX_SIGNAL 2000
#define MIN_SIGNAL 700
#define MOTOR_PIN 9
LiquidCrystal_I2C lcd(0x27,2,16);
const byte rows = 4;
const byte cols = 4;
char keys[rows][cols] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[rows] = {4,5,6,7};
byte colPins[cols] = {8,10,11,12};
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, rows, cols );
Servo motor;
double Setpoint, Input, Output;
int toofast, inputspeed, rpmcount, rpm, timeold;
PID myPID (&Input, &Output, &Setpoint,2,5,1, DIRECT);
volatile int status=LOW;
void setup() {
char key = keypad.waitForKey();
char exitkey = keypad.getKey();
//turn on lcd
lcd.init();
lcd.init();
lcd.begin(16,2);
lcd.backlight();
lcd.setCursor(1,1);
//calibrate esc controller
motor.attach(10);
motor.writeMicroseconds(2400);
lcd.print("Turn on motor, wait 2 sec and press key");
key;
lcd.clear();
motor.writeMicroseconds(544);
//initialize variables
//getInputSpeed();
//determineRpm();
Input= determineRpm();
//toofast=0;
//inputspeed=0;
Setpoint = getInputSpeed();
//turn on the PID
myPID.SetMode(AUTOMATIC);
attachInterrupt(digitalPinToInterrupt(3), rpm_fun, FALLING);
//pinMode(3, OUTPUT);
rpmcount = 0;
rpm = 0;
timeold = 0;
status = LOW;
}
void loop() {
//pid control
int inputspeed;
int rpm;
Input= determineRpm();
char key = keypad.waitForKey();
char exitkey = keypad.getKey();
while(exitkey != 'B')
{
Input = rpm;
myPID.Compute();
analogWrite(9,Output);
lcd.print(inputspeed);
}
}
//get setpoint for pid loop (the desired speed for the spincoater)
//exit key is a
//enter input speed is b
int getInputSpeed(){
int count;
int accumulator=0;
char exitkey = keypad.getKey();
char key = keypad.getKey();
if (key != NO_KEY)
{
lcd.print(key);
count++; if (key =='A'){accumulator=inputspeed;}
accumulator=accumulator*10;
accumulator+key;
if (count==6)
{
lcd.clear();
count=0;
}
}return inputspeed;
}
//rpm function
void rpm_fun() {
rpmcount++;
if (status == LOW)
{ status = HIGH; }
else { status = LOW; }
digitalWrite(3, status);
}
int determineRpm() {
delay(1000);
detachInterrupt(3);
rpm = 60000/(millis() - timeold)*rpmcount;
timeold = millis();
rpmcount = 0;
//Write it out to lcd
lcd.setCursor(0,1);
lcd.print(rpm);
//Restart the interrupt processing
attachInterrupt(3, rpm_fun, FALLING);
return rpm;
}