How can I set a high score

I want to be able to make it so that while a value from a sensor is being read it will only save if the new value is higher than the previous one but I've hit a roadblock and none of my code attempts work.

In general you would do it like this

if (currentValue > topValue)
{
  topValue = currentValue;
}

none of my code attempts work.

Post your best effort here

I tried doing something like this:

  int y = 0;
  while(y < x)
  {
    y++;
    Serial.println(y);
  }

Where basically if y (the value top score) is less than x (the analog pin) it will constantly increment until it has reached x and once at that point it will stay the same but it didn’t work.

Please post a complete sketch rather than a snippet so that the context can be seen. For instance, how and where are the variables declared ?

int x = analogRead(A0);

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

void loop()
{
  int y = 0;
  while(y < x)
  {
    y++;
    Serial.println(y);
  }
}

Here ya go

What are you expecting the sketch to do and what does it actually do ?

Declare the int y in global instead. Because with how you’re doing it right now, variable “y” will always be set to 0 everytime it loops. So, corrected code might look like this:

int x = analogRead(A0);
int y = 0;

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

void loop()
{
  while (y < x)
  {
    y++;
    Serial.println(y);
  }
}

Have you tried printing x before the while loop in your original code ?

I'm trying to make an impact recording vest for my assignment and I while active I only want the highest value to be recorded to basically show the highest amount of impact received by the wearer.

No I have not tried printing x, I'll try.

Thanks for the help I'm grateful you are volunteering your time to help make this forum a better place, take a karma.

:o Ok so it turns out that

int x = analogRead(A0);

does not actually work so I removed that and just kept it at

analogRead(A0);

So I tried out your original code suggestion,

if (currentValue > topValue)[color=#222222][/color]
{[color=#222222][/color]
  topValue = currentValue;[color=#222222][/color]
}

and while a proper value was being recorded the high score function didn't work out the way I wanted as it worked as if a normal value was being recorded in the serial monitor.

Let the loop() function do what it is best at, ie looping

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

void loop()
{
  int currentValue = analogRead(A7);
  static int topValue = 0;
  if (currentValue > topValue)
  {
    topValue = currentValue;
    Serial.println(topValue);
  }
}