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() {

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

void led() {

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


if(sum = prev_sum

should be

if(sum == prev_sum

and I think that will solve your problem


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


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

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


Time to read the basics of if()