To control stepper motor's direction from Pressure Sensor's feedback

Hey guys, I want to control the direction of my stepper motor from the values of pressure sensor. For example, when the pressure sensor gives a reading of 40mBar, the motor should reverse its direction and should continue in this direction until the pressure reaches 0mBar, Once the pressure reaches 0mBar the motor should again reverse its direction,i.e, a pressure range of 0 to 40mBar has been set. This process should go on and on infinitely. I have written a code for the same purpose(written below) but the motor is not reversing it’s direction at any predefined pressure range. I would be really thankful if anyone could help me out with the code. :slight_smile:

const int sensor=A1; //assigned A1 as pressure sensor’s input
double rpm=350;
double si=18750/rpm; //delay calculations according to the rpm
int sp=10; //pin given to step input on the driver
int dir=8; //pin given to direction input on the driver
float vout;

void setup()
{
pinMode(dir,OUTPUT);
pinMode(sp,OUTPUT);
pinMode(sensor,INPUT);
Serial.begin(9600);
}

void loop()
{
vout=((analogRead(sensor))*4.9/44.13)-5.2; // calculation of pressure in mBar
digitalWrite(dir,LOW); // motor’s direction change

while(vout<=40)
{
digitalWrite(sp,HIGH);
delayMicroseconds(si);
digitalWrite(sp,LOW);
delayMicroseconds(si);
vout=((analogRead(sensor))*4.9/44.13)-5.2;
}
vout=((analogRead(sensor))*4.9/44.13)-5.2;
digitalWrite(dir,HIGH); // motor’s direction change

while(vout>=0)
{
digitalWrite(sp,LOW);
delayMicroseconds(si);
digitalWrite(sp,HIGH);
delayMicroseconds(si);
vout=((analogRead(sensor))*4.9/44.13)-5.2;
}

}

You need a variable that holds the direction - perhaps HIGH for forward and LOW for reverse.

The motor code will then set the direction based on that variable - something like

digitalWrite(directionPin, motorDirection);

and the code that reads the sensor will set the value of that variable something like

pressVal = analogRead(sensor);
if (pressVal > (pressThreshold + smallAmount) {
  motorDirection = HIGH;
}
if (pressVal < (pressThreshold - smallAmount) {
  motorDirection = LOW;
}

Unless you need it for some other purpose don’t bother converting the analog value to any other unit,

This calculation vout=((analogRead(sensor))*4.9/44.13)-5.2; is unlikely to do what you think because of the different data types.

…R
Edited 27 March to change motorDirection == HIGH; to motorDirection = HIGH; - apologies for any confusion.

something like

But not exactly like that. Use =, not ==, for the assignment statements.

I can’t believe that Robin2 did that.

PaulS: I can't believe that Robin2 did that.

Neither can I. :)

I have corrected it.

...R