How can I exactly put my sensor at 4 Hz readings? I'm using the grove GSR sensor: http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor with this code:

const int GSR=A0;
int threshold=0;
int sensorValue;
const long interval = 1000;  
void setup(){
  long sum=0;
  Serial.begin(9600);
  delay(1000);

  for(int i=0;i&lt;500;i++)
  {
  sensorValue=analogRead(GSR);
  sum += sensorValue;
  delay(5);
  }
  threshold = sum/500;
   Serial.print("threshold =");
   Serial.println(threshold);
  }

void loop(){
  int temp;
  sensorValue=analogRead(GSR);
  Serial.println(sensorValue);
  temp = threshold - sensorValue;
  delay(250);
  }


There is the delay way to skip milliseconds or the millis() function. Do you have ideas on how can I implement it? The delay has the problem that doesn't consider the time the sensor uses to read the data.

Here's what I am trying

const int GSR=A0;
int threshold=0;
int sensorValue;
const long interval = 1000; 
unsigned long startTime=millis();


void setup(){
  long sum=0;
  Serial.begin(9600);
  delay(1000);

  for(int i=0;i&lt;500;i++)
  {
  sensorValue=analogRead(GSR);
  sum += sensorValue;
  delay(5);
  }
  threshold = sum/500;
   Serial.print("threshold =");
   Serial.println(threshold);
  }

void loop(){


  if((millis() - startTime) % 250 == 0) {
   int temp;
  sensorValue=analogRead(GSR);
  Serial.println(sensorValue);
  temp = threshold - sensorValue;

  }
  }
The difference between your first code and the second one is that the first one is blocking execution when it reaches the delay function, but the second code keeps running without being blocked.

Now your algorithm has a drawback, the loop may or may not reach the if condition exactly when the modulo is strictly equal to 0. So you may prefer to use something like :

unsigned long T = millis();

...

if( millis() - T &gt;= 250 ) {
    ... // sensor stuff
    T = millis();
}


This idea is also presented in this article https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay.

Another approach is to use Timers and Interrupts, but this is far more complicated (http://playground.arduino.cc/Code/Timer1).