Hello, i am trying to control two dc motors to control the ph value of a solution. I am using two n channel mosfets. When one of the motors turns on, the value of the pH decreases a lot and right after it turns off it comes back. I am using a 12v power source to feed both rs385 motors. And i also want to turn off the motor when the ph is close to the setpoint.
Here is the code i am using:
#define PWM1 6 // ph up
#define PWM2 9 // ph down
const int analogInPin = A0;
int sensorValue = 0;
unsigned long int avgValue;
float b;
int buf[10],temp;
int phValue = 0;
long prevT = 0;
float eprev = 0;
float eintegral = 0;
void setup() {
Serial.begin(9600);
Serial.println("Setpoint");
}
void loop() {
for(int i=0;i<10;i++)
{
buf[i]=analogRead(analogInPin);
delay(10);
}
for(int i=0;i<9;i++)
{
for(int j=i+1;j<10;j++)
{
if(buf[i]>buf[j])
{
temp=buf[i];
buf[i]=buf[j];
buf[j]=temp;
}
}
}
avgValue=0;
for(int i=2;i<8;i++)
avgValue+=buf[i];
float pHVol=(float)avgValue*5.0/1024/6;
float phValue = (-5.70 * pHVol + 21.25);
delay(20);
// set target position
int target = 12;
// PID constants
float kp = 97; //to keep u between 0-255
float kd = 0.000025;
float ki = 0.1;
// time difference
long currT = micros();
float deltaT = ((float) (currT - prevT))/( 1.0e6 );
prevT = currT;
// error
float e =phValue-target;
// Serial.print(e);
//Serial.print(" ");
// derivative
float dedt = (e-eprev)/(deltaT);
// integral
eintegral = eintegral + e*deltaT;
// control signal
float u = kp*e + kd*dedt + ki*eintegral;
// motor power
float pwr = fabs(u);
if( pwr > 255 ){
pwr = 255;
}
// motor selection
if(u<0){
setMotor1(pwr);
setMotor2(0);
}
else{
setMotor1(0);
setMotor2(pwr);
}
// signal the motor
// store previous error
eprev = e;
Serial.print(target);
Serial.print(" pH ");
Serial.print(phValue);
Serial.println();
}
void setMotor1(int pwr){
analogWrite(PWM1,pwr);
}
void setMotor2( int pwr){
analogWrite(PWM2,pwr);
}




