sorry...it's still not to where i need to be but I'm getting there. here's my code now...
#include <PID_v1.h>
#define encoder0PinA 2
#define encoder0PinB 4
volatile long int encoder0Pos = 0;
double Setpoint, Input, Output;
double Kp=0.1;
double Ki=0;
double Kd=0;
PID myPID(&Input, &Output, &Setpoint,Kp,Ki,Kd,DIRECT);
PID PID2(&Input, &Output, &Setpoint,Kp,Ki,Kd,REVERSE);
int error;
int M1DIR=6;
void setup() {
pinMode(encoder0PinA, INPUT);
digitalWrite(encoder0PinA, HIGH); // turn on pullup resistor
pinMode(encoder0PinB, INPUT);
digitalWrite(encoder0PinB, HIGH); // turn on pullup resistor
attachInterrupt(0, doEncoder, CHANGE); // encoder pin on interrupt 0 - pin 2
Serial.begin (9600);
Serial.println("start"); // a personal quirk
Input =encoder0Pos;
Setpoint = (-1800*2);
myPID.SetMode(AUTOMATIC);
PID2.SetMode(AUTOMATIC);
}
void loop(){
Input =encoder0Pos;
error=Setpoint-encoder0Pos;
if(error<0)
{
digitalWrite (M1DIR,HIGH);
PID2.Compute();
/*if (Output<20)
{
Output=20;
if (Output<17)
{
Output=0;
}
}*/
analogWrite(5,Output);
}
if(error>0)
{
digitalWrite (M1DIR,LOW);
myPID.Compute();
/*if (Output<20)
{
Output=20;
if (Output<17)
{
Output=0;
}
}*/
analogWrite(5,Output);
}
Serial.println(Output,DEC);
// do some stuff here - the joy of interrupts is that they take care of themselves
}
void doEncoder() {
/* If pinA and pinB are both high or both low, it is spinning
* forward. If they're different, it's going backward.
*
* For more information on speeding up this process, see
* [Reference/PortManipulation], specifically the PIND register.
*/
if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB)) {
encoder0Pos++;
} else {
encoder0Pos--;
}
}
I need to work on PWM offset...the motor won't turn at PWM values under around 25, so I need the PWM range linearly from 25 to 255 rather than 0 to 255.