storing live data

Hello,
I am currently using an analog sensor and I am going to try and calculate the gradient. I amd going to have a time step which will be my x2-x1 and then I will have my live data which will be y1. I just need to be able to lag the live data by a time step.

so I am trying to display the same as the live value, just a few milliseconds behind.
thanks
Mitchell

In the simplest form, you can use a delay between two readings. You will need to store the first reading and the second reading in different variables (e.g. y1 and y2) to be able to calculate the difference.

Delay will work if your code does not have anything else to do; else you will need a millis() based approach. Record when you did the first reading, wait till a certain interval has passed and do the second reading.

thank you for your reply.

I am unsure how to write code to store a value for a brief moment. Do you know any of examples?

Thanks
Mitchell

const unsigned long interval = 500; // read new value every 500 ms
unsigned long t1; // "old" time value
int y1; // "old" sensor value

void setup() {
  t1 = millis();
  y1 = readSensorValue();
}
void loop() {
  unsigned long t2 = millis(); // "new" time value
  if (t2 - t1 > interval) {  // check BWD (Blink Without Delay)
    int y2 = readSensorValue(); // "new" sensor value
    int gradient = (y2 - y1) / (t2 - t1);
    t1 = t2; // next time the loop repeats, "new" will be "old"
    y1 = y2;
  }
}

Pieter

thank you ever so much for that, I think I understand it enough to have a play around with this project now.

thanks
Mitchell

Hello,

I am currently having an issue with " 'readSensorValue' cannot be used as a function "

building_Optimus_Prime:
I am currently having an issue with " 'readSensorValue' cannot be used as a function "

That's probably because you declared 'readSensorValue' as a variable instead of declaring it as a function. PeiterP used that function name without declaring it as a hint to you that that's a thing you need to write - it's specific to your code and hardware.

int readSensorValue() {
  // do stuff here to read your sensor value

  return the_value_that_i_read;
}

It may be a simple as reading an analogInput(), or it may be as complex as talking to a sensor module using i2c or serial. PeiterP and I don't know how your sensor works: you have to write readSensorValue().