how to store values in a list or array

I have a sensor reading values periodically, and I want to store these values in an array so that I can perform logic on the list before I do anything with it.

For example:
My code is reading the sensor value in a while loop, but I only want to record values higher than 50, and only print all the values recorded if at least one of them was higher than 150.

This would be straightforward in python, but I can't seem to figure out the array syntax in arduino.
Is there a way to do this in arduino?
Would be something like:

int sensorPin = A0;
int sensorVal = 0;
int trigger = 0;
int var = 0;
declare array of unknown length

void setup() {
  Serial.begin(9600);
}

void loop() {

  while (var < 200) {
    val = analogRead(sensorPin);
    if (val > 150)
    {
     trigger = 1;
    }
    if (val >50)
    {
    append val to array**
    }
    var++;
  }

  if (trigger == 1)
  {
  Serial.println(array);
  }

}

This is microcontroller land.

You can't "declare array of unknown length".

How many readings do you expect?

1 Like

First you need to declare an array of the appropriate data type with enough elements to hold the highest expected number of entries. Then you can save data at a specific entry in the array. Normally you would start from entry 0 and increment an index variable ready for the next entry. It is good practice to ensure that the array bounds are not exceeded

Example

int anArray[20];  //an array capable of holding 20 entries numbered 0 to 19
byte arrayIndex = 0;
anArray[arrayIndex] = 123;  //put a value in entry 0
arrayIndex++;  //increment the array index
anArray[arrayIndex] = 456;  //put a value in entry 1
//etc, etc

Typically this would be done in a loop and after incrementing the index variable its value would be tested to ensure that it did not exceed the array bounds (19 in this example)

2 Likes

Great that worked, thanks!!