#include <AccelStepper.h> // http://www.airspayce.com/mikem/arduino/AccelStepper/
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <PID_v1.h>
//Connections
Adafruit_SSD1306 display(128, 64, &Wire, -1);
const byte dirPin = 11; // varaible speed stepper motor
const byte stepPin = 12;
const byte potPin = A0; // Potentiometer input
//const bool useDeadband = true;
const int deadband = 200;
const int step_per_rev = 200;
AccelStepper stepper(AccelStepper::DRIVER, stepPin, dirPin);
int potState = 510;
float motorSpeed = 0;
float motorRPM = 0;
float maxRPM = 50;
double Setpoint ; // will be the desired value
double Input; // photo sensor
double Output ; //LED
//PID parameters
double Kp=0, Ki=10, Kd=0;
//create PID instance
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);
void setup() {
Serial.begin(115200);
display.begin(SSD1306_SWITCHCAPVCC, 0x3c);
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(WHITE);
stepper.setMaxSpeed(2000);
stepper.setSpeed(0);
//Hardcode the brigdness value
Setpoint = 175;
//Turn the PID on
myPID.SetMode(AUTOMATIC);
//Adjust PID values
myPID.SetTunings(Kp, Ki, Kd);
}
void loop() {
//Read the value from the light sensor. Analog input : 0 to 1024. We map is to a value from 0 to 255 as it's used for our PWM function.
Input = map(analogRead(5), 0, 1024, 0, 255); // photo senor is set on analog pin 5
//PID calculation
myPID.Compute();
//Write the output as calculated by the PID function
analogWrite(3,Output); //LED is set to digital 3 this is a pwm pin.
int pot_val = analogRead(A0);
if (pot_val != potState ) {
potState = pot_val;
motorRPM = map(potState, 0, 1023, 0, maxRPM); // no deadband
motorSpeed = motorRPM * step_per_rev / 60;
stepper.setSpeed(motorSpeed);
display.clearDisplay();
display.setCursor(0,0);
display.print(potState);
display.setCursor(55,0);
display.print(motorRPM);
display.display();
}
Serial.print(Input);
Serial.print(" ");
Serial.print(Output);
Serial.print(" ");
Serial.println(motorSpeed);
stepper.runSpeed();
}