quarta-feira, 10 de fevereiro de 2016

Arduino Project #1: RGB LED Adjusted by Potentiometer


Overview

Arduino's digital pins 9, 10, and 11 have PWM (Pulse-Width Modulation), which means they are able to output a kind of analog signal. This given signal is 8-bits large, that is, integer values ranging from 0 to 255.

On the other hand, Arduino's analog pins can be used to read integer values of 10-bits (from 0 to 1023).

In this project, we'll use a single potentiometer to control bright of 3 Super LEDs at the same time!



Components

  • 3 Super LEDs (red, green, and blue)
  • 3 Current Resistors
  • 20 kOhm Potentiometer
  • Jumper wires
  • Breadboard
  • Arduino Uno compatible

Schematics

[https://github.com/hjort/arduino-toys/blob/master/rgb/RgbLedPot.fz]

Source Code

// RGB LED Adjusted by Potentiometer

const int redPin = 11;
const int greenPin = 10;
const int bluePin = 9;
const int potPin = 2; // select the input pin for the potentiometer

unsigned int potValue, lastValue; // 16-bit (0..16535)
byte red, green, blue, alpha; // 8-bit (0..255)

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

void loop() {

  // read the value from the pot (10 bits => 0 to 1023)
  potValue = analogRead(potPin);
  
  if (lastValue == potValue)
    return;
  else
    lastValue = potValue;
  
  // 16-bit placement:
  // ------ARRRGGGBBB
  
  alpha = (potValue >> 9);                  // 0..1
  red   = ((potValue << 7) >> 9) << alpha;  // 0..255
  green = ((potValue << 10) >> 9) << alpha; // 0..255
  blue  = ((potValue << 13) >> 9) << alpha; // 0..255
  
  Serial.print("potValue = ");
  Serial.print(potValue);
  Serial.print(", R = ");
  Serial.print(red);
  Serial.print(", G = ");
  Serial.print(green);
  Serial.print(", B = ");
  Serial.print(blue);
  Serial.print(", A = ");
  Serial.println(alpha);
  
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);
  delay(100);
}

[https://github.com/hjort/arduino-toys/blob/master/rgb/RgbLedPot.ino]


Project in Action


[https://www.youtube.com/watch?v=To8oFhSXuy0]