Hello There!
I am new to Interrupt stuff, and was wondering if anyone could look on my code, before i add LCD and Stuff.
It is for a Eddy Current Hub Dyno for Cars.
I alreaddy have the ControlSystem for one retarder, so i need one more to operate as a Slave.
with PID Setpoint from the other one.
/*Slave PID with Setpoint from Master.
Eddy Current Brake Retarders connected to Driveshaft on Car
Driverside Retarder gets Speedsettings from other Controller.
Slave is only following at equal Speed.
*/
#include <PID_v1.h>
const int pulserev = 60; // the pickup's number of impulses per revolution
const int maxrpm = 4000; // Max.RPM of the spindle
const int stablerpm = 50; // Min. RPM for your setup to run stable
int rpmS; // measured RPM on Slave
int rpmM; // measured RPM on Master
long time = 0; // time between two interrupts
long timeOld = 0; // absolute time of last interrupt
float frequency; // frequency of the interrupts in Hz
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
double Kp = 0.15, Ki = 0.1, Kd = 0.005;
//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, REVERSE);
void setup()
{
// Sample Time of 5 ms
myPID.SetSampleTime(5);
// Interrupt on Pin 3
attachInterrupt(1, measurerpmS, RISING);
// Interupt on Pin 2
attachInterrupt(0, measurerpmM, RISING);
// turn the PID on
myPID.SetMode(AUTOMATIC);
}
void loop()
{
Setpoint = rpmM;
rpmM = 60 * (frequency / pulserev); //Calculating the RPM of Master
rpmS = 60 * (frequency / pulserev); // Calculating the RPM of SLAVE
Input = rpmM; // Input variable for PID control
myPID.SetTunings(Kp, Ki, Kd);
myPID.Compute();
if(Setpoint <= stablerpm){ // No PWM output on Pin 9 if the desired RPM isn't running stable
analogWrite(9, 0);
}
else{
analogWrite(9, Output); // PWM Output to motorcontroller on Pin 9
}
}
void measurerpmS() // Interrupt for measuring the frequency on SLAVE
{
time = micros() - timeOld;
timeOld = micros();
frequency = time;
frequency = 1000000 / frequency;
}
void measurerpmM() // Interrupt for measuring the frequency on Master
{
time = micros() - timeOld;
timeOld = micros();
frequency = time;
frequency = 1000000 / frequency;
}