Threshold Switching

Sometimes you will want to switch an output when a value exceeds a certain threshold. 

To do this with a potentiometer, change the loop() code to:

Download: file
    void loop() {
  int threshold = 512;
  if(analogRead(sensorPin) > threshold) { 
    digitalWrite(ledPin, HIGH);
  }
  else {
    digitalWrite(ledPin, LOW);
  }
}
  

This will cause the LED to turn on when the value is above 512 (halfway on the potentiometer dial), you can adjust the sensitivity by changing the threshold value. 

Fading

Let's control the brightness of an LED directly from the potentiometer. To do this we need to first change the pin the LED is connected to. 

Move the wire from Pin 13 to Pin 9 and change the following line in the code:

     int ledPin = 13; -> int ledPin = 9;

Then, change the loop code to:

Download: file
void loop() {
  int value = analogRead(potPin) / 4;
  analogWrite(ledPin, value);
}

Upload the code and watch as your LED fades in relation to your potentiometer spinning. (Note: the reason we divide the value by 4 is the analogRead() function returns a value from 0 to 1023 (10 bits), and analogWrite() takes a value from 0 to 255 (8 bits))

Controlling the servo

This is a really neat example and brings a couple of circuits changing the threshold value. Wire up the servo like you did in CIRC-04:

Then, open the example program Knob (File > Examples > Servo > Knob). Upload to your METRO and then watch as the servo shaft turns as you turn the potentiometer. 

This guide was first published on Aug 18, 2017. It was last updated on Aug 18, 2017.

This page (Make It Better) was last updated on Nov 07, 2020.