While Loop Challenge

This questions comes from Jim Kenyon:

  • Arduino Course for Absolute Beginners, 2nd Edition,
    • Control Structures
      • Using the While Loop
        • Challenge #5 – Add a potentiometer to the circuit. Write a program that turns off an LED while the input from the potentiometer is below a certain threshold.

Question:

I’m having problems with challenge 5 for the While Loop lesson.

The challenge states:
“Add a potentiometer to the circuit.  Write a program that turns off an LED while the input from the potentiometer is below a certain threshold.”

I have a potentiometer instead of the button.  I’m using the KOAS. (Kit-on-a-Shield for Arduino)

Here is my solution:

const byte LED = 9;
const byte potPin = A0;

void setup() {
  Serial.begin(9600);
  pinMode(LED, OUTPUT);
  pinMode(potPin, INPUT);
}
void loop() {
  int LEDon = analogRead(potPin);
  Serial.println(LEDon);
  while (LEDon < 500) {
    digitalWrite(LED, HIGH);
  }
  digitalWrite(LED, LOW);
  delay(1);
}

The problem is that when the pot reads less than 500 the program crashes and the LED will not turn off.  This is confirmed by the serial monitor print out.  I’ve tried everything I can think of.

Thank you for your help.

Your Challenge:

The number of times something like this has happened to me in innumerable!

Take a look at the sketch above and see if you can come up with an answer.

Hint:

  1. Take a close look at the while loop condition…

Solution:

Here is what I came up with…

[fvplayer src=”https://vimeo.com/333866654″ transcript=”auto” splash=”https://i.vimeocdn.com/video/779985969_1280x720.jpg?r=pad” caption=”Jim Kenyon – while loop – B”]

const byte LED = 9;
const byte potPin = A0;

void setup() {
  Serial.begin(9600);
  pinMode(LED, OUTPUT);
  pinMode(potPin, INPUT);
}

void loop() {
  
  Serial.println(analogRead(potPin));
  
  while (analogRead(potPin) < 500) {
    digitalWrite(LED, HIGH);
  }
  
  digitalWrite(LED, LOW);
  delay(1);
}

Your Thoughts:

What do you think?  Ever done this yourself?

Let us know in the comments below!

Leave a Comment