I cannot figure out why this while loop isn't working

I have been trying to get the while loop to actually loop for the whole day but I only get a blank display. The serial write command also doesnt work in the while loop. I know there are unnecessary functions and variables because I tried everything to fix it. I have some experience with JavaScript but i am relatively new to C++ so any help will be appreciated.

Here is the sketch:

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

byte pixel[8] = {
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111
};

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

  lcd.begin(16, 2);
  lcd.createChar(3, pixel);
  lcd.clear();
  lcd.setCursor(0, 0);
}

void loop() {
  int pm = (analogRead(A0));
  Serial.println(pm);
  int xin = pm / 63;
  int x2 = xin;
  Serial.println(xin);
  Serial.println(x2);

  while (x2 > 0); {
  lcd.setCursor(xin , 0);
  lcd.write(3);
  xin--;
  x2--;
  Serial.println(xin);
  delay(500);
  }
  
  delay(3000);
  lcd.clear();
  lcd.setCursor(0, 0);
}

Your JavaScript experience should help you to see the problem in this line:

Yes, in that line. That's where the problem is. Take a good, close look at it.
Hint: If the language were JavaScript rather than C++, it would also be a bug in that language, too.

1 Like

Do you realize you will soon be sending negative position instructions to the lcd?
And that x2 could be 0 at the start of while...(so it will not start).

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

How do you figure that? I don't see anything that looks like that.

First thing you are right. Will not happen (as long as x2 is equal to xin).

Second: say analogRead reads 62...

Oops, I forgot about that. D'oh!

It rounds itself

Oh yeah I see it now. I just put a semicolon on everything and didn't see that. I'm getting a result now so thanks for the help

So:

62 / 63 = ..
1 Like

62 / 63 = 0.9841269841 which is read as 1

Try again!
Hint: look up "integer division C/C++".

2 Likes

I had it add 1 because I got this exact problem but I removed it to make it easier to debug.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.