Variable is not set correctly

Hello my name is Jannick and I am new to arduino programming.

Currently I am trying to make a curcuit to check if a button is pressed, and if that happenes a led turns on.
I think the curcuit is wired correctly because the “sum” variable gives me the correct response. My only problem is that the “prev_sum” variable is always 0. It should be the previous sum value. Button is connected to 3,3V and is read at A0. When the button is pressed the sum value is 682.

int average,readd,prev_sum;
static int sum = 0;

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

void loop() {
  prev_sum = sum;
  
  for(int i = 0; i< 20; i++) {
    readd = analogRead(A0);
    average = average + readd;
    delay(1);
  }
  sum = average/20;
  average = 0;
  
  Serial.print("sum: ");
  Serial.println(sum);
  Serial.print("prev_sum: ");
  Serial.println(prev_sum);
  
  if(sum = prev_sum && sum > 680 && sum < 683) {
    led();
  }
  
  delay(1000);
}

void led() {
  digitalWrite(2,HIGH);
  delay(1000);
}

and this is the output of the serial monitor:

sum: 400
prev_sum: 0
sum: 382
prev_sum: 0
sum: 389
prev_sum: 0
sum: 392
prev_sum: 0
sum: 398
prev_sum: 0
sum: 398
prev_sum: 0
sum: 391
prev_sum: 0
sum: 386
prev_sum: 0
sum: 388
prev_sum: 0

This

if(sum = prev_sum

should be

if(sum == prev_sum

and I think that will solve your problem

...R

Thank you very much, it really solved the problem. Can you explain why this solved my problem?

Hi,

‘=’ sets the value of the first variable to the same as the second variable.

while ‘==’ test if the two variables are the same.

Peter

Time to read the basics of if()

https://www.arduino.cc/reference/en/language/structure/control-structure/if/