break out of a loop

Hi I’m trying to write a really simple program to read in values from a pressure sensor and then flick a switch when the pressure drops below a certian value. I need it to then switch off after a specified time, but also carry on reading values, and NOT switch on again.

Initially i put it all in a loop like so:

int pressuresensor=0;
int pumppin=13;
int pressurevalue=0;
int cutoff=500;
int time=5000;

void setup(){
  pinMode(pumppin, OUTPUT);
  Serial.begin(9600);
}
void loop(){
  pressurevalue = analogRead(pressuresensor);
  Serial.println(pressurevalue,DEC);
  if (pressurevalue<500)
  {digitalWrite(pumppin,HIGH);
  delay(5000);
  digitalWrite(pumppin,LOW);
  delay(1000);
}}

but obviously this means that it keeps switching on and off as long as the pressure is below 500. I tried taking the digitalWrite out of the loop, but I get an error: expected unqualified-id before switch.

int pressuresensor=0;
int pump=0;
int pumppin=13;
int pressurevalue=0;
int k=0;
int time=5000;
int cutoff=500;

void setup(){
  pinMode(pumppin, OUTPUT);
  Serial.begin(9600);
}

void loop(){
  pressurevalue = analogRead(pressuresensor);
  //print pressure readings to serial monitor
  Serial.println(pressurevalue,DEC);
  delay (500);
  if (pressurevalue<cutoff){
    k=1;
  }
}

switch (k){
case 1:{
  //switch on pump for specified time
  digitalWrite(pumppin,HIGH);
  delay(time);
  digitalWrite(pumppin,LOW);
}
break;
  //delay(1000);
}

any ideas?
Thanks

I need it to then switch off after a specified time, but also carry on reading values, and NOT switch on again.

If you want the Arduino to carry on reading values, you can’t use delay(). Look at the Blink Without Delay example for an example of how to use millis(0 to determine if it is time to do something.

You’ll need to use a boolean variable to determine whether the pump should be turned on (initially false; true when the value goes low; false again when the time expires).

You’ll need to know what time it is (unsigned long now = millis():wink: and what time the pump was turned on (use a global unsigned long).

On each pass through loop, read the sensor value. Then determine, if the pump is on, if now minus when the pump was turned on is greater than the pump on time. If so, turn the pump off and clear the flag. Then, see if the sensor value requires turning the pump on. If so, set the flag that says the pump is on, set the time the pump was turned on, and turn the pump on.

Great thanks, I shall work on this and let you know! If I can't use delay in the read loop, how do I specify that I only want the readings to be printed every 500ms?

The millis() function acts like you looking at your watch. You are going to use this to determine when to turn the pump off. You can use a very similar approach to determine when the last print occurred, and whether it is time to print again.