Potentiometer

This follows on from the Button’s example.

CIRCUIT:

Potentiometer

 

To build this circuit, push the potentiometer into the breadboard. Now attach a wire from the 5v power rail to one side of the potentiometer and another wire from the other side to the ground rail. Connect the middle pin to Analog pin A0 on the GCDuino.

A potentiometer is a simple knob that provides a variable resistance, which we can read into the GCDuino board as an analog value. By turning the shaft of the potentiometer, we change the amount of resistence on either side of the wiper which is connected to the centre pin of the potentiometer. This changes the relative “closeness” of that pin to 5 volts and ground, giving us a different analog input. When the shaft is turned all the way in one direction, there are 0 volts going to the pin, and we read 0. When the shaft is turned all the way in the other direction, there are 5 volts going to the pin and we read 1023. In between, analogRead() returns a number between 0 and 1023 that is proportional to the amount of voltage being applied to the pin.

CODE:

In this the code, fadeLevel is assigned to store the raw analog value coming in from the potentiometer. Because the GCDuino has an analogRead resolution of 0-1023, and an analogWrite resolution of only 0-255, this raw data from the potentiometer needs to be scaled before using it to dim the LED.

In order to scale this value, we use a function called map()

This converts fadeLevel to be equal to the scaled value read from the potentiometer. map() accepts five arguments: The value to be mapped, the low range and high range of the raw data, and the low and high values for that data to be scaled too. In this case, the sensor data is mapped down from its original range of 0 to 1023 to 0 to 255.

The newly mapped sensor data is then written to the PWM capable digital pin. Dimming or brightening the LED as the potentiometer is turned. PWM pins are defined with the symbol “~” in front of the number.

Here is a link to a quick guide to PWM.

ALTERNATE CODE:

 

When you leave out a test condition on an if statement, it tests to see if the condition is true (HIGH or 1). This will only work if testing boolean variables.

The line onOff = !onOff; toggles the variable. “!=” means it is Not equal to.

Leave a Reply

Your email address will not be published. Required fields are marked *