Wrote this last year to demonstrate a potentiometer controlling an RGB LED.
Disclaimer: There are a thousand ways to do this better, with less code, but I "hacked" this into life.
paste this into your Arduino app and it will read better, I promise.
/* Pot as spectrum control
with new function Console for Serial monitoring
Hand coded by Terry Stainton*/
const int RED = 9;
const int GREEN = 10;
const int BLUE = 11;
const int SensorPin = 0;
int Red_Intensity=0;
int Green_Intensity=0;
int Blue_Intensity=0;
int PotVal=0;//Value of the potentiometer in 0-1023
int LoopCount=0;//used to control how often the console function is called
int Delay_ms=50;//50 best match for stability vs smooth glide
void setup () {
Serial.begin(9600);
pinMode(RED, OUTPUT);
pinMode(GREEN, OUTPUT);
pinMode(BLUE, OUTPUT);
}
void loop()
{
//if (LoopCount>50) {
//delay(Delay_ms);
//Console();//services the Seriol I/O Console at a controlled rate
//}
//++LoopCount;
PotVal = analogRead(SensorPin); //Red
delay(10);
if (PotVal <= 340) {//low end of the spectrum
Red_Intensity = (255-(PotVal*0.73));//starts at 255 full red. 0.73 scales the 340 sensor window to 255
analogWrite(RED, Red_Intensity); }
if (PotVal > 340) { //no Red in midrange of spectrum
Red_Intensity =0;
analogWrite(RED, Red_Intensity); }
if (PotVal >= 680){ //picks up Red again for indigo
Red_Intensity = ((PotVal-680)*0.73);
analogWrite(RED, Red_Intensity); }
//Green (only indented for clarity. Above comments apply to green and blue
delay(Delay_ms);
if (PotVal <= 340) {
Green_Intensity = ((PotVal*0.73));
analogWrite(GREEN, Green_Intensity); }
if (PotVal > 340) {
Green_Intensity = ((255-(PotVal-340)*0.73));
analogWrite(GREEN, Green_Intensity);
} if (PotVal >= 680){
Green_Intensity =0;
analogWrite(GREEN, Green_Intensity);
} //Blue
delay(Delay_ms);
if (PotVal >= 340)
{ Blue_Intensity = (((PotVal-340)*0.73));
analogWrite(BLUE, Blue_Intensity);
} if (PotVal > 680)
{ Blue_Intensity = ((255-(PotVal-680)*0.73));
analogWrite(BLUE, Blue_Intensity);
} if (PotVal < 340)
{ Blue_Intensity =0;
analogWrite(BLUE, Blue_Intensity);
} delay(Delay_ms);
}
//function Console for Serial Monitor
void Console()
{
delay(10);
LoopCount=0; //resets the loop count
Serial.print("PotVal=");
Serial.println(PotVal);
Serial.print("Red_Intensity=");
Serial.println(Red_Intensity);
Serial.print("Green_Intensity=");
Serial.println(Green_Intensity);
Serial.print("Blue_Intensity=");
Serial.println(Blue_Intensity);
Serial.println("");
Serial.println("");
}